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/java/org/wings/SForm.java b/src/java/org/wings/SForm.java
index 494dc973..0ebf6a1a 100644
--- a/src/java/org/wings/SForm.java
+++ b/src/java/org/wings/SForm.java
@@ -1,472 +1,474 @@
/*
* $Id$
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://www.j-wings.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
package org.wings;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wings.plaf.FormCG;
import javax.swing.event.EventListenerList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.*;
/**
* Container in which you need to wrap HTML input fields (ie. <code>STextField</code>)
* to work correctly.
* <p/>
* The browser uses this object/tag to identify how (POST or GET) and where
* to send an request originating from any input inside this form.
* <p/>
* <b>Note:</b>Please be aware, that some components render differently if
* placed inside a <code>SForm</code>.
*
* @author <a href="mailto:[email protected]">Armin Haaf</a>
* @version $Revision$
*/
public class SForm extends SContainer implements LowLevelEventListener {
private final transient static Log log = LogFactory.getLog(SForm.class);
/**
* Default Form encoding type. See {@link #setEncodingType(String)}.
*/
// TODO check this encoding type!
public final static String ENC_TYPE_TEXT_PLAIN = "text/plain";
/**
* Multipart form encoding. Needed for file uploads. See {@link #setEncodingType(String)}.
*/
public final static String ENC_TYPE_MULTIPART_FORM = "multipart/form-data";
/**
* URL form encoding. See {@link #setEncodingType(String)}.
*/
public static final String URL_ENCODING = "application/x-www-form-urlencoded";
/**
* Use method POST for submission of the data.
*/
private boolean postMethod = true;
/**
* EncondingType for submission of the data.
*/
private String encType;
/**
* URL to which data
* should be sent to
*/
private URL action;
protected final EventListenerList listenerList = new EventListenerList();
protected String actionCommand;
/**
* the button, that is activated, if no other button is pressed in this
* form.
*/
private SButton defaultButton;
/**
* the WingS event thread is the servlet doGet()/doPost() context
* thread. Within this thread, we collect all armed components. A
* 'armed' component is a component, that will 'fire' an event after the
* first processRequest() stage is completed.
*/
private static ThreadLocal threadArmedComponents = new ThreadLocal() {
protected synchronized Object initialValue() {
return new HashSet(2);
}
};
/**
* Create a standard form component.
*/
public SForm() {
}
/**
* Create a standard form component but redirects the request to the passed
* URL. Use this i.e. to address other servlets.
*
* @param action The target URL.
*/
public SForm(URL action) {
setAction(action);
}
/**
* Create a standard form component.
*
* @param layout The layout to apply to this container.
* @see SContainer
*/
public SForm(SLayoutManager layout) {
super(layout);
}
/**
* A SForm fires an event each time it was triggered (i.e. pressing asubmit button inside)
*
* @param actionCommand The action command to place insiside the {@link ActionEvent}
*/
public void setActionCommand(String actionCommand) {
this.actionCommand = actionCommand;
}
/**
* @see #setActionCommand(String)
*/
public String getActionCommand() {
return actionCommand;
}
/**
* Set the default button activated upon <b>enter</b>.
* The button is triggered if you press <b>enter</b> inside a form to submit it.
* @param defaultButton A button which will be rendered <b>invisible</b>.
* If <code>null</code> enter key pressed will be catched by the wings framework.
*/
public void setDefaultButton(SButton defaultButton) {
this.defaultButton = defaultButton;
}
/**
* @see #setDefaultButton(SButton)
*/
public SButton getDefaultButton() {
return this.defaultButton;
}
/**
* Add a listener for Form events. A Form event is always triggered, when
* a form has been submitted. Usually, this happens, whenever a submit
* button is pressed or some other mechanism triggered the posting of the
* form. Other mechanisms are
* <ul>
* <li> Java Script submit() event</li>
* <li> If a form contains a single text input, then many browsers
* submit the form, if the user presses RETURN in that field. In that
* case, the submit button will <em>not</em> receive any event but
* only the form.
* <li> The {@link SFileChooser} will trigger a form event, if the file
* size exceeded the allowed size. In that case, even if the submit
* button has been pressed, no submit-button event will be triggered.
* (For details, see {@link SFileChooser}).
* </ul>
* Form events are guaranteed to be triggered <em>after</em> all
* Selection-Changes and Button ActionListeners.
*/
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
/**
* Remove a form action listener, that has been added in
* {@link #addActionListener(ActionListener)}
*/
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
/**
* Fire a ActionEvent at each registered listener.
*/
protected void fireActionPerformed(String pActionCommand) {
ActionEvent e = null;
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ActionListener.class) {
// lazy create ActionEvent
if (e == null) {
e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
pActionCommand);
}
((ActionListener) listeners[i + 1]).actionPerformed(e);
}
}
}
public final static void addArmedComponent(LowLevelEventListener component) {
Set armedComponents = (Set) threadArmedComponents.get();
armedComponents.add(component);
}
/**
* clear armed components. This is usually not necessary, since sessions
* clear clear their armed components. But if there was some Exception, it
* might well be, that this does not happen.
*/
public static void clearArmedComponents() {
Set armedComponents = (Set) threadArmedComponents.get();
armedComponents.clear();
}
/*
* Die Sache muss natuerlich Thread Save sein, d.h. es duerfen nur
* die Events gefeuert werden, die auch aus dem feuernden Thread
* stammen (eben dem Dispatcher Thread). Sichergestellt wird das
* dadurch das beim abfeuern der Event in eine Queue (ArrayList)
* gestellt wird, die zu dem feuernden Event gehoert. Diese Queues
* der verschiedenen Threads werden in einer Map verwaltet.
* Beim feuern wird dann die Queue, die dem aktuellen Thread
* entspricht gefeuert und aus der Map entfernt.
*/
/**
* This method fires the low level events for all "armed" components of
* this thread (http session) in an ordered manner:
* <ul><li>forms
* <li>buttons / clickables
* <li>"regular" components</ul>
* This order derives out of the assumption, that a user first modifies
* regular components before he presses the button submitting his changes.
* Otherwise button actions would get fired before the edit components
* fired their events.
*/
public static void fireEvents() {
- Set armedComponents = (Set) threadArmedComponents.get();
+ // use a copy to avoid concurrent modification exceptions if a
+ // LowLevelEventListener adds itself to the armedComponents again
+ List armedComponents = new ArrayList((Collection) threadArmedComponents.get());
try {
LowLevelEventListener component;
// handle form special, form event should be fired last
// hopefully there is only one form ;-)
Iterator iterator = armedComponents.iterator();
LinkedList formEvents = null;
LinkedList buttonEvents = null;
while (iterator.hasNext()) {
component = (LowLevelEventListener) iterator.next();
/* fire form events at last
* there could be more than one form event (e.g. mozilla posts a
* hidden element even if it is in a form outside the posted
* form (if the form is nested). Forms should not be nested in HTML.
*/
if (component instanceof SForm) {
if (formEvents == null) {
formEvents = new LinkedList();
} // end of if ()
formEvents.add(component);
} else if (component instanceof SAbstractIconTextCompound) {
if (buttonEvents == null) {
buttonEvents = new LinkedList();
}
buttonEvents.add(component);
} else {
component.fireIntermediateEvents();
}
}
/*
* no buttons in forms pressed ? Then consider the default-Button.
*/
if (buttonEvents == null && formEvents != null) {
Iterator fit = formEvents.iterator();
while (fit.hasNext()) {
SForm form = (SForm) fit.next();
SButton defaultButton = form.getDefaultButton();
if (defaultButton != null) {
if (buttonEvents == null) {
buttonEvents = new LinkedList();
}
buttonEvents.add(defaultButton);
}
}
}
if (buttonEvents != null) {
iterator = buttonEvents.iterator();
while (iterator.hasNext()) {
((SAbstractIconTextCompound) iterator.next()).fireIntermediateEvents();
}
}
if (formEvents != null) {
iterator = formEvents.iterator();
while (iterator.hasNext()) {
((SForm) iterator.next()).fireIntermediateEvents();
}
}
iterator = armedComponents.iterator();
while (iterator.hasNext()) {
component = (LowLevelEventListener) iterator.next();
// fire form events at last
if (!(component instanceof SForm || component instanceof SAbstractIconTextCompound)) {
component.fireFinalEvents();
}
}
if (buttonEvents != null) {
iterator = buttonEvents.iterator();
while (iterator.hasNext()) {
((SAbstractIconTextCompound) iterator.next()).fireFinalEvents();
}
buttonEvents.clear();
}
if (formEvents != null) {
iterator = formEvents.iterator();
while (iterator.hasNext()) {
((SForm) iterator.next()).fireFinalEvents();
}
formEvents.clear();
}
} finally {
armedComponents.clear();
}
}
/**
* Set, whether this form is to be transmitted via <code>POST</code> (true)
* or <code>GET</code> (false). The default, and this is what you
* usually want, is <code>POST</code>.
*/
public void setPostMethod(boolean postMethod) {
this.postMethod = postMethod;
}
/**
* Returns, whether this form is transmitted via <code>POST</code> (true)
* or <code>GET</code> (false). <p>
* <b>Default</b> is <code>true</code>.
*
* @return <code>true</code> if form postedt via <code>POST</code>,
* <code>false</code> if via <code>GET</code> (false).
*/
public boolean isPostMethod() {
return postMethod;
}
/**
* Set the encoding of this form. This actually is an HTML interna
* that bubbles up here. By default, the encoding type of any HTML-form
* is <code>application/x-www-form-urlencoded</code>, and as such, needn't
* be explicitly set with this setter. However, if you've included a
* file upload element (as represented by {@link SFileChooser}) in your
* form, this must be set to <code>multipart/form-data</code>, since only
* then, files are transmitted correctly. In 'normal' forms without
* file upload, it is not necessary to set it to
* <code>multipart/form-data</code>; actually it enlarges the data to
* be transmitted, so you probably don't want to do this, then.
*
* @param type the encoding type; one of <code>multipart/form-data</code>,
* <code>application/x-www-form-urlencoded</code> or null to detect encoding.
*/
public void setEncodingType(String type) {
encType = type;
}
/**
* Get the current encoding type, as set with
* {@link #setEncodingType(String)}. If no encoding type was set, this
* method detects the best encoding type. This can be expensive, so if
* you can, set the encoding type.
*
* @return string containing the encoding type. This is something like
* <code>multipart/form-data</code>,
* <code>application/x-www-form-urlencoded</code> .. or 'null'
* by default.
*/
public String getEncodingType() {
if (encType == null) {
return detectEncodingType(this);
} else {
return encType;
}
}
/**
* Detects if the Container contains a component that needs a certain encoding type
* @param pContainer
* @return <code>null</code> or {@link #ENC_TYPE_MULTIPART_FORM}
*/
protected String detectEncodingType(SContainer pContainer) {
for (int i = 0; i < pContainer.getComponentCount(); i++) {
SComponent tComponent = pContainer.getComponent(i);
if (tComponent instanceof SFileChooser && tComponent.isVisible()) {
return ENC_TYPE_MULTIPART_FORM;
} else if ((tComponent instanceof SContainer) && tComponent.isVisible()) {
String tContainerEncoding = detectEncodingType((SContainer) tComponent);
if (tContainerEncoding != null) {
return tContainerEncoding;
}
}
}
return null;
}
public void setAction(URL action) {
this.action = action;
}
public URL getAction() {
return action;
}
public RequestURL getRequestURL() {
RequestURL addr = super.getRequestURL();
if (getAction() != null) {
addr.addParameter(getAction().toString()); // ??
}
return addr;
}
public void processLowLevelEvent(String action, String[] values) {
processKeyEvents(values);
// we have to wait, until all changed states of our form have
// changed, before we anything can happen.
SForm.addArmedComponent(this);
}
public void fireIntermediateEvents() {
}
public void fireFinalEvents() {
fireKeyEvents();
fireActionPerformed(getActionCommand());
}
/** @see LowLevelEventListener#isEpochCheckEnabled() */
private boolean epochCheckEnabled = true;
/** @see LowLevelEventListener#isEpochCheckEnabled() */
public boolean isEpochCheckEnabled() {
return epochCheckEnabled;
}
/** @see LowLevelEventListener#isEpochCheckEnabled() */
public void setEpochCheckEnabled(boolean epochCheckEnabled) {
this.epochCheckEnabled = epochCheckEnabled;
}
public SComponent addComponent(SComponent c, Object constraint, int index) {
if (c instanceof SForm)
log.warn("WARNING: attempt to nest forms; won't work.");
return super.addComponent(c, constraint, index);
}
public void setCG(FormCG cg) {
super.setCG(cg);
}
}
| true | true | public static void fireEvents() {
Set armedComponents = (Set) threadArmedComponents.get();
try {
LowLevelEventListener component;
// handle form special, form event should be fired last
// hopefully there is only one form ;-)
Iterator iterator = armedComponents.iterator();
LinkedList formEvents = null;
LinkedList buttonEvents = null;
while (iterator.hasNext()) {
component = (LowLevelEventListener) iterator.next();
/* fire form events at last
* there could be more than one form event (e.g. mozilla posts a
* hidden element even if it is in a form outside the posted
* form (if the form is nested). Forms should not be nested in HTML.
*/
if (component instanceof SForm) {
if (formEvents == null) {
formEvents = new LinkedList();
} // end of if ()
formEvents.add(component);
} else if (component instanceof SAbstractIconTextCompound) {
if (buttonEvents == null) {
buttonEvents = new LinkedList();
}
buttonEvents.add(component);
} else {
component.fireIntermediateEvents();
}
}
/*
* no buttons in forms pressed ? Then consider the default-Button.
*/
if (buttonEvents == null && formEvents != null) {
Iterator fit = formEvents.iterator();
while (fit.hasNext()) {
SForm form = (SForm) fit.next();
SButton defaultButton = form.getDefaultButton();
if (defaultButton != null) {
if (buttonEvents == null) {
buttonEvents = new LinkedList();
}
buttonEvents.add(defaultButton);
}
}
}
if (buttonEvents != null) {
iterator = buttonEvents.iterator();
while (iterator.hasNext()) {
((SAbstractIconTextCompound) iterator.next()).fireIntermediateEvents();
}
}
if (formEvents != null) {
iterator = formEvents.iterator();
while (iterator.hasNext()) {
((SForm) iterator.next()).fireIntermediateEvents();
}
}
iterator = armedComponents.iterator();
while (iterator.hasNext()) {
component = (LowLevelEventListener) iterator.next();
// fire form events at last
if (!(component instanceof SForm || component instanceof SAbstractIconTextCompound)) {
component.fireFinalEvents();
}
}
if (buttonEvents != null) {
iterator = buttonEvents.iterator();
while (iterator.hasNext()) {
((SAbstractIconTextCompound) iterator.next()).fireFinalEvents();
}
buttonEvents.clear();
}
if (formEvents != null) {
iterator = formEvents.iterator();
while (iterator.hasNext()) {
((SForm) iterator.next()).fireFinalEvents();
}
formEvents.clear();
}
} finally {
armedComponents.clear();
}
}
| public static void fireEvents() {
// use a copy to avoid concurrent modification exceptions if a
// LowLevelEventListener adds itself to the armedComponents again
List armedComponents = new ArrayList((Collection) threadArmedComponents.get());
try {
LowLevelEventListener component;
// handle form special, form event should be fired last
// hopefully there is only one form ;-)
Iterator iterator = armedComponents.iterator();
LinkedList formEvents = null;
LinkedList buttonEvents = null;
while (iterator.hasNext()) {
component = (LowLevelEventListener) iterator.next();
/* fire form events at last
* there could be more than one form event (e.g. mozilla posts a
* hidden element even if it is in a form outside the posted
* form (if the form is nested). Forms should not be nested in HTML.
*/
if (component instanceof SForm) {
if (formEvents == null) {
formEvents = new LinkedList();
} // end of if ()
formEvents.add(component);
} else if (component instanceof SAbstractIconTextCompound) {
if (buttonEvents == null) {
buttonEvents = new LinkedList();
}
buttonEvents.add(component);
} else {
component.fireIntermediateEvents();
}
}
/*
* no buttons in forms pressed ? Then consider the default-Button.
*/
if (buttonEvents == null && formEvents != null) {
Iterator fit = formEvents.iterator();
while (fit.hasNext()) {
SForm form = (SForm) fit.next();
SButton defaultButton = form.getDefaultButton();
if (defaultButton != null) {
if (buttonEvents == null) {
buttonEvents = new LinkedList();
}
buttonEvents.add(defaultButton);
}
}
}
if (buttonEvents != null) {
iterator = buttonEvents.iterator();
while (iterator.hasNext()) {
((SAbstractIconTextCompound) iterator.next()).fireIntermediateEvents();
}
}
if (formEvents != null) {
iterator = formEvents.iterator();
while (iterator.hasNext()) {
((SForm) iterator.next()).fireIntermediateEvents();
}
}
iterator = armedComponents.iterator();
while (iterator.hasNext()) {
component = (LowLevelEventListener) iterator.next();
// fire form events at last
if (!(component instanceof SForm || component instanceof SAbstractIconTextCompound)) {
component.fireFinalEvents();
}
}
if (buttonEvents != null) {
iterator = buttonEvents.iterator();
while (iterator.hasNext()) {
((SAbstractIconTextCompound) iterator.next()).fireFinalEvents();
}
buttonEvents.clear();
}
if (formEvents != null) {
iterator = formEvents.iterator();
while (iterator.hasNext()) {
((SForm) iterator.next()).fireFinalEvents();
}
formEvents.clear();
}
} finally {
armedComponents.clear();
}
}
|
diff --git a/jsonhome-example/src/main/java/de/otto/jsonhome/example/products/ProductsController.java b/jsonhome-example/src/main/java/de/otto/jsonhome/example/products/ProductsController.java
index b8e1b19..212ce95 100644
--- a/jsonhome-example/src/main/java/de/otto/jsonhome/example/products/ProductsController.java
+++ b/jsonhome-example/src/main/java/de/otto/jsonhome/example/products/ProductsController.java
@@ -1,169 +1,169 @@
/**
Copyright 2012 Guido Steinacker
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package de.otto.jsonhome.example.products;
import de.otto.jsonhome.annotation.Doc;
import de.otto.jsonhome.annotation.Hints;
import de.otto.jsonhome.annotation.Rel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Map;
import static de.otto.jsonhome.example.products.ProductConverter.*;
import static java.util.Collections.singletonMap;
import static javax.servlet.http.HttpServletResponse.SC_CREATED;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.PRECONDITION_FAILED;
/**
* @author Guido Steinacker
* @since 15.09.12
*/
@Controller
@RequestMapping(value = "/products")
@Doc(value = {
"A single product.",
"This is a second paragraph, describing the link-relation type."},
link = "http://de.wikipedia.org/wiki/Produkt_(Wirtschaft)"
)
public class ProductsController {
@Autowired
private ProductService productService;
@RequestMapping(
method = RequestMethod.GET,
produces = "text/html"
)
@Rel("/rel/products")
@Doc(value = {
"The collection of products.",
"This is a second paragraph, describing the collection of products."
})
public ModelAndView getProductsHtml(final @RequestParam(required = false, defaultValue = "*") String query) {
final List<Product> products = productService.findProducts(query);
return new ModelAndView("example/products", singletonMap("products", products));
}
@RequestMapping(
method = RequestMethod.GET,
produces = {"application/example-products", "application/json"}
)
@ResponseBody
@Rel("/rel/products")
@Doc(value = {
"The collection of products.",
"This is a second paragraph, describing the collection of products."
})
public Map<String, ?> getProductsJson(final @RequestParam(required = false, defaultValue = "*") String query,
final HttpServletRequest request) {
final List<Product> products = productService.findProducts(query);
return productsToJson(products, request.getContextPath());
}
@RequestMapping(
method = RequestMethod.POST,
consumes = "application/x-www-form-urlencoded",
produces = "text/html"
)
@Rel("/rel/product/form")
@Doc(value = {
"Service to create a product.",
"This is a second paragraph, describing the link-relation type."
})
public ModelAndView postProductUrlEncoded(final @RequestParam String title,
final @RequestParam String price,
final HttpServletRequest request,
final HttpServletResponse response) {
// Create a new product with id generated by the service:
final long id = productService.addProduct(title, price);
final List<Product> products = productService.findProducts("*");
// Return the URI of the created product in Location header:
response.setHeader("Location", request.getContextPath() + "/products/" + id);
response.setStatus(SC_CREATED);
return new ModelAndView("example/products", singletonMap("products", products));
}
@RequestMapping(
value = "/{productId}",
method = RequestMethod.GET,
produces = "text/html"
)
@Rel("/rel/product")
public ModelAndView getProductAsHtml(@Doc({"The unique identifier of the requested product.",
"A second line of valuable documentation."})
@PathVariable final long productId) {
final Product product = productService.findProduct(productId);
return new ModelAndView("example/product", singletonMap("product", product));
}
@RequestMapping(
value = "/{productId}",
method = RequestMethod.GET,
produces = {"application/example-product", "application/json"}
)
@ResponseBody
@Rel("/rel/product")
public Map<String, Object> getProductAsJson(final @PathVariable long productId,
final HttpServletRequest request) {
return productToJson(productService.findProduct(productId), request.getContextPath());
}
@RequestMapping(
value = "/{productId}",
method = RequestMethod.PUT,
consumes = {"application/example-product", "application/json"},
produces = {"application/example-product", "application/json"}
)
@ResponseBody
@Rel("/rel/product")
@Hints(preconditionReq = "etag")
public Map<String, ?> putProduct(final @PathVariable long productId,
final @RequestBody Map<String, String> document,
final HttpServletRequest request,
final HttpServletResponse response) throws IOException {
- final String etag = request.getHeader("ETag");
+ final String expectedETag = request.getHeader("If-Match");
final Product expected = productService.findProduct(productId);
- if (expected == null || expected.getETag().equals(etag)) {
+ if (expected == null || expectedETag.equals("*") || expected.getETag().equals(expectedETag)) {
final Product product = jsonToProduct(productId, document);
final Product previous = productService.createOrUpdateProduct(product, expected);
response.setStatus(previous == null ? SC_CREATED : SC_OK);
return productToJson(product, request.getContextPath());
} else {
throw new ConcurrentModificationException("product was concurrently modified.");
}
}
@ResponseStatus(value = BAD_REQUEST)
@ExceptionHandler({IllegalArgumentException.class})
public void handleNotFound() throws IOException {
}
@ResponseStatus(value = PRECONDITION_FAILED)
@ExceptionHandler({ConcurrentModificationException.class})
public void handleConcurrentModification() throws IOException {
}
}
| false | true | public Map<String, ?> putProduct(final @PathVariable long productId,
final @RequestBody Map<String, String> document,
final HttpServletRequest request,
final HttpServletResponse response) throws IOException {
final String etag = request.getHeader("ETag");
final Product expected = productService.findProduct(productId);
if (expected == null || expected.getETag().equals(etag)) {
final Product product = jsonToProduct(productId, document);
final Product previous = productService.createOrUpdateProduct(product, expected);
response.setStatus(previous == null ? SC_CREATED : SC_OK);
return productToJson(product, request.getContextPath());
} else {
throw new ConcurrentModificationException("product was concurrently modified.");
}
}
| public Map<String, ?> putProduct(final @PathVariable long productId,
final @RequestBody Map<String, String> document,
final HttpServletRequest request,
final HttpServletResponse response) throws IOException {
final String expectedETag = request.getHeader("If-Match");
final Product expected = productService.findProduct(productId);
if (expected == null || expectedETag.equals("*") || expected.getETag().equals(expectedETag)) {
final Product product = jsonToProduct(productId, document);
final Product previous = productService.createOrUpdateProduct(product, expected);
response.setStatus(previous == null ? SC_CREATED : SC_OK);
return productToJson(product, request.getContextPath());
} else {
throw new ConcurrentModificationException("product was concurrently modified.");
}
}
|
diff --git a/src/javachallenge/server/Main.java b/src/javachallenge/server/Main.java
index 4077efb..02b47f1 100644
--- a/src/javachallenge/server/Main.java
+++ b/src/javachallenge/server/Main.java
@@ -1,85 +1,85 @@
package javachallenge.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javachallenge.common.Action;
import javachallenge.common.ClientMessage;
import javachallenge.common.InitMessage;
import javachallenge.common.Point;
import javachallenge.common.ServerMessage;
import javachallenge.graphics.GraphicClient;
import javachallenge.graphics.GraphicClient.OutOfMapException;
import javachallenge.graphics.util.Position;
public class Main {
private static int PORT = 5555;
private static int CYCLE_TIME = 500;
private GraphicClient graphicClient;
public void run() throws IOException, InterruptedException, OutOfMapException {
ServerSocket ss = new ServerSocket(PORT);
ServerMap sampleMap = ServerMap.load("map/m1.txt");
Position[] tmpFlagPositions = new Position[sampleMap.getFlagLocations().size()];
for(int i = 0 ; i < sampleMap.getFlagLocations().size() ; i++) {
Point flag = sampleMap.getFlagLocations().get(i);
tmpFlagPositions[i] = new Position(flag.x, flag.y);
}
graphicClient = new GraphicClient(sampleMap);
Engine engine = new Engine(sampleMap, graphicClient);
ArrayList<TeamConnection> connections = new ArrayList<TeamConnection>();
for (int i = 0; i < sampleMap.getTeamCount(); i++) {
System.out.println("Waiting for team " + i);
Socket socket = ss.accept();
connections.add(new TeamConnection(engine.getTeam(i), socket));
}
ArrayList<InitMessage> initialMessage = engine.getInitialMessage();
for (TeamConnection c: connections) {
c.sendInitialMessage(initialMessage.get(c.getTeam().getId()));
}
engine.beginStep();
engine.teamStep(new ArrayList<Action>());
engine.endStep();
while (!engine.gameIsOver()) {
- System.out.println("Cylce filan " + engine.getCycle());
+ System.out.println("Cycle " + engine.getCycle());
ArrayList<ServerMessage> stepMessage = engine.getStepMessage();
for (int i = 0; i < sampleMap.getTeamCount(); i++) {
connections.get(i).sendStepMessage(stepMessage.get(i));
connections.get(i).clearClientMessage();
}
Thread.sleep(CYCLE_TIME);
ArrayList<Action> allActions = new ArrayList<Action>();
for (int i = 0; i < sampleMap.getTeamCount(); i++) {
ClientMessage msg = connections.get(i).getClientMessage();
if (msg == null) {
System.out.println("Team " + i + " message miss");
} else {
allActions.addAll(msg.getActions(i));
}
}
engine.beginStep();
engine.teamStep(allActions);
engine.endStep();
}
ss.close();
}
public static void main(String[] args) throws IOException, InterruptedException, OutOfMapException {
new Main().run();
}
}
| true | true | public void run() throws IOException, InterruptedException, OutOfMapException {
ServerSocket ss = new ServerSocket(PORT);
ServerMap sampleMap = ServerMap.load("map/m1.txt");
Position[] tmpFlagPositions = new Position[sampleMap.getFlagLocations().size()];
for(int i = 0 ; i < sampleMap.getFlagLocations().size() ; i++) {
Point flag = sampleMap.getFlagLocations().get(i);
tmpFlagPositions[i] = new Position(flag.x, flag.y);
}
graphicClient = new GraphicClient(sampleMap);
Engine engine = new Engine(sampleMap, graphicClient);
ArrayList<TeamConnection> connections = new ArrayList<TeamConnection>();
for (int i = 0; i < sampleMap.getTeamCount(); i++) {
System.out.println("Waiting for team " + i);
Socket socket = ss.accept();
connections.add(new TeamConnection(engine.getTeam(i), socket));
}
ArrayList<InitMessage> initialMessage = engine.getInitialMessage();
for (TeamConnection c: connections) {
c.sendInitialMessage(initialMessage.get(c.getTeam().getId()));
}
engine.beginStep();
engine.teamStep(new ArrayList<Action>());
engine.endStep();
while (!engine.gameIsOver()) {
System.out.println("Cylce filan " + engine.getCycle());
ArrayList<ServerMessage> stepMessage = engine.getStepMessage();
for (int i = 0; i < sampleMap.getTeamCount(); i++) {
connections.get(i).sendStepMessage(stepMessage.get(i));
connections.get(i).clearClientMessage();
}
Thread.sleep(CYCLE_TIME);
ArrayList<Action> allActions = new ArrayList<Action>();
for (int i = 0; i < sampleMap.getTeamCount(); i++) {
ClientMessage msg = connections.get(i).getClientMessage();
if (msg == null) {
System.out.println("Team " + i + " message miss");
} else {
allActions.addAll(msg.getActions(i));
}
}
engine.beginStep();
engine.teamStep(allActions);
engine.endStep();
}
ss.close();
}
| public void run() throws IOException, InterruptedException, OutOfMapException {
ServerSocket ss = new ServerSocket(PORT);
ServerMap sampleMap = ServerMap.load("map/m1.txt");
Position[] tmpFlagPositions = new Position[sampleMap.getFlagLocations().size()];
for(int i = 0 ; i < sampleMap.getFlagLocations().size() ; i++) {
Point flag = sampleMap.getFlagLocations().get(i);
tmpFlagPositions[i] = new Position(flag.x, flag.y);
}
graphicClient = new GraphicClient(sampleMap);
Engine engine = new Engine(sampleMap, graphicClient);
ArrayList<TeamConnection> connections = new ArrayList<TeamConnection>();
for (int i = 0; i < sampleMap.getTeamCount(); i++) {
System.out.println("Waiting for team " + i);
Socket socket = ss.accept();
connections.add(new TeamConnection(engine.getTeam(i), socket));
}
ArrayList<InitMessage> initialMessage = engine.getInitialMessage();
for (TeamConnection c: connections) {
c.sendInitialMessage(initialMessage.get(c.getTeam().getId()));
}
engine.beginStep();
engine.teamStep(new ArrayList<Action>());
engine.endStep();
while (!engine.gameIsOver()) {
System.out.println("Cycle " + engine.getCycle());
ArrayList<ServerMessage> stepMessage = engine.getStepMessage();
for (int i = 0; i < sampleMap.getTeamCount(); i++) {
connections.get(i).sendStepMessage(stepMessage.get(i));
connections.get(i).clearClientMessage();
}
Thread.sleep(CYCLE_TIME);
ArrayList<Action> allActions = new ArrayList<Action>();
for (int i = 0; i < sampleMap.getTeamCount(); i++) {
ClientMessage msg = connections.get(i).getClientMessage();
if (msg == null) {
System.out.println("Team " + i + " message miss");
} else {
allActions.addAll(msg.getActions(i));
}
}
engine.beginStep();
engine.teamStep(allActions);
engine.endStep();
}
ss.close();
}
|
diff --git a/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/classes/AbstractNewClassPage.java b/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/classes/AbstractNewClassPage.java
index fe4d7f71..91584d66 100644
--- a/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/classes/AbstractNewClassPage.java
+++ b/bundles/org.eclipse.e4.tools/src/org/eclipse/e4/internal/tools/wizards/classes/AbstractNewClassPage.java
@@ -1,367 +1,368 @@
/*******************************************************************************
* Copyright (c) 2010 BestSolution.at 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:
* Tom Schindl <[email protected]> - initial API and implementation
******************************************************************************/
package org.eclipse.e4.internal.tools.wizards.classes;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.conversion.Converter;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.ui.JavaElementComparator;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jface.databinding.swt.IWidgetValueProperty;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.jface.databinding.wizard.WizardPageSupport;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
public abstract class AbstractNewClassPage extends WizardPage {
public static class JavaClass {
protected PropertyChangeSupport support = new PropertyChangeSupport(this);
private IPackageFragmentRoot fragmentRoot;
private IPackageFragment packageFragment;
private String name;
public JavaClass(IPackageFragmentRoot fragmentRoot) {
this.fragmentRoot = fragmentRoot;
}
public IPackageFragmentRoot getFragmentRoot() {
return fragmentRoot;
}
public void setFragmentRoot(IPackageFragmentRoot fragmentRoot) {
support.firePropertyChange("fragementRoot", this.fragmentRoot, this.fragmentRoot = fragmentRoot);
}
public IPackageFragment getPackageFragment() {
return packageFragment;
}
public void setPackageFragment(IPackageFragment packageFragment) {
support.firePropertyChange("packageFragment", this.packageFragment, this.packageFragment = packageFragment);
}
public String getName() {
return name;
}
public void setName(String name) {
support.firePropertyChange("name", this.name, this.name = name);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}
}
private JavaClass clazz;
private IPackageFragmentRoot froot;
private IWorkspaceRoot fWorkspaceRoot;
protected AbstractNewClassPage(String pageName, String title, String description, IPackageFragmentRoot froot, IWorkspaceRoot fWorkspaceRoot) {
super(pageName);
this.froot = froot;
this.fWorkspaceRoot = fWorkspaceRoot;
setTitle(title);
setDescription(description);
}
public void createControl(Composite parent) {
final Image img = new Image(parent.getDisplay(), getClass().getClassLoader().getResourceAsStream("/icons/full/wizban/newclass_wiz.png"));
setImageDescriptor(ImageDescriptor.createFromImage(img));
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
img.dispose();
setImageDescriptor(null);
}
});
parent = new Composite(parent, SWT.NULL);
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
parent.setLayout(new GridLayout(3, false));
clazz = createInstance();
DataBindingContext dbc = new DataBindingContext();
WizardPageSupport.create(this, dbc);
{
Label l = new Label(parent, SWT.NONE);
l.setText("Source folder");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
t.setEditable(false);
final Binding bd = dbc.bindValue(
WidgetProperties.text().observe(t),
BeanProperties.value("fragmentRoot").observe(clazz),
new UpdateValueStrategy(),
new UpdateValueStrategy().setConverter(new PackageFragmentRootToStringConverter())
);
Button b = new Button(parent, SWT.PUSH);
b.setText("Browse ...");
b.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IPackageFragmentRoot root = choosePackageRoot();
if( root != null ) {
+ froot = root;
clazz.setFragmentRoot(root);
}
bd.updateModelToTarget(); //TODO Find out why this is needed
}
});
}
{
Label l = new Label(parent, SWT.NONE);
l.setText("Package");
Text t = new Text(parent, SWT.BORDER);
t.setEditable(false);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
final Binding bd = dbc.bindValue(
WidgetProperties.text().observe(t),
BeanProperties.value("packageFragment").observe(clazz),
new UpdateValueStrategy(),
new UpdateValueStrategy().setConverter(new PackageFragmentToStringConverter())
);
Button b = new Button(parent, SWT.PUSH);
b.setText("Browse ...");
b.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IPackageFragment fragment = choosePackage();
if( fragment != null ) {
clazz.setPackageFragment(fragment);
}
bd.updateModelToTarget(); //TODO Find out why this is needed
}
});
}
{
IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);
Label l = new Label(parent, SWT.NONE);
l.setText("Name");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
dbc.bindValue(textProp.observe(t), BeanProperties.value("name", String.class).observe(clazz));
new Label(parent, SWT.NONE);
}
{
Label l = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
l.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false, 3, 1));
}
createFields(parent, dbc);
setControl(parent);
}
private IPackageFragmentRoot choosePackageRoot() {
IJavaElement initElement= clazz.getFragmentRoot();
Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) {
public boolean isSelectedValid(Object element) {
try {
if (element instanceof IJavaProject) {
IJavaProject jproject= (IJavaProject)element;
IPath path= jproject.getProject().getFullPath();
return (jproject.findPackageFragmentRoot(path) != null);
} else if (element instanceof IPackageFragmentRoot) {
return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE);
}
return true;
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus()); // just log, no UI in validation
}
return false;
}
};
acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class };
ViewerFilter filter= new TypedViewerFilter(acceptedClasses) {
public boolean select(Viewer viewer, Object parent, Object element) {
if (element instanceof IPackageFragmentRoot) {
try {
return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE);
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus()); // just log, no UI in validation
return false;
}
}
return super.select(viewer, parent, element);
}
};
StandardJavaElementContentProvider provider= new StandardJavaElementContentProvider();
ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
dialog.setValidator(validator);
dialog.setComparator(new JavaElementComparator());
dialog.setTitle(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_title);
dialog.setMessage(NewWizardMessages.NewContainerWizardPage_ChooseSourceContainerDialog_description);
dialog.addFilter(filter);
dialog.setInput(JavaCore.create(fWorkspaceRoot));
dialog.setInitialSelection(initElement);
dialog.setHelpAvailable(false);
if (dialog.open() == Window.OK) {
Object element= dialog.getFirstResult();
if (element instanceof IJavaProject) {
IJavaProject jproject= (IJavaProject)element;
return jproject.getPackageFragmentRoot(jproject.getProject());
} else if (element instanceof IPackageFragmentRoot) {
return (IPackageFragmentRoot)element;
}
return null;
}
return null;
}
private IPackageFragment choosePackage() {
IJavaElement[] packages= null;
try {
if (froot != null && froot.exists()) {
packages= froot.getChildren();
}
} catch (JavaModelException e) {
e.printStackTrace();
}
if (packages == null) {
packages= new IJavaElement[0];
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
dialog.setIgnoreCase(false);
dialog.setTitle("Choose Package");
dialog.setMessage("Choose a Package");
dialog.setEmptyListMessage("You need to select a package");
dialog.setElements(packages);
dialog.setHelpAvailable(false);
IPackageFragment pack= clazz.getPackageFragment();
if (pack != null) {
dialog.setInitialSelections(new Object[] { pack });
}
if (dialog.open() == Window.OK) {
return (IPackageFragment) dialog.getFirstResult();
}
return null;
}
protected abstract void createFields(Composite parent, DataBindingContext dbc);
protected abstract JavaClass createInstance();
public JavaClass getClazz() {
return clazz;
}
static class ClassnameValidator implements IValidator {
public IStatus validate(Object value) {
String name = value.toString();
char[] ar = name.toCharArray();
for (char c : ar) {
if (!Character.isJavaIdentifierPart(c)) {
return new Status(IStatus.ERROR, "", "'" + c + "' is not allowed in a Class-Name");
}
}
if (!Character.isJavaIdentifierStart(ar[0])) {
return new Status(IStatus.ERROR, "", "'" + ar[0] + "' is not allowed as the first character of a Class-Name");
}
return Status.OK_STATUS;
}
}
static class PackageFragmentRootToStringConverter extends Converter {
public PackageFragmentRootToStringConverter() {
super(IPackageFragmentRoot.class, String.class);
}
public Object convert(Object fromObject) {
IPackageFragmentRoot f = (IPackageFragmentRoot) fromObject;
return f.getPath().makeRelative().toString();
}
}
static class PackageFragmentToStringConverter extends Converter {
public PackageFragmentToStringConverter() {
super(IPackageFragment.class, String.class);
}
public Object convert(Object fromObject) {
if( fromObject == null ) {
return "";
}
IPackageFragment f = (IPackageFragment) fromObject;
return f.getElementName();
}
}
}
| true | true | public void createControl(Composite parent) {
final Image img = new Image(parent.getDisplay(), getClass().getClassLoader().getResourceAsStream("/icons/full/wizban/newclass_wiz.png"));
setImageDescriptor(ImageDescriptor.createFromImage(img));
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
img.dispose();
setImageDescriptor(null);
}
});
parent = new Composite(parent, SWT.NULL);
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
parent.setLayout(new GridLayout(3, false));
clazz = createInstance();
DataBindingContext dbc = new DataBindingContext();
WizardPageSupport.create(this, dbc);
{
Label l = new Label(parent, SWT.NONE);
l.setText("Source folder");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
t.setEditable(false);
final Binding bd = dbc.bindValue(
WidgetProperties.text().observe(t),
BeanProperties.value("fragmentRoot").observe(clazz),
new UpdateValueStrategy(),
new UpdateValueStrategy().setConverter(new PackageFragmentRootToStringConverter())
);
Button b = new Button(parent, SWT.PUSH);
b.setText("Browse ...");
b.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IPackageFragmentRoot root = choosePackageRoot();
if( root != null ) {
clazz.setFragmentRoot(root);
}
bd.updateModelToTarget(); //TODO Find out why this is needed
}
});
}
{
Label l = new Label(parent, SWT.NONE);
l.setText("Package");
Text t = new Text(parent, SWT.BORDER);
t.setEditable(false);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
final Binding bd = dbc.bindValue(
WidgetProperties.text().observe(t),
BeanProperties.value("packageFragment").observe(clazz),
new UpdateValueStrategy(),
new UpdateValueStrategy().setConverter(new PackageFragmentToStringConverter())
);
Button b = new Button(parent, SWT.PUSH);
b.setText("Browse ...");
b.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IPackageFragment fragment = choosePackage();
if( fragment != null ) {
clazz.setPackageFragment(fragment);
}
bd.updateModelToTarget(); //TODO Find out why this is needed
}
});
}
{
IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);
Label l = new Label(parent, SWT.NONE);
l.setText("Name");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
dbc.bindValue(textProp.observe(t), BeanProperties.value("name", String.class).observe(clazz));
new Label(parent, SWT.NONE);
}
{
Label l = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
l.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false, 3, 1));
}
createFields(parent, dbc);
setControl(parent);
}
| public void createControl(Composite parent) {
final Image img = new Image(parent.getDisplay(), getClass().getClassLoader().getResourceAsStream("/icons/full/wizban/newclass_wiz.png"));
setImageDescriptor(ImageDescriptor.createFromImage(img));
parent.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
img.dispose();
setImageDescriptor(null);
}
});
parent = new Composite(parent, SWT.NULL);
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
parent.setLayout(new GridLayout(3, false));
clazz = createInstance();
DataBindingContext dbc = new DataBindingContext();
WizardPageSupport.create(this, dbc);
{
Label l = new Label(parent, SWT.NONE);
l.setText("Source folder");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
t.setEditable(false);
final Binding bd = dbc.bindValue(
WidgetProperties.text().observe(t),
BeanProperties.value("fragmentRoot").observe(clazz),
new UpdateValueStrategy(),
new UpdateValueStrategy().setConverter(new PackageFragmentRootToStringConverter())
);
Button b = new Button(parent, SWT.PUSH);
b.setText("Browse ...");
b.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IPackageFragmentRoot root = choosePackageRoot();
if( root != null ) {
froot = root;
clazz.setFragmentRoot(root);
}
bd.updateModelToTarget(); //TODO Find out why this is needed
}
});
}
{
Label l = new Label(parent, SWT.NONE);
l.setText("Package");
Text t = new Text(parent, SWT.BORDER);
t.setEditable(false);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
final Binding bd = dbc.bindValue(
WidgetProperties.text().observe(t),
BeanProperties.value("packageFragment").observe(clazz),
new UpdateValueStrategy(),
new UpdateValueStrategy().setConverter(new PackageFragmentToStringConverter())
);
Button b = new Button(parent, SWT.PUSH);
b.setText("Browse ...");
b.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IPackageFragment fragment = choosePackage();
if( fragment != null ) {
clazz.setPackageFragment(fragment);
}
bd.updateModelToTarget(); //TODO Find out why this is needed
}
});
}
{
IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);
Label l = new Label(parent, SWT.NONE);
l.setText("Name");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
dbc.bindValue(textProp.observe(t), BeanProperties.value("name", String.class).observe(clazz));
new Label(parent, SWT.NONE);
}
{
Label l = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
l.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false, 3, 1));
}
createFields(parent, dbc);
setControl(parent);
}
|
diff --git a/server/src/main/java/com/metamx/druid/index/v1/QueryableIndexStorageAdapter.java b/server/src/main/java/com/metamx/druid/index/v1/QueryableIndexStorageAdapter.java
index 0dfded5417..1cde70b5c7 100644
--- a/server/src/main/java/com/metamx/druid/index/v1/QueryableIndexStorageAdapter.java
+++ b/server/src/main/java/com/metamx/druid/index/v1/QueryableIndexStorageAdapter.java
@@ -1,867 +1,867 @@
/*
* Druid - a distributed column store.
* Copyright (C) 2012 Metamarkets Group Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.metamx.druid.index.v1;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import com.metamx.common.collect.MoreIterators;
import com.metamx.common.guava.FunctionalIterable;
import com.metamx.common.guava.FunctionalIterator;
import com.metamx.druid.BaseStorageAdapter;
import com.metamx.druid.Capabilities;
import com.metamx.druid.QueryGranularity;
import com.metamx.druid.index.QueryableIndex;
import com.metamx.druid.index.brita.BitmapIndexSelector;
import com.metamx.druid.index.brita.Filter;
import com.metamx.druid.index.column.Column;
import com.metamx.druid.index.column.ColumnSelector;
import com.metamx.druid.index.column.ComplexColumn;
import com.metamx.druid.index.column.DictionaryEncodedColumn;
import com.metamx.druid.index.column.GenericColumn;
import com.metamx.druid.index.column.ValueType;
import com.metamx.druid.index.v1.processing.Cursor;
import com.metamx.druid.index.v1.processing.DimensionSelector;
import com.metamx.druid.index.v1.processing.Offset;
import com.metamx.druid.kv.Indexed;
import com.metamx.druid.kv.IndexedInts;
import com.metamx.druid.kv.IndexedIterable;
import com.metamx.druid.processing.ComplexMetricSelector;
import com.metamx.druid.processing.FloatMetricSelector;
import it.uniroma3.mat.extendedset.intset.ImmutableConciseSet;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import java.util.Iterator;
import java.util.Map;
/**
*/
public class QueryableIndexStorageAdapter extends BaseStorageAdapter
{
private final QueryableIndex index;
public QueryableIndexStorageAdapter(
QueryableIndex index
)
{
this.index = index;
}
@Override
public String getSegmentIdentifier()
{
throw new UnsupportedOperationException();
}
@Override
public Interval getInterval()
{
return index.getDataInterval();
}
@Override
public int getDimensionCardinality(String dimension)
{
if (dimension == null) {
return 0;
}
Column column = index.getColumn(dimension.toLowerCase());
if (column == null) {
return 0;
}
if (!column.getCapabilities().isDictionaryEncoded()) {
throw new UnsupportedOperationException("Only know cardinality of dictionary encoded columns.");
}
return column.getDictionaryEncoding().getCardinality();
}
@Override
public DateTime getMinTime()
{
GenericColumn column = null;
try {
column = index.getTimeColumn().getGenericColumn();
return new DateTime(column.getLongSingleValueRow(0));
}
finally {
Closeables.closeQuietly(column);
}
}
@Override
public DateTime getMaxTime()
{
GenericColumn column = null;
try {
column = index.getTimeColumn().getGenericColumn();
return new DateTime(column.getLongSingleValueRow(column.length() - 1));
}
finally {
Closeables.closeQuietly(column);
}
}
@Override
public Capabilities getCapabilities()
{
return Capabilities.builder().dimensionValuesSorted(true).build();
}
@Override
public Iterable<Cursor> makeCursors(Filter filter, Interval interval, QueryGranularity gran)
{
Interval actualInterval = interval;
final Interval dataInterval = getInterval();
if (!actualInterval.overlaps(dataInterval)) {
return ImmutableList.of();
}
if (actualInterval.getStart().isBefore(dataInterval.getStart())) {
actualInterval = actualInterval.withStart(dataInterval.getStart());
}
if (actualInterval.getEnd().isAfter(dataInterval.getEnd())) {
actualInterval = actualInterval.withEnd(dataInterval.getEnd());
}
final Iterable<Cursor> iterable;
if (filter == null) {
iterable = new NoFilterCursorIterable(index, actualInterval, gran);
} else {
Offset offset = new ConciseOffset(filter.goConcise(new MMappedBitmapIndexSelector(index)));
iterable = new CursorIterable(index, actualInterval, gran, offset);
}
return FunctionalIterable.create(iterable).keep(Functions.<Cursor>identity());
}
@Override
public Indexed<String> getAvailableDimensions()
{
return index.getAvailableDimensions();
}
@Override
public Indexed<String> getDimValueLookup(String dimension)
{
final Column column = index.getColumn(dimension.toLowerCase());
if (column == null || !column.getCapabilities().isDictionaryEncoded()) {
return null;
}
final DictionaryEncodedColumn dictionary = column.getDictionaryEncoding();
return new Indexed<String>()
{
@Override
public Class<? extends String> getClazz()
{
return String.class;
}
@Override
public int size()
{
return dictionary.getCardinality();
}
@Override
public String get(int index)
{
return dictionary.lookupName(index);
}
@Override
public int indexOf(String value)
{
return dictionary.lookupId(value);
}
@Override
public Iterator<String> iterator()
{
return IndexedIterable.create(this).iterator();
}
};
}
@Override
public ImmutableConciseSet getInvertedIndex(String dimension, String dimVal)
{
final Column column = index.getColumn(dimension.toLowerCase());
if (column == null) {
return new ImmutableConciseSet();
}
if (!column.getCapabilities().hasBitmapIndexes()) {
return new ImmutableConciseSet();
}
return column.getBitmapIndex().getConciseSet(dimVal);
}
@Override
public Offset getFilterOffset(Filter filter)
{
return new ConciseOffset(filter.goConcise(new MMappedBitmapIndexSelector(index)));
}
private static class CursorIterable implements Iterable<Cursor>
{
private final ColumnSelector index;
private final Interval interval;
private final QueryGranularity gran;
private final Offset offset;
public CursorIterable(
ColumnSelector index,
Interval interval,
QueryGranularity gran,
Offset offset
)
{
this.index = index;
this.interval = interval;
this.gran = gran;
this.offset = offset;
}
@Override
public Iterator<Cursor> iterator()
{
final Offset baseOffset = offset.clone();
final Map<String, GenericColumn> genericColumnCache = Maps.newHashMap();
final Map<String, ComplexColumn> complexColumnCache = Maps.newHashMap();
final GenericColumn timestamps = index.getTimeColumn().getGenericColumn();
final FunctionalIterator<Cursor> retVal = FunctionalIterator
.create(gran.iterable(interval.getStartMillis(), interval.getEndMillis()).iterator())
.transform(
new Function<Long, Cursor>()
{
@Override
public Cursor apply(final Long input)
{
final long timeStart = Math.max(interval.getStartMillis(), input);
while (baseOffset.withinBounds()
&& timestamps.getLongSingleValueRow(baseOffset.getOffset()) < timeStart) {
baseOffset.increment();
}
final Offset offset = new TimestampCheckingOffset(
- baseOffset, timestamps, Math.min(interval.getEndMillis(), gran.next(timeStart))
+ baseOffset, timestamps, Math.min(interval.getEndMillis(), gran.next(input))
);
return new Cursor()
{
private final Offset initOffset = offset.clone();
private final DateTime myBucket = gran.toDateTime(input);
private Offset cursorOffset = offset;
@Override
public DateTime getTime()
{
return myBucket;
}
@Override
public void advance()
{
cursorOffset.increment();
}
@Override
public boolean isDone()
{
return !cursorOffset.withinBounds();
}
@Override
public void reset()
{
cursorOffset = initOffset.clone();
}
@Override
public DimensionSelector makeDimensionSelector(String dimension)
{
final String dimensionName = dimension.toLowerCase();
final Column columnDesc = index.getColumn(dimensionName);
if (columnDesc == null) {
return null;
}
final DictionaryEncodedColumn column = columnDesc.getDictionaryEncoding();
if (columnDesc.getCapabilities().hasMultipleValues()) {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
return column.getMultiValueRow(cursorOffset.getOffset());
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
final String retVal = column.lookupName(id);
return retVal == null ? "" : retVal;
}
@Override
public int lookupId(String name)
{
return column.lookupId(name);
}
};
}
else {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
final int value = column.getSingleValueRow(cursorOffset.getOffset());
return new IndexedInts()
{
@Override
public int size()
{
return 1;
}
@Override
public int get(int index)
{
return value;
}
@Override
public Iterator<Integer> iterator()
{
return Iterators.singletonIterator(value);
}
};
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
return column.lookupName(id);
}
@Override
public int lookupId(String name)
{
return column.lookupId(name);
}
};
}
}
@Override
public FloatMetricSelector makeFloatMetricSelector(String metric)
{
final String metricName = metric.toLowerCase();
GenericColumn cachedMetricVals = genericColumnCache.get(metricName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(metricName);
if (holder != null && holder.getCapabilities().getType() == ValueType.FLOAT) {
cachedMetricVals = holder.getGenericColumn();
genericColumnCache.put(metricName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return new FloatMetricSelector()
{
@Override
public float get()
{
return 0.0f;
}
};
}
final GenericColumn metricVals = cachedMetricVals;
return new FloatMetricSelector()
{
@Override
public float get()
{
return metricVals.getFloatSingleValueRow(cursorOffset.getOffset());
}
};
}
@Override
public ComplexMetricSelector makeComplexMetricSelector(String metric)
{
final String metricName = metric.toLowerCase();
ComplexColumn cachedMetricVals = complexColumnCache.get(metricName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(metricName);
if (holder != null && holder.getCapabilities().getType() == ValueType.COMPLEX) {
cachedMetricVals = holder.getComplexColumn();
complexColumnCache.put(metricName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return null;
}
final ComplexColumn metricVals = cachedMetricVals;
return new ComplexMetricSelector()
{
@Override
public Class classOfObject()
{
return metricVals.getClazz();
}
@Override
public Object get()
{
return metricVals.getRowValue(cursorOffset.getOffset());
}
};
}
};
}
}
);
// This after call is not perfect, if there is an exception during processing, it will never get called,
// but it's better than nothing and doing this properly all the time requires a lot more fixerating
return MoreIterators.after(
retVal,
new Runnable()
{
@Override
public void run()
{
Closeables.closeQuietly(timestamps);
for (GenericColumn column : genericColumnCache.values()) {
Closeables.closeQuietly(column);
}
for (ComplexColumn complexColumn : complexColumnCache.values()) {
Closeables.closeQuietly(complexColumn);
}
}
}
);
}
}
private static class TimestampCheckingOffset implements Offset
{
private final Offset baseOffset;
private final GenericColumn timestamps;
private final long threshold;
public TimestampCheckingOffset(
Offset baseOffset,
GenericColumn timestamps,
long threshold
)
{
this.baseOffset = baseOffset;
this.timestamps = timestamps;
this.threshold = threshold;
}
@Override
public int getOffset()
{
return baseOffset.getOffset();
}
@Override
public Offset clone()
{
return new TimestampCheckingOffset(baseOffset.clone(), timestamps, threshold);
}
@Override
public boolean withinBounds()
{
return baseOffset.withinBounds() && timestamps.getLongSingleValueRow(baseOffset.getOffset()) < threshold;
}
@Override
public void increment()
{
baseOffset.increment();
}
}
private static class NoFilterCursorIterable implements Iterable<Cursor>
{
private final ColumnSelector index;
private final Interval interval;
private final QueryGranularity gran;
public NoFilterCursorIterable(
ColumnSelector index,
Interval interval,
QueryGranularity gran
)
{
this.index = index;
this.interval = interval;
this.gran = gran;
}
/**
* This produces iterators of Cursor objects that must be fully processed (until isDone() returns true) before the
* next Cursor is processed. It is *not* safe to pass these cursors off to another thread for parallel processing
*
* @return
*/
@Override
public Iterator<Cursor> iterator()
{
final Map<String, GenericColumn> genericColumnCache = Maps.newHashMap();
final Map<String, ComplexColumn> complexColumnCache = Maps.newHashMap();
final GenericColumn timestamps = index.getTimeColumn().getGenericColumn();
final FunctionalIterator<Cursor> retVal = FunctionalIterator
.create(gran.iterable(interval.getStartMillis(), interval.getEndMillis()).iterator())
.transform(
new Function<Long, Cursor>()
{
private int currRow = 0;
@Override
public Cursor apply(final Long input)
{
final long timeStart = Math.max(interval.getStartMillis(), input);
while (currRow < timestamps.length() && timestamps.getLongSingleValueRow(currRow) < timeStart) {
++currRow;
}
return new Cursor()
{
private final DateTime myBucket = gran.toDateTime(input);
private final long nextBucket = Math.min(gran.next(myBucket.getMillis()), interval.getEndMillis());
private final int initRow = currRow;
@Override
public DateTime getTime()
{
return myBucket;
}
@Override
public void advance()
{
++currRow;
}
@Override
public boolean isDone()
{
return currRow >= timestamps.length() || timestamps.getLongSingleValueRow(currRow) >= nextBucket;
}
@Override
public void reset()
{
currRow = initRow;
}
@Override
public DimensionSelector makeDimensionSelector(String dimension)
{
final String dimensionName = dimension.toLowerCase();
final Column columnDesc = index.getColumn(dimensionName);
if (columnDesc == null) {
return null;
}
final DictionaryEncodedColumn column = columnDesc.getDictionaryEncoding();
if (columnDesc.getCapabilities().hasMultipleValues()) {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
return column.getMultiValueRow(currRow);
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
final String retVal = column.lookupName(id);
return retVal == null ? "" : retVal;
}
@Override
public int lookupId(String name)
{
return column.lookupId(name);
}
};
}
else {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
final int value = column.getSingleValueRow(currRow);
return new IndexedInts()
{
@Override
public int size()
{
return 1;
}
@Override
public int get(int index)
{
return value;
}
@Override
public Iterator<Integer> iterator()
{
return Iterators.singletonIterator(value);
}
};
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
return column.lookupName(id);
}
@Override
public int lookupId(String name)
{
return column.lookupId(name);
}
};
}
}
@Override
public FloatMetricSelector makeFloatMetricSelector(String metric)
{
final String metricName = metric.toLowerCase();
GenericColumn cachedMetricVals = genericColumnCache.get(metricName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(metricName);
if (holder != null && holder.getCapabilities().getType() == ValueType.FLOAT) {
cachedMetricVals = holder.getGenericColumn();
genericColumnCache.put(metricName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return new FloatMetricSelector()
{
@Override
public float get()
{
return 0.0f;
}
};
}
final GenericColumn metricVals = cachedMetricVals;
return new FloatMetricSelector()
{
@Override
public float get()
{
return metricVals.getFloatSingleValueRow(currRow);
}
};
}
@Override
public ComplexMetricSelector makeComplexMetricSelector(String metric)
{
final String metricName = metric.toLowerCase();
ComplexColumn cachedMetricVals = complexColumnCache.get(metricName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(metricName);
if (holder != null && holder.getCapabilities().getType() == ValueType.COMPLEX) {
cachedMetricVals = holder.getComplexColumn();
complexColumnCache.put(metricName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return null;
}
final ComplexColumn metricVals = cachedMetricVals;
return new ComplexMetricSelector()
{
@Override
public Class classOfObject()
{
return metricVals.getClazz();
}
@Override
public Object get()
{
return metricVals.getRowValue(currRow);
}
};
}
};
}
}
);
return MoreIterators.after(
retVal,
new Runnable()
{
@Override
public void run()
{
Closeables.closeQuietly(timestamps);
for (GenericColumn column : genericColumnCache.values()) {
Closeables.closeQuietly(column);
}
for (ComplexColumn complexColumn : complexColumnCache.values()) {
Closeables.closeQuietly(complexColumn);
}
}
}
);
}
}
private class MMappedBitmapIndexSelector implements BitmapIndexSelector
{
private final ColumnSelector index;
public MMappedBitmapIndexSelector(final ColumnSelector index)
{
this.index = index;
}
@Override
public Indexed<String> getDimensionValues(String dimension)
{
final Column columnDesc = index.getColumn(dimension.toLowerCase());
if (columnDesc == null || !columnDesc.getCapabilities().isDictionaryEncoded()) {
return null;
}
final DictionaryEncodedColumn column = columnDesc.getDictionaryEncoding();
return new Indexed<String>()
{
@Override
public Class<? extends String> getClazz()
{
return String.class;
}
@Override
public int size()
{
return column.getCardinality();
}
@Override
public String get(int index)
{
return column.lookupName(index);
}
@Override
public int indexOf(String value)
{
return column.lookupId(value);
}
@Override
public Iterator<String> iterator()
{
return IndexedIterable.create(this).iterator();
}
};
}
@Override
public int getNumRows()
{
GenericColumn column = null;
try {
column = index.getTimeColumn().getGenericColumn();
return column.length();
}
finally {
Closeables.closeQuietly(column);
}
}
@Override
public ImmutableConciseSet getConciseInvertedIndex(String dimension, String value)
{
return getInvertedIndex(dimension, value);
}
}
}
| true | true | public Iterator<Cursor> iterator()
{
final Offset baseOffset = offset.clone();
final Map<String, GenericColumn> genericColumnCache = Maps.newHashMap();
final Map<String, ComplexColumn> complexColumnCache = Maps.newHashMap();
final GenericColumn timestamps = index.getTimeColumn().getGenericColumn();
final FunctionalIterator<Cursor> retVal = FunctionalIterator
.create(gran.iterable(interval.getStartMillis(), interval.getEndMillis()).iterator())
.transform(
new Function<Long, Cursor>()
{
@Override
public Cursor apply(final Long input)
{
final long timeStart = Math.max(interval.getStartMillis(), input);
while (baseOffset.withinBounds()
&& timestamps.getLongSingleValueRow(baseOffset.getOffset()) < timeStart) {
baseOffset.increment();
}
final Offset offset = new TimestampCheckingOffset(
baseOffset, timestamps, Math.min(interval.getEndMillis(), gran.next(timeStart))
);
return new Cursor()
{
private final Offset initOffset = offset.clone();
private final DateTime myBucket = gran.toDateTime(input);
private Offset cursorOffset = offset;
@Override
public DateTime getTime()
{
return myBucket;
}
@Override
public void advance()
{
cursorOffset.increment();
}
@Override
public boolean isDone()
{
return !cursorOffset.withinBounds();
}
@Override
public void reset()
{
cursorOffset = initOffset.clone();
}
@Override
public DimensionSelector makeDimensionSelector(String dimension)
{
final String dimensionName = dimension.toLowerCase();
final Column columnDesc = index.getColumn(dimensionName);
if (columnDesc == null) {
return null;
}
final DictionaryEncodedColumn column = columnDesc.getDictionaryEncoding();
if (columnDesc.getCapabilities().hasMultipleValues()) {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
return column.getMultiValueRow(cursorOffset.getOffset());
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
final String retVal = column.lookupName(id);
return retVal == null ? "" : retVal;
}
@Override
public int lookupId(String name)
{
return column.lookupId(name);
}
};
}
else {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
final int value = column.getSingleValueRow(cursorOffset.getOffset());
return new IndexedInts()
{
@Override
public int size()
{
return 1;
}
@Override
public int get(int index)
{
return value;
}
@Override
public Iterator<Integer> iterator()
{
return Iterators.singletonIterator(value);
}
};
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
return column.lookupName(id);
}
@Override
public int lookupId(String name)
{
return column.lookupId(name);
}
};
}
}
@Override
public FloatMetricSelector makeFloatMetricSelector(String metric)
{
final String metricName = metric.toLowerCase();
GenericColumn cachedMetricVals = genericColumnCache.get(metricName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(metricName);
if (holder != null && holder.getCapabilities().getType() == ValueType.FLOAT) {
cachedMetricVals = holder.getGenericColumn();
genericColumnCache.put(metricName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return new FloatMetricSelector()
{
@Override
public float get()
{
return 0.0f;
}
};
}
final GenericColumn metricVals = cachedMetricVals;
return new FloatMetricSelector()
{
@Override
public float get()
{
return metricVals.getFloatSingleValueRow(cursorOffset.getOffset());
}
};
}
@Override
public ComplexMetricSelector makeComplexMetricSelector(String metric)
{
final String metricName = metric.toLowerCase();
ComplexColumn cachedMetricVals = complexColumnCache.get(metricName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(metricName);
if (holder != null && holder.getCapabilities().getType() == ValueType.COMPLEX) {
cachedMetricVals = holder.getComplexColumn();
complexColumnCache.put(metricName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return null;
}
final ComplexColumn metricVals = cachedMetricVals;
return new ComplexMetricSelector()
{
@Override
public Class classOfObject()
{
return metricVals.getClazz();
}
@Override
public Object get()
{
return metricVals.getRowValue(cursorOffset.getOffset());
}
};
}
};
}
}
);
// This after call is not perfect, if there is an exception during processing, it will never get called,
// but it's better than nothing and doing this properly all the time requires a lot more fixerating
return MoreIterators.after(
retVal,
new Runnable()
{
@Override
public void run()
{
Closeables.closeQuietly(timestamps);
for (GenericColumn column : genericColumnCache.values()) {
Closeables.closeQuietly(column);
}
for (ComplexColumn complexColumn : complexColumnCache.values()) {
Closeables.closeQuietly(complexColumn);
}
}
}
);
}
| public Iterator<Cursor> iterator()
{
final Offset baseOffset = offset.clone();
final Map<String, GenericColumn> genericColumnCache = Maps.newHashMap();
final Map<String, ComplexColumn> complexColumnCache = Maps.newHashMap();
final GenericColumn timestamps = index.getTimeColumn().getGenericColumn();
final FunctionalIterator<Cursor> retVal = FunctionalIterator
.create(gran.iterable(interval.getStartMillis(), interval.getEndMillis()).iterator())
.transform(
new Function<Long, Cursor>()
{
@Override
public Cursor apply(final Long input)
{
final long timeStart = Math.max(interval.getStartMillis(), input);
while (baseOffset.withinBounds()
&& timestamps.getLongSingleValueRow(baseOffset.getOffset()) < timeStart) {
baseOffset.increment();
}
final Offset offset = new TimestampCheckingOffset(
baseOffset, timestamps, Math.min(interval.getEndMillis(), gran.next(input))
);
return new Cursor()
{
private final Offset initOffset = offset.clone();
private final DateTime myBucket = gran.toDateTime(input);
private Offset cursorOffset = offset;
@Override
public DateTime getTime()
{
return myBucket;
}
@Override
public void advance()
{
cursorOffset.increment();
}
@Override
public boolean isDone()
{
return !cursorOffset.withinBounds();
}
@Override
public void reset()
{
cursorOffset = initOffset.clone();
}
@Override
public DimensionSelector makeDimensionSelector(String dimension)
{
final String dimensionName = dimension.toLowerCase();
final Column columnDesc = index.getColumn(dimensionName);
if (columnDesc == null) {
return null;
}
final DictionaryEncodedColumn column = columnDesc.getDictionaryEncoding();
if (columnDesc.getCapabilities().hasMultipleValues()) {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
return column.getMultiValueRow(cursorOffset.getOffset());
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
final String retVal = column.lookupName(id);
return retVal == null ? "" : retVal;
}
@Override
public int lookupId(String name)
{
return column.lookupId(name);
}
};
}
else {
return new DimensionSelector()
{
@Override
public IndexedInts getRow()
{
final int value = column.getSingleValueRow(cursorOffset.getOffset());
return new IndexedInts()
{
@Override
public int size()
{
return 1;
}
@Override
public int get(int index)
{
return value;
}
@Override
public Iterator<Integer> iterator()
{
return Iterators.singletonIterator(value);
}
};
}
@Override
public int getValueCardinality()
{
return column.getCardinality();
}
@Override
public String lookupName(int id)
{
return column.lookupName(id);
}
@Override
public int lookupId(String name)
{
return column.lookupId(name);
}
};
}
}
@Override
public FloatMetricSelector makeFloatMetricSelector(String metric)
{
final String metricName = metric.toLowerCase();
GenericColumn cachedMetricVals = genericColumnCache.get(metricName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(metricName);
if (holder != null && holder.getCapabilities().getType() == ValueType.FLOAT) {
cachedMetricVals = holder.getGenericColumn();
genericColumnCache.put(metricName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return new FloatMetricSelector()
{
@Override
public float get()
{
return 0.0f;
}
};
}
final GenericColumn metricVals = cachedMetricVals;
return new FloatMetricSelector()
{
@Override
public float get()
{
return metricVals.getFloatSingleValueRow(cursorOffset.getOffset());
}
};
}
@Override
public ComplexMetricSelector makeComplexMetricSelector(String metric)
{
final String metricName = metric.toLowerCase();
ComplexColumn cachedMetricVals = complexColumnCache.get(metricName);
if (cachedMetricVals == null) {
Column holder = index.getColumn(metricName);
if (holder != null && holder.getCapabilities().getType() == ValueType.COMPLEX) {
cachedMetricVals = holder.getComplexColumn();
complexColumnCache.put(metricName, cachedMetricVals);
}
}
if (cachedMetricVals == null) {
return null;
}
final ComplexColumn metricVals = cachedMetricVals;
return new ComplexMetricSelector()
{
@Override
public Class classOfObject()
{
return metricVals.getClazz();
}
@Override
public Object get()
{
return metricVals.getRowValue(cursorOffset.getOffset());
}
};
}
};
}
}
);
// This after call is not perfect, if there is an exception during processing, it will never get called,
// but it's better than nothing and doing this properly all the time requires a lot more fixerating
return MoreIterators.after(
retVal,
new Runnable()
{
@Override
public void run()
{
Closeables.closeQuietly(timestamps);
for (GenericColumn column : genericColumnCache.values()) {
Closeables.closeQuietly(column);
}
for (ComplexColumn complexColumn : complexColumnCache.values()) {
Closeables.closeQuietly(complexColumn);
}
}
}
);
}
|
diff --git a/src/au/gov/naa/digipres/xena/plugin/office/OfficeCompObj.java b/src/au/gov/naa/digipres/xena/plugin/office/OfficeCompObj.java
index d34cd221..e1bdadf2 100644
--- a/src/au/gov/naa/digipres/xena/plugin/office/OfficeCompObj.java
+++ b/src/au/gov/naa/digipres/xena/plugin/office/OfficeCompObj.java
@@ -1,247 +1,250 @@
/*
* Created on 27/02/2006
* justinw5
*
*/
package au.gov.naa.digipres.xena.plugin.office;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
/**
* This class handles reading the data found in the CompObj block
* of an MPP file. The bits we can decypher allow us to determine
* the file format, and a method is provided to determine if the
* file is handled by Office or not.
*
* This class is mostly cut and pasted from Tapster Rock's source files.
* Needed to do this because most of their classes have only been given
* package access... *sigh*
*/
public class OfficeCompObj
{
/**
* Constructor. Reads and processes the block data.
*
* @param is input stream
* @throws IOException on read failure
*/
public OfficeCompObj (InputStream is) throws IOException
{
int length;
is.skip(28);
length = readInt(is);
- m_applicationName = new String (readByteArray(is, length), 0, length-1);
+ m_applicationName = length > 0 ? new String (readByteArray(is, length), 0, length-1)
+ : "";
if (m_applicationName != null && m_applicationName.equals("Microsoft Project 4.0") == true)
{
m_fileFormat = "MSProject.MPP4";
m_applicationID = "MSProject.Project.4";
}
else
{
length = readInt(is);
- m_fileFormat = new String (readByteArray(is, length), 0, length-1);
+ m_fileFormat = length > 0 ? new String (readByteArray(is, length), 0, length-1)
+ : "";
length = readInt(is);
- m_applicationID = new String (readByteArray(is, length), 0, length-1);
+ m_applicationID = length > 0 ? new String (readByteArray(is, length), 0, length-1)
+ : "";
}
}
/**
* Returns true if this file is handled by OpenOffice.
* At the moment it only returns false if it's a Project file.
* @return
*/
public boolean isOfficeFile()
{
// TODO: Get a definitive list of all the file formats that OO can handle.
// Given the fantastic documentation that exists for both Microsoft's
// document format and for OO, this will obviously be a trivial job.
String format = getFileFormat();
if (format.equals("MSProject.MPP9") ||
format.equals("MSProject.MPP8"))
{
return false;
}
else
{
return true;
}
}
/**
* Accessor method to retrieve the application name.
*
* @return Name of the application
*/
public String getApplicationName ()
{
return (m_applicationName);
}
/**
* Accessor method to retrieve the application ID.
*
* @return Application ID
*/
public String getApplicationID ()
{
return (m_applicationID);
}
/**
* Accessor method to retrieve the file format.
*
* @return File format
*/
public String getFileFormat ()
{
return (m_fileFormat);
}
/**
* Application name.
*/
private String m_applicationName;
/**
* Application identifier.
*/
private String m_applicationID;
/**
* File format.
*/
private String m_fileFormat;
/**
* This method reads a single byte from the input stream
*
* @param is the input stream
* @return byte value
* @throws IOException on file read error or EOF
*/
protected int readByte (InputStream is)
throws IOException
{
byte[] data = new byte[1];
if (is.read(data) != data.length)
{
throw new EOFException ();
}
return getByte(data, 0);
}
/**
* This method reads a two byte integer from the input stream
*
* @param is the input stream
* @return integer value
* @throws IOException on file read error or EOF
*/
protected int readShort (InputStream is)
throws IOException
{
byte[] data = new byte[2];
if (is.read(data) != data.length)
{
throw new EOFException ();
}
return getShort(data, 0);
}
/**
* This method reads a four byte integer from the input stream
*
* @param is the input stream
* @return byte value
* @throws IOException on file read error or EOF
*/
protected int readInt (InputStream is)
throws IOException
{
byte[] data = new byte[4];
if (is.read(data) != data.length)
{
throw new EOFException ();
}
return getInt(data, 0);
}
/**
* This method reads a byte array from the input stream
*
* @param is the input stream
* @param size number of bytes to read
* @return byte array
* @throws IOException on file read error or EOF
*/
protected byte[] readByteArray (InputStream is, int size)
throws IOException
{
byte[] buffer = new byte[size];
if (is.read(buffer) != buffer.length)
{
throw new EOFException ();
}
return (buffer);
}
/**
* This method reads a single byte from the input array
*
* @param data byte array of data
* @param offset offset of byte data in the array
* @return byte value
*/
public static final int getByte (byte[] data, int offset)
{
int result = data[offset] & 0x0F;
result += (((data[offset] >> 4) & 0x0F) * 16);
return (result);
}
/**
* This method reads a four byte integer from the input array.
*
* @param data the input array
* @param offset offset of integer data in the array
* @return integer value
*/
public static final int getInt (byte[] data, int offset)
{
int result = (data[offset] & 0x0F);
result += (((data[offset] >> 4) & 0x0F) * 16);
result += ((data[offset + 1] & 0x0F) * 256);
result += (((data[offset + 1] >> 4) & 0x0F) * 4096);
result += ((data[offset + 2] & 0x0F) * 65536);
result += (((data[offset + 2] >> 4) & 0x0F) * 1048576);
result += ((data[offset + 3] & 0x0F) * 16777216);
result += (((data[offset + 3] >> 4) & 0x0F) * 268435456);
return (result);
}
/**
* This method reads a two byte integer from the input array.
*
* @param data the input array
* @param offset offset of integer data in the array
* @return integer value
*/
public static final int getShort (byte[] data, int offset)
{
int result = (data[offset] & 0x0F);
result += (((data[offset] >> 4) & 0x0F) * 16);
result += ((data[offset + 1] & 0x0F) * 256);
result += (((data[offset + 1] >> 4) & 0x0F) * 4096);
return (result);
}
}
| false | true | public OfficeCompObj (InputStream is) throws IOException
{
int length;
is.skip(28);
length = readInt(is);
m_applicationName = new String (readByteArray(is, length), 0, length-1);
if (m_applicationName != null && m_applicationName.equals("Microsoft Project 4.0") == true)
{
m_fileFormat = "MSProject.MPP4";
m_applicationID = "MSProject.Project.4";
}
else
{
length = readInt(is);
m_fileFormat = new String (readByteArray(is, length), 0, length-1);
length = readInt(is);
m_applicationID = new String (readByteArray(is, length), 0, length-1);
}
}
| public OfficeCompObj (InputStream is) throws IOException
{
int length;
is.skip(28);
length = readInt(is);
m_applicationName = length > 0 ? new String (readByteArray(is, length), 0, length-1)
: "";
if (m_applicationName != null && m_applicationName.equals("Microsoft Project 4.0") == true)
{
m_fileFormat = "MSProject.MPP4";
m_applicationID = "MSProject.Project.4";
}
else
{
length = readInt(is);
m_fileFormat = length > 0 ? new String (readByteArray(is, length), 0, length-1)
: "";
length = readInt(is);
m_applicationID = length > 0 ? new String (readByteArray(is, length), 0, length-1)
: "";
}
}
|
diff --git a/src/biz/bokhorst/xprivacy/ActivityMain.java b/src/biz/bokhorst/xprivacy/ActivityMain.java
index 440b37cc..a9285afd 100644
--- a/src/biz/bokhorst/xprivacy/ActivityMain.java
+++ b/src/biz/bokhorst/xprivacy/ActivityMain.java
@@ -1,1973 +1,1974 @@
package biz.bokhorst.xprivacy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Process;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityMain extends ActivityBase implements OnItemSelectedListener {
private Spinner spRestriction = null;
private AppListAdapter mAppAdapter = null;
private int mSortMode;
private boolean mSortInvert;
private int mProgressWidth = 0;
private int mProgress = 0;
private Handler mProHandler = new Handler();
public static final int STATE_ATTENTION = 0;
public static final int STATE_CHANGED = 1;
public static final int STATE_SHARED = 2;
private static final int SORT_BY_NAME = 0;
private static final int SORT_BY_UID = 1;
private static final int SORT_BY_INSTALL_TIME = 2;
private static final int SORT_BY_UPDATE_TIME = 3;
private static final int SORT_BY_MODIFY_TIME = 4;
private static final int ACTIVITY_LICENSE = 0;
private static final int LICENSED = 0x0100;
private static final int NOT_LICENSED = 0x0231;
private static final int RETRY = 0x0123;
private static final int ERROR_CONTACTING_SERVER = 0x101;
private static final int ERROR_INVALID_PACKAGE_NAME = 0x102;
private static final int ERROR_NON_MATCHING_UID = 0x103;
public static final Uri cProUri = Uri.parse("http://www.xprivacy.eu/");
public static final String cXUrl = "https://github.com/M66B/XPrivacy?mobile=0";
private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
new PriorityThreadFactory());
private static class PriorityThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
private Comparator<ApplicationInfoEx> mSorter = new Comparator<ApplicationInfoEx>() {
@Override
public int compare(ApplicationInfoEx appInfo0, ApplicationInfoEx appInfo1) {
int sortOrder = mSortInvert ? -1 : 1;
switch (mSortMode) {
case SORT_BY_NAME:
return sortOrder * appInfo0.compareTo(appInfo1);
case SORT_BY_UID:
// default lowest first
return sortOrder * (appInfo0.getUid() - appInfo1.getUid());
case SORT_BY_INSTALL_TIME:
// default newest first
Long iTime0 = appInfo0.getInstallTime(ActivityMain.this);
Long iTime1 = appInfo1.getInstallTime(ActivityMain.this);
return sortOrder * iTime1.compareTo(iTime0);
case SORT_BY_UPDATE_TIME:
// default newest first
Long uTime0 = appInfo0.getUpdateTime(ActivityMain.this);
Long uTime1 = appInfo1.getUpdateTime(ActivityMain.this);
return sortOrder * uTime1.compareTo(uTime0);
case SORT_BY_MODIFY_TIME:
// default newest first
Long mTime0 = appInfo0.getModificationTime(ActivityMain.this);
Long mTime1 = appInfo1.getModificationTime(ActivityMain.this);
return sortOrder * mTime1.compareTo(mTime0);
}
return 0;
}
};
private boolean mPackageChangeReceiverRegistered = false;
private BroadcastReceiver mPackageChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ActivityMain.this.recreate();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final int userId = Util.getUserId(Process.myUid());
// Check privacy service client
if (!PrivacyService.checkClient())
return;
// Salt should be the same when exporting/importing
String salt = PrivacyManager.getSetting(userId, PrivacyManager.cSettingSalt, null, false);
if (salt == null) {
salt = Build.SERIAL;
if (salt == null)
salt = "";
PrivacyManager.setSetting(userId, PrivacyManager.cSettingSalt, salt);
}
// Set layout
setContentView(R.layout.mainlist);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if (Util.hasProLicense(this) != null)
setTitle(String.format("%s - %s", getString(R.string.app_name), getString(R.string.menu_pro)));
// Get localized restriction name
List<String> listRestrictionName = new ArrayList<String>(PrivacyManager.getRestrictions(this).navigableKeySet());
listRestrictionName.add(0, getString(R.string.menu_all));
// Build spinner adapter
SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spAdapter.addAll(listRestrictionName);
// Handle info
ImageView imgInfo = (ImageView) findViewById(R.id.imgInfo);
imgInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = spRestriction.getSelectedItemPosition();
if (position != AdapterView.INVALID_POSITION) {
String query = (position == 0 ? "restrictions" : (String) PrivacyManager
.getRestrictions(ActivityMain.this).values().toArray()[position - 1]);
Util.viewUri(ActivityMain.this, Uri.parse(cXUrl + "#" + query));
}
}
});
// Setup spinner
int pos = 0;
String restrictionName = PrivacyManager
.getSetting(userId, PrivacyManager.cSettingSelectedCategory, null, false);
if (restrictionName != null)
for (String restriction : PrivacyManager.getRestrictions(this).values()) {
pos++;
if (restrictionName.equals(restriction))
break;
}
spRestriction = (Spinner) findViewById(R.id.spRestriction);
spRestriction.setAdapter(spAdapter);
spRestriction.setOnItemSelectedListener(this);
spRestriction.setSelection(pos);
// Setup sort
mSortMode = Integer.parseInt(PrivacyManager.getSetting(userId, PrivacyManager.cSettingSortMode, "0", false));
mSortInvert = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingSortInverted, false, false);
// Setup name filter
final EditText etFilter = (EditText) findViewById(R.id.etFilter);
etFilter.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = etFilter.getText().toString();
ImageView imgClear = (ImageView) findViewById(R.id.imgClear);
imgClear.setImageDrawable(getResources().getDrawable(
getThemed(text.equals("") ? R.attr.icon_clear_grayed : R.attr.icon_clear)));
applyFilter();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
ImageView imgClear = (ImageView) findViewById(R.id.imgClear);
imgClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
etFilter.setText("");
}
});
// Start task to get app list
AppListTask appListTask = new AppListTask();
appListTask.executeOnExecutor(mExecutor, (Object) null);
// Check environment
Requirements.check(this);
// Licensing
checkLicense();
// Listen for package add/remove
IntentFilter iff = new IntentFilter();
iff.addAction(Intent.ACTION_PACKAGE_ADDED);
iff.addAction(Intent.ACTION_PACKAGE_REMOVED);
iff.addDataScheme("package");
registerReceiver(mPackageChangeReceiver, iff);
mPackageChangeReceiverRegistered = true;
// First run
if (PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFirstRun, true, false)) {
optionAbout();
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFirstRun, Boolean.FALSE.toString());
}
// Tutorial
if (!PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingTutorialMain, false, false)) {
((ScrollView) findViewById(R.id.svTutorialHeader)).setVisibility(View.VISIBLE);
((ScrollView) findViewById(R.id.svTutorialDetails)).setVisibility(View.VISIBLE);
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
ViewParent parent = view.getParent();
while (!parent.getClass().equals(ScrollView.class))
parent = parent.getParent();
((View) parent).setVisibility(View.GONE);
PrivacyManager.setSetting(userId, PrivacyManager.cSettingTutorialMain, Boolean.TRUE.toString());
}
};
((Button) findViewById(R.id.btnTutorialHeader)).setOnClickListener(listener);
((Button) findViewById(R.id.btnTutorialDetails)).setOnClickListener(listener);
}
@Override
protected void onResume() {
super.onResume();
if (mAppAdapter != null)
mAppAdapter.notifyDataSetChanged();
}
@Override
protected void onNewIntent(Intent intent) {
if (mAppAdapter != null)
mAppAdapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mPackageChangeReceiverRegistered) {
unregisterReceiver(mPackageChangeReceiver);
mPackageChangeReceiverRegistered = false;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent dataIntent) {
super.onActivityResult(requestCode, resultCode, dataIntent);
if (requestCode == ACTIVITY_LICENSE) {
// License check
if (dataIntent != null) {
int code = dataIntent.getIntExtra("Code", -1);
int reason = dataIntent.getIntExtra("Reason", -1);
String sReason;
if (reason == LICENSED)
sReason = "LICENSED";
else if (reason == NOT_LICENSED)
sReason = "NOT_LICENSED";
else if (reason == RETRY)
sReason = "RETRY";
else if (reason == ERROR_CONTACTING_SERVER)
sReason = "ERROR_CONTACTING_SERVER";
else if (reason == ERROR_INVALID_PACKAGE_NAME)
sReason = "ERROR_INVALID_PACKAGE_NAME";
else if (reason == ERROR_NON_MATCHING_UID)
sReason = "ERROR_NON_MATCHING_UID";
else
sReason = Integer.toString(reason);
Util.log(null, Log.WARN, "Licensing: code=" + code + " reason=" + sReason);
if (code > 0) {
Util.setPro(true);
invalidateOptionsMenu();
Toast toast = Toast.makeText(this, getString(R.string.menu_pro), Toast.LENGTH_LONG);
toast.show();
} else if (reason == RETRY) {
Util.setPro(false);
mProHandler.postDelayed(new Runnable() {
@Override
public void run() {
checkLicense();
}
}, 30 * 1000);
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
if (inflater != null && PrivacyService.checkClient()) {
inflater.inflate(R.menu.main, menu);
return true;
} else
return false;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
int userId = Util.getUserId(Process.myUid());
boolean mounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
menu.findItem(R.id.menu_dump).setVisible(Util.isDebuggable(this));
menu.findItem(R.id.menu_clear_db).setVisible(userId == 0);
menu.findItem(R.id.menu_export).setEnabled(mounted);
menu.findItem(R.id.menu_import).setEnabled(mounted);
menu.findItem(R.id.menu_pro).setVisible(!Util.isProEnabled() && Util.hasProLicense(this) == null);
// Update filter count
// Get settings
boolean fUsed = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUsed, false, false);
boolean fInternet = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFInternet, false, false);
boolean fRestriction = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFRestriction, false, false);
boolean fPermission = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFPermission, true, false);
boolean fOnDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFOnDemand, false, false);
boolean fUser = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUser, true, false);
boolean fSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFSystem, false, false);
// Count number of active filters
int numberOfFilters = 0;
if (fUsed)
numberOfFilters++;
if (fInternet)
numberOfFilters++;
if (fRestriction)
numberOfFilters++;
if (fPermission)
numberOfFilters++;
if (fOnDemand)
numberOfFilters++;
if (fUser)
numberOfFilters++;
if (fSystem)
numberOfFilters++;
if (numberOfFilters > 0) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_filter).copy(
Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.GRAY);
paint.setTextSize(bitmap.getWidth() / 3);
paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
String text = Integer.toString(numberOfFilters);
Canvas canvas = new Canvas(bitmap);
canvas.drawText(text, bitmap.getWidth() - paint.measureText(text), bitmap.getHeight(), paint);
MenuItem fMenu = menu.findItem(R.id.menu_filter);
fMenu.setIcon(new BitmapDrawable(getResources(), bitmap));
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
try {
switch (item.getItemId()) {
case R.id.menu_dump:
optionDump();
return true;
case R.id.menu_help:
optionHelp();
return true;
case R.id.menu_select_all:
optionSelectAll();
return true;
case R.id.menu_sort:
optionSort();
return true;
case R.id.menu_filter:
optionFilter();
return true;
case R.id.menu_tutorial:
optionTutorial();
return true;
case R.id.menu_usage:
optionUsage();
return true;
case R.id.menu_toggle:
optionToggle();
return true;
case R.id.menu_clear_db:
optionClearDB();
return true;
case R.id.menu_export:
optionExport();
return true;
case R.id.menu_import:
optionImport();
return true;
case R.id.menu_submit:
optionSubmit();
return true;
case R.id.menu_fetch:
optionFetch();
return true;
case R.id.menu_pro:
optionPro();
return true;
case R.id.menu_report:
optionReportIssue();
return true;
case R.id.menu_theme:
optionSwitchTheme();
return true;
case R.id.menu_template:
optionTemplate();
return true;
case R.id.menu_settings:
SettingsDialog.edit(ActivityMain.this, null);
return true;
case R.id.menu_about:
optionAbout();
return true;
default:
return super.onOptionsItemSelected(item);
}
} catch (Throwable ex) {
Util.bug(null, ex);
return true;
}
}
// Filtering
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selectRestriction(pos);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
selectRestriction(0);
}
private void selectRestriction(int pos) {
if (mAppAdapter != null) {
int userId = Util.getUserId(Process.myUid());
String restrictionName = (pos == 0 ? null : (String) PrivacyManager.getRestrictions(this).values()
.toArray()[pos - 1]);
mAppAdapter.setRestrictionName(restrictionName);
PrivacyManager.setSetting(userId, PrivacyManager.cSettingSelectedCategory, restrictionName);
applyFilter();
}
}
private void applyFilter() {
if (mAppAdapter != null) {
EditText etFilter = (EditText) findViewById(R.id.etFilter);
ProgressBar pbFilter = (ProgressBar) findViewById(R.id.pbFilter);
TextView tvStats = (TextView) findViewById(R.id.tvStats);
TextView tvState = (TextView) findViewById(R.id.tvState);
// Get settings
int userId = Util.getUserId(Process.myUid());
boolean fUsed = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUsed, false, false);
boolean fInternet = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFInternet, false, false);
boolean fRestriction = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFRestriction, false,
false);
boolean fRestrictionNot = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFRestrictionNot,
false, false);
boolean fPermission = PrivacyManager
.getSettingBool(userId, PrivacyManager.cSettingFPermission, true, false);
boolean fOnDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFOnDemand, false, false);
boolean fOnDemandNot = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFOnDemandNot, false,
false);
boolean fUser = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUser, true, false);
boolean fSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFSystem, false, false);
String filter = String.format("%s\n%b\n%b\n%b\n%b\n%b\n%b\n%b\n%b\n%b", etFilter.getText().toString(),
fUsed, fInternet, fRestriction, fRestrictionNot, fPermission, fOnDemand, fOnDemandNot, fUser,
fSystem);
pbFilter.setVisibility(ProgressBar.VISIBLE);
tvStats.setVisibility(TextView.GONE);
// Adjust progress state width
RelativeLayout.LayoutParams tvStateLayout = (RelativeLayout.LayoutParams) tvState.getLayoutParams();
tvStateLayout.addRule(RelativeLayout.LEFT_OF, R.id.pbFilter);
mAppAdapter.getFilter().filter(filter);
invalidateOptionsMenu();
}
}
private void applySort() {
if (mAppAdapter != null)
mAppAdapter.sort();
}
// Options
private void optionUsage() {
Intent intent = new Intent(this, ActivityUsage.class);
if (mAppAdapter != null && mAppAdapter.getRestrictionName() != null)
intent.putExtra(ActivityUsage.cRestriction, mAppAdapter.getRestrictionName());
startActivity(intent);
}
private void optionToggle() {
if (mAppAdapter != null) {
Intent intent = new Intent(ActivityShare.ACTION_TOGGLE);
intent.putExtra(ActivityShare.cInteractive, true);
intent.putExtra(ActivityShare.cUidList,
mAppAdapter == null ? new int[0] : mAppAdapter.getSelectedOrVisibleUid(0));
intent.putExtra(ActivityShare.cRestriction, mAppAdapter.getRestrictionName());
startActivity(intent);
}
}
private void optionClearDB() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityMain.this);
alertDialogBuilder.setTitle(R.string.menu_clear_db);
alertDialogBuilder.setMessage(R.string.msg_sure);
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... arg0) {
PrivacyManager.clear();
return null;
}
@Override
protected void onPostExecute(Object result) {
spRestriction.setSelection(0);
((EditText) findViewById(R.id.etFilter)).setText("");
ActivityMain.this.recreate();
}
}.executeOnExecutor(mExecutor);
}
});
alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void optionTemplate() {
// Build dialog
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.menu_template);
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
ExpandableListView elvTemplate = new ExpandableListView(this);
elvTemplate.setPadding(6, 0, 6, 0);
elvTemplate.setAdapter(new TemplateListAdapter(this, R.layout.templateentry));
elvTemplate.setScrollBarStyle(ExpandableListView.SCROLLBARS_INSIDE_INSET);
alertDialogBuilder.setView(elvTemplate);
alertDialogBuilder.setPositiveButton(getString(R.string.msg_done), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Show dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void optionReportIssue() {
// Report issue
Util.viewUri(this, Uri.parse("https://github.com/M66B/XPrivacy/issues?mobile=0"));
}
private void optionExport() {
Intent intent = new Intent(ActivityShare.ACTION_EXPORT);
intent.putExtra(ActivityShare.cInteractive, true);
intent.putExtra(ActivityShare.cUidList,
mAppAdapter == null ? new int[0] : mAppAdapter.getSelectedOrVisibleUid(AppListAdapter.cSelectAppAll));
startActivity(intent);
}
private void optionImport() {
Intent intent = new Intent(ActivityShare.ACTION_IMPORT);
intent.putExtra(ActivityShare.cInteractive, true);
intent.putExtra(ActivityShare.cUidList,
mAppAdapter == null ? new int[0] : mAppAdapter.getSelectedOrVisibleUid(0));
startActivity(intent);
}
private void optionSubmit() {
if (ActivityShare.registerDevice(this)) {
int[] uid = (mAppAdapter == null ? new int[0] : mAppAdapter
.getSelectedOrVisibleUid(AppListAdapter.cSelectAppNone));
if (uid.length == 0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.app_name);
alertDialogBuilder.setMessage(R.string.msg_select);
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else if (uid.length <= ActivityShare.cSubmitLimit) {
if (mAppAdapter != null) {
Intent intent = new Intent(ActivityShare.ACTION_SUBMIT);
intent.putExtra(ActivityShare.cInteractive, true);
intent.putExtra(ActivityShare.cUidList, uid);
startActivity(intent);
}
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.app_name);
alertDialogBuilder.setMessage(getString(R.string.msg_limit, ActivityShare.cSubmitLimit + 1));
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
}
private void optionFetch() {
if (Util.hasProLicense(this) == null) {
// Redirect to pro page
Util.viewUri(this, cProUri);
} else {
if (mAppAdapter != null) {
Intent intent = new Intent(ActivityShare.ACTION_FETCH);
intent.putExtra(ActivityShare.cInteractive, true);
intent.putExtra(
ActivityShare.cUidList,
mAppAdapter == null ? new int[0] : mAppAdapter
.getSelectedOrVisibleUid(AppListAdapter.cSelectAppUser));
startActivity(intent);
}
}
}
private void optionSwitchTheme() {
int userId = Util.getUserId(Process.myUid());
String themeName = PrivacyManager.getSetting(userId, PrivacyManager.cSettingTheme, "", false);
themeName = (themeName.equals("Dark") ? "Light" : "Dark");
PrivacyManager.setSetting(userId, PrivacyManager.cSettingTheme, themeName);
this.recreate();
}
private void optionPro() {
// Redirect to pro page
Util.viewUri(this, cProUri);
}
private void optionAbout() {
// About
Dialog dlgAbout = new Dialog(this);
dlgAbout.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dlgAbout.setTitle(R.string.menu_about);
dlgAbout.setContentView(R.layout.about);
dlgAbout.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, getThemed(R.attr.icon_launcher));
// Show version
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
TextView tvVersion = (TextView) dlgAbout.findViewById(R.id.tvVersion);
tvVersion.setText(String.format(getString(R.string.app_version), pInfo.versionName, pInfo.versionCode));
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Show Xposed version
int xVersion = Util.getXposedAppProcessVersion();
TextView tvXVersion = (TextView) dlgAbout.findViewById(R.id.tvXVersion);
tvXVersion.setText(String.format(getString(R.string.app_xversion), xVersion));
// Show license
String licensed = Util.hasProLicense(this);
TextView tvLicensed = (TextView) dlgAbout.findViewById(R.id.tvLicensed);
if (licensed == null)
tvLicensed.setText(Environment.getExternalStorageDirectory().getAbsolutePath());
else
tvLicensed.setText(String.format(getString(R.string.app_licensed), licensed));
dlgAbout.setCancelable(true);
dlgAbout.show();
}
private void optionDump() {
try {
PrivacyService.getClient().dump(0);
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private void optionHelp() {
// Show help
Dialog dialog = new Dialog(ActivityMain.this);
dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dialog.setTitle(R.string.menu_help);
dialog.setContentView(R.layout.help);
dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, getThemed(R.attr.icon_launcher));
((ImageView) dialog.findViewById(R.id.imgHelpHalf)).setImageBitmap(getHalfCheckBox());
((ImageView) dialog.findViewById(R.id.imgHelpOnDemand)).setImageBitmap(getOnDemandCheckBox());
dialog.setCancelable(true);
dialog.show();
}
private void optionSelectAll() {
// Select all visible apps
if (mAppAdapter != null)
mAppAdapter.selectAllVisible();
}
private void optionSort() {
LayoutInflater LayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = LayoutInflater.inflate(R.layout.sort, null);
final RadioGroup rgSMode = (RadioGroup) view.findViewById(R.id.rgSMode);
final CheckBox cbSInvert = (CheckBox) view.findViewById(R.id.cbSInvert);
// Initialise controls
switch (mSortMode) {
case SORT_BY_NAME:
rgSMode.check(R.id.rbSName);
break;
case SORT_BY_UID:
rgSMode.check(R.id.rbSUid);
break;
case SORT_BY_INSTALL_TIME:
rgSMode.check(R.id.rbSInstalled);
break;
case SORT_BY_UPDATE_TIME:
rgSMode.check(R.id.rbSUpdated);
break;
case SORT_BY_MODIFY_TIME:
rgSMode.check(R.id.rbSModified);
break;
}
cbSInvert.setChecked(mSortInvert);
// Build dialog
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityMain.this);
alertDialogBuilder.setTitle(R.string.menu_sort);
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
alertDialogBuilder.setView(view);
alertDialogBuilder.setPositiveButton(ActivityMain.this.getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (rgSMode.getCheckedRadioButtonId()) {
case R.id.rbSName:
mSortMode = SORT_BY_NAME;
break;
case R.id.rbSUid:
mSortMode = SORT_BY_UID;
break;
case R.id.rbSInstalled:
mSortMode = SORT_BY_INSTALL_TIME;
break;
case R.id.rbSUpdated:
mSortMode = SORT_BY_UPDATE_TIME;
break;
case R.id.rbSModified:
mSortMode = SORT_BY_MODIFY_TIME;
break;
}
mSortInvert = cbSInvert.isChecked();
int userId = Util.getUserId(Process.myUid());
PrivacyManager.setSetting(userId, PrivacyManager.cSettingSortMode, Integer.toString(mSortMode));
PrivacyManager.setSetting(userId, PrivacyManager.cSettingSortInverted,
Boolean.toString(mSortInvert));
applySort();
}
});
// Show dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void optionFilter() {
LayoutInflater LayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = LayoutInflater.inflate(R.layout.filters, null);
final CheckBox cbFUsed = (CheckBox) view.findViewById(R.id.cbFUsed);
final CheckBox cbFInternet = (CheckBox) view.findViewById(R.id.cbFInternet);
final CheckBox cbFPermission = (CheckBox) view.findViewById(R.id.cbFPermission);
final CheckBox cbFRestriction = (CheckBox) view.findViewById(R.id.cbFRestriction);
final CheckBox cbFRestrictionNot = (CheckBox) view.findViewById(R.id.cbFRestrictionNot);
final CheckBox cbFOnDemand = (CheckBox) view.findViewById(R.id.cbFOnDemand);
final CheckBox cbFOnDemandNot = (CheckBox) view.findViewById(R.id.cbFOnDemandNot);
final CheckBox cbFUser = (CheckBox) view.findViewById(R.id.cbFUser);
final CheckBox cbFSystem = (CheckBox) view.findViewById(R.id.cbFSystem);
final Button btnClear = (Button) view.findViewById(R.id.btnClear);
// Get settings
final int userId = Util.getUserId(Process.myUid());
boolean fUsed = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUsed, false, false);
boolean fInternet = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFInternet, false, false);
boolean fPermission = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFPermission, true, false);
boolean fRestriction = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFRestriction, false, false);
boolean fRestrictionNot = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFRestrictionNot, false,
false);
boolean fOnDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFOnDemand, false, false);
boolean fOnDemandNot = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFOnDemandNot, false, false);
boolean fUser = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUser, true, false);
boolean fSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFSystem, false, false);
boolean ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true, false);
// Setup checkboxes
cbFUsed.setChecked(fUsed);
cbFInternet.setChecked(fInternet);
cbFPermission.setChecked(fPermission);
cbFRestriction.setChecked(fRestriction);
cbFRestrictionNot.setChecked(fRestrictionNot);
cbFOnDemand.setChecked(fOnDemand && ondemand);
cbFOnDemandNot.setChecked(fOnDemandNot && ondemand);
cbFUser.setChecked(fUser);
cbFSystem.setChecked(fSystem);
cbFRestrictionNot.setEnabled(fRestriction);
cbFOnDemand.setEnabled(ondemand);
cbFOnDemandNot.setEnabled(fOnDemand && ondemand);
// Manage user/system filter exclusivity
OnCheckedChangeListener checkListener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView == cbFUser) {
if (isChecked)
cbFSystem.setChecked(false);
} else if (buttonView == cbFSystem) {
if (isChecked)
cbFUser.setChecked(false);
} else if (buttonView == cbFRestriction)
cbFRestrictionNot.setEnabled(cbFRestriction.isChecked());
else if (buttonView == cbFOnDemand)
cbFOnDemandNot.setEnabled(cbFOnDemand.isChecked());
}
};
cbFUser.setOnCheckedChangeListener(checkListener);
cbFSystem.setOnCheckedChangeListener(checkListener);
cbFRestriction.setOnCheckedChangeListener(checkListener);
cbFOnDemand.setOnCheckedChangeListener(checkListener);
// Clear button
btnClear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
cbFUsed.setChecked(false);
cbFInternet.setChecked(false);
cbFPermission.setChecked(false);
cbFRestriction.setChecked(false);
cbFRestrictionNot.setChecked(false);
cbFOnDemand.setChecked(false);
cbFOnDemandNot.setChecked(false);
cbFUser.setChecked(false);
cbFSystem.setChecked(false);
}
});
// Build dialog
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityMain.this);
alertDialogBuilder.setTitle(R.string.menu_filter);
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
alertDialogBuilder.setView(view);
alertDialogBuilder.setPositiveButton(ActivityMain.this.getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFUsed,
Boolean.toString(cbFUsed.isChecked()));
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFInternet,
Boolean.toString(cbFInternet.isChecked()));
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFRestriction,
Boolean.toString(cbFRestriction.isChecked()));
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFRestrictionNot,
Boolean.toString(cbFRestrictionNot.isChecked()));
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFPermission,
Boolean.toString(cbFPermission.isChecked()));
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFOnDemand,
Boolean.toString(cbFOnDemand.isChecked()));
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFOnDemandNot,
Boolean.toString(cbFOnDemandNot.isChecked()));
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFUser,
Boolean.toString(cbFUser.isChecked()));
PrivacyManager.setSetting(userId, PrivacyManager.cSettingFSystem,
Boolean.toString(cbFSystem.isChecked()));
applyFilter();
}
});
alertDialogBuilder.setNegativeButton(ActivityMain.this.getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
// Show dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void optionTutorial() {
((ScrollView) findViewById(R.id.svTutorialHeader)).setVisibility(View.VISIBLE);
((ScrollView) findViewById(R.id.svTutorialDetails)).setVisibility(View.VISIBLE);
int userId = Util.getUserId(Process.myUid());
PrivacyManager.setSetting(userId, PrivacyManager.cSettingTutorialMain, Boolean.FALSE.toString());
}
// Tasks
private class AppListTask extends AsyncTask<Object, Integer, List<ApplicationInfoEx>> {
private String mRestrictionName;
private ProgressDialog mProgressDialog;
@Override
protected List<ApplicationInfoEx> doInBackground(Object... params) {
mRestrictionName = null;
// Delegate
return ApplicationInfoEx.getXApplicationList(ActivityMain.this, mProgressDialog);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// Show progress dialog
mProgressDialog = new ProgressDialog(ActivityMain.this);
mProgressDialog.setMessage(getString(R.string.msg_loading));
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setProgressNumberFormat(null);
mProgressDialog.setCancelable(false);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
@Override
protected void onPostExecute(List<ApplicationInfoEx> listApp) {
if (!ActivityMain.this.isFinishing()) {
// Display app list
mAppAdapter = new AppListAdapter(ActivityMain.this, R.layout.mainentry, listApp, mRestrictionName);
ListView lvApp = (ListView) findViewById(R.id.lvApp);
lvApp.setAdapter(mAppAdapter);
// Dismiss progress dialog
if (mProgressDialog.isShowing())
try {
mProgressDialog.dismiss();
} catch (IllegalArgumentException ignored) {
}
// Restore state
ActivityMain.this.selectRestriction(spRestriction.getSelectedItemPosition());
}
super.onPostExecute(listApp);
}
}
// Adapters
private class SpinnerAdapter extends ArrayAdapter<String> {
public SpinnerAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
}
@SuppressLint("DefaultLocale")
private class TemplateListAdapter extends BaseExpandableListAdapter {
private List<String> listRestrictionName;
private List<String> listLocalizedTitle;
private boolean ondemand;
private boolean dangerous;
private LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
public TemplateListAdapter(Context context, int resource) {
// Get restriction categories
TreeMap<String, String> tmRestriction = PrivacyManager.getRestrictions(context);
listRestrictionName = new ArrayList<String>(tmRestriction.values());
listLocalizedTitle = new ArrayList<String>(tmRestriction.navigableKeySet());
int userId = Util.getUserId(Process.myUid());
ondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true, false);
dangerous = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingDangerous, false, false);
}
private class ViewHolder {
private View row;
public TextView tvRestriction;
public ImageView imgCbRestrict;
public ImageView imgCbAsk;
public boolean restricted;
public boolean asked;
public ViewHolder(View theRow) {
row = theRow;
tvRestriction = (TextView) row.findViewById(R.id.tvRestriction);
imgCbRestrict = (ImageView) row.findViewById(R.id.imgCbRestrict);
imgCbAsk = (ImageView) row.findViewById(R.id.imgCbAsk);
}
}
@Override
public Object getGroup(int groupPosition) {
return listRestrictionName.get(groupPosition);
}
@Override
public int getGroupCount() {
return listRestrictionName.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.templateentry, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// Get entry
final String restrictionName = (String) getGroup(groupPosition);
// Get info
final int userId = Util.getUserId(Process.myUid());
String value = PrivacyManager.getSetting(userId, Meta.cTypeTemplate, restrictionName,
Boolean.toString(!ondemand) + "+ask", false);
holder.restricted = value.contains("true");
holder.asked = (!ondemand || value.contains("asked"));
Bitmap bmRestricted = (holder.restricted ? getFullCheckBox() : getOffCheckBox());
Bitmap bmAsked = (holder.asked ? getOffCheckBox() : getOnDemandCheckBox());
// Set data
holder.tvRestriction.setTypeface(null, Typeface.BOLD);
holder.tvRestriction.setText(listLocalizedTitle.get(groupPosition));
holder.imgCbRestrict.setImageBitmap(bmRestricted);
holder.imgCbAsk.setImageBitmap(bmAsked);
holder.imgCbAsk.setVisibility(ondemand ? View.VISIBLE : View.GONE);
holder.imgCbRestrict.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// Update setting
holder.restricted = !holder.restricted;
PrivacyManager.setSetting(userId, Meta.cTypeTemplate, restrictionName, (holder.restricted ? "true"
: "false") + "+" + (holder.asked ? "asked" : "ask"));
// Update view
Bitmap bmRestricted = (holder.restricted ? getFullCheckBox() : getOffCheckBox());
holder.imgCbRestrict.setImageBitmap(bmRestricted);
notifyDataSetChanged(); // update childs
}
});
holder.imgCbAsk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// Update setting
holder.asked = (!ondemand || !holder.asked);
PrivacyManager.setSetting(userId, Meta.cTypeTemplate, restrictionName, (holder.restricted ? "true"
: "false") + "+" + (holder.asked ? "asked" : "ask"));
// Update view
Bitmap bmAsked = (holder.asked ? getOffCheckBox() : getOnDemandCheckBox());
holder.imgCbAsk.setImageBitmap(bmAsked);
notifyDataSetChanged(); // update childs
}
});
return convertView;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return PrivacyManager.getHooks((String) getGroup(groupPosition)).get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public int getChildrenCount(int groupPosition) {
return PrivacyManager.getHooks((String) getGroup(groupPosition)).size();
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.templateentry, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// Get entry
final int userId = Util.getUserId(Process.myUid());
final String restrictionName = (String) getGroup(groupPosition);
final Hook hook = (Hook) getChild(groupPosition, childPosition);
final String settingName = restrictionName + "." + hook.getName();
// Get parent info
String parentValue = PrivacyManager.getSetting(userId, Meta.cTypeTemplate, restrictionName,
Boolean.toString(!ondemand) + "+ask", false);
boolean parentRestricted = parentValue.contains("true");
boolean parentAsked = (!ondemand || parentValue.contains("asked"));
// Get child info
String value = PrivacyManager.getSetting(userId, Meta.cTypeTemplate, settingName,
Boolean.toString(parentRestricted && (hook.isDangerous() ? dangerous : true))
+ (parentAsked ? "+asked" : "+ask"), false);
holder.restricted = value.contains("true");
holder.asked = (!ondemand || value.contains("asked"));
Bitmap bmRestricted = (parentRestricted && holder.restricted ? getFullCheckBox() : getOffCheckBox());
Bitmap bmAsked = (parentAsked || holder.asked ? getOffCheckBox() : getOnDemandCheckBox());
// Set data
if (hook.isDangerous())
holder.row.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous)));
else
holder.row.setBackgroundColor(Color.TRANSPARENT);
holder.tvRestriction.setText(hook.getName());
holder.imgCbRestrict.setEnabled(parentRestricted);
holder.imgCbRestrict.setImageBitmap(bmRestricted);
holder.imgCbAsk.setEnabled(!parentAsked);
holder.imgCbAsk.setImageBitmap(bmAsked);
holder.imgCbAsk.setVisibility(ondemand ? View.VISIBLE : View.GONE);
// Listen for long press
if (Util.getUserId(Process.myUid()) == 0)
holder.tvRestriction.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
hook.toggleDangerous();
// Change background color
if (hook.isDangerous())
holder.row.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous)));
else
holder.row.setBackgroundColor(Color.TRANSPARENT);
return true;
}
});
holder.imgCbRestrict.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Update setting
holder.restricted = !holder.restricted;
PrivacyManager.setSetting(userId, Meta.cTypeTemplate, settingName, (holder.restricted ? "true"
: "false") + "+" + (holder.asked ? "asked" : "ask"));
// Update view
Bitmap bmRestricted = (holder.restricted ? getFullCheckBox() : getOffCheckBox());
holder.imgCbRestrict.setImageBitmap(bmRestricted);
}
});
holder.imgCbAsk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Update setting
holder.asked = !holder.asked;
PrivacyManager.setSetting(userId, Meta.cTypeTemplate, settingName, (holder.restricted ? "true"
: "false") + "+" + (holder.asked ? "asked" : "ask"));
// Update view
Bitmap bmAsked = (holder.asked ? getOffCheckBox() : getOnDemandCheckBox());
holder.imgCbAsk.setImageBitmap(bmAsked);
}
});
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
}
@SuppressLint("DefaultLocale")
private class AppListAdapter extends ArrayAdapter<ApplicationInfoEx> {
private Context mContext;
private boolean mSelecting = false;
private List<ApplicationInfoEx> mListAppAll;
private List<ApplicationInfoEx> mListAppSelected = new ArrayList<ApplicationInfoEx>();
private String mRestrictionName;
private LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
private AtomicInteger mFiltersRunning = new AtomicInteger(0);
private int mHighlightColor;
public final static int cSelectAppAll = 1;
public final static int cSelectAppNone = 2;
public final static int cSelectAppUser = 3;
public AppListAdapter(Context context, int resource, List<ApplicationInfoEx> objects,
String initialRestrictionName) {
super(context, resource, objects);
mContext = context;
mListAppAll = new ArrayList<ApplicationInfoEx>();
mListAppAll.addAll(objects);
mRestrictionName = initialRestrictionName;
TypedArray ta1 = context.getTheme().obtainStyledAttributes(
new int[] { android.R.attr.colorLongPressedHighlight });
mHighlightColor = ta1.getColor(0, 0xFF00FF);
ta1.recycle();
}
public void setRestrictionName(String restrictionName) {
mRestrictionName = restrictionName;
}
public String getRestrictionName() {
return mRestrictionName;
}
public List<ApplicationInfoEx> getSelectedOrVisible(int flags) {
if (mListAppSelected.size() > 0)
return mListAppSelected;
else {
if (flags == cSelectAppAll)
return mListAppAll;
else {
List<ApplicationInfoEx> listApp = new ArrayList<ApplicationInfoEx>();
if (flags == cSelectAppUser)
for (int i = 0; i < this.getCount(); i++) {
ApplicationInfoEx appInfo = this.getItem(i);
if (!appInfo.isSystem())
listApp.add(appInfo);
}
else if (flags != cSelectAppNone)
for (int i = 0; i < this.getCount(); i++)
listApp.add(this.getItem(i));
return listApp;
}
}
}
public int[] getSelectedOrVisibleUid(int flags) {
List<ApplicationInfoEx> listAppInfo = getSelectedOrVisible(flags);
int[] uid = new int[listAppInfo.size()];
for (int pos = 0; pos < listAppInfo.size(); pos++)
uid[pos] = listAppInfo.get(pos).getUid();
return uid;
}
public void selectAllVisible() {
// Look through the visible apps to figure out what to do
mSelecting = false;
for (int i = 0; i < this.getCount(); i++) {
if (!mListAppSelected.contains(this.getItem(i))) {
mSelecting = true;
break;
}
}
if (mSelecting) {
// Add the visible apps not already selected
for (int i = 0; i < this.getCount(); i++)
if (!mListAppSelected.contains(this.getItem(i)))
mListAppSelected.add(this.getItem(i));
} else
mListAppSelected.clear();
this.showStats();
this.notifyDataSetChanged();
}
public void showStats() {
TextView tvStats = (TextView) findViewById(R.id.tvStats);
String stats = String.format("%d/%d", this.getCount(), mListAppAll.size());
if (mListAppSelected.size() > 0)
stats += String.format(" (%d)", mListAppSelected.size());
tvStats.setText(stats);
}
@Override
public Filter getFilter() {
return new AppFilter();
}
private class AppFilter extends Filter {
public AppFilter() {
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
int filtersRunning = mFiltersRunning.addAndGet(1);
FilterResults results = new FilterResults();
// Get arguments
String[] components = ((String) constraint).split("\\n");
String fName = components[0];
boolean fUsed = Boolean.parseBoolean(components[1]);
boolean fInternet = Boolean.parseBoolean(components[2]);
boolean fRestricted = Boolean.parseBoolean(components[3]);
boolean fRestrictedNot = Boolean.parseBoolean(components[4]);
boolean fPermission = Boolean.parseBoolean(components[5]);
boolean fOnDemand = Boolean.parseBoolean(components[6]);
boolean fOnDemandNot = Boolean.parseBoolean(components[7]);
boolean fUser = Boolean.parseBoolean(components[8]);
boolean fSystem = Boolean.parseBoolean(components[9]);
// Match applications
int current = 0;
int max = AppListAdapter.this.mListAppAll.size();
List<ApplicationInfoEx> lstApp = new ArrayList<ApplicationInfoEx>();
for (ApplicationInfoEx xAppInfo : AppListAdapter.this.mListAppAll) {
// Check if another filter has been started
if (filtersRunning != mFiltersRunning.get())
return null;
// Send progress info to main activity
current++;
if (current % 5 == 0) {
final int position = current;
final int maximum = max;
runOnUiThread(new Runnable() {
@Override
public void run() {
setProgress(getString(R.string.msg_applying), position, maximum);
}
});
}
// Get if name contains
boolean contains = false;
if (!fName.equals(""))
contains = (xAppInfo.toString().toLowerCase().contains(((String) fName).toLowerCase()));
// Get if used
boolean used = false;
if (fUsed)
used = (PrivacyManager.getUsage(xAppInfo.getUid(), mRestrictionName, null) != 0);
// Get if internet
boolean internet = false;
if (fInternet)
internet = xAppInfo.hasInternet(mContext);
// Get some restricted
boolean someRestricted = false;
if (fRestricted)
for (PRestriction restriction : PrivacyManager.getRestrictionList(xAppInfo.getUid(),
mRestrictionName))
if (restriction.restricted) {
someRestricted = true;
break;
}
// Get Android permission
boolean permission = false;
if (fPermission)
if (mRestrictionName == null)
permission = true;
else if (PrivacyManager.hasPermission(mContext, xAppInfo, mRestrictionName)
|| PrivacyManager.getUsage(xAppInfo.getUid(), mRestrictionName, null) > 0)
permission = true;
// Get if onDemand
boolean onDemand = false;
if (fOnDemand && PrivacyManager.isApplication(xAppInfo.getUid())) {
onDemand = PrivacyManager.getSettingBool(-xAppInfo.getUid(), PrivacyManager.cSettingOnDemand,
false, false);
if (onDemand && mRestrictionName != null)
onDemand = !PrivacyManager.getRestrictionEx(xAppInfo.getUid(), mRestrictionName, null).asked;
}
// Get if user
boolean user = false;
if (fUser)
user = !xAppInfo.isSystem();
// Get if system
boolean system = false;
if (fSystem)
system = xAppInfo.isSystem();
// Apply filters
if ((fName.equals("") ? true : contains) && (fUsed ? used : true) && (fInternet ? internet : true)
&& (fRestricted ? (fRestrictedNot ? !someRestricted : someRestricted) : true)
&& (fPermission ? permission : true)
&& (fOnDemand ? (fOnDemandNot ? !onDemand : onDemand) : true) && (fUser ? user : true)
&& (fSystem ? system : true))
lstApp.add(xAppInfo);
}
// Check again whether another filter has been started
if (filtersRunning != mFiltersRunning.get())
return null;
// Apply current sorting
Collections.sort(lstApp, mSorter);
// Last check whether another filter has been started
if (filtersRunning != mFiltersRunning.get())
return null;
synchronized (this) {
results.values = lstApp;
results.count = lstApp.size();
}
return results;
}
@Override
@SuppressWarnings("unchecked")
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null) {
clear();
TextView tvStats = (TextView) findViewById(R.id.tvStats);
TextView tvState = (TextView) findViewById(R.id.tvState);
ProgressBar pbFilter = (ProgressBar) findViewById(R.id.pbFilter);
pbFilter.setVisibility(ProgressBar.GONE);
tvStats.setVisibility(TextView.VISIBLE);
runOnUiThread(new Runnable() {
@Override
public void run() {
setProgress(getString(R.string.title_restrict), 0, 1);
}
});
// Adjust progress state width
RelativeLayout.LayoutParams tvStateLayout = (RelativeLayout.LayoutParams) tvState.getLayoutParams();
tvStateLayout.addRule(RelativeLayout.LEFT_OF, R.id.tvStats);
if (results.values == null)
notifyDataSetInvalidated();
else {
addAll((ArrayList<ApplicationInfoEx>) results.values);
notifyDataSetChanged();
}
AppListAdapter.this.showStats();
}
}
}
public void sort() {
sort(mSorter);
}
private class ViewHolder {
private View row;
private int position;
public View vwState;
public LinearLayout llAppType;
public ImageView imgIcon;
public ImageView imgUsed;
public ImageView imgGranted;
public ImageView imgInternet;
public ImageView imgFrozen;
public TextView tvName;
public ImageView imgCbRestricted;
public ProgressBar pbRunning;
public LinearLayout llName;
public ImageView imgCbAsk;
public ViewHolder(View theRow, int thePosition) {
row = theRow;
position = thePosition;
vwState = (View) row.findViewById(R.id.vwState);
llAppType = (LinearLayout) row.findViewById(R.id.llAppType);
imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
imgUsed = (ImageView) row.findViewById(R.id.imgUsed);
imgGranted = (ImageView) row.findViewById(R.id.imgGranted);
imgInternet = (ImageView) row.findViewById(R.id.imgInternet);
imgFrozen = (ImageView) row.findViewById(R.id.imgFrozen);
tvName = (TextView) row.findViewById(R.id.tvName);
imgCbRestricted = (ImageView) row.findViewById(R.id.imgCbRestricted);
pbRunning = (ProgressBar) row.findViewById(R.id.pbRunning);
llName = (LinearLayout) row.findViewById(R.id.llName);
imgCbAsk = (ImageView) row.findViewById(R.id.imgCbAsk);
}
}
private class HolderTask extends AsyncTask<Object, Object, Object> {
private int position;
private ViewHolder holder;
private ApplicationInfoEx xAppInfo = null;
private int state;
private boolean used;
private boolean enabled;
private boolean granted;
private RState rstate;
private boolean gondemand;
private boolean ondemand;
public HolderTask(int thePosition, ViewHolder theHolder, ApplicationInfoEx theAppInfo) {
position = thePosition;
holder = theHolder;
xAppInfo = theAppInfo;
}
@Override
protected Object doInBackground(Object... params) {
if (xAppInfo != null) {
int userId = Util.getUserId(Process.myUid());
// Get state
state = xAppInfo.getState(ActivityMain.this);
// Get if used
used = (PrivacyManager.getUsage(xAppInfo.getUid(), mRestrictionName, null) != 0);
// Get if enabled
enabled = PrivacyManager.getSettingBool(xAppInfo.getUid(), PrivacyManager.cSettingRestricted, true,
false);
// Get if on demand
gondemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true, false);
ondemand = (PrivacyManager.isApplication(xAppInfo.getUid()) && (mRestrictionName == null ? true
: PrivacyManager.getSettingBool(-xAppInfo.getUid(), PrivacyManager.cSettingOnDemand, false,
false)));
// Get if granted
granted = true;
if (mRestrictionName != null)
if (!PrivacyManager.hasPermission(ActivityMain.this, xAppInfo, mRestrictionName))
granted = false;
// Get restriction/ask state
rstate = new RState(xAppInfo.getUid(), mRestrictionName, null);
return holder;
}
return null;
}
@Override
protected void onPostExecute(Object result) {
if (holder.position == position && result != null) {
// Set background color
if (xAppInfo.isSystem())
holder.llAppType.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous)));
else
holder.llAppType.setBackgroundColor(Color.TRANSPARENT);
// Display state
if (state == STATE_ATTENTION)
holder.vwState.setBackgroundColor(getResources().getColor(
getThemed(R.attr.color_state_attention)));
else if (state == STATE_SHARED)
holder.vwState
.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_state_shared)));
else
holder.vwState.setBackgroundColor(getResources().getColor(
getThemed(R.attr.color_state_restricted)));
// Display icon
holder.imgIcon.setImageDrawable(xAppInfo.getIcon(ActivityMain.this));
holder.imgIcon.setVisibility(View.VISIBLE);
// Display on demand
if (gondemand) {
if (ondemand) {
holder.imgCbAsk.setImageBitmap(getAskBoxImage(rstate));
holder.imgCbAsk.setVisibility(View.VISIBLE);
} else
holder.imgCbAsk.setVisibility(View.INVISIBLE);
} else
holder.imgCbAsk.setVisibility(View.GONE);
// Display usage
holder.tvName.setTypeface(null, used ? Typeface.BOLD_ITALIC : Typeface.NORMAL);
holder.imgUsed.setVisibility(used ? View.VISIBLE : View.INVISIBLE);
// Display if permissions
holder.imgGranted.setVisibility(granted ? View.VISIBLE : View.INVISIBLE);
// Display if internet access
holder.imgInternet.setVisibility(xAppInfo.hasInternet(ActivityMain.this) ? View.VISIBLE
: View.INVISIBLE);
// Display if frozen
holder.imgFrozen
.setVisibility(xAppInfo.isFrozen(ActivityMain.this) ? View.VISIBLE : View.INVISIBLE);
// Display restriction
holder.imgCbRestricted.setImageBitmap(getCheckBoxImage(rstate));
holder.imgCbRestricted.setVisibility(View.VISIBLE);
// Display enabled state
holder.tvName.setEnabled(enabled);
holder.imgCbRestricted.setEnabled(enabled);
holder.llName.setEnabled(enabled);
// Display selection
if (mListAppSelected.contains(xAppInfo))
holder.row.setBackgroundColor(mHighlightColor);
else
holder.row.setBackgroundColor(Color.TRANSPARENT);
// Listen for multiple select
holder.llName.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mListAppSelected.contains(xAppInfo)) {
mSelecting = false;
mListAppSelected.clear();
mAppAdapter.notifyDataSetChanged();
} else {
mSelecting = true;
mListAppSelected.add(xAppInfo);
holder.row.setBackgroundColor(mHighlightColor);
}
showStats();
return true;
}
});
// Listen for restriction changes
holder.llName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
if (mSelecting) {
if (mListAppSelected.contains(xAppInfo)) {
mListAppSelected.remove(xAppInfo);
holder.row.setBackgroundColor(Color.TRANSPARENT);
if (mListAppSelected.size() == 0)
mSelecting = false;
} else {
mListAppSelected.add(xAppInfo);
holder.row.setBackgroundColor(mHighlightColor);
}
showStats();
} else {
if (mRestrictionName == null && rstate.restricted != false) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityMain.this);
alertDialogBuilder.setTitle(R.string.menu_clear_all);
alertDialogBuilder.setMessage(R.string.msg_sure);
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteRestrictions();
}
});
alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else
toggleRestrictions();
}
}
});
// Listen for ask changes
if (gondemand && ondemand)
holder.imgCbAsk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
holder.imgCbAsk.setVisibility(View.GONE);
holder.pbRunning.setVisibility(View.VISIBLE);
new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... arg0) {
rstate.toggleAsked();
+ rstate = new RState(xAppInfo.getUid(), mRestrictionName, null);
return null;
}
@Override
protected void onPostExecute(Object result) {
holder.imgCbAsk.setImageBitmap(getAskBoxImage(rstate));
holder.pbRunning.setVisibility(View.GONE);
holder.imgCbAsk.setVisibility(View.VISIBLE);
}
}.executeOnExecutor(mExecutor);
}
});
else
holder.imgCbAsk.setClickable(false);
}
}
private void deleteRestrictions() {
holder.llName.setEnabled(false);
holder.imgCbRestricted.setVisibility(View.GONE);
holder.pbRunning.setVisibility(View.VISIBLE);
new AsyncTask<Object, Object, Object>() {
private List<Boolean> oldState;
@Override
protected Object doInBackground(Object... arg0) {
// Update restriction
oldState = PrivacyManager.getRestartStates(xAppInfo.getUid(), mRestrictionName);
PrivacyManager.deleteRestrictions(xAppInfo.getUid(), null, true);
PrivacyManager.setSetting(xAppInfo.getUid(), PrivacyManager.cSettingOnDemand,
Boolean.toString(true));
return null;
}
@Override
protected void onPostExecute(Object result) {
// Update visible state
holder.vwState.setBackgroundColor(getResources().getColor(
getThemed(R.attr.color_state_attention)));
// Update stored state
rstate = new RState(xAppInfo.getUid(), mRestrictionName, null);
holder.imgCbRestricted.setImageBitmap(getCheckBoxImage(rstate));
holder.imgCbAsk.setImageBitmap(getAskBoxImage(rstate));
// Notify restart
if (oldState.contains(true))
Toast.makeText(ActivityMain.this, getString(R.string.msg_restart), Toast.LENGTH_SHORT)
.show();
// Display new state
showState();
holder.pbRunning.setVisibility(View.GONE);
holder.imgCbRestricted.setVisibility(View.VISIBLE);
holder.llName.setEnabled(true);
}
}.executeOnExecutor(mExecutor);
}
private void toggleRestrictions() {
holder.llName.setEnabled(false);
holder.imgCbRestricted.setVisibility(View.GONE);
holder.pbRunning.setVisibility(View.VISIBLE);
new AsyncTask<Object, Object, Object>() {
private List<Boolean> oldState;
private List<Boolean> newState;
@Override
protected Object doInBackground(Object... arg0) {
// Change restriction
oldState = PrivacyManager.getRestartStates(xAppInfo.getUid(), mRestrictionName);
rstate.toggleRestriction();
newState = PrivacyManager.getRestartStates(xAppInfo.getUid(), mRestrictionName);
return null;
}
@Override
protected void onPostExecute(Object result) {
// Update restriction display
rstate = new RState(xAppInfo.getUid(), mRestrictionName, null);
holder.imgCbRestricted.setImageBitmap(getCheckBoxImage(rstate));
holder.imgCbAsk.setImageBitmap(getAskBoxImage(rstate));
// Notify restart
if (!newState.equals(oldState))
Toast.makeText(ActivityMain.this, getString(R.string.msg_restart), Toast.LENGTH_SHORT)
.show();
// Display new state
showState();
holder.pbRunning.setVisibility(View.GONE);
holder.imgCbRestricted.setVisibility(View.VISIBLE);
holder.llName.setEnabled(true);
}
}.executeOnExecutor(mExecutor);
}
private void showState() {
state = xAppInfo.getState(ActivityMain.this);
if (state == STATE_ATTENTION)
holder.vwState.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_state_attention)));
else if (state == STATE_SHARED)
holder.vwState.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_state_shared)));
else
holder.vwState
.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_state_restricted)));
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mainentry, null);
holder = new ViewHolder(convertView, position);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.position = position;
}
// Get info
final ApplicationInfoEx xAppInfo = getItem(holder.position);
// Handle details click
holder.imgIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intentSettings = new Intent(ActivityMain.this, ActivityApp.class);
intentSettings.putExtra(ActivityApp.cUid, xAppInfo.getUid());
intentSettings.putExtra(ActivityApp.cRestrictionName, mRestrictionName);
ActivityMain.this.startActivity(intentSettings);
}
});
// Set data
holder.row.setBackgroundColor(Color.TRANSPARENT);
holder.vwState.setBackgroundColor(Color.TRANSPARENT);
holder.llAppType.setBackgroundColor(Color.TRANSPARENT);
holder.imgIcon.setVisibility(View.INVISIBLE);
holder.tvName.setText(xAppInfo.toString());
holder.tvName.setTypeface(null, Typeface.NORMAL);
holder.imgUsed.setVisibility(View.INVISIBLE);
holder.imgGranted.setVisibility(View.INVISIBLE);
holder.imgInternet.setVisibility(View.INVISIBLE);
holder.imgFrozen.setVisibility(View.INVISIBLE);
holder.imgCbRestricted.setVisibility(View.INVISIBLE);
holder.imgCbAsk.setVisibility(View.INVISIBLE);
holder.tvName.setEnabled(false);
holder.imgCbRestricted.setEnabled(false);
holder.llName.setEnabled(false);
// Async update
new HolderTask(position, holder, xAppInfo).executeOnExecutor(mExecutor, (Object) null);
return convertView;
}
}
// Share operations progress listener
private void setProgress(String text, int progress, int max) {
// Set up the progress bar
if (mProgressWidth == 0) {
final View vProgressEmpty = (View) findViewById(R.id.vProgressEmpty);
mProgressWidth = vProgressEmpty.getMeasuredWidth();
}
// Display stuff
TextView tvState = (TextView) findViewById(R.id.tvState);
if (text != null)
tvState.setText(text);
if (max == 0)
max = 1;
mProgress = (int) ((float) mProgressWidth) * progress / max;
View vProgressFull = (View) findViewById(R.id.vProgressFull);
vProgressFull.getLayoutParams().width = mProgress;
}
// Helper methods
private void checkLicense() {
if (!Util.isProEnabled() && Util.hasProLicense(this) == null)
if (Util.isProEnablerInstalled(this))
try {
int uid = getPackageManager().getPackageInfo("biz.bokhorst.xprivacy.pro", 0).applicationInfo.uid;
PrivacyManager.deleteRestrictions(uid, null, true);
Util.log(null, Log.INFO, "Licensing: check");
startActivityForResult(new Intent("biz.bokhorst.xprivacy.pro.CHECK"), ACTIVITY_LICENSE);
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
}
| true | true | protected void onPostExecute(Object result) {
if (holder.position == position && result != null) {
// Set background color
if (xAppInfo.isSystem())
holder.llAppType.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous)));
else
holder.llAppType.setBackgroundColor(Color.TRANSPARENT);
// Display state
if (state == STATE_ATTENTION)
holder.vwState.setBackgroundColor(getResources().getColor(
getThemed(R.attr.color_state_attention)));
else if (state == STATE_SHARED)
holder.vwState
.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_state_shared)));
else
holder.vwState.setBackgroundColor(getResources().getColor(
getThemed(R.attr.color_state_restricted)));
// Display icon
holder.imgIcon.setImageDrawable(xAppInfo.getIcon(ActivityMain.this));
holder.imgIcon.setVisibility(View.VISIBLE);
// Display on demand
if (gondemand) {
if (ondemand) {
holder.imgCbAsk.setImageBitmap(getAskBoxImage(rstate));
holder.imgCbAsk.setVisibility(View.VISIBLE);
} else
holder.imgCbAsk.setVisibility(View.INVISIBLE);
} else
holder.imgCbAsk.setVisibility(View.GONE);
// Display usage
holder.tvName.setTypeface(null, used ? Typeface.BOLD_ITALIC : Typeface.NORMAL);
holder.imgUsed.setVisibility(used ? View.VISIBLE : View.INVISIBLE);
// Display if permissions
holder.imgGranted.setVisibility(granted ? View.VISIBLE : View.INVISIBLE);
// Display if internet access
holder.imgInternet.setVisibility(xAppInfo.hasInternet(ActivityMain.this) ? View.VISIBLE
: View.INVISIBLE);
// Display if frozen
holder.imgFrozen
.setVisibility(xAppInfo.isFrozen(ActivityMain.this) ? View.VISIBLE : View.INVISIBLE);
// Display restriction
holder.imgCbRestricted.setImageBitmap(getCheckBoxImage(rstate));
holder.imgCbRestricted.setVisibility(View.VISIBLE);
// Display enabled state
holder.tvName.setEnabled(enabled);
holder.imgCbRestricted.setEnabled(enabled);
holder.llName.setEnabled(enabled);
// Display selection
if (mListAppSelected.contains(xAppInfo))
holder.row.setBackgroundColor(mHighlightColor);
else
holder.row.setBackgroundColor(Color.TRANSPARENT);
// Listen for multiple select
holder.llName.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mListAppSelected.contains(xAppInfo)) {
mSelecting = false;
mListAppSelected.clear();
mAppAdapter.notifyDataSetChanged();
} else {
mSelecting = true;
mListAppSelected.add(xAppInfo);
holder.row.setBackgroundColor(mHighlightColor);
}
showStats();
return true;
}
});
// Listen for restriction changes
holder.llName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
if (mSelecting) {
if (mListAppSelected.contains(xAppInfo)) {
mListAppSelected.remove(xAppInfo);
holder.row.setBackgroundColor(Color.TRANSPARENT);
if (mListAppSelected.size() == 0)
mSelecting = false;
} else {
mListAppSelected.add(xAppInfo);
holder.row.setBackgroundColor(mHighlightColor);
}
showStats();
} else {
if (mRestrictionName == null && rstate.restricted != false) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityMain.this);
alertDialogBuilder.setTitle(R.string.menu_clear_all);
alertDialogBuilder.setMessage(R.string.msg_sure);
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteRestrictions();
}
});
alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else
toggleRestrictions();
}
}
});
// Listen for ask changes
if (gondemand && ondemand)
holder.imgCbAsk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
holder.imgCbAsk.setVisibility(View.GONE);
holder.pbRunning.setVisibility(View.VISIBLE);
new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... arg0) {
rstate.toggleAsked();
return null;
}
@Override
protected void onPostExecute(Object result) {
holder.imgCbAsk.setImageBitmap(getAskBoxImage(rstate));
holder.pbRunning.setVisibility(View.GONE);
holder.imgCbAsk.setVisibility(View.VISIBLE);
}
}.executeOnExecutor(mExecutor);
}
});
else
holder.imgCbAsk.setClickable(false);
}
}
| protected void onPostExecute(Object result) {
if (holder.position == position && result != null) {
// Set background color
if (xAppInfo.isSystem())
holder.llAppType.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous)));
else
holder.llAppType.setBackgroundColor(Color.TRANSPARENT);
// Display state
if (state == STATE_ATTENTION)
holder.vwState.setBackgroundColor(getResources().getColor(
getThemed(R.attr.color_state_attention)));
else if (state == STATE_SHARED)
holder.vwState
.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_state_shared)));
else
holder.vwState.setBackgroundColor(getResources().getColor(
getThemed(R.attr.color_state_restricted)));
// Display icon
holder.imgIcon.setImageDrawable(xAppInfo.getIcon(ActivityMain.this));
holder.imgIcon.setVisibility(View.VISIBLE);
// Display on demand
if (gondemand) {
if (ondemand) {
holder.imgCbAsk.setImageBitmap(getAskBoxImage(rstate));
holder.imgCbAsk.setVisibility(View.VISIBLE);
} else
holder.imgCbAsk.setVisibility(View.INVISIBLE);
} else
holder.imgCbAsk.setVisibility(View.GONE);
// Display usage
holder.tvName.setTypeface(null, used ? Typeface.BOLD_ITALIC : Typeface.NORMAL);
holder.imgUsed.setVisibility(used ? View.VISIBLE : View.INVISIBLE);
// Display if permissions
holder.imgGranted.setVisibility(granted ? View.VISIBLE : View.INVISIBLE);
// Display if internet access
holder.imgInternet.setVisibility(xAppInfo.hasInternet(ActivityMain.this) ? View.VISIBLE
: View.INVISIBLE);
// Display if frozen
holder.imgFrozen
.setVisibility(xAppInfo.isFrozen(ActivityMain.this) ? View.VISIBLE : View.INVISIBLE);
// Display restriction
holder.imgCbRestricted.setImageBitmap(getCheckBoxImage(rstate));
holder.imgCbRestricted.setVisibility(View.VISIBLE);
// Display enabled state
holder.tvName.setEnabled(enabled);
holder.imgCbRestricted.setEnabled(enabled);
holder.llName.setEnabled(enabled);
// Display selection
if (mListAppSelected.contains(xAppInfo))
holder.row.setBackgroundColor(mHighlightColor);
else
holder.row.setBackgroundColor(Color.TRANSPARENT);
// Listen for multiple select
holder.llName.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mListAppSelected.contains(xAppInfo)) {
mSelecting = false;
mListAppSelected.clear();
mAppAdapter.notifyDataSetChanged();
} else {
mSelecting = true;
mListAppSelected.add(xAppInfo);
holder.row.setBackgroundColor(mHighlightColor);
}
showStats();
return true;
}
});
// Listen for restriction changes
holder.llName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
if (mSelecting) {
if (mListAppSelected.contains(xAppInfo)) {
mListAppSelected.remove(xAppInfo);
holder.row.setBackgroundColor(Color.TRANSPARENT);
if (mListAppSelected.size() == 0)
mSelecting = false;
} else {
mListAppSelected.add(xAppInfo);
holder.row.setBackgroundColor(mHighlightColor);
}
showStats();
} else {
if (mRestrictionName == null && rstate.restricted != false) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityMain.this);
alertDialogBuilder.setTitle(R.string.menu_clear_all);
alertDialogBuilder.setMessage(R.string.msg_sure);
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
alertDialogBuilder.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteRestrictions();
}
});
alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else
toggleRestrictions();
}
}
});
// Listen for ask changes
if (gondemand && ondemand)
holder.imgCbAsk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
holder.imgCbAsk.setVisibility(View.GONE);
holder.pbRunning.setVisibility(View.VISIBLE);
new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... arg0) {
rstate.toggleAsked();
rstate = new RState(xAppInfo.getUid(), mRestrictionName, null);
return null;
}
@Override
protected void onPostExecute(Object result) {
holder.imgCbAsk.setImageBitmap(getAskBoxImage(rstate));
holder.pbRunning.setVisibility(View.GONE);
holder.imgCbAsk.setVisibility(View.VISIBLE);
}
}.executeOnExecutor(mExecutor);
}
});
else
holder.imgCbAsk.setClickable(false);
}
}
|
diff --git a/src/com/android/camera/Switcher.java b/src/com/android/camera/Switcher.java
index c88ddb8a..e0038751 100644
--- a/src/com/android/camera/Switcher.java
+++ b/src/com/android/camera/Switcher.java
@@ -1,184 +1,183 @@
/*
* 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.camera;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
/**
* A widget which switchs between the {@code Camera} and the {@code VideoCamera}
* activities.
*/
public class Switcher extends ImageView implements View.OnTouchListener {
@SuppressWarnings("unused")
private static final String TAG = "Switcher";
/** A callback to be called when the user wants to switch activity. */
public interface OnSwitchListener {
// Returns true if the listener agrees that the switch can be changed.
public boolean onSwitchChanged(Switcher source, boolean onOff);
}
private static final int ANIMATION_SPEED = 200;
private static final long NO_ANIMATION = -1;
private boolean mSwitch = false;
private int mPosition = 0;
private long mAnimationStartTime = NO_ANIMATION;
private int mAnimationStartPosition;
private OnSwitchListener mListener;
public Switcher(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSwitch(boolean onOff) {
if (mSwitch == onOff) return;
mSwitch = onOff;
invalidate();
}
// Try to change the switch position. (The client can veto it.)
private void tryToSetSwitch(boolean onOff) {
try {
if (mSwitch == onOff) return;
if (mListener != null) {
if (!mListener.onSwitchChanged(this, onOff)) {
return;
}
}
mSwitch = onOff;
} finally {
startParkingAnimation();
}
}
public void setOnSwitchListener(OnSwitchListener listener) {
mListener = listener;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) return false;
final int available = getHeight() - getPaddingTop() - getPaddingBottom()
- getDrawable().getIntrinsicHeight();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mAnimationStartTime = NO_ANIMATION;
setPressed(true);
trackTouchEvent(event);
break;
case MotionEvent.ACTION_MOVE:
trackTouchEvent(event);
break;
case MotionEvent.ACTION_UP:
trackTouchEvent(event);
tryToSetSwitch(mPosition >= available / 2);
setPressed(false);
break;
case MotionEvent.ACTION_CANCEL:
tryToSetSwitch(mSwitch);
setPressed(false);
break;
}
return true;
}
private void startParkingAnimation() {
mAnimationStartTime = AnimationUtils.currentAnimationTimeMillis();
mAnimationStartPosition = mPosition;
}
private void trackTouchEvent(MotionEvent event) {
Drawable drawable = getDrawable();
int drawableHeight = drawable.getIntrinsicHeight();
final int height = getHeight();
final int available = height - getPaddingTop() - getPaddingBottom()
- drawableHeight;
int x = (int) event.getY();
mPosition = x - getPaddingTop() - drawableHeight / 2;
if (mPosition < 0) mPosition = 0;
if (mPosition > available) mPosition = available;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
int drawableHeight = drawable.getIntrinsicHeight();
int drawableWidth = drawable.getIntrinsicWidth();
if (drawableWidth == 0 || drawableHeight == 0) {
return; // nothing to draw (empty bounds)
}
final int available = getHeight() - getPaddingTop()
- getPaddingBottom() - drawableHeight;
if (mAnimationStartTime != NO_ANIMATION) {
long time = AnimationUtils.currentAnimationTimeMillis();
int deltaTime = (int) (time - mAnimationStartTime);
mPosition = mAnimationStartPosition +
ANIMATION_SPEED * (mSwitch ? deltaTime : -deltaTime) / 1000;
if (mPosition < 0) mPosition = 0;
if (mPosition > available) mPosition = available;
boolean done = (mPosition == (mSwitch ? available : 0));
if (!done) {
invalidate();
} else {
mAnimationStartTime = NO_ANIMATION;
}
} else if (!isPressed()){
mPosition = mSwitch ? available : 0;
}
int offsetTop = getPaddingTop() + mPosition;
- int offsetLeft = (getWidth()
- - drawableWidth - getPaddingLeft() - getPaddingRight()) / 2;
+ int offsetLeft = (getWidth() - drawableWidth) / 2;
int saveCount = canvas.getSaveCount();
canvas.save();
canvas.translate(offsetLeft, offsetTop);
drawable.draw(canvas);
canvas.restoreToCount(saveCount);
}
// Consume the touch events for the specified view.
public void addTouchView(View v) {
v.setOnTouchListener(this);
}
// This implements View.OnTouchListener so we intercept the touch events
// and pass them to ourselves.
public boolean onTouch(View v, MotionEvent event) {
onTouchEvent(event);
return true;
}
}
| true | true | protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
int drawableHeight = drawable.getIntrinsicHeight();
int drawableWidth = drawable.getIntrinsicWidth();
if (drawableWidth == 0 || drawableHeight == 0) {
return; // nothing to draw (empty bounds)
}
final int available = getHeight() - getPaddingTop()
- getPaddingBottom() - drawableHeight;
if (mAnimationStartTime != NO_ANIMATION) {
long time = AnimationUtils.currentAnimationTimeMillis();
int deltaTime = (int) (time - mAnimationStartTime);
mPosition = mAnimationStartPosition +
ANIMATION_SPEED * (mSwitch ? deltaTime : -deltaTime) / 1000;
if (mPosition < 0) mPosition = 0;
if (mPosition > available) mPosition = available;
boolean done = (mPosition == (mSwitch ? available : 0));
if (!done) {
invalidate();
} else {
mAnimationStartTime = NO_ANIMATION;
}
} else if (!isPressed()){
mPosition = mSwitch ? available : 0;
}
int offsetTop = getPaddingTop() + mPosition;
int offsetLeft = (getWidth()
- drawableWidth - getPaddingLeft() - getPaddingRight()) / 2;
int saveCount = canvas.getSaveCount();
canvas.save();
canvas.translate(offsetLeft, offsetTop);
drawable.draw(canvas);
canvas.restoreToCount(saveCount);
}
| protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
int drawableHeight = drawable.getIntrinsicHeight();
int drawableWidth = drawable.getIntrinsicWidth();
if (drawableWidth == 0 || drawableHeight == 0) {
return; // nothing to draw (empty bounds)
}
final int available = getHeight() - getPaddingTop()
- getPaddingBottom() - drawableHeight;
if (mAnimationStartTime != NO_ANIMATION) {
long time = AnimationUtils.currentAnimationTimeMillis();
int deltaTime = (int) (time - mAnimationStartTime);
mPosition = mAnimationStartPosition +
ANIMATION_SPEED * (mSwitch ? deltaTime : -deltaTime) / 1000;
if (mPosition < 0) mPosition = 0;
if (mPosition > available) mPosition = available;
boolean done = (mPosition == (mSwitch ? available : 0));
if (!done) {
invalidate();
} else {
mAnimationStartTime = NO_ANIMATION;
}
} else if (!isPressed()){
mPosition = mSwitch ? available : 0;
}
int offsetTop = getPaddingTop() + mPosition;
int offsetLeft = (getWidth() - drawableWidth) / 2;
int saveCount = canvas.getSaveCount();
canvas.save();
canvas.translate(offsetLeft, offsetTop);
drawable.draw(canvas);
canvas.restoreToCount(saveCount);
}
|
diff --git a/src/main/java/fr/univnantes/atal/web/piubella/servlets/Fetch.java b/src/main/java/fr/univnantes/atal/web/piubella/servlets/Fetch.java
index c2705f5..047c7d7 100644
--- a/src/main/java/fr/univnantes/atal/web/piubella/servlets/Fetch.java
+++ b/src/main/java/fr/univnantes/atal/web/piubella/servlets/Fetch.java
@@ -1,205 +1,206 @@
package fr.univnantes.atal.web.piubella.servlets;
import au.com.bytecode.opencsv.CSVReader;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import fr.univnantes.atal.web.piubella.app.Constants;
import fr.univnantes.atal.web.piubella.model.Address;
import fr.univnantes.atal.web.piubella.model.CollectDay;
import fr.univnantes.atal.web.piubella.model.JSONInfo;
import fr.univnantes.atal.web.piubella.persistence.PMF;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.channels.Channels;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
/**
* Servlet fetching data on NOD.
*
* This servlet has two roles. The first one is to store the current NOD dataset
* in the datastore. The second one is to create a blob in the blobstore
* containing a filtered dataset for use by the client in a typeahead for
* example.
*/
public class Fetch extends HttpServlet {
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query q = pm.newQuery(JSONInfo.class);
try {
FileService fileService = FileServiceFactory.getFileService();
JSONInfo jsonInfo;
List<JSONInfo> results =
(List<JSONInfo>) q.execute();
AppEngineFile file;
if (results.isEmpty()) {
jsonInfo = new JSONInfo();
pm.makePersistent(jsonInfo);
} else {
jsonInfo = results.get(0);
}
file = fileService.createNewBlobFile("text/plain");
boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
JsonFactory f = new JsonFactory();
try (OutputStream os = Channels.newOutputStream(writeChannel);
JsonGenerator g = f.createJsonGenerator(os)) {
g.writeStartObject();
g.writeArrayFieldStart("data");
try (PrintWriter out = response.getWriter()) {
out.println(file.getFullPath());
}
q = pm.newQuery(Address.class);
q.deletePersistentAll();
URL url = new URL(Constants.NOD_DATASET_CSV_URL);
CSVReader reader = new CSVReader(new InputStreamReader(url.openStream(), "UTF-8"));
String[] nextLine;
Collection<Address> addresses = new ArrayList<>();
while ((nextLine = reader.readNext()) != null) {
if (nextLine.length < 13) {
System.err.println("Data import failed.");
System.err.println("Couldn't find 13 fields in the dataset "
+ "which means I don't know what to do.");
return;
} else {
String blue = nextLine[10],
obsCollect = nextLine[12];
if (!blue.isEmpty() && obsCollect.isEmpty()) {
String street = nextLine[1],
obsStreet = nextLine[9],
yellow = nextLine[11];
Set<CollectDay> blueDays = new HashSet<>(),
yellowDays = new HashSet<>();
Boolean singleCollect = false;
if (yellow.isEmpty()) {
singleCollect = true;
}
if (blue.contains("lundi")) {
blueDays.add(CollectDay.MONDAY);
}
if (blue.contains("mardi")) {
blueDays.add(CollectDay.TUESDAY);
}
if (blue.contains("mercredi")) {
blueDays.add(CollectDay.WEDNESDAY);
} else if (blue.contains("merc_sem_impaires")) {
blueDays.add(CollectDay.WEDNESDAY_ODD);
} else if (blue.contains("merc_sem_paires")) {
blueDays.add(CollectDay.WEDNESDAY_EVEN);
}
if (blue.contains("jeudi")) {
blueDays.add(CollectDay.THURSDAY);
}
if (blue.contains("vendredi")) {
blueDays.add(CollectDay.FRIDAY);
}
if (blue.contains("samedi")) {
blueDays.add(CollectDay.SATURDAY);
}
if (blue.contains("dimanche")) {
blueDays.add(CollectDay.SUNDAY);
}
if (yellow.contains("lundi")) {
yellowDays.add(CollectDay.MONDAY);
}
if (yellow.contains("mardi")) {
yellowDays.add(CollectDay.TUESDAY);
}
if (yellow.contains("mercredi")) {
yellowDays.add(CollectDay.WEDNESDAY);
} else if (yellow.contains("merc_sem_impaires")) {
yellowDays.add(CollectDay.WEDNESDAY_ODD);
} else if (yellow.contains("merc_sem_paires")) {
yellowDays.add(CollectDay.WEDNESDAY_EVEN);
}
if (yellow.contains("jeudi")) {
yellowDays.add(CollectDay.THURSDAY);
}
if (yellow.contains("vendredi")) {
yellowDays.add(CollectDay.FRIDAY);
}
if (yellow.contains("samedi")) {
yellowDays.add(CollectDay.SATURDAY);
}
if (yellow.contains("dimanche")) {
yellowDays.add(CollectDay.SUNDAY);
}
Address address = new Address();
- address.setStreet(street + (obsStreet.isEmpty()
+ street = street + (obsStreet.isEmpty()
? ""
- : " " + obsStreet));
+ : " " + obsStreet);
+ address.setStreet(street);
address.setBlueDays(blueDays);
address.setYellowDays(yellowDays);
addresses.add(address);
g.writeStartArray();
g.writeString(street);
g.writeStartArray();
for (CollectDay cd : blueDays) {
g.writeNumber(cd.ordinal());
}
g.writeEndArray();
if (!yellowDays.isEmpty()) {
g.writeStartArray();
for (CollectDay cd : yellowDays) {
g.writeNumber(cd.ordinal());
}
g.writeEndArray();
}
g.writeEndArray();
}
}
if (addresses.size() > 100) {
pm.makePersistentAll(addresses);
addresses.clear();
}
}
g.writeEndArray();
g.writeEndObject();
}
writeChannel.closeFinally();
if (jsonInfo.getBlobKey() != null) {
BlobstoreService blobstoreService =
BlobstoreServiceFactory.getBlobstoreService();
blobstoreService.delete(jsonInfo.getBlobKey());
}
jsonInfo.setBlobKey(fileService.getBlobKey(file));
} finally {
q.closeAll();
}
}
}
| false | true | protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query q = pm.newQuery(JSONInfo.class);
try {
FileService fileService = FileServiceFactory.getFileService();
JSONInfo jsonInfo;
List<JSONInfo> results =
(List<JSONInfo>) q.execute();
AppEngineFile file;
if (results.isEmpty()) {
jsonInfo = new JSONInfo();
pm.makePersistent(jsonInfo);
} else {
jsonInfo = results.get(0);
}
file = fileService.createNewBlobFile("text/plain");
boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
JsonFactory f = new JsonFactory();
try (OutputStream os = Channels.newOutputStream(writeChannel);
JsonGenerator g = f.createJsonGenerator(os)) {
g.writeStartObject();
g.writeArrayFieldStart("data");
try (PrintWriter out = response.getWriter()) {
out.println(file.getFullPath());
}
q = pm.newQuery(Address.class);
q.deletePersistentAll();
URL url = new URL(Constants.NOD_DATASET_CSV_URL);
CSVReader reader = new CSVReader(new InputStreamReader(url.openStream(), "UTF-8"));
String[] nextLine;
Collection<Address> addresses = new ArrayList<>();
while ((nextLine = reader.readNext()) != null) {
if (nextLine.length < 13) {
System.err.println("Data import failed.");
System.err.println("Couldn't find 13 fields in the dataset "
+ "which means I don't know what to do.");
return;
} else {
String blue = nextLine[10],
obsCollect = nextLine[12];
if (!blue.isEmpty() && obsCollect.isEmpty()) {
String street = nextLine[1],
obsStreet = nextLine[9],
yellow = nextLine[11];
Set<CollectDay> blueDays = new HashSet<>(),
yellowDays = new HashSet<>();
Boolean singleCollect = false;
if (yellow.isEmpty()) {
singleCollect = true;
}
if (blue.contains("lundi")) {
blueDays.add(CollectDay.MONDAY);
}
if (blue.contains("mardi")) {
blueDays.add(CollectDay.TUESDAY);
}
if (blue.contains("mercredi")) {
blueDays.add(CollectDay.WEDNESDAY);
} else if (blue.contains("merc_sem_impaires")) {
blueDays.add(CollectDay.WEDNESDAY_ODD);
} else if (blue.contains("merc_sem_paires")) {
blueDays.add(CollectDay.WEDNESDAY_EVEN);
}
if (blue.contains("jeudi")) {
blueDays.add(CollectDay.THURSDAY);
}
if (blue.contains("vendredi")) {
blueDays.add(CollectDay.FRIDAY);
}
if (blue.contains("samedi")) {
blueDays.add(CollectDay.SATURDAY);
}
if (blue.contains("dimanche")) {
blueDays.add(CollectDay.SUNDAY);
}
if (yellow.contains("lundi")) {
yellowDays.add(CollectDay.MONDAY);
}
if (yellow.contains("mardi")) {
yellowDays.add(CollectDay.TUESDAY);
}
if (yellow.contains("mercredi")) {
yellowDays.add(CollectDay.WEDNESDAY);
} else if (yellow.contains("merc_sem_impaires")) {
yellowDays.add(CollectDay.WEDNESDAY_ODD);
} else if (yellow.contains("merc_sem_paires")) {
yellowDays.add(CollectDay.WEDNESDAY_EVEN);
}
if (yellow.contains("jeudi")) {
yellowDays.add(CollectDay.THURSDAY);
}
if (yellow.contains("vendredi")) {
yellowDays.add(CollectDay.FRIDAY);
}
if (yellow.contains("samedi")) {
yellowDays.add(CollectDay.SATURDAY);
}
if (yellow.contains("dimanche")) {
yellowDays.add(CollectDay.SUNDAY);
}
Address address = new Address();
address.setStreet(street + (obsStreet.isEmpty()
? ""
: " " + obsStreet));
address.setBlueDays(blueDays);
address.setYellowDays(yellowDays);
addresses.add(address);
g.writeStartArray();
g.writeString(street);
g.writeStartArray();
for (CollectDay cd : blueDays) {
g.writeNumber(cd.ordinal());
}
g.writeEndArray();
if (!yellowDays.isEmpty()) {
g.writeStartArray();
for (CollectDay cd : yellowDays) {
g.writeNumber(cd.ordinal());
}
g.writeEndArray();
}
g.writeEndArray();
}
}
if (addresses.size() > 100) {
pm.makePersistentAll(addresses);
addresses.clear();
}
}
g.writeEndArray();
g.writeEndObject();
}
writeChannel.closeFinally();
if (jsonInfo.getBlobKey() != null) {
BlobstoreService blobstoreService =
BlobstoreServiceFactory.getBlobstoreService();
blobstoreService.delete(jsonInfo.getBlobKey());
}
jsonInfo.setBlobKey(fileService.getBlobKey(file));
} finally {
q.closeAll();
}
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query q = pm.newQuery(JSONInfo.class);
try {
FileService fileService = FileServiceFactory.getFileService();
JSONInfo jsonInfo;
List<JSONInfo> results =
(List<JSONInfo>) q.execute();
AppEngineFile file;
if (results.isEmpty()) {
jsonInfo = new JSONInfo();
pm.makePersistent(jsonInfo);
} else {
jsonInfo = results.get(0);
}
file = fileService.createNewBlobFile("text/plain");
boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
JsonFactory f = new JsonFactory();
try (OutputStream os = Channels.newOutputStream(writeChannel);
JsonGenerator g = f.createJsonGenerator(os)) {
g.writeStartObject();
g.writeArrayFieldStart("data");
try (PrintWriter out = response.getWriter()) {
out.println(file.getFullPath());
}
q = pm.newQuery(Address.class);
q.deletePersistentAll();
URL url = new URL(Constants.NOD_DATASET_CSV_URL);
CSVReader reader = new CSVReader(new InputStreamReader(url.openStream(), "UTF-8"));
String[] nextLine;
Collection<Address> addresses = new ArrayList<>();
while ((nextLine = reader.readNext()) != null) {
if (nextLine.length < 13) {
System.err.println("Data import failed.");
System.err.println("Couldn't find 13 fields in the dataset "
+ "which means I don't know what to do.");
return;
} else {
String blue = nextLine[10],
obsCollect = nextLine[12];
if (!blue.isEmpty() && obsCollect.isEmpty()) {
String street = nextLine[1],
obsStreet = nextLine[9],
yellow = nextLine[11];
Set<CollectDay> blueDays = new HashSet<>(),
yellowDays = new HashSet<>();
Boolean singleCollect = false;
if (yellow.isEmpty()) {
singleCollect = true;
}
if (blue.contains("lundi")) {
blueDays.add(CollectDay.MONDAY);
}
if (blue.contains("mardi")) {
blueDays.add(CollectDay.TUESDAY);
}
if (blue.contains("mercredi")) {
blueDays.add(CollectDay.WEDNESDAY);
} else if (blue.contains("merc_sem_impaires")) {
blueDays.add(CollectDay.WEDNESDAY_ODD);
} else if (blue.contains("merc_sem_paires")) {
blueDays.add(CollectDay.WEDNESDAY_EVEN);
}
if (blue.contains("jeudi")) {
blueDays.add(CollectDay.THURSDAY);
}
if (blue.contains("vendredi")) {
blueDays.add(CollectDay.FRIDAY);
}
if (blue.contains("samedi")) {
blueDays.add(CollectDay.SATURDAY);
}
if (blue.contains("dimanche")) {
blueDays.add(CollectDay.SUNDAY);
}
if (yellow.contains("lundi")) {
yellowDays.add(CollectDay.MONDAY);
}
if (yellow.contains("mardi")) {
yellowDays.add(CollectDay.TUESDAY);
}
if (yellow.contains("mercredi")) {
yellowDays.add(CollectDay.WEDNESDAY);
} else if (yellow.contains("merc_sem_impaires")) {
yellowDays.add(CollectDay.WEDNESDAY_ODD);
} else if (yellow.contains("merc_sem_paires")) {
yellowDays.add(CollectDay.WEDNESDAY_EVEN);
}
if (yellow.contains("jeudi")) {
yellowDays.add(CollectDay.THURSDAY);
}
if (yellow.contains("vendredi")) {
yellowDays.add(CollectDay.FRIDAY);
}
if (yellow.contains("samedi")) {
yellowDays.add(CollectDay.SATURDAY);
}
if (yellow.contains("dimanche")) {
yellowDays.add(CollectDay.SUNDAY);
}
Address address = new Address();
street = street + (obsStreet.isEmpty()
? ""
: " " + obsStreet);
address.setStreet(street);
address.setBlueDays(blueDays);
address.setYellowDays(yellowDays);
addresses.add(address);
g.writeStartArray();
g.writeString(street);
g.writeStartArray();
for (CollectDay cd : blueDays) {
g.writeNumber(cd.ordinal());
}
g.writeEndArray();
if (!yellowDays.isEmpty()) {
g.writeStartArray();
for (CollectDay cd : yellowDays) {
g.writeNumber(cd.ordinal());
}
g.writeEndArray();
}
g.writeEndArray();
}
}
if (addresses.size() > 100) {
pm.makePersistentAll(addresses);
addresses.clear();
}
}
g.writeEndArray();
g.writeEndObject();
}
writeChannel.closeFinally();
if (jsonInfo.getBlobKey() != null) {
BlobstoreService blobstoreService =
BlobstoreServiceFactory.getBlobstoreService();
blobstoreService.delete(jsonInfo.getBlobKey());
}
jsonInfo.setBlobKey(fileService.getBlobKey(file));
} finally {
q.closeAll();
}
}
|
diff --git a/src/com/itmill/toolkit/demo/testbench/TestBench.java b/src/com/itmill/toolkit/demo/testbench/TestBench.java
index 15b115a3e..86e8cf40d 100644
--- a/src/com/itmill/toolkit/demo/testbench/TestBench.java
+++ b/src/com/itmill/toolkit/demo/testbench/TestBench.java
@@ -1,204 +1,209 @@
package com.itmill.toolkit.demo.testbench;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import com.itmill.toolkit.Application;
import com.itmill.toolkit.data.Property;
import com.itmill.toolkit.data.util.HierarchicalContainer;
import com.itmill.toolkit.terminal.Sizeable;
import com.itmill.toolkit.ui.Component;
import com.itmill.toolkit.ui.CustomComponent;
import com.itmill.toolkit.ui.ExpandLayout;
import com.itmill.toolkit.ui.Label;
import com.itmill.toolkit.ui.Panel;
import com.itmill.toolkit.ui.SplitPanel;
import com.itmill.toolkit.ui.Tree;
import com.itmill.toolkit.ui.Window;
/**
* TestBench finds out testable classes within given java packages and adds them
* to menu from where they can be executed. Class is considered testable if it
* is of class CustomComponent.
*
* Note: edit TestBench.testablePackages array
*
* @author IT Mill Ltd.
*
*/
public class TestBench extends com.itmill.toolkit.Application implements
Property.ValueChangeListener {
// Add here packages which are used for finding testable classes
String[] testablePackages = { "com.itmill.toolkit.demo.testbench" };
HierarchicalContainer testables = new HierarchicalContainer();
Window mainWindow = new Window("TestBench window");
// Main layout consists of tree menu and body layout
SplitPanel mainLayout = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL);
Tree menu;
Panel bodyLayout = new Panel();
HashMap itemCaptions = new HashMap();
public void init() {
// Add testable classes to hierarchical container
for (int p = 0; p < testablePackages.length; p++) {
testables.addItem(testablePackages[p]);
try {
List testableClasses = getTestableClassesForPackage(testablePackages[p]);
for (Iterator it = testableClasses.iterator(); it.hasNext();) {
Class t = (Class) it.next();
// ignore TestBench itself
if (t.equals(TestBench.class)) {
continue;
}
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
continue;
} catch (Exception e) {
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
continue;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
menu = new Tree("Testables", testables);
- // simplify captions
for (Iterator i = itemCaptions.keySet().iterator(); i.hasNext();) {
Class testable = (Class) i.next();
- menu.setItemCaption(testable, testable.getName());
+ // simplify captions
+ String name = testable.getName().replaceAll("com.itmill.toolkit.",
+ "");
+ menu.setItemCaption(testable, name);
+ // TODO fix #1191
+ System.err.println(name);
+ menu.collapseItem(testable);
}
menu.addListener(this);
menu.setImmediate(true);
mainLayout.addComponent(menu);
bodyLayout.addStyleName("light");
bodyLayout.setHeight(100);
bodyLayout.setHeightUnits(Sizeable.UNITS_PERCENTAGE);
bodyLayout.setLayout(new ExpandLayout());
mainLayout.addComponent(bodyLayout);
mainLayout.setSplitPosition(30);
mainWindow.setLayout(mainLayout);
setMainWindow(mainWindow);
}
private Component createTestable(Class c) {
try {
Application app = (Application) c.newInstance();
app.init();
return app.getMainWindow().getLayout();
} catch (Exception e) {
try {
CustomComponent cc = (CustomComponent) c.newInstance();
return cc;
} catch (Exception e1) {
e1.printStackTrace();
return new Label("Cannot create custom component: "
+ e1.toString());
}
}
}
// Handle menu selection and update body
public void valueChange(Property.ValueChangeEvent event) {
bodyLayout.removeAllComponents();
bodyLayout.setCaption(null);
String title = ((Class) menu.getValue()).getName();
bodyLayout.setCaption(title);
bodyLayout.addComponent(createTestable((Class) menu.getValue()));
}
/**
* Return all testable classes within given package. Class is considered
* testable if it's superclass is CustomComponent.
*
* @param packageName
* @return
* @throws ClassNotFoundException
*/
public static List getTestableClassesForPackage(String packageName)
throws Exception {
ArrayList directories = new ArrayList();
try {
ClassLoader cld = Thread.currentThread().getContextClassLoader();
if (cld == null) {
throw new ClassNotFoundException("Can't get class loader.");
}
String path = packageName.replace('.', '/');
// Ask for all resources for the path
Enumeration resources = cld.getResources(path);
while (resources.hasMoreElements()) {
URL url = (URL) resources.nextElement();
directories.add(new File(url.getFile()));
}
} catch (Exception x) {
throw new Exception(packageName
+ " does not appear to be a valid package.");
}
ArrayList classes = new ArrayList();
// For every directory identified capture all the .class files
for (Iterator it = directories.iterator(); it.hasNext();) {
File directory = (File) it.next();
if (directory.exists()) {
// Get the list of the files contained in the package
String[] files = directory.list();
for (int j = 0; j < files.length; j++) {
// we are only interested in .class files
if (files[j].endsWith(".class")) {
// removes the .class extension
String p = packageName + '.'
+ files[j].substring(0, files[j].length() - 6);
Class c = Class.forName(p);
if (c.getSuperclass() != null) {
// if ((c.getSuperclass()
// .equals(com.itmill.toolkit.Application.class))) {
// classes.add(c);
// } else
if ((c.getSuperclass()
.equals(com.itmill.toolkit.ui.CustomComponent.class))) {
classes.add(c);
}
}
}
}
} else {
throw new ClassNotFoundException(packageName + " ("
+ directory.getPath()
+ ") does not appear to be a valid package");
}
}
return classes;
}
}
| false | true | public void init() {
// Add testable classes to hierarchical container
for (int p = 0; p < testablePackages.length; p++) {
testables.addItem(testablePackages[p]);
try {
List testableClasses = getTestableClassesForPackage(testablePackages[p]);
for (Iterator it = testableClasses.iterator(); it.hasNext();) {
Class t = (Class) it.next();
// ignore TestBench itself
if (t.equals(TestBench.class)) {
continue;
}
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
continue;
} catch (Exception e) {
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
continue;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
menu = new Tree("Testables", testables);
// simplify captions
for (Iterator i = itemCaptions.keySet().iterator(); i.hasNext();) {
Class testable = (Class) i.next();
menu.setItemCaption(testable, testable.getName());
}
menu.addListener(this);
menu.setImmediate(true);
mainLayout.addComponent(menu);
bodyLayout.addStyleName("light");
bodyLayout.setHeight(100);
bodyLayout.setHeightUnits(Sizeable.UNITS_PERCENTAGE);
bodyLayout.setLayout(new ExpandLayout());
mainLayout.addComponent(bodyLayout);
mainLayout.setSplitPosition(30);
mainWindow.setLayout(mainLayout);
setMainWindow(mainWindow);
}
| public void init() {
// Add testable classes to hierarchical container
for (int p = 0; p < testablePackages.length; p++) {
testables.addItem(testablePackages[p]);
try {
List testableClasses = getTestableClassesForPackage(testablePackages[p]);
for (Iterator it = testableClasses.iterator(); it.hasNext();) {
Class t = (Class) it.next();
// ignore TestBench itself
if (t.equals(TestBench.class)) {
continue;
}
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
continue;
} catch (Exception e) {
try {
testables.addItem(t);
itemCaptions.put(t, t.getName());
testables.setParent(t, testablePackages[p]);
continue;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
menu = new Tree("Testables", testables);
for (Iterator i = itemCaptions.keySet().iterator(); i.hasNext();) {
Class testable = (Class) i.next();
// simplify captions
String name = testable.getName().replaceAll("com.itmill.toolkit.",
"");
menu.setItemCaption(testable, name);
// TODO fix #1191
System.err.println(name);
menu.collapseItem(testable);
}
menu.addListener(this);
menu.setImmediate(true);
mainLayout.addComponent(menu);
bodyLayout.addStyleName("light");
bodyLayout.setHeight(100);
bodyLayout.setHeightUnits(Sizeable.UNITS_PERCENTAGE);
bodyLayout.setLayout(new ExpandLayout());
mainLayout.addComponent(bodyLayout);
mainLayout.setSplitPosition(30);
mainWindow.setLayout(mainLayout);
setMainWindow(mainWindow);
}
|
diff --git a/test/test/RunXmlTest.java b/test/test/RunXmlTest.java
index 3ee13c3..c8ad1d8 100644
--- a/test/test/RunXmlTest.java
+++ b/test/test/RunXmlTest.java
@@ -1,53 +1,51 @@
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package test;
import com.google.caliper.MeasurementSet;
import com.google.caliper.Run;
import com.google.caliper.Scenario;
import com.google.caliper.Xml;
import com.google.common.collect.ImmutableMap;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import junit.framework.TestCase;
public class RunXmlTest extends TestCase {
public void testXmlRoundtrip() {
Scenario a15dalvik = new Scenario(ImmutableMap.of(
"foo", "A", "bar", "15", "vm", "dalvikvm"));
Scenario b15dalvik = new Scenario(ImmutableMap.of(
"foo", "B", "bar", "15", "vm", "dalvikvm"));
Run toEncode = new Run(ImmutableMap.of(a15dalvik, new MeasurementSet(1200.1, 1198.8),
- b15dalvik, new MeasurementSet(1100.2, 1110.0)),
- "examples.FooBenchmark", "A0:1F:CAFE:BABE", new Date());
+ b15dalvik, new MeasurementSet(1100.2, 1110.0)), "examples.FooBenchmark", new Date());
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
Xml.runToXml(toEncode, bytesOut);
// we don't validate the XML directly because it's a hassle to cope with arbitrary orderings of
// an element's attributes
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesOut.toByteArray());
Run decoded = Xml.runFromXml(bytesIn);
assertEquals(toEncode.getBenchmarkName(), decoded.getBenchmarkName());
- assertEquals(toEncode.getApiKey(), decoded.getApiKey());
- assertEquals(toEncode.getMeasurements().keySet(), decoded.getMeasurements().keySet());
+ assertEquals(toEncode.getMeasurements().keySet(), decoded.getMeasurements().keySet());
}
}
| false | true | public void testXmlRoundtrip() {
Scenario a15dalvik = new Scenario(ImmutableMap.of(
"foo", "A", "bar", "15", "vm", "dalvikvm"));
Scenario b15dalvik = new Scenario(ImmutableMap.of(
"foo", "B", "bar", "15", "vm", "dalvikvm"));
Run toEncode = new Run(ImmutableMap.of(a15dalvik, new MeasurementSet(1200.1, 1198.8),
b15dalvik, new MeasurementSet(1100.2, 1110.0)),
"examples.FooBenchmark", "A0:1F:CAFE:BABE", new Date());
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
Xml.runToXml(toEncode, bytesOut);
// we don't validate the XML directly because it's a hassle to cope with arbitrary orderings of
// an element's attributes
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesOut.toByteArray());
Run decoded = Xml.runFromXml(bytesIn);
assertEquals(toEncode.getBenchmarkName(), decoded.getBenchmarkName());
assertEquals(toEncode.getApiKey(), decoded.getApiKey());
assertEquals(toEncode.getMeasurements().keySet(), decoded.getMeasurements().keySet());
}
| public void testXmlRoundtrip() {
Scenario a15dalvik = new Scenario(ImmutableMap.of(
"foo", "A", "bar", "15", "vm", "dalvikvm"));
Scenario b15dalvik = new Scenario(ImmutableMap.of(
"foo", "B", "bar", "15", "vm", "dalvikvm"));
Run toEncode = new Run(ImmutableMap.of(a15dalvik, new MeasurementSet(1200.1, 1198.8),
b15dalvik, new MeasurementSet(1100.2, 1110.0)), "examples.FooBenchmark", new Date());
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
Xml.runToXml(toEncode, bytesOut);
// we don't validate the XML directly because it's a hassle to cope with arbitrary orderings of
// an element's attributes
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesOut.toByteArray());
Run decoded = Xml.runFromXml(bytesIn);
assertEquals(toEncode.getBenchmarkName(), decoded.getBenchmarkName());
assertEquals(toEncode.getMeasurements().keySet(), decoded.getMeasurements().keySet());
}
|
diff --git a/src/net/derkholm/nmica/extra/app/ModelScoreEvaluator.java b/src/net/derkholm/nmica/extra/app/ModelScoreEvaluator.java
index 0373378..43e1546 100644
--- a/src/net/derkholm/nmica/extra/app/ModelScoreEvaluator.java
+++ b/src/net/derkholm/nmica/extra/app/ModelScoreEvaluator.java
@@ -1,777 +1,778 @@
package net.derkholm.nmica.extra.app;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import net.derkholm.nmica.apps.ConsensusMotifCreator;
import net.derkholm.nmica.apps.MetaMotifFinder;
import net.derkholm.nmica.build.NMExtraApp;
import net.derkholm.nmica.build.VirtualMachine;
import net.derkholm.nmica.maths.DoubleFunction;
import net.derkholm.nmica.maths.IdentityDoubleFunction;
import net.derkholm.nmica.matrix.Matrix1D;
import net.derkholm.nmica.matrix.Matrix2D;
import net.derkholm.nmica.matrix.MatrixTools;
import net.derkholm.nmica.matrix.ObjectMatrix1D;
import net.derkholm.nmica.matrix.SimpleMatrix2D;
import net.derkholm.nmica.model.ContributionGroup;
import net.derkholm.nmica.model.ContributionItem;
import net.derkholm.nmica.model.Datum;
import net.derkholm.nmica.model.Facette;
import net.derkholm.nmica.model.SimpleContributionGroup;
import net.derkholm.nmica.model.SimpleContributionItem;
import net.derkholm.nmica.model.SimpleDatum;
import net.derkholm.nmica.model.SimpleFacetteMap;
import net.derkholm.nmica.model.SimpleMultiICAModel;
import net.derkholm.nmica.model.metamotif.Dirichlet;
import net.derkholm.nmica.model.metamotif.MetaMotif;
import net.derkholm.nmica.model.metamotif.MetaMotifFacette;
import net.derkholm.nmica.model.metamotif.MetaMotifIOTools;
import net.derkholm.nmica.model.metamotif.NamedMotifSet;
import net.derkholm.nmica.model.metamotif.RingBufferMetaMotif;
import net.derkholm.nmica.model.metamotif.bg.MetaMotifDirichletBackground;
import net.derkholm.nmica.model.motif.Mosaic;
import net.derkholm.nmica.model.motif.MosaicIO;
import net.derkholm.nmica.model.motif.MosaicSequenceBackground;
import net.derkholm.nmica.model.motif.MotifClippedSimplexPrior;
import net.derkholm.nmica.model.motif.MotifFacette;
import net.derkholm.nmica.model.motif.NMWeightMatrix;
import net.derkholm.nmica.model.motif.PosSpecWeightMatrixPrior;
import net.derkholm.nmica.model.motif.SequenceBackground;
import net.derkholm.nmica.motif.Motif;
import net.derkholm.nmica.motif.MotifIOTools;
import net.derkholm.nmica.motif.MotifTools;
import net.derkholm.nmica.seq.NMSimpleDistribution;
import org.biojava.bio.BioException;
import org.biojava.bio.dist.Distribution;
import org.biojava.bio.dp.WeightMatrix;
import org.biojava.bio.seq.DNATools;
import org.biojava.bio.seq.Sequence;
import org.biojava.bio.seq.SequenceIterator;
import org.biojava.bio.seq.db.HashSequenceDB;
import org.biojava.bio.seq.db.IllegalIDException;
import org.biojava.bio.seq.db.SequenceDB;
import org.biojava.bio.seq.io.SeqIOTools;
import org.biojava.bio.symbol.FiniteAlphabet;
import org.biojava.bio.symbol.IllegalAlphabetException;
import org.biojava.bio.symbol.Symbol;
import org.bjv2.util.cli.App;
import org.bjv2.util.cli.ConfigurationException;
import org.bjv2.util.cli.Option;
import org.bjv2.util.cli.UserLevel;
//TODO: Implement in a more generic way (such that it also works with motifs)
@App(overview = "Model evaluator " +
"(used for debugging purposes to " +
"check correctness of likelihood calculations)", generateStub = true)
@NMExtraApp(launchName = "nmeval", vm = VirtualMachine.SERVER)
public class ModelScoreEvaluator {
public static final String OCC_COL_SEPARATOR = ";";
protected MetaMotif[] metaMotifs;
protected Motif[] motifs;
protected File occupancyMatrixFile;
protected File inputDataSet;
protected double bgAlphaSum = 2.5;
protected double uncountedExpectation = 1;
protected boolean revComp = false;
protected double edgePruneThreshold = 0;
protected double pseudoCount;
protected ContributionGroup contribGrp;
private int mixturePermutations = 0;
private int modelShuffles = 0;
private SimpleMultiICAModel model;
private Occupancy<?,?> occ;
private SequenceDB seqs;
private boolean motifModel;
private MosaicSequenceBackground seqBackgroundModel;
private double edgePrune = 0.0;
private int minLength = -1;
private int maxLength = 10;
private int extraLength = 0;
private double minClip = Double.NEGATIVE_INFINITY;
private double maxClip = 1.0;
private boolean dirichletPriorFsSpecified;
private boolean consensusStrsSpecified;
private String[] consensusStrings;
private File[] dirichletPriorFiles;
private double priorPrecision = ConsensusMotifCreator.DEFAULT_ALPHASUM;
private double priorPseudoCount = ConsensusMotifCreator.DEFAULT_PSEUDOCOUNT;
private boolean priorPrecisionOrPseudoCountSpecified = false;
//TODO: Integrate this type of model evaluation into being part of nmmetainfer
//such that you can compare the current likelihood values to those achievable for the correct model
//as a benchmarking mode
@Option(help = "The metamotifs models",
optional = true)
public void setMetaMotifs(File[] files) throws Exception {
this.metaMotifs = MetaMotifIOTools.loadMetaMotifsFromMultipleFiles(files);
}
@Option(help = "The sequences for which model (motif set + occupancy) likelihood is to be evaluated",
optional = true)
public void setSeqs(File file) throws Exception {
this.seqs = loadDB(file, DNATools.getDNA());
}
@Option(help="XMS file with metamotif models to read a column-specific informative prior from " +
"(-consensus can also be used to specify one)", optional=true)
public void setPriorMetaMotifs(File[] f) {
this.dirichletPriorFiles = f;
dirichletPriorFsSpecified = true;
}
@Option(help="Consensus string(s) that will be made to metamotif models", optional=true)
public void setConsensus(String[] strs) {
this.consensusStrings = strs;
}
@Option(help="The Dirichlet prior precision parameter " +
"(used in conjunction with -consensus)", optional=true, userLevel=UserLevel.EXPERT)
public void setPriorPrecision(double d) {
this.priorPrecision = d;
this.priorPrecisionOrPseudoCountSpecified = true;
}
@Option(help="The Dirichlet prior mean pseudocount " +
"(used in conjunction with -consensus)", optional=true, userLevel=UserLevel.EXPERT)
public void setPriorPseudoCount(double d) {
this.priorPseudoCount = d;
this.priorPrecisionOrPseudoCountSpecified = true;
}
@Option(help="The sequence background model to use for likelihood calculation",optional=true)
public void setBackgroundModel(InputStream is)
throws Exception {;
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader r = factory.createXMLStreamReader(is);
Mosaic m = MosaicIO.readMosaic(r);
seqBackgroundModel = new MosaicSequenceBackground(m.getDistributions(), m.getTransition());
}
private SequenceDB loadDB(File file, FiniteAlphabet alphabet)
throws
NoSuchElementException,
BioException,
FileNotFoundException {
SequenceIterator si = SeqIOTools.readFasta(
new BufferedReader(
new FileReader(file)),
alphabet.getTokenization("token"));
SequenceDB seqDB = new HashSequenceDB();
while (si.hasNext()) {
Sequence seq = si.nextSequence();
if (seqDB.ids().contains(seq.getName())) {
throw new IllegalIDException(
"Duplicate sequence name '" + seq.getName() + "'");
}
seqDB.addSequence(seq);
}
return seqDB;
}
public void setMetaMotifs(MetaMotif[] mms) {
this.metaMotifs = mms;
}
@Option(help = "The input dataset to score with the given models",
optional = true)
public void setMotifs(File file) throws Exception {
this.motifs = MotifIOTools.loadMotifSetXML(new FileInputStream(file));
}
@Option(help = "The background alpha parameter " +
"(for an uniform 0th order Dirichlet background)",
optional = true, userLevel = UserLevel.EXPERT)
public void setBgAlphaSum(double d) {
this.bgAlphaSum = d;
}
@Option(help = "Allow motifs to occur in either orientation",
optional = true)
public void setRevComp(boolean b) {
this.revComp = b;
}
@Option(help = "The expected number of motif occurrences per sequence",
userLevel = UserLevel.EXPERT, optional = true)
public void setUncountedExpectation(double i) {
this.uncountedExpectation = i;
}
@Option(help = "Pseudocounts to add to input motifs",
userLevel = UserLevel.EXPERT, optional = true)
public void setPseudoCount(double d) {
this.pseudoCount = d;
}
@Option(help = "The occupancy matrix " +
"(see nmeval -occmatrixformat for help)", optional=true)
public void setOcc(File file) throws Exception {
this.occupancyMatrixFile = file;
}
@Option(help = "Number of mixing matrix permutations to make " +
"(to compare the specified model state against others)",
optional = true)
public void setMixPerms(int i) {
this.mixturePermutations = i;
}
@Option(help = "Number of metamotif model shuffling operations to make " +
"(to compare the specified model state against others)",
optional = true)
public void setShuffles(int i) {
this.modelShuffles = i;
}
public SimpleMultiICAModel makeModel()
throws Exception {
if (!motifModel)
makeAndFillOccupancyMatrix(occupancyMatrixFile);
contribGrp = new SimpleContributionGroup("metamotifs",
MetaMotif.class);
Facette[] facettes;
MotifFacette[] mFacettes;
MetaMotifDirichletBackground mmBackground = null;
DoubleFunction mixTransferFunction = IdentityDoubleFunction.INSTANCE;
//if evaluating sequence--motif model
if (motifModel) {
facettes = mFacettes = new MotifFacette[1];
mFacettes[0] = new MotifFacette(
seqBackgroundModel,
0.0,
true,
true,
revComp,
uncountedExpectation,
false,
edgePrune,
DNATools.getDNA()
);
mFacettes[0].setMixTransferFunction(mixTransferFunction);
}
//if evaluating motif--metamotif model
else {
MetaMotifDirichletBackground background =
new MetaMotifDirichletBackground(bgAlphaSum,DNATools.getDNA());
MetaMotifFacette[] mmFacettes;
facettes = mmFacettes = new MetaMotifFacette[1];
facettes[0] = new MetaMotifFacette(
background,
revComp,
uncountedExpectation,
edgePruneThreshold,
- background.getAlphabet());
+ background.getAlphabet(),
+ maxLength);
mmFacettes[0].setMixTransferFunction(mixTransferFunction);
}
SimpleFacetteMap facetteMap = new SimpleFacetteMap(
new ContributionGroup[] {contribGrp},
facettes);
facetteMap.setContributesToFacette(
contribGrp,
facettes[0],
true);
Datum[] data;
SimpleMultiICAModel model;
//if were're evaluating a sequence--motif model
if (motifModel) {
data = loadSequenceData(
new SequenceDB[] {seqs},
new SequenceBackground[] {seqBackgroundModel});
for (Motif m : motifs) {
MotifTools.addPseudoCounts(m.getWeightMatrix(),pseudoCount);
for (int i = 0; i < m.getWeightMatrix().columns(); i++) {
Distribution distrib = m.getWeightMatrix().getColumn(i);
for (Iterator it = ((FiniteAlphabet) distrib.getAlphabet())
.iterator(); it.hasNext();) {
Symbol sym = (Symbol) it.next();
System.err.printf("%f ", distrib.getWeight(sym));
}
System.err.println();
}
}
model = new SimpleMultiICAModel(facetteMap, data, motifs.length);
for (int i = 0; i < model.getContributions(contribGrp).size(); i++) {
model
.getContributions(contribGrp)
.set(i, new SimpleContributionItem(motifs[i].getWeightMatrix()));
}
for (int i = 0, rows=model.getMixingMatrix().rows(); i < rows; i++) {
for (int j = 0, cols=model.getMixingMatrix().columns(); j < cols; j++) {
model.getMixingMatrix().set(i, j, 1.0);
}
}
}
//if we're evaluating a motif--metamotif model
else {
NamedMotifSet[] motifSets = new NamedMotifSet[1];
motifSets[0] = new NamedMotifSet(motifs, null);
data = MetaMotifFinder.loadData(motifSets);
MetaMotifFinder.addPseudoCounts(data, pseudoCount);
model = new SimpleMultiICAModel(facetteMap, data, metaMotifs.length);
for (int i = 0; i < model.getContributions(contribGrp).size(); i++) {
model
.getContributions(contribGrp)
.set(i, new SimpleContributionItem(metaMotifs[i]));
}
}
if (!motifModel) fillMotifMetaMotifMixingMatrix(model, (Occupancy<Motif,MetaMotif>)occ);
else fillSequenceMotifMixingMatrix(model,(Occupancy<Sequence,Motif>)occ);
/*
if (motifModel) {
Set<String> ids = seqs.ids();
System.err.println("Data length :" + data.length);
System.err.println("First data obj:" + data[0]);
double likelihood = 0;
System.err.println(seqBackgroundModel);
for (int i = 0; i < data.length; i++) {
Datum d = data[i];
System.err.println("Datum facetted data length: " + d.getFacettedData().length);
Sequence seq = (Sequence)d.getFacettedData()[0];
MotifUncountedLikelihood likelihoodCalc =
new MotifUncountedLikelihood(
(MotifFacette)facettes[0], seq);
double thisLikelihood = likelihoodCalc.likelihood(
model.getContributions(contribGrp),
model.getMixture(i));
for (int j = 0; j < model.getMixture(i).size(); j++) {
System.err.printf("%f ", model.getMixture(i).get(j));
}
System.err.println();
System.err.println(thisLikelihood);
likelihood = likelihood + thisLikelihood;
}
System.err.println("man likelihood:" + likelihood);
}
*/
return model;
}
private Datum[] loadSequenceData(
SequenceDB[] seqDBs,
SequenceBackground[] backgroundModels)
throws IllegalIDException, BioException {
Datum[] data;
Set<String> allIds = new HashSet<String>();
for (int s = 0; s < seqDBs.length; ++s) {
allIds.addAll((Set<? extends String>) seqDBs[s].ids());
}
List<Datum> dl = new ArrayList<Datum>();
for (Iterator<String> i = allIds.iterator(); i.hasNext(); ) {
String id = i.next();
Sequence[] datumSeqs = new Sequence[seqDBs.length];
boolean gotDatumSeq = false;
for (int s = 0; s < seqDBs.length; ++s) {
if (seqDBs[s].ids().contains(id)) {
Sequence seq = seqDBs[s].getSequence(id);
int ssOrder = 0;
SequenceBackground ssBg =
backgroundModels.length > 1 ?
backgroundModels[s] : backgroundModels[0];
if (ssBg instanceof MosaicSequenceBackground) {
ssOrder = ((MosaicSequenceBackground) ssBg)
.getBackgroundDistributions()[0].getAlphabet().getAlphabets().size() - 1;
}
datumSeqs[s] = seqDBs[s].getSequence(id);
gotDatumSeq = true;
}
}
if (gotDatumSeq) {
dl.add(new SimpleDatum(id, datumSeqs));
}
}
data = dl.toArray(new Datum[dl.size()]);
return data;
}
//this method is a bridge between the OccupancyMatrix objects
//should really just read the occupancy matrix
private void fillMotifMetaMotifMixingMatrix(
SimpleMultiICAModel model,
Occupancy<Motif, MetaMotif> occMatrix) {
for (Motif motif : occMatrix.dataEntries) {
int mI = occMatrix.indexOfDataEntry(motif);
Set<MetaMotif> mms = occMatrix.getModels(motif);
Matrix1D mixture = model.getMixture(mI);
for (MetaMotif mm : mms) mixture.set(occMatrix.indexOfModel(mm), 1.0);
}
}
//this method is a bridge between the OccupancyMatrix objects
//should really just read the occupancy matrix
private void fillSequenceMotifMixingMatrix(
SimpleMultiICAModel model,
Occupancy<Sequence, Motif> occMatrix) {
for (Sequence motif : occMatrix.dataEntries) {
int mI = occMatrix.indexOfDataEntry(motif);
Set<Motif> mms = occMatrix.getModels(motif);
Matrix1D mixture = model.getMixture(mI);
for (Motif mm : mms) mixture.set(occMatrix.indexOfModel(mm), 1.0);
}
}
public static void printMixingMatrix(SimpleMultiICAModel model) {
for (int i = 0; i < model.getMixingMatrix().rows(); i++) {
for (int j = 0; j < model.getMixingMatrix().columns(); j++) {
System.out.print(model.getMixingMatrix().get(i, j) + " ");
}
System.out.print("\n");
}
}
public SimpleMultiICAModel getModel() {
return model;
}
public void main(String[] args) throws Exception {
if (seqs != null && motifs != null) {
motifModel = true;
} else if (motifs != null && metaMotifs != null) {
motifModel = false;
}
if (seqs != null && metaMotifs != null) {
System.err.println("Specify either -seqs or -metaMotifs, not both");
System.exit(1);
}
if (consensusStrsSpecified && dirichletPriorFsSpecified)
throw new ConfigurationException(
"Define either -consensus or -dirichletPrior, not both");
RingBufferMetaMotif[] priorMetamotifs = null;
if (consensusStrsSpecified) {
System.err.println("Consensus strings specified");
priorMetamotifs =
(RingBufferMetaMotif[])
toRingBufferMetaMotifs(ConsensusMotifCreator.consensusToMetamotifs(
consensusStrings,
priorPseudoCount,
priorPrecision,
DNATools.getDNA()));
} else if (dirichletPriorFsSpecified) {
System.err.println("Dirichlet prior specified");
if (this.priorPrecisionOrPseudoCountSpecified) {
System.err.println(
"Prior precision or pseudocount were specified " +
"(either motifset file loaded as metamotifs with " +
"fixed per-column precisions, " +
"or metamotif-specific precision overriden)");
priorMetamotifs =
(RingBufferMetaMotif[])
toRingBufferMetaMotifs(MetaMotifIOTools
.loadMetaMotifsFromMultipleFiles(
dirichletPriorFiles,
this.priorPseudoCount,
this.priorPrecision));
System.err.printf("pseudocount: %f precision: %f%n",
priorPseudoCount, priorPrecision );
for (MetaMotif mm : priorMetamotifs) {
for (int i=0,cols=mm.columns(); i < cols; i++) {
Dirichlet dir = mm.getColumn(i);
for (Iterator it = ((FiniteAlphabet) dir
.getAlphabet()).iterator(); it.hasNext();) {
Symbol sym = (Symbol) it.next();
System.err.printf("%f ",dir.getWeight(sym));
}
}
System.err.println();
}
} else {
System.err.println("Metamotif prior specified (no pseudocount specified or precision overrides)");
//this XMS file should contain correctly annotated metamotifs
priorMetamotifs = (RingBufferMetaMotif[]) toRingBufferMetaMotifs(MetaMotifIOTools
.loadMetaMotifsFromMultipleFiles(dirichletPriorFiles));
}
}
System.err.println("Prior metamotifs: "+priorMetamotifs);
model = makeModel();
System.out.printf("likelihood %f%n", model.likelihood());
MotifClippedSimplexPrior uninfoPrior =
new MotifClippedSimplexPrior(
DNATools.getDNA(),
minLength, maxLength, maxLength + extraLength, minClip, maxClip);
PosSpecWeightMatrixPrior pswmpPrior =
new PosSpecWeightMatrixPrior
(DNATools.getDNA(),
minLength,
maxLength,
maxLength + extraLength,
priorMetamotifs);
ObjectMatrix1D<?> contribs = model.getContributions(contribGrp);
double accumProbability = 0;
for (int i = 0; i < contribs.size(); i++) {
ContributionItem nwmItem = (ContributionItem) contribs.get(i);
WeightMatrix wm = (WeightMatrix)nwmItem.getItem();
NMWeightMatrix nwm = wmtoNWM(wm, wm.columns(), 0);
double uninfoLogProbability = uninfoPrior.probability(nwm);
double infoLogProbability = pswmpPrior.probability(nwm);
System.err.printf("motif%d prior %f %f%n",i,uninfoLogProbability, infoLogProbability);
accumProbability = accumProbability + uninfoLogProbability;
}
if (mixturePermutations > 0) {
//System.out.println("Likelihoods after mixing matrix permutations:");
//double[] likelihoods = new double[mixturePermutations];
for (int i=0; i < mixturePermutations; i++) {
SimpleMultiICAModel permutedModel = permuteMixture(model);
//likelihoods[i] = permutedModel.likelihood();
System.err.println(permutedModel.likelihood());
}
}
if (modelShuffles > 0) {
System.out.println("Shuffled likelihoods:");
double[] likelihoods = new double[modelShuffles];
for (int i=0;i < modelShuffles; i++) {
SimpleMultiICAModel shuffledModel = shuffleMetaMotifs(model);
likelihoods[i] = shuffledModel.likelihood();
}
}
}
private NMWeightMatrix
wmtoNWM(WeightMatrix wm, int cols, int offset)
throws IllegalAlphabetException {
NMSimpleDistribution[] dists
= new NMSimpleDistribution[cols + extraLength];
//System.err.printf("cols: %d wm.columns(): %d %n",cols,wm.columns());
for (int i = 0,len=wm.columns(); i < len; i++) {
dists[i] = new NMSimpleDistribution(wm.getColumn(i));
}
return new NMWeightMatrix(dists, cols, offset);
}
//TODO: Implement
private SimpleMultiICAModel shuffleMetaMotifs(SimpleMultiICAModel model) {
SimpleMultiICAModel shuffledModel = new SimpleMultiICAModel(model);
net.derkholm.nmica.matrix.ObjectMatrix1D contribs = shuffledModel.getContributions(contribGrp);
for (int i = 0; i < shuffledModel.getComponents(); i++) {
ContributionItem contribItem = (ContributionItem)contribs.get(i);
}
return shuffledModel;
}
private static List<Integer> fromTo(int from, int to) {
List<Integer> ints = new ArrayList<Integer>(to -from + 1);
for (int i = from; i <= to; i++)
ints.add(i);
return ints;
}
private Matrix1D reorder(Matrix1D matrix, List<Integer> is) {
double[] ds = matrix.getRaw().clone();
for (int i = 0; i < is.size(); i++)
matrix.set(is.get(i), ds[i]);
return matrix;
}
//hack.hack.hack.
//TODO: Check row and column indices...
private SimpleMultiICAModel permuteMixture(SimpleMultiICAModel model) {
Matrix2D mixtMatrixCopy = new SimpleMatrix2D(model.getMixingMatrix());
for (int j = 0; j < metaMotifs.length; j++) {
List<Integer> ints = fromTo(0, motifs.length - 1); //s
Collections.shuffle(ints);
for (int k=0; k < ints.size(); k++) {
mixtMatrixCopy.set(j, k, model.getMixingMatrix().get(j, ints.get(k)));
}
}
SimpleMultiICAModel permutedModel = new SimpleMultiICAModel(model);
MatrixTools.copy(permutedModel.getMixingMatrix(), mixtMatrixCopy);
return permutedModel;
}
public Occupancy<?,?> makeAndFillOccupancyMatrix(
File occupancyMatrixFile) throws FileNotFoundException,
IOException {
BufferedReader reader = new BufferedReader(new FileReader(occupancyMatrixFile));
Occupancy<Object,Object> occMatrix = new Occupancy<Object,Object>(motifs, metaMotifs);
String line = null;
int i = 0;
while ((line = reader.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(line, OCC_COL_SEPARATOR);
while (tokenizer.hasMoreTokens()) {
String str = tokenizer.nextToken();
int index = Integer.parseInt(str);
if (index < 0 || index >= motifs.length)
throw new IllegalArgumentException(
"The input file contains an invalid index: " + index);
occMatrix.addModel((Object)metaMotifs[index], i);
}
i++;
}
if (i != motifs.length)
throw new IllegalArgumentException(
"The input file does not contain " +
"the correct number of rows (one per input metamotif)");
return occMatrix;
}
private static RingBufferMetaMotif[] toRingBufferMetaMotifs(MetaMotif[] metamotifs) {
RingBufferMetaMotif[] rbs = new RingBufferMetaMotif[metamotifs.length];
for (int i = 0; i < rbs.length; i++) {
rbs[i] = new RingBufferMetaMotif(metamotifs[i]);
}
return rbs;
}
public class Occupancy<DataType,ModelType> {
private ModelType[] models;
private DataType[] dataEntries;
private HashMap<DataType, Set<ModelType>>
modelsByData = new HashMap<DataType, Set<ModelType>>();
private HashMap<ModelType, Set<DataType>>
dataByModels = new HashMap<ModelType, Set<DataType>>();
public Set<ModelType> getModels(DataType m) {
return modelsByData.get(m);
}
public Set<DataType> getDataEntries(ModelType mm) {
return dataByModels.get(mm);
}
public Occupancy(DataType[] motifs, ModelType[] metaMotifs) {
this.dataEntries = motifs;
this.models = metaMotifs;
for (DataType m : motifs)
modelsByData.put(m, new HashSet<ModelType>());
for (ModelType mm : metaMotifs)
dataByModels.put(mm, new HashSet<DataType>());
}
public ModelType[] getModels() {
return models;
}
public DataType[] getDataEntries() {
return dataEntries;
}
public void addModel(ModelType mm, int[] indices) {
for (int i : indices)
addModel(mm, i);
}
private void addModel(ModelType mm, int i) {
if (i >= 0 && i < dataEntries.length) {
DataType m = dataEntries[i];
modelsByData.get(m).add(mm);
dataByModels.get(mm).add(m);
} else throw new IllegalArgumentException("Invalid index " + i);
}
public boolean isPresent(ModelType mm, DataType m) {
return dataByModels.get(mm).contains(m);
}
public boolean isPresent(ModelType mm, int i) {
return dataByModels.get(mm).contains(dataEntries[i]);
}
public boolean isPresent(int i, int j) {
return dataByModels.get(models[i]).contains(dataEntries[i]);
}
public boolean isPresent(int i, DataType m) {
return dataByModels.get(models[i]).contains(m);
}
public int indexOfModel(ModelType mm) {
for (int i = 0; i < models.length; i++)
if (mm == models[i]) return i;
return -1;
}
public int indexOfDataEntry(DataType mm) {
for (int i = 0; i < dataEntries.length; i++)
if (mm == dataEntries[i]) return i;
return -1;
}
}
}
| true | true | public SimpleMultiICAModel makeModel()
throws Exception {
if (!motifModel)
makeAndFillOccupancyMatrix(occupancyMatrixFile);
contribGrp = new SimpleContributionGroup("metamotifs",
MetaMotif.class);
Facette[] facettes;
MotifFacette[] mFacettes;
MetaMotifDirichletBackground mmBackground = null;
DoubleFunction mixTransferFunction = IdentityDoubleFunction.INSTANCE;
//if evaluating sequence--motif model
if (motifModel) {
facettes = mFacettes = new MotifFacette[1];
mFacettes[0] = new MotifFacette(
seqBackgroundModel,
0.0,
true,
true,
revComp,
uncountedExpectation,
false,
edgePrune,
DNATools.getDNA()
);
mFacettes[0].setMixTransferFunction(mixTransferFunction);
}
//if evaluating motif--metamotif model
else {
MetaMotifDirichletBackground background =
new MetaMotifDirichletBackground(bgAlphaSum,DNATools.getDNA());
MetaMotifFacette[] mmFacettes;
facettes = mmFacettes = new MetaMotifFacette[1];
facettes[0] = new MetaMotifFacette(
background,
revComp,
uncountedExpectation,
edgePruneThreshold,
background.getAlphabet());
mmFacettes[0].setMixTransferFunction(mixTransferFunction);
}
SimpleFacetteMap facetteMap = new SimpleFacetteMap(
new ContributionGroup[] {contribGrp},
facettes);
facetteMap.setContributesToFacette(
contribGrp,
facettes[0],
true);
Datum[] data;
SimpleMultiICAModel model;
//if were're evaluating a sequence--motif model
if (motifModel) {
data = loadSequenceData(
new SequenceDB[] {seqs},
new SequenceBackground[] {seqBackgroundModel});
for (Motif m : motifs) {
MotifTools.addPseudoCounts(m.getWeightMatrix(),pseudoCount);
for (int i = 0; i < m.getWeightMatrix().columns(); i++) {
Distribution distrib = m.getWeightMatrix().getColumn(i);
for (Iterator it = ((FiniteAlphabet) distrib.getAlphabet())
.iterator(); it.hasNext();) {
Symbol sym = (Symbol) it.next();
System.err.printf("%f ", distrib.getWeight(sym));
}
System.err.println();
}
}
model = new SimpleMultiICAModel(facetteMap, data, motifs.length);
for (int i = 0; i < model.getContributions(contribGrp).size(); i++) {
model
.getContributions(contribGrp)
.set(i, new SimpleContributionItem(motifs[i].getWeightMatrix()));
}
for (int i = 0, rows=model.getMixingMatrix().rows(); i < rows; i++) {
for (int j = 0, cols=model.getMixingMatrix().columns(); j < cols; j++) {
model.getMixingMatrix().set(i, j, 1.0);
}
}
}
//if we're evaluating a motif--metamotif model
else {
NamedMotifSet[] motifSets = new NamedMotifSet[1];
motifSets[0] = new NamedMotifSet(motifs, null);
data = MetaMotifFinder.loadData(motifSets);
MetaMotifFinder.addPseudoCounts(data, pseudoCount);
model = new SimpleMultiICAModel(facetteMap, data, metaMotifs.length);
for (int i = 0; i < model.getContributions(contribGrp).size(); i++) {
model
.getContributions(contribGrp)
.set(i, new SimpleContributionItem(metaMotifs[i]));
}
}
if (!motifModel) fillMotifMetaMotifMixingMatrix(model, (Occupancy<Motif,MetaMotif>)occ);
else fillSequenceMotifMixingMatrix(model,(Occupancy<Sequence,Motif>)occ);
/*
if (motifModel) {
Set<String> ids = seqs.ids();
System.err.println("Data length :" + data.length);
System.err.println("First data obj:" + data[0]);
double likelihood = 0;
System.err.println(seqBackgroundModel);
for (int i = 0; i < data.length; i++) {
Datum d = data[i];
System.err.println("Datum facetted data length: " + d.getFacettedData().length);
Sequence seq = (Sequence)d.getFacettedData()[0];
MotifUncountedLikelihood likelihoodCalc =
new MotifUncountedLikelihood(
(MotifFacette)facettes[0], seq);
double thisLikelihood = likelihoodCalc.likelihood(
model.getContributions(contribGrp),
model.getMixture(i));
for (int j = 0; j < model.getMixture(i).size(); j++) {
System.err.printf("%f ", model.getMixture(i).get(j));
}
System.err.println();
System.err.println(thisLikelihood);
likelihood = likelihood + thisLikelihood;
}
System.err.println("man likelihood:" + likelihood);
}
*/
return model;
}
| public SimpleMultiICAModel makeModel()
throws Exception {
if (!motifModel)
makeAndFillOccupancyMatrix(occupancyMatrixFile);
contribGrp = new SimpleContributionGroup("metamotifs",
MetaMotif.class);
Facette[] facettes;
MotifFacette[] mFacettes;
MetaMotifDirichletBackground mmBackground = null;
DoubleFunction mixTransferFunction = IdentityDoubleFunction.INSTANCE;
//if evaluating sequence--motif model
if (motifModel) {
facettes = mFacettes = new MotifFacette[1];
mFacettes[0] = new MotifFacette(
seqBackgroundModel,
0.0,
true,
true,
revComp,
uncountedExpectation,
false,
edgePrune,
DNATools.getDNA()
);
mFacettes[0].setMixTransferFunction(mixTransferFunction);
}
//if evaluating motif--metamotif model
else {
MetaMotifDirichletBackground background =
new MetaMotifDirichletBackground(bgAlphaSum,DNATools.getDNA());
MetaMotifFacette[] mmFacettes;
facettes = mmFacettes = new MetaMotifFacette[1];
facettes[0] = new MetaMotifFacette(
background,
revComp,
uncountedExpectation,
edgePruneThreshold,
background.getAlphabet(),
maxLength);
mmFacettes[0].setMixTransferFunction(mixTransferFunction);
}
SimpleFacetteMap facetteMap = new SimpleFacetteMap(
new ContributionGroup[] {contribGrp},
facettes);
facetteMap.setContributesToFacette(
contribGrp,
facettes[0],
true);
Datum[] data;
SimpleMultiICAModel model;
//if were're evaluating a sequence--motif model
if (motifModel) {
data = loadSequenceData(
new SequenceDB[] {seqs},
new SequenceBackground[] {seqBackgroundModel});
for (Motif m : motifs) {
MotifTools.addPseudoCounts(m.getWeightMatrix(),pseudoCount);
for (int i = 0; i < m.getWeightMatrix().columns(); i++) {
Distribution distrib = m.getWeightMatrix().getColumn(i);
for (Iterator it = ((FiniteAlphabet) distrib.getAlphabet())
.iterator(); it.hasNext();) {
Symbol sym = (Symbol) it.next();
System.err.printf("%f ", distrib.getWeight(sym));
}
System.err.println();
}
}
model = new SimpleMultiICAModel(facetteMap, data, motifs.length);
for (int i = 0; i < model.getContributions(contribGrp).size(); i++) {
model
.getContributions(contribGrp)
.set(i, new SimpleContributionItem(motifs[i].getWeightMatrix()));
}
for (int i = 0, rows=model.getMixingMatrix().rows(); i < rows; i++) {
for (int j = 0, cols=model.getMixingMatrix().columns(); j < cols; j++) {
model.getMixingMatrix().set(i, j, 1.0);
}
}
}
//if we're evaluating a motif--metamotif model
else {
NamedMotifSet[] motifSets = new NamedMotifSet[1];
motifSets[0] = new NamedMotifSet(motifs, null);
data = MetaMotifFinder.loadData(motifSets);
MetaMotifFinder.addPseudoCounts(data, pseudoCount);
model = new SimpleMultiICAModel(facetteMap, data, metaMotifs.length);
for (int i = 0; i < model.getContributions(contribGrp).size(); i++) {
model
.getContributions(contribGrp)
.set(i, new SimpleContributionItem(metaMotifs[i]));
}
}
if (!motifModel) fillMotifMetaMotifMixingMatrix(model, (Occupancy<Motif,MetaMotif>)occ);
else fillSequenceMotifMixingMatrix(model,(Occupancy<Sequence,Motif>)occ);
/*
if (motifModel) {
Set<String> ids = seqs.ids();
System.err.println("Data length :" + data.length);
System.err.println("First data obj:" + data[0]);
double likelihood = 0;
System.err.println(seqBackgroundModel);
for (int i = 0; i < data.length; i++) {
Datum d = data[i];
System.err.println("Datum facetted data length: " + d.getFacettedData().length);
Sequence seq = (Sequence)d.getFacettedData()[0];
MotifUncountedLikelihood likelihoodCalc =
new MotifUncountedLikelihood(
(MotifFacette)facettes[0], seq);
double thisLikelihood = likelihoodCalc.likelihood(
model.getContributions(contribGrp),
model.getMixture(i));
for (int j = 0; j < model.getMixture(i).size(); j++) {
System.err.printf("%f ", model.getMixture(i).get(j));
}
System.err.println();
System.err.println(thisLikelihood);
likelihood = likelihood + thisLikelihood;
}
System.err.println("man likelihood:" + likelihood);
}
*/
return model;
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/EnqueueMediatorSerializer.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/EnqueueMediatorSerializer.java
index 682b92cec..3b4f1e590 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/EnqueueMediatorSerializer.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/EnqueueMediatorSerializer.java
@@ -1,65 +1,63 @@
/*
* 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.synapse.config.xml;
import org.apache.axiom.om.OMElement;
import org.apache.synapse.Mediator;
import org.apache.synapse.mediators.builtin.EnqueueMediator;
public class EnqueueMediatorSerializer extends AbstractMediatorSerializer{
public OMElement serializeMediator(OMElement parent, Mediator m) {
assert m instanceof EnqueueMediator :
"Unsupported mediator passed in for serialization : " + m.getType();
EnqueueMediator mediator = (EnqueueMediator) m;
OMElement enqueue = fac.createOMElement("enqueue", synNS);
saveTracingState(enqueue, mediator);
if (mediator.getExecutorName() != null) {
enqueue.addAttribute(fac.createOMAttribute(
"executor", nullNS, mediator.getExecutorName()));
} else {
handleException("Invalid enqueue mediator. queue is required");
}
if (mediator.getSequenceName() != null) {
enqueue.addAttribute(fac.createOMAttribute(
"sequence", nullNS, mediator.getSequenceName()));
} else {
handleException("Invalid enqueue mediator. sequence is required");
}
- if (mediator.getPriority() != 1) {
- enqueue.addAttribute(fac.createOMAttribute(
- "priority", nullNS, mediator.getPriority() + ""));
- }
+ enqueue.addAttribute(fac.createOMAttribute(
+ "priority", nullNS, mediator.getPriority() + ""));
if (parent != null) {
parent.addChild(enqueue);
}
return enqueue;
}
public String getMediatorClassName() {
return EnqueueMediator.class.getName();
}
}
| true | true | public OMElement serializeMediator(OMElement parent, Mediator m) {
assert m instanceof EnqueueMediator :
"Unsupported mediator passed in for serialization : " + m.getType();
EnqueueMediator mediator = (EnqueueMediator) m;
OMElement enqueue = fac.createOMElement("enqueue", synNS);
saveTracingState(enqueue, mediator);
if (mediator.getExecutorName() != null) {
enqueue.addAttribute(fac.createOMAttribute(
"executor", nullNS, mediator.getExecutorName()));
} else {
handleException("Invalid enqueue mediator. queue is required");
}
if (mediator.getSequenceName() != null) {
enqueue.addAttribute(fac.createOMAttribute(
"sequence", nullNS, mediator.getSequenceName()));
} else {
handleException("Invalid enqueue mediator. sequence is required");
}
if (mediator.getPriority() != 1) {
enqueue.addAttribute(fac.createOMAttribute(
"priority", nullNS, mediator.getPriority() + ""));
}
if (parent != null) {
parent.addChild(enqueue);
}
return enqueue;
}
| public OMElement serializeMediator(OMElement parent, Mediator m) {
assert m instanceof EnqueueMediator :
"Unsupported mediator passed in for serialization : " + m.getType();
EnqueueMediator mediator = (EnqueueMediator) m;
OMElement enqueue = fac.createOMElement("enqueue", synNS);
saveTracingState(enqueue, mediator);
if (mediator.getExecutorName() != null) {
enqueue.addAttribute(fac.createOMAttribute(
"executor", nullNS, mediator.getExecutorName()));
} else {
handleException("Invalid enqueue mediator. queue is required");
}
if (mediator.getSequenceName() != null) {
enqueue.addAttribute(fac.createOMAttribute(
"sequence", nullNS, mediator.getSequenceName()));
} else {
handleException("Invalid enqueue mediator. sequence is required");
}
enqueue.addAttribute(fac.createOMAttribute(
"priority", nullNS, mediator.getPriority() + ""));
if (parent != null) {
parent.addChild(enqueue);
}
return enqueue;
}
|
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java b/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java
index f07bf0de9..e8c38bbb8 100755
--- a/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java
+++ b/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java
@@ -1,1461 +1,1462 @@
/*
* 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.codegen;
import static com.sun.tools.javac.code.Flags.FINAL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.antlr.runtime.Token;
import com.redhat.ceylon.compiler.java.loader.CeylonModelLoader;
import com.redhat.ceylon.compiler.java.loader.TypeFactory;
import com.redhat.ceylon.compiler.java.tools.CeylonLog;
import com.redhat.ceylon.compiler.java.util.Decl;
import com.redhat.ceylon.compiler.java.util.Util;
import com.redhat.ceylon.compiler.loader.ModelLoader.DeclarationType;
import com.redhat.ceylon.compiler.typechecker.model.Annotation;
import com.redhat.ceylon.compiler.typechecker.model.BottomType;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.ModuleImport;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.Factory;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.JCTree.LetExpr;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Position;
import com.sun.tools.javac.util.Position.LineMap;
/**
* Base class for all delegating transformers
*/
public abstract class AbstractTransformer implements Transformation {
private Context context;
private TreeMaker make;
private Name.Table names;
private Symtab syms;
private CeylonModelLoader loader;
private TypeFactory typeFact;
protected Log log;
public AbstractTransformer(Context context) {
this.context = context;
make = TreeMaker.instance(context);
names = Name.Table.instance(context);
syms = Symtab.instance(context);
loader = CeylonModelLoader.instance(context);
typeFact = TypeFactory.instance(context);
log = CeylonLog.instance(context);
}
public Context getContext() {
return context;
}
@Override
public TreeMaker make() {
return make;
}
private static JavaPositionsRetriever javaPositionsRetriever = null;
public static void trackNodePositions(JavaPositionsRetriever positionsRetriever) {
javaPositionsRetriever = positionsRetriever;
}
@Override
public Factory at(Node node) {
if (node == null) {
make.at(Position.NOPOS);
}
else {
Token token = node.getToken();
if (token != null) {
int tokenStartPosition = getMap().getStartPosition(token.getLine()) + token.getCharPositionInLine();
make().at(tokenStartPosition);
if (javaPositionsRetriever != null) {
javaPositionsRetriever.addCeylonNode(tokenStartPosition, node);
}
}
}
return make();
}
@Override
public Symtab syms() {
return syms;
}
@Override
public Name.Table names() {
return names;
}
@Override
public CeylonModelLoader loader() {
return loader;
}
@Override
public TypeFactory typeFact() {
return typeFact;
}
public void setMap(LineMap map) {
gen().setMap(map);
}
protected LineMap getMap() {
return gen().getMap();
}
@Override
public CeylonTransformer gen() {
return CeylonTransformer.getInstance(context);
}
@Override
public ExpressionTransformer expressionGen() {
return ExpressionTransformer.getInstance(context);
}
@Override
public StatementTransformer statementGen() {
return StatementTransformer.getInstance(context);
}
@Override
public ClassTransformer classGen() {
return ClassTransformer.getInstance(context);
}
/**
* Makes an <strong>unquoted</strong> simple identifier
* @param ident The identifier
* @return The ident
*/
protected JCExpression makeUnquotedIdent(String ident) {
return make().Ident(names().fromString(ident));
}
/**
* Makes an <strong>quoted</strong> simple identifier
* @param ident The identifier
* @return The ident
*/
protected JCIdent makeQuotedIdent(String ident) {
return make().Ident(names().fromString(Util.quoteIfJavaKeyword(ident)));
}
/**
* Makes an <strong>unquoted</strong> qualified (compound) identifier from
* the given qualified name.
* @param qualifiedName The qualified name
* @see #makeQuotedQualIdentFromString(String)
*/
protected JCExpression makeQualIdentFromString(String qualifiedName) {
return makeQualIdent(null, qualifiedName.split("\\."));
}
/**
* Makes a <strong>quoted</strong> qualified (compound) identifier from
* the given qualified name. Each part of the name will be
* quoted if it is a Java keyword.
* @param qualifiedName The qualified name
*/
protected JCExpression makeQuotedQualIdentFromString(String qualifiedName) {
return makeQualIdent(null, Util.quoteJavaKeywords(qualifiedName.split("\\.")));
}
/**
* Makes an <strong>unquoted</strong> qualified (compound) identifier
* from the given qualified name components
* @param components The components of the name.
* @see #makeQuotedQualIdentFromString(String)
*/
protected JCExpression makeQualIdent(Iterable<String> components) {
JCExpression type = null;
for (String component : components) {
if (type == null)
type = makeUnquotedIdent(component);
else
type = makeSelect(type, component);
}
return type;
}
protected JCExpression makeQuotedQualIdent(Iterable<String> components) {
JCExpression type = null;
for (String component : components) {
if (type == null)
type = makeQuotedIdent(component);
else
type = makeSelect(type, Util.quoteIfJavaKeyword(component));
}
return type;
}
/**
* Makes an <strong>unquoted</strong> qualified (compound) identifier
* from the given qualified name components
* @param expr A starting expression (may be null)
* @param names The components of the name (may be null)
* @see #makeQuotedQualIdentFromString(String)
*/
protected JCExpression makeQualIdent(JCExpression expr, String... names) {
if (names != null) {
for (String component : names) {
if (component != null) {
if (expr == null) {
expr = makeUnquotedIdent(component);
} else {
expr = makeSelect(expr, component);
}
}
}
}
return expr;
}
protected JCExpression makeQuotedQualIdent(JCExpression expr, String... names) {
if (names != null) {
for (String component : names) {
if (component != null) {
if (expr == null) {
expr = makeQuotedIdent(component);
} else {
expr = makeSelect(expr, Util.quoteIfJavaKeyword(component));
}
}
}
}
return expr;
}
protected JCExpression makeFQIdent(String... components) {
return makeQualIdent(makeUnquotedIdent(""), components);
}
protected JCExpression makeQuotedFQIdent(String... components) {
return makeQuotedQualIdent(makeUnquotedIdent(""), components);
}
protected JCExpression makeQuotedFQIdent(String qualifiedName) {
return makeQuotedFQIdent(Util.quoteJavaKeywords(qualifiedName.split("\\.")));
}
protected JCExpression makeIdent(Type type) {
return make().QualIdent(type.tsym);
}
/**
* Makes a <strong>unquoted</strong> field access
* @param s1 The base expression
* @param s2 The field to access
* @return The field access
*/
protected JCFieldAccess makeSelect(JCExpression s1, String s2) {
return make().Select(s1, names().fromString(s2));
}
/**
* Makes a <strong>unquoted</strong> field access
* @param s1 The base expression
* @param s2 The field to access
* @return The field access
*/
protected JCFieldAccess makeSelect(String s1, String s2) {
return makeSelect(makeUnquotedIdent(s1), s2);
}
/**
* Makes a sequence of <strong>unquoted</strong> field accesses
* @param s1 The base expression
* @param s2 The first field to access
* @param rest The remaining fields to access
* @return The field access
*/
protected JCFieldAccess makeSelect(String s1, String s2, String... rest) {
return makeSelect(makeSelect(s1, s2), rest);
}
private JCFieldAccess makeSelect(JCFieldAccess s1, String[] rest) {
JCFieldAccess acc = s1;
for (String s : rest) {
acc = makeSelect(acc, s);
}
return acc;
}
protected JCLiteral makeNull() {
return make().Literal(TypeTags.BOT, null);
}
protected JCExpression makeInteger(int i) {
return make().Literal(Integer.valueOf(i));
}
protected JCExpression makeLong(long i) {
return make().Literal(Long.valueOf(i));
}
protected JCExpression makeBoolean(boolean b) {
JCExpression expr;
if (b) {
expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(1));
} else {
expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(0));
}
return expr;
}
// Creates a "foo foo = new foo();"
protected JCTree.JCVariableDecl makeLocalIdentityInstance(String varName, boolean isShared) {
JCExpression name = makeQuotedIdent(varName);
JCExpression initValue = makeNewClass(varName, false);
List<JCAnnotation> annots = List.<JCAnnotation>nil();
int modifiers = isShared ? 0 : FINAL;
JCTree.JCVariableDecl var = make().VarDef(
make().Modifiers(modifiers, annots),
names().fromString(varName),
name,
initValue);
return var;
}
// Creates a "new foo();"
protected JCTree.JCNewClass makeNewClass(String className, boolean fullyQualified) {
return makeNewClass(className, List.<JCTree.JCExpression>nil(), fullyQualified);
}
// Creates a "new foo(arg1, arg2, ...);"
protected JCTree.JCNewClass makeNewClass(String className, List<JCTree.JCExpression> args, boolean fullyQualified) {
JCExpression name = fullyQualified ? makeQuotedFQIdent(className) : makeQuotedQualIdentFromString(className);
return makeNewClass(name, args);
}
// Creates a "new foo(arg1, arg2, ...);"
protected JCTree.JCNewClass makeNewClass(JCExpression clazz, List<JCTree.JCExpression> args) {
return make().NewClass(null, null, clazz, args, null);
}
protected JCVariableDecl makeVar(String varName, JCExpression typeExpr, JCExpression valueExpr) {
return make().VarDef(make().Modifiers(0), names().fromString(varName), typeExpr, valueExpr);
}
// Creates a "( let var1=expr1,var2=expr2,...,varN=exprN in varN; )"
// or a "( let var1=expr1,var2=expr2,...,varN=exprN,exprO in exprO; )"
protected JCExpression makeLetExpr(JCExpression... args) {
return makeLetExpr(tempName(), null, args);
}
// Creates a "( let var1=expr1,var2=expr2,...,varN=exprN in statements; varN; )"
// or a "( let var1=expr1,var2=expr2,...,varN=exprN,exprO in statements; exprO; )"
protected JCExpression makeLetExpr(String varBaseName, List<JCStatement> statements, JCExpression... args) {
String varName = null;
List<JCVariableDecl> decls = List.nil();
int i;
for (i = 0; (i + 1) < args.length; i += 2) {
JCExpression typeExpr = args[i];
JCExpression valueExpr = args[i+1];
varName = varBaseName + ((args.length > 3) ? "$" + i : "");
JCVariableDecl varDecl = makeVar(varName, typeExpr, valueExpr);
decls = decls.append(varDecl);
}
JCExpression result;
if (i == args.length) {
result = makeUnquotedIdent(varName);
} else {
result = args[i];
}
if (statements != null) {
return make().LetExpr(decls, statements, result);
} else {
return make().LetExpr(decls, result);
}
}
/*
* Methods for making unique temporary and alias names
*/
static class UniqueId {
private long id = 0;
private long nextId() {
return id++;
}
}
private long nextUniqueId() {
UniqueId id = context.get(UniqueId.class);
if (id == null) {
id = new UniqueId();
context.put(UniqueId.class, id);
}
return id.nextId();
}
protected String tempName() {
String result = "$ceylontmp" + nextUniqueId();
return result;
}
protected String tempName(String prefix) {
String result = "$ceylontmp" + prefix + nextUniqueId();
return result;
}
protected String aliasName(String name) {
String result = "$" + name + "$" + nextUniqueId();
return result;
}
/*
* Type handling
*/
boolean isBooleanTrue(Declaration decl) {
return decl == loader().getDeclaration("ceylon.language.$true", DeclarationType.VALUE);
}
boolean isBooleanFalse(Declaration decl) {
return decl == loader().getDeclaration("ceylon.language.$false", DeclarationType.VALUE);
}
// A type is optional when it is a union of Nothing|Type...
protected boolean isOptional(ProducedType type) {
return typeFact().isOptionalType(type);
}
protected boolean isNothing(ProducedType type) {
return typeFact.getNothingDeclaration().getType().isExactly(type);
}
protected boolean isVoid(ProducedType type) {
return typeFact.getVoidDeclaration().getType().isExactly(type);
}
protected ProducedType simplifyType(ProducedType type) {
if (isOptional(type)) {
// For an optional type T?:
// - The Ceylon type T? results in the Java type T
// Nasty cast because we just so happen to know that nothingType is a Class
type = typeFact().getDefiniteType(type);
}
TypeDeclaration tdecl = type.getDeclaration();
if (tdecl instanceof UnionType && tdecl.getCaseTypes().size() == 1) {
// Special case when the Union contains only a single CaseType
// FIXME This is not correct! We might lose information about type arguments!
type = tdecl.getCaseTypes().get(0);
} else if (tdecl instanceof IntersectionType && tdecl.getSatisfiedTypes().size() == 1) {
// Special case when the Intersection contains only a single SatisfiedType
// FIXME This is not correct! We might lose information about type arguments!
type = tdecl.getSatisfiedTypes().get(0);
}
return type;
}
protected ProducedType actualType(Tree.TypedDeclaration decl) {
return decl.getType().getTypeModel();
}
protected TypedDeclaration nonWideningTypeDecl(TypedDeclaration decl) {
TypedDeclaration refinedDeclaration = (TypedDeclaration) decl.getRefinedDeclaration();
if(decl != refinedDeclaration){
/*
* We are widening if the type:
* - is not object
* - is erased to object
* - refines a declaration that is not erased to object
*/
boolean isWidening = !sameType(syms().ceylonObjectType, decl.getType())
&& willEraseToObject(decl.getType())
&& !willEraseToObject(refinedDeclaration.getType());
if(isWidening)
return refinedDeclaration;
}
return decl;
}
protected ProducedType toPType(com.sun.tools.javac.code.Type t) {
return loader().getType(t.tsym.getQualifiedName().toString(), null);
}
protected boolean sameType(Type t1, ProducedType t2) {
return toPType(t1).isExactly(t2);
}
// Determines if a type will be erased to java.lang.Object once converted to Java
protected boolean willEraseToObject(ProducedType type) {
type = simplifyType(type);
return (sameType(syms().ceylonVoidType, type) || sameType(syms().ceylonObjectType, type)
|| sameType(syms().ceylonNothingType, type)
|| sameType(syms().ceylonIdentifiableObjectType, type)
|| type.getDeclaration() instanceof BottomType
|| typeFact().isUnion(type)|| typeFact().isIntersection(type));
}
protected boolean willEraseToException(ProducedType type) {
type = simplifyType(type);
return (sameType(syms().ceylonExceptionType, type));
}
protected boolean isCeylonString(ProducedType type) {
return (sameType(syms().ceylonStringType, type));
}
protected boolean isCeylonBoolean(ProducedType type) {
return type.isSubtypeOf(typeFact.getBooleanDeclaration().getType())
&& !(type.getDeclaration() instanceof BottomType);
}
protected boolean isCeylonInteger(ProducedType type) {
return (sameType(syms().ceylonIntegerType, type));
}
protected boolean isCeylonFloat(ProducedType type) {
return (sameType(syms().ceylonFloatType, type));
}
protected boolean isCeylonCharacter(ProducedType type) {
return (sameType(syms().ceylonCharacterType, type));
}
protected boolean isCeylonArray(ProducedType type) {
return (sameType(syms().ceylonArrayType, type.getDeclaration().getType()));
}
protected boolean isCeylonBasicType(ProducedType type) {
return (isCeylonString(type) || isCeylonBoolean(type) || isCeylonInteger(type) || isCeylonFloat(type) || isCeylonCharacter(type));
}
/*
* Java Type creation
*/
static final int SATISFIES = 1 << 0;
static final int EXTENDS = 1 << 1;
static final int TYPE_ARGUMENT = 1 << 2;
static final int NO_PRIMITIVES = 1 << 2; // Yes, same as TYPE_ARGUMENT
static final int WANT_RAW_TYPE = 1 << 3;
static final int CATCH = 1 << 4;
static final int SMALL_TYPE = 1 << 5;
static final int CLASS_NEW = 1 << 6;
/**
* This function is used solely for method return types and parameters
*/
protected JCExpression makeJavaType(TypedDeclaration typeDecl) {
boolean usePrimitives = Util.isUnBoxed(typeDecl);
return makeJavaType(typeDecl.getType(), usePrimitives ? 0 : AbstractTransformer.NO_PRIMITIVES);
}
protected JCExpression makeJavaType(ProducedType producedType) {
return makeJavaType(producedType, 0);
}
protected JCExpression makeJavaType(ProducedType type, int flags) {
if(type == null)
return make().Erroneous();
// ERASURE
if (willEraseToObject(type)) {
// For an erased type:
// - Any of the Ceylon types Void, Object, Nothing,
// IdentifiableObject, and Bottom result in the Java type Object
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type U|V results in the Java type Object
ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(type));
if (iterType != null) {
// We special case the erasure of X[] and X[]?
type = iterType;
} else {
if ((flags & SATISFIES) != 0) {
return null;
} else {
return make().Type(syms().objectType);
}
}
} else if (willEraseToException(type)) {
if ((flags & CLASS_NEW) != 0
|| (flags & EXTENDS) != 0) {
return make().Type(syms().ceylonExceptionType);
} else if ((flags & CATCH) != 0) {
return make().Type(syms().exceptionType);
} else {
return make().Type(syms().throwableType);
}
} else if ((flags & (SATISFIES | EXTENDS | TYPE_ARGUMENT | CLASS_NEW)) == 0
&& (!isOptional(type) || isJavaString(type))) {
if (isCeylonString(type) || isJavaString(type)) {
return make().Type(syms().stringType);
} else if (isCeylonBoolean(type)) {
return make().TypeIdent(TypeTags.BOOLEAN);
} else if (isCeylonInteger(type)) {
if ("byte".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.BYTE);
} else if ("short".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.SHORT);
} else if ((flags & SMALL_TYPE) != 0 || "int".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.INT);
} else {
return make().TypeIdent(TypeTags.LONG);
}
} else if (isCeylonFloat(type)) {
if ((flags & SMALL_TYPE) != 0 || "float".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.FLOAT);
} else {
return make().TypeIdent(TypeTags.DOUBLE);
}
} else if (isCeylonCharacter(type)) {
if ("char".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.CHAR);
} else {
return make().TypeIdent(TypeTags.INT);
}
} else if (isCeylonArray(type)) {
ProducedType simpleType = simplifyType(type);
java.util.List<ProducedType> tal = simpleType.getTypeArgumentList();
return make().TypeArray(makeJavaType(tal.get(0), 0));
}
}
JCExpression jt;
ProducedType simpleType = simplifyType(type);
TypeDeclaration tdecl = simpleType.getDeclaration();
java.util.List<ProducedType> tal = simpleType.getTypeArgumentList();
if (((flags & WANT_RAW_TYPE) == 0) && tal != null && !tal.isEmpty()) {
// GENERIC TYPES
ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
int idx = 0;
for (ProducedType ta : tal) {
if (isOptional(ta)) {
// For an optional type T?:
// - The Ceylon type Foo<T?> results in the Java type Foo<T>.
ta = typeFact().getDefiniteType(ta);
}
if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) {
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type Foo<U|V> results in the raw Java type Foo.
// For any other intersection type U|V:
// - The Ceylon type Foo<U&V> results in the raw Java type Foo.
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(ta));
// don't break if the union type is erased to something better than Object
if(iterType == null){
typeArgs = null;
break;
}else
ta = iterType;
}
JCExpression jta;
if (sameType(syms().ceylonVoidType, ta)) {
// For the root type Void:
if ((flags & (SATISFIES | EXTENDS)) != 0) {
// - The Ceylon type Foo<Void> appearing in an extends or satisfies
// clause results in the Java raw type Foo<Object>
jta = make().Type(syms().objectType);
} else {
// - The Ceylon type Foo<Void> appearing anywhere else results in the Java type
// - Foo<Object> if Foo<T> is invariant in T
// - Foo<?> if Foo<T> is covariant in T, or
// - Foo<Object> if Foo<T> is contravariant in T
TypeParameter tp = tdecl.getTypeParameters().get(idx);
if (tp.isContravariant()) {
jta = make().Type(syms().objectType);
} else if (tp.isCovariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags));
} else {
jta = make().Type(syms().objectType);
}
}
} else if (ta.getDeclaration() instanceof BottomType) {
// For the bottom type Bottom:
if ((flags & (SATISFIES | EXTENDS)) != 0) {
// - The Ceylon type Foo<Bottom> appearing in an extends or satisfies
// clause results in the Java raw type Foo
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
} else {
// - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type
// - raw Foo if Foo<T> is invariant in T,
// - raw Foo if Foo<T> is covariant in T, or
// - Foo<?> if Foo<T> is contravariant in T
TypeParameter tp = tdecl.getTypeParameters().get(idx);
if (tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta));
} else {
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
}
}
} else {
// For an ordinary class or interface type T:
if ((flags & (SATISFIES | EXTENDS)) != 0) {
// - The Ceylon type Foo<T> appearing in an extends or satisfies clause
// results in the Java type Foo<T>
jta = makeJavaType(ta, TYPE_ARGUMENT);
} else {
// - The Ceylon type Foo<T> appearing anywhere else results in the Java type
// - Foo<T> if Foo is invariant in T,
// - Foo<? extends T> if Foo is covariant in T, or
// - Foo<? super T> if Foo is contravariant in T
TypeParameter tp = tdecl.getTypeParameters().get(idx);
if (((flags & CLASS_NEW) == 0) && tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, TYPE_ARGUMENT));
} else if (((flags & CLASS_NEW) == 0) && tp.isCovariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, TYPE_ARGUMENT));
} else {
jta = makeJavaType(ta, TYPE_ARGUMENT);
}
}
}
typeArgs.add(jta);
idx++;
}
if (typeArgs != null && typeArgs.size() > 0) {
jt = make().TypeApply(getDeclarationName(tdecl), typeArgs.toList());
} else {
jt = getDeclarationName(tdecl);
}
} else {
// For an ordinary class or interface type T:
// - The Ceylon type T results in the Java type T
if(tdecl instanceof TypeParameter)
jt = makeQuotedIdent(tdecl.getName());
- else if(simpleType.getUnderlyingType() == null)
+ // don't use underlying type if we want no primitives
+ else if((flags & (SATISFIES | NO_PRIMITIVES)) != 0 || simpleType.getUnderlyingType() == null)
jt = getDeclarationName(tdecl);
else
jt = makeQuotedFQIdent(simpleType.getUnderlyingType());
}
return jt;
}
private boolean isJavaString(ProducedType type) {
return "java.lang.String".equals(type.getUnderlyingType());
}
private JCExpression getDeclarationName(Declaration decl) {
if (Decl.isLocal(decl)) {
return makeQuotedQualIdentFromString(decl.getName());
} else {
return makeQuotedFQIdent(decl.getQualifiedNameString());
}
}
protected ProducedType getThisType(Tree.Declaration decl) {
if (decl instanceof Tree.TypeDeclaration) {
return getThisType(((Tree.TypeDeclaration)decl).getDeclarationModel());
} else {
return getThisType(((Tree.TypedDeclaration)decl).getDeclarationModel());
}
}
protected ProducedType getThisType(Declaration decl) {
ProducedType thisType;
if (decl instanceof ClassOrInterface) {
thisType = ((ClassOrInterface)decl).getType();
} else if (decl.isToplevel()) {
thisType = ((TypedDeclaration)decl).getType();
} else {
thisType = getThisType((Declaration)decl.getContainer());
}
return thisType;
}
protected ProducedType getTypeForParameter(Parameter parameter, boolean isRaw, java.util.List<ProducedType> typeArgumentModels) {
ProducedType type = parameter.getType();
if(isTypeParameter(type)){
TypeParameter tp = (TypeParameter) type.getDeclaration();
if(!isRaw && typeArgumentModels != null){
// try to use the inferred type if we're not going raw
Scope scope = parameter.getContainer();
int typeParamIndex = getTypeParameterIndex(scope, tp);
if(typeParamIndex != -1)
return typeArgumentModels.get(typeParamIndex);
}
if(tp.getSatisfiedTypes().size() >= 1){
// try the first satisfied type
type = tp.getSatisfiedTypes().get(0).getType();
// unless it's erased, in which case try for more specific
if(!willEraseToObject(type))
return type;
}
}
return type;
}
private int getTypeParameterIndex(Scope scope, TypeParameter tp) {
if(scope instanceof Method)
return ((Method)scope).getTypeParameters().indexOf(tp);
return ((ClassOrInterface)scope).getTypeParameters().indexOf(tp);
}
/*
* Annotation generation
*/
List<JCAnnotation> makeAtOverride() {
return List.<JCAnnotation> of(make().Annotation(makeIdent(syms().overrideType), List.<JCExpression> nil()));
}
// FIXME
public static boolean disableModelAnnotations = false;
public boolean checkCompilerAnnotations(Tree.Declaration decl){
boolean old = disableModelAnnotations;
if(Util.hasCompilerAnnotation(decl, "nomodel"))
disableModelAnnotations = true;
return old;
}
public void resetCompilerAnnotations(boolean value){
disableModelAnnotations = value;
}
private List<JCAnnotation> makeModelAnnotation(Type annotationType, List<JCExpression> annotationArgs) {
if (disableModelAnnotations)
return List.nil();
return List.of(make().Annotation(makeIdent(annotationType), annotationArgs));
}
private List<JCAnnotation> makeModelAnnotation(Type annotationType) {
return makeModelAnnotation(annotationType, List.<JCExpression>nil());
}
protected List<JCAnnotation> makeAtCeylon() {
return makeModelAnnotation(syms().ceylonAtCeylonType);
}
protected List<JCAnnotation> makeAtModule(Module module) {
String name = module.getNameAsString();
String version = module.getVersion();
java.util.List<ModuleImport> dependencies = module.getImports();
ListBuffer<JCExpression> imports = new ListBuffer<JCTree.JCExpression>();
for(ModuleImport dependency : dependencies){
Module dependencyModule = dependency.getModule();
// do not include the implicit java module as a dependency
if(dependencyModule.getNameAsString().equals("java"))
continue;
JCExpression dependencyName = make().Assign(makeUnquotedIdent("name"), make().Literal(dependencyModule.getNameAsString()));
JCExpression dependencyVersion = null;
if(dependencyModule.getVersion() != null)
dependencyVersion = make().Assign(makeUnquotedIdent("version"), make().Literal(dependencyModule.getVersion()));
List<JCExpression> spec;
if(dependencyVersion != null)
spec = List.<JCExpression>of(dependencyName, dependencyVersion);
else
spec = List.<JCExpression>of(dependencyName);
JCAnnotation atImport = make().Annotation(makeIdent(syms().ceylonAtImportType), spec);
// TODO : add the export & optional annotations also ?
imports.add(atImport);
}
JCExpression nameAttribute = make().Assign(makeUnquotedIdent("name"), make().Literal(name));
JCExpression versionAttribute = make().Assign(makeUnquotedIdent("version"), make().Literal(version));
JCExpression importAttribute = make().Assign(makeUnquotedIdent("dependencies"), make().NewArray(null, null, imports.toList()));
return makeModelAnnotation(syms().ceylonAtModuleType,
List.<JCExpression>of(nameAttribute, versionAttribute, importAttribute));
}
protected List<JCAnnotation> makeAtPackage(Package pkg) {
String name = pkg.getNameAsString();
boolean shared = pkg.isShared();
JCExpression nameAttribute = make().Assign(makeUnquotedIdent("name"), make().Literal(name));
JCExpression sharedAttribute = make().Assign(makeUnquotedIdent("shared"), makeBoolean(shared));
return makeModelAnnotation(syms().ceylonAtPackageType,
List.<JCExpression>of(nameAttribute, sharedAttribute));
}
protected List<JCAnnotation> makeAtName(String name) {
return makeModelAnnotation(syms().ceylonAtNameType, List.<JCExpression>of(make().Literal(name)));
}
protected List<JCAnnotation> makeAtType(String name) {
return makeModelAnnotation(syms().ceylonAtTypeInfoType, List.<JCExpression>of(make().Literal(name)));
}
public JCAnnotation makeAtTypeParameter(String name, java.util.List<ProducedType> satisfiedTypes, boolean covariant, boolean contravariant) {
JCExpression nameAttribute = make().Assign(makeUnquotedIdent("value"), make().Literal(name));
// variance
String variance = "NONE";
if(covariant)
variance = "OUT";
else if(contravariant)
variance = "IN";
JCExpression varianceAttribute = make().Assign(makeUnquotedIdent("variance"),
make().Select(makeIdent(syms().ceylonVarianceType), names().fromString(variance)));
// upper bounds
ListBuffer<JCExpression> upperBounds = new ListBuffer<JCTree.JCExpression>();
for(ProducedType satisfiedType : satisfiedTypes){
String type = serialiseTypeSignature(satisfiedType);
upperBounds.append(make().Literal(type));
}
JCExpression satisfiesAttribute = make().Assign(makeUnquotedIdent("satisfies"),
make().NewArray(null, null, upperBounds.toList()));
// all done
return make().Annotation(makeIdent(syms().ceylonAtTypeParameter),
List.<JCExpression>of(nameAttribute, varianceAttribute, satisfiesAttribute));
}
public List<JCAnnotation> makeAtTypeParameters(List<JCExpression> typeParameters) {
JCExpression value = make().NewArray(null, null, typeParameters);
return makeModelAnnotation(syms().ceylonAtTypeParameters, List.of(value));
}
protected List<JCAnnotation> makeAtSequenced() {
return makeModelAnnotation(syms().ceylonAtSequencedType);
}
protected List<JCAnnotation> makeAtDefaulted() {
return makeModelAnnotation(syms().ceylonAtDefaultedType);
}
protected List<JCAnnotation> makeAtAttribute() {
return makeModelAnnotation(syms().ceylonAtAttributeType);
}
protected List<JCAnnotation> makeAtMethod() {
return makeModelAnnotation(syms().ceylonAtMethodType);
}
protected List<JCAnnotation> makeAtObject() {
return makeModelAnnotation(syms().ceylonAtObjectType);
}
protected List<JCAnnotation> makeAtClass(ProducedType extendedType) {
List<JCExpression> attributes = List.nil();
if(!extendedType.isExactly(typeFact.getIdentifiableObjectDeclaration().getType())){
JCExpression extendsAttribute = make().Assign(makeUnquotedIdent("extendsType"),
make().Literal(serialiseTypeSignature(extendedType)));
attributes = attributes.prepend(extendsAttribute);
}
return makeModelAnnotation(syms().ceylonAtClassType, attributes);
}
protected List<JCAnnotation> makeAtSatisfiedTypes(java.util.List<ProducedType> satisfiedTypes) {
return makeTypesListAnnotation(syms().ceylonAtSatisfiedTypes, satisfiedTypes);
}
protected List<JCAnnotation> makeAtCaseTypes(java.util.List<ProducedType> caseTypes) {
return makeTypesListAnnotation(syms().ceylonAtCaseTypes, caseTypes);
}
private List<JCAnnotation> makeTypesListAnnotation(Type annotationType, java.util.List<ProducedType> types) {
if(types.isEmpty())
return List.nil();
ListBuffer<JCExpression> upperBounds = new ListBuffer<JCTree.JCExpression>();
for(ProducedType type : types){
String typeSig = serialiseTypeSignature(type);
upperBounds.append(make().Literal(typeSig));
}
JCExpression caseAttribute = make().Assign(makeUnquotedIdent("value"),
make().NewArray(null, null, upperBounds.toList()));
return makeModelAnnotation(annotationType, List.of(caseAttribute));
}
protected List<JCAnnotation> makeAtIgnore() {
return makeModelAnnotation(syms().ceylonAtIgnore);
}
protected List<JCAnnotation> makeAtAnnotations(java.util.List<Annotation> annotations) {
if(annotations == null || annotations.isEmpty())
return List.nil();
ListBuffer<JCExpression> array = new ListBuffer<JCTree.JCExpression>();
for(Annotation annotation : annotations){
array.append(makeAtAnnotation(annotation));
}
JCExpression annotationsAttribute = make().Assign(makeUnquotedIdent("value"),
make().NewArray(null, null, array.toList()));
return makeModelAnnotation(syms().ceylonAtAnnotationsType, List.of(annotationsAttribute));
}
private JCExpression makeAtAnnotation(Annotation annotation) {
JCExpression valueAttribute = make().Assign(makeUnquotedIdent("value"),
make().Literal(annotation.getName()));
List<JCExpression> attributes;
if(!annotation.getPositionalArguments().isEmpty()){
java.util.List<String> positionalArguments = annotation.getPositionalArguments();
ListBuffer<JCExpression> array = new ListBuffer<JCTree.JCExpression>();
for(String val : positionalArguments)
array.add(make().Literal(val));
JCExpression argumentsAttribute = make().Assign(makeUnquotedIdent("arguments"),
make().NewArray(null, null, array.toList()));
attributes = List.of(valueAttribute, argumentsAttribute);
}else if(!annotation.getNamedArguments().isEmpty()){
Map<String, String> namedArguments = annotation.getNamedArguments();
ListBuffer<JCExpression> array = new ListBuffer<JCTree.JCExpression>();
for(Entry<String, String> entry : namedArguments.entrySet()){
JCExpression argNameAttribute = make().Assign(makeUnquotedIdent("name"),
make().Literal(entry.getKey()));
JCExpression argValueAttribute = make().Assign(makeUnquotedIdent("value"),
make().Literal(entry.getValue()));
JCAnnotation namedArg = make().Annotation(makeIdent(syms().ceylonAtNamedArgumentType),
List.of(argNameAttribute, argValueAttribute));
array.add(namedArg);
}
JCExpression argumentsAttribute = make().Assign(makeUnquotedIdent("namedArguments"),
make().NewArray(null, null, array.toList()));
attributes = List.of(valueAttribute, argumentsAttribute);
}else
attributes = List.of(valueAttribute);
return make().Annotation(makeIdent(syms().ceylonAtAnnotationType), attributes);
}
protected boolean needsAnnotations(Declaration decl) {
Declaration reqdecl = decl;
if (reqdecl instanceof Parameter) {
Parameter p = (Parameter)reqdecl;
reqdecl = p.getDeclaration();
}
return reqdecl.isToplevel() || (reqdecl.isClassOrInterfaceMember() && reqdecl.isShared() && !Decl.isAncestorLocal(reqdecl));
}
protected List<JCTree.JCAnnotation> makeJavaTypeAnnotations(TypedDeclaration decl) {
if(decl.getType() == null)
return List.nil();
return makeJavaTypeAnnotations(decl.getType(), needsAnnotations(decl));
}
protected List<JCTree.JCAnnotation> makeJavaTypeAnnotations(ProducedType type, boolean required) {
if (!required)
return List.nil();
// Add the original type to the annotations
return makeAtType(serialiseTypeSignature(type));
}
protected String serialiseTypeSignature(ProducedType type){
if(isTypeParameter(type))
return type.getProducedTypeName();
return type.getProducedTypeQualifiedName();
}
/*
* Boxing
*/
public enum BoxingStrategy {
UNBOXED, BOXED, INDIFFERENT;
}
protected JCExpression boxUnboxIfNecessary(JCExpression javaExpr, Tree.Term expr,
ProducedType exprType,
BoxingStrategy boxingStrategy) {
boolean exprBoxed = !Util.isUnBoxed(expr);
return boxUnboxIfNecessary(javaExpr, exprBoxed, exprType, boxingStrategy);
}
protected JCExpression boxUnboxIfNecessary(JCExpression javaExpr, boolean exprBoxed,
ProducedType exprType,
BoxingStrategy boxingStrategy) {
if(boxingStrategy == BoxingStrategy.INDIFFERENT)
return javaExpr;
boolean targetBoxed = boxingStrategy == BoxingStrategy.BOXED;
// only box if the two differ
if(targetBoxed == exprBoxed)
return javaExpr;
if (targetBoxed) {
// box
javaExpr = boxType(javaExpr, exprType);
} else {
// unbox
javaExpr = unboxType(javaExpr, exprType);
}
return javaExpr;
}
protected boolean isTypeParameter(ProducedType type) {
return type.getDeclaration() instanceof TypeParameter;
}
protected JCExpression unboxType(JCExpression expr, ProducedType targetType) {
if (isCeylonInteger(targetType)) {
expr = unboxInteger(expr);
} else if (isCeylonFloat(targetType)) {
expr = unboxFloat(expr);
} else if (isCeylonString(targetType)) {
expr = unboxString(expr);
} else if (isCeylonCharacter(targetType)) {
boolean isJavaCharacter = targetType.getUnderlyingType() != null;
expr = unboxCharacter(expr, isJavaCharacter);
} else if (isCeylonBoolean(targetType)) {
expr = unboxBoolean(expr);
} else if (isCeylonArray(targetType)) {
expr = unboxArray(expr);
}
return expr;
}
protected JCExpression boxType(JCExpression expr, ProducedType exprType) {
if (isCeylonInteger(exprType)) {
expr = boxInteger(expr);
} else if (isCeylonFloat(exprType)) {
expr = boxFloat(expr);
} else if (isCeylonString(exprType)) {
expr = boxString(expr);
} else if (isCeylonCharacter(exprType)) {
expr = boxCharacter(expr);
} else if (isCeylonBoolean(exprType)) {
expr = boxBoolean(expr);
} else if (isCeylonArray(exprType)) {
expr = boxArray(expr);
}
return expr;
}
private JCTree.JCMethodInvocation boxInteger(JCExpression value) {
return makeBoxType(value, syms().ceylonIntegerType);
}
private JCTree.JCMethodInvocation boxFloat(JCExpression value) {
return makeBoxType(value, syms().ceylonFloatType);
}
private JCTree.JCMethodInvocation boxString(JCExpression value) {
return makeBoxType(value, syms().ceylonStringType);
}
private JCTree.JCMethodInvocation boxCharacter(JCExpression value) {
return makeBoxType(value, syms().ceylonCharacterType);
}
private JCTree.JCMethodInvocation boxBoolean(JCExpression value) {
return makeBoxType(value, syms().ceylonBooleanType);
}
private JCTree.JCMethodInvocation boxArray(JCExpression value) {
return makeBoxType(value, syms().ceylonArrayType);
}
private JCTree.JCMethodInvocation makeBoxType(JCExpression value, Type type) {
return make().Apply(null, makeSelect(makeIdent(type), "instance"), List.<JCExpression>of(value));
}
private JCTree.JCMethodInvocation unboxInteger(JCExpression value) {
return makeUnboxType(value, "longValue");
}
private JCTree.JCMethodInvocation unboxFloat(JCExpression value) {
return makeUnboxType(value, "doubleValue");
}
private JCTree.JCMethodInvocation unboxString(JCExpression value) {
return makeUnboxType(value, "toString");
}
private JCTree.JCMethodInvocation unboxCharacter(JCExpression value, boolean isJava) {
return makeUnboxType(value, isJava ? "charValue" : "intValue");
}
private JCTree.JCMethodInvocation unboxBoolean(JCExpression value) {
return makeUnboxType(value, "booleanValue");
}
private JCTree.JCMethodInvocation unboxArray(JCExpression value) {
return makeUnboxType(value, "toArray");
}
private JCTree.JCMethodInvocation makeUnboxType(JCExpression value, String unboxMethodName) {
return make().Apply(null, makeSelect(value, unboxMethodName), List.<JCExpression>nil());
}
protected ProducedType determineExpressionType(Tree.Expression expr) {
return determineExpressionType(expr.getTerm());
}
protected ProducedType determineExpressionType(Tree.Term term) {
ProducedType exprType = term.getTypeModel();
if (term instanceof Tree.InvocationExpression) {
Tree.InvocationExpression invocation = (Tree.InvocationExpression)term;
Tree.MemberOrTypeExpression primary = (Tree.MemberOrTypeExpression)invocation.getPrimary();
Declaration decl = primary.getDeclaration().getRefinedDeclaration();
if (decl instanceof Method) {
exprType = ((Method)decl).getType();
}
}
return exprType;
}
/*
* Sequences
*/
/**
* Returns a JCExpression along the lines of
* {@code new ArraySequence<seqElemType>(list...)}
* @param list The elements in the sequence
* @param seqElemType The sequence type parameter
* @return a JCExpression
* @see #makeSequenceRaw(java.util.List)
*/
protected JCExpression makeSequence(java.util.List<Expression> list, ProducedType seqElemType) {
ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
for (Expression expr : list) {
// no need for erasure casts here
elems.append(expressionGen().transformExpression(expr));
}
ProducedType seqType = typeFact().getDefaultSequenceType(seqElemType);
JCExpression typeExpr = makeJavaType(seqType, CeylonTransformer.TYPE_ARGUMENT);
return makeNewClass(typeExpr, elems.toList());
}
/**
* Returns a JCExpression along the lines of
* {@code new ArraySequence(list...)}
* @param list The elements in the sequence
* @return a JCExpression
* @see #makeSequence(java.util.List, ProducedType)
*/
protected JCExpression makeSequenceRaw(java.util.List<Expression> list) {
ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();
for (Expression expr : list) {
// no need for erasure casts here
elems.append(expressionGen().transformExpression(expr));
}
ProducedType seqType = typeFact().getDefaultSequenceType(typeFact().getObjectDeclaration().getType());
JCExpression typeExpr = makeJavaType(seqType, CeylonTransformer.WANT_RAW_TYPE);
return makeNewClass(typeExpr, elems.toList());
}
protected JCExpression makeEmpty() {
return make().Apply(
List.<JCTree.JCExpression>nil(),
makeFQIdent("ceylon", "language", "$empty", Util.getGetterName("$empty")),
List.<JCTree.JCExpression>nil());
}
protected JCExpression makeFinished() {
return make().Apply(
List.<JCTree.JCExpression>nil(),
makeFQIdent("ceylon", "language", "$finished", Util.getGetterName("$finished")),
List.<JCTree.JCExpression>nil());
}
/*
* Variable name substitution
*/
@SuppressWarnings("serial")
protected static class VarMapper extends HashMap<String, String> {
}
private Map<String, String> getVarMapper() {
VarMapper map = context.get(VarMapper.class);
if (map == null) {
map = new VarMapper();
context.put(VarMapper.class, map);
}
return map;
}
String addVariableSubst(String origVarName, String substVarName) {
return getVarMapper().put(origVarName, substVarName);
}
void removeVariableSubst(String origVarName, String prevSubst) {
if (prevSubst != null) {
getVarMapper().put(origVarName, prevSubst);
} else {
getVarMapper().remove(origVarName);
}
}
/*
* Checks a global map of variable name substitutions and returns
* either the original name if none was found or the substitute.
*/
String substitute(String varName) {
if (getVarMapper().containsKey(varName)) {
return getVarMapper().get(varName);
} else {
return varName;
}
}
// Creates comparisons of expressions against types
// The expression to pass must be free of side-effects!
protected JCExpression makeTypeTest(JCExpression testExpr, ProducedType type) {
return makeTypeTest(testExpr, testExpr, type);
}
// Creates comparisons of expressions against types
// In case the expression is free of side effects just pass the same one twice
// otherwise pass the expression with side-effect as the first one and an alternative
// one free of side effects as the second
protected JCExpression makeTypeTest(JCExpression firstTestExpr, JCExpression restTestExpr, ProducedType type) {
JCExpression result = null;
if (typeFact().isUnion(type)) {
UnionType union = (UnionType)type.getDeclaration();
for (ProducedType pt : union.getCaseTypes()) {
JCExpression partExpr = makeTypeTest(firstTestExpr, restTestExpr, pt);
if (result == null) {
result = partExpr;
} else {
result = make().Binary(JCTree.OR, result, partExpr);
}
firstTestExpr = restTestExpr;
}
} else if (typeFact().isIntersection(type)) {
IntersectionType union = (IntersectionType)type.getDeclaration();
for (ProducedType pt : union.getSatisfiedTypes()) {
JCExpression partExpr = makeTypeTest(firstTestExpr, restTestExpr, pt);
if (result == null) {
result = partExpr;
} else {
result = make().Binary(JCTree.AND, result, partExpr);
}
firstTestExpr = restTestExpr;
}
} else if (type.isExactly(typeFact().getNothingDeclaration().getType())){
// is Nothing => is null
return make().Binary(JCTree.EQ, firstTestExpr, makeNull());
} else if (type.isExactly(typeFact().getObjectDeclaration().getType())){
// is Object => is not null
return make().Binary(JCTree.NE, firstTestExpr, makeNull());
} else if (type.isExactly(typeFact().getVoidDeclaration().getType())){
// everything is Void, it's the root of the hierarchy
return makeIgnoredEvalAndReturn(firstTestExpr, makeBoolean(true));
} else if (type.isExactly(typeFact().getObjectDeclaration().getType())){
// it's erased
return makeUtilInvocation("isEquality", List.of(firstTestExpr));
} else if (type.isExactly(typeFact().getIdentifiableObjectDeclaration().getType())){
// it's erased
return makeUtilInvocation("isIdentifiableObject", List.of(firstTestExpr));
} else if (type.getDeclaration() instanceof BottomType){
// nothing is Bottom
return makeIgnoredEvalAndReturn(firstTestExpr, makeBoolean(false));
} else {
JCExpression rawTypeExpr = makeJavaType(type, NO_PRIMITIVES | WANT_RAW_TYPE);
result = make().TypeTest(firstTestExpr, rawTypeExpr);
}
return result;
}
/**
* Invokes a static method of the Util helper class
* @param methodName name of the method
* @param params parameters
* @return the invocation AST
*/
protected JCExpression makeUtilInvocation(String methodName, List<JCExpression> params) {
return make().Apply(null, make().Select(make().QualIdent(syms().ceylonUtilType.tsym),
names().fromString(methodName)),
params);
}
protected LetExpr makeIgnoredEvalAndReturn(JCExpression toEval, JCExpression toReturn){
// define a variable of type j.l.Object to hold the result of the evaluation
JCVariableDecl def = makeVar(tempName(), make().Type(syms().objectType), toEval);
// then ignore this result and return something else
return make().LetExpr(def, toReturn);
}
protected JCExpression makeErroneous() {
return makeErroneous(null);
}
/**
* Makes an 'erroneous' AST node with no message
*/
protected JCExpression makeErroneous(Node node) {
return makeErroneous(node, null, List.<JCTree>nil());
}
/**
* Makes an 'erroneous' AST node with a message to be logged as an error
*/
protected JCExpression makeErroneous(Node node, String message) {
return makeErroneous(node, message, List.<JCTree>nil());
}
/**
* Makes an 'erroneous' AST node with a message to be logged as an error
*/
protected JCExpression makeErroneous(Node node, String message, List<? extends JCTree> errs) {
if (node != null) {
at(node);
}
if (message != null) {
if (node != null) {
log.error(getPosition(node), "ceylon", message);
} else {
log.error("ceylon", message);
}
}
return make().Erroneous(errs);
}
private int getPosition(Node node) {
int pos = getMap().getStartPosition(node.getToken().getLine())
+ node.getToken().getCharPositionInLine();
log.useSource(gen().getFileObject());
return pos;
}
}
| true | true | protected JCExpression makeJavaType(ProducedType type, int flags) {
if(type == null)
return make().Erroneous();
// ERASURE
if (willEraseToObject(type)) {
// For an erased type:
// - Any of the Ceylon types Void, Object, Nothing,
// IdentifiableObject, and Bottom result in the Java type Object
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type U|V results in the Java type Object
ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(type));
if (iterType != null) {
// We special case the erasure of X[] and X[]?
type = iterType;
} else {
if ((flags & SATISFIES) != 0) {
return null;
} else {
return make().Type(syms().objectType);
}
}
} else if (willEraseToException(type)) {
if ((flags & CLASS_NEW) != 0
|| (flags & EXTENDS) != 0) {
return make().Type(syms().ceylonExceptionType);
} else if ((flags & CATCH) != 0) {
return make().Type(syms().exceptionType);
} else {
return make().Type(syms().throwableType);
}
} else if ((flags & (SATISFIES | EXTENDS | TYPE_ARGUMENT | CLASS_NEW)) == 0
&& (!isOptional(type) || isJavaString(type))) {
if (isCeylonString(type) || isJavaString(type)) {
return make().Type(syms().stringType);
} else if (isCeylonBoolean(type)) {
return make().TypeIdent(TypeTags.BOOLEAN);
} else if (isCeylonInteger(type)) {
if ("byte".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.BYTE);
} else if ("short".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.SHORT);
} else if ((flags & SMALL_TYPE) != 0 || "int".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.INT);
} else {
return make().TypeIdent(TypeTags.LONG);
}
} else if (isCeylonFloat(type)) {
if ((flags & SMALL_TYPE) != 0 || "float".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.FLOAT);
} else {
return make().TypeIdent(TypeTags.DOUBLE);
}
} else if (isCeylonCharacter(type)) {
if ("char".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.CHAR);
} else {
return make().TypeIdent(TypeTags.INT);
}
} else if (isCeylonArray(type)) {
ProducedType simpleType = simplifyType(type);
java.util.List<ProducedType> tal = simpleType.getTypeArgumentList();
return make().TypeArray(makeJavaType(tal.get(0), 0));
}
}
JCExpression jt;
ProducedType simpleType = simplifyType(type);
TypeDeclaration tdecl = simpleType.getDeclaration();
java.util.List<ProducedType> tal = simpleType.getTypeArgumentList();
if (((flags & WANT_RAW_TYPE) == 0) && tal != null && !tal.isEmpty()) {
// GENERIC TYPES
ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
int idx = 0;
for (ProducedType ta : tal) {
if (isOptional(ta)) {
// For an optional type T?:
// - The Ceylon type Foo<T?> results in the Java type Foo<T>.
ta = typeFact().getDefiniteType(ta);
}
if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) {
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type Foo<U|V> results in the raw Java type Foo.
// For any other intersection type U|V:
// - The Ceylon type Foo<U&V> results in the raw Java type Foo.
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(ta));
// don't break if the union type is erased to something better than Object
if(iterType == null){
typeArgs = null;
break;
}else
ta = iterType;
}
JCExpression jta;
if (sameType(syms().ceylonVoidType, ta)) {
// For the root type Void:
if ((flags & (SATISFIES | EXTENDS)) != 0) {
// - The Ceylon type Foo<Void> appearing in an extends or satisfies
// clause results in the Java raw type Foo<Object>
jta = make().Type(syms().objectType);
} else {
// - The Ceylon type Foo<Void> appearing anywhere else results in the Java type
// - Foo<Object> if Foo<T> is invariant in T
// - Foo<?> if Foo<T> is covariant in T, or
// - Foo<Object> if Foo<T> is contravariant in T
TypeParameter tp = tdecl.getTypeParameters().get(idx);
if (tp.isContravariant()) {
jta = make().Type(syms().objectType);
} else if (tp.isCovariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags));
} else {
jta = make().Type(syms().objectType);
}
}
} else if (ta.getDeclaration() instanceof BottomType) {
// For the bottom type Bottom:
if ((flags & (SATISFIES | EXTENDS)) != 0) {
// - The Ceylon type Foo<Bottom> appearing in an extends or satisfies
// clause results in the Java raw type Foo
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
} else {
// - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type
// - raw Foo if Foo<T> is invariant in T,
// - raw Foo if Foo<T> is covariant in T, or
// - Foo<?> if Foo<T> is contravariant in T
TypeParameter tp = tdecl.getTypeParameters().get(idx);
if (tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta));
} else {
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
}
}
} else {
// For an ordinary class or interface type T:
if ((flags & (SATISFIES | EXTENDS)) != 0) {
// - The Ceylon type Foo<T> appearing in an extends or satisfies clause
// results in the Java type Foo<T>
jta = makeJavaType(ta, TYPE_ARGUMENT);
} else {
// - The Ceylon type Foo<T> appearing anywhere else results in the Java type
// - Foo<T> if Foo is invariant in T,
// - Foo<? extends T> if Foo is covariant in T, or
// - Foo<? super T> if Foo is contravariant in T
TypeParameter tp = tdecl.getTypeParameters().get(idx);
if (((flags & CLASS_NEW) == 0) && tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, TYPE_ARGUMENT));
} else if (((flags & CLASS_NEW) == 0) && tp.isCovariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, TYPE_ARGUMENT));
} else {
jta = makeJavaType(ta, TYPE_ARGUMENT);
}
}
}
typeArgs.add(jta);
idx++;
}
if (typeArgs != null && typeArgs.size() > 0) {
jt = make().TypeApply(getDeclarationName(tdecl), typeArgs.toList());
} else {
jt = getDeclarationName(tdecl);
}
} else {
// For an ordinary class or interface type T:
// - The Ceylon type T results in the Java type T
if(tdecl instanceof TypeParameter)
jt = makeQuotedIdent(tdecl.getName());
else if(simpleType.getUnderlyingType() == null)
jt = getDeclarationName(tdecl);
else
jt = makeQuotedFQIdent(simpleType.getUnderlyingType());
}
return jt;
}
| protected JCExpression makeJavaType(ProducedType type, int flags) {
if(type == null)
return make().Erroneous();
// ERASURE
if (willEraseToObject(type)) {
// For an erased type:
// - Any of the Ceylon types Void, Object, Nothing,
// IdentifiableObject, and Bottom result in the Java type Object
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type U|V results in the Java type Object
ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(type));
if (iterType != null) {
// We special case the erasure of X[] and X[]?
type = iterType;
} else {
if ((flags & SATISFIES) != 0) {
return null;
} else {
return make().Type(syms().objectType);
}
}
} else if (willEraseToException(type)) {
if ((flags & CLASS_NEW) != 0
|| (flags & EXTENDS) != 0) {
return make().Type(syms().ceylonExceptionType);
} else if ((flags & CATCH) != 0) {
return make().Type(syms().exceptionType);
} else {
return make().Type(syms().throwableType);
}
} else if ((flags & (SATISFIES | EXTENDS | TYPE_ARGUMENT | CLASS_NEW)) == 0
&& (!isOptional(type) || isJavaString(type))) {
if (isCeylonString(type) || isJavaString(type)) {
return make().Type(syms().stringType);
} else if (isCeylonBoolean(type)) {
return make().TypeIdent(TypeTags.BOOLEAN);
} else if (isCeylonInteger(type)) {
if ("byte".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.BYTE);
} else if ("short".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.SHORT);
} else if ((flags & SMALL_TYPE) != 0 || "int".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.INT);
} else {
return make().TypeIdent(TypeTags.LONG);
}
} else if (isCeylonFloat(type)) {
if ((flags & SMALL_TYPE) != 0 || "float".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.FLOAT);
} else {
return make().TypeIdent(TypeTags.DOUBLE);
}
} else if (isCeylonCharacter(type)) {
if ("char".equals(type.getUnderlyingType())) {
return make().TypeIdent(TypeTags.CHAR);
} else {
return make().TypeIdent(TypeTags.INT);
}
} else if (isCeylonArray(type)) {
ProducedType simpleType = simplifyType(type);
java.util.List<ProducedType> tal = simpleType.getTypeArgumentList();
return make().TypeArray(makeJavaType(tal.get(0), 0));
}
}
JCExpression jt;
ProducedType simpleType = simplifyType(type);
TypeDeclaration tdecl = simpleType.getDeclaration();
java.util.List<ProducedType> tal = simpleType.getTypeArgumentList();
if (((flags & WANT_RAW_TYPE) == 0) && tal != null && !tal.isEmpty()) {
// GENERIC TYPES
ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
int idx = 0;
for (ProducedType ta : tal) {
if (isOptional(ta)) {
// For an optional type T?:
// - The Ceylon type Foo<T?> results in the Java type Foo<T>.
ta = typeFact().getDefiniteType(ta);
}
if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) {
// For any other union type U|V (U nor V is Optional):
// - The Ceylon type Foo<U|V> results in the raw Java type Foo.
// For any other intersection type U|V:
// - The Ceylon type Foo<U&V> results in the raw Java type Foo.
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(ta));
// don't break if the union type is erased to something better than Object
if(iterType == null){
typeArgs = null;
break;
}else
ta = iterType;
}
JCExpression jta;
if (sameType(syms().ceylonVoidType, ta)) {
// For the root type Void:
if ((flags & (SATISFIES | EXTENDS)) != 0) {
// - The Ceylon type Foo<Void> appearing in an extends or satisfies
// clause results in the Java raw type Foo<Object>
jta = make().Type(syms().objectType);
} else {
// - The Ceylon type Foo<Void> appearing anywhere else results in the Java type
// - Foo<Object> if Foo<T> is invariant in T
// - Foo<?> if Foo<T> is covariant in T, or
// - Foo<Object> if Foo<T> is contravariant in T
TypeParameter tp = tdecl.getTypeParameters().get(idx);
if (tp.isContravariant()) {
jta = make().Type(syms().objectType);
} else if (tp.isCovariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags));
} else {
jta = make().Type(syms().objectType);
}
}
} else if (ta.getDeclaration() instanceof BottomType) {
// For the bottom type Bottom:
if ((flags & (SATISFIES | EXTENDS)) != 0) {
// - The Ceylon type Foo<Bottom> appearing in an extends or satisfies
// clause results in the Java raw type Foo
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
} else {
// - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type
// - raw Foo if Foo<T> is invariant in T,
// - raw Foo if Foo<T> is covariant in T, or
// - Foo<?> if Foo<T> is contravariant in T
TypeParameter tp = tdecl.getTypeParameters().get(idx);
if (tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta));
} else {
// A bit ugly, but we need to escape from the loop and create a raw type, no generics
typeArgs = null;
break;
}
}
} else {
// For an ordinary class or interface type T:
if ((flags & (SATISFIES | EXTENDS)) != 0) {
// - The Ceylon type Foo<T> appearing in an extends or satisfies clause
// results in the Java type Foo<T>
jta = makeJavaType(ta, TYPE_ARGUMENT);
} else {
// - The Ceylon type Foo<T> appearing anywhere else results in the Java type
// - Foo<T> if Foo is invariant in T,
// - Foo<? extends T> if Foo is covariant in T, or
// - Foo<? super T> if Foo is contravariant in T
TypeParameter tp = tdecl.getTypeParameters().get(idx);
if (((flags & CLASS_NEW) == 0) && tp.isContravariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, TYPE_ARGUMENT));
} else if (((flags & CLASS_NEW) == 0) && tp.isCovariant()) {
jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, TYPE_ARGUMENT));
} else {
jta = makeJavaType(ta, TYPE_ARGUMENT);
}
}
}
typeArgs.add(jta);
idx++;
}
if (typeArgs != null && typeArgs.size() > 0) {
jt = make().TypeApply(getDeclarationName(tdecl), typeArgs.toList());
} else {
jt = getDeclarationName(tdecl);
}
} else {
// For an ordinary class or interface type T:
// - The Ceylon type T results in the Java type T
if(tdecl instanceof TypeParameter)
jt = makeQuotedIdent(tdecl.getName());
// don't use underlying type if we want no primitives
else if((flags & (SATISFIES | NO_PRIMITIVES)) != 0 || simpleType.getUnderlyingType() == null)
jt = getDeclarationName(tdecl);
else
jt = makeQuotedFQIdent(simpleType.getUnderlyingType());
}
return jt;
}
|
diff --git a/cometd-java/cometd-java-server/src/test/java/org/cometd/server/BayeuxServerTest.java b/cometd-java/cometd-java-server/src/test/java/org/cometd/server/BayeuxServerTest.java
index 8fc122974..e6b68b417 100644
--- a/cometd-java/cometd-java-server/src/test/java/org/cometd/server/BayeuxServerTest.java
+++ b/cometd-java/cometd-java-server/src/test/java/org/cometd/server/BayeuxServerTest.java
@@ -1,424 +1,425 @@
/*
* Copyright (c) 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cometd.server;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSession;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ConfigurableServerChannel;
import org.cometd.bayeux.server.LocalSession;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerMessage.Mutable;
import org.cometd.bayeux.server.ServerSession;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class BayeuxServerTest
{
private final Queue<Object> _events = new ConcurrentLinkedQueue<Object>();
private final BayeuxServerImpl _bayeux = new BayeuxServerImpl();
private ServerSessionImpl newServerSession()
{
ServerSessionImpl session = _bayeux.newServerSession();
_bayeux.addServerSession(session);
session.handshake();
session.connected();
return session;
}
@Before
public void init() throws Exception
{
_bayeux.start();
}
@After
public void destroy() throws Exception
{
_bayeux.stop();
_events.clear();
}
@Test
public void testListeners() throws Exception
{
_bayeux.addListener(new SubListener());
_bayeux.addListener(new SessListener());
_bayeux.addListener(new CListener());
String channelName = "/foo/bar";
_bayeux.createIfAbsent(channelName);
ServerChannelImpl foobar = (ServerChannelImpl)_bayeux.getChannel(channelName);
channelName = "/foo/*";
_bayeux.createIfAbsent(channelName);
ServerChannelImpl foostar = (ServerChannelImpl)_bayeux.getChannel(channelName);
channelName = "/**";
_bayeux.createIfAbsent(channelName);
ServerChannelImpl starstar = (ServerChannelImpl)_bayeux.getChannel(channelName);
channelName = "/foo/bob";
_bayeux.createIfAbsent(channelName);
ServerChannelImpl foobob = (ServerChannelImpl)_bayeux.getChannel(channelName);
channelName = "/wibble";
_bayeux.createIfAbsent(channelName);
ServerChannelImpl wibble = (ServerChannelImpl)_bayeux.getChannel(channelName);
Assert.assertEquals("channelAdded",_events.poll());
Assert.assertEquals(_bayeux.getChannel("/foo"),_events.poll());
Assert.assertEquals("channelAdded",_events.poll());
Assert.assertEquals(foobar,_events.poll());
Assert.assertEquals("channelAdded",_events.poll());
Assert.assertEquals(foostar,_events.poll());
Assert.assertEquals("channelAdded",_events.poll());
Assert.assertEquals(starstar,_events.poll());
Assert.assertEquals("channelAdded",_events.poll());
Assert.assertEquals(foobob,_events.poll());
Assert.assertEquals("channelAdded",_events.poll());
Assert.assertEquals(wibble,_events.poll());
wibble.remove();
Assert.assertEquals("channelRemoved",_events.poll());
Assert.assertEquals(wibble.getId(),_events.poll());
ServerSessionImpl session0 = newServerSession();
ServerSessionImpl session1 = newServerSession();
ServerSessionImpl session2 = newServerSession();
Assert.assertEquals("sessionAdded",_events.poll());
Assert.assertEquals(session0,_events.poll());
Assert.assertEquals("sessionAdded",_events.poll());
Assert.assertEquals(session1,_events.poll());
Assert.assertEquals("sessionAdded",_events.poll());
Assert.assertEquals(session2,_events.poll());
foobar.subscribe(session0);
foobar.unsubscribe(session0);
Assert.assertEquals("subscribed",_events.poll());
Assert.assertEquals(session0,_events.poll());
Assert.assertEquals(foobar,_events.poll());
Assert.assertEquals("unsubscribed",_events.poll());
Assert.assertEquals(session0,_events.poll());
Assert.assertEquals(foobar,_events.poll());
}
@Test
public void testSessionAttributes() throws Exception
{
LocalSession local = _bayeux.newLocalSession("s0");
local.handshake();
ServerSession session = local.getServerSession();
local.setAttribute("foo","bar");
Assert.assertEquals("bar",local.getAttribute("foo"));
Assert.assertEquals(null,session.getAttribute("foo"));
session.setAttribute("bar","foo");
Assert.assertEquals(null,local.getAttribute("bar"));
Assert.assertEquals("foo",session.getAttribute("bar"));
Assert.assertTrue(local.getAttributeNames().contains("foo"));
Assert.assertFalse(local.getAttributeNames().contains("bar"));
Assert.assertFalse(session.getAttributeNames().contains("foo"));
Assert.assertTrue(session.getAttributeNames().contains("bar"));
Assert.assertEquals("bar",local.removeAttribute("foo"));
Assert.assertEquals(null,local.removeAttribute("foo"));
Assert.assertEquals("foo",session.removeAttribute("bar"));
Assert.assertEquals(null,local.removeAttribute("bar"));
}
@Test
public void testLocalSessions() throws Exception
{
LocalSession session0 = _bayeux.newLocalSession("s0");
- Assert.assertTrue(session0.toString().indexOf("s0?")>=0);
+ Assert.assertEquals("L:s0_", session0.toString());
session0.handshake();
- Assert.assertTrue(session0.toString().indexOf("s0_")>=0);
+ Assert.assertNotEquals("L:s0_", session0.toString());
+ Assert.assertTrue(session0.toString().startsWith("L:s0_"));
final LocalSession session1 = _bayeux.newLocalSession("s1");
session1.handshake();
final LocalSession session2 = _bayeux.newLocalSession("s2");
session2.handshake();
final Queue<String> events = new ConcurrentLinkedQueue<String>();
ClientSessionChannel.MessageListener listener = new ClientSessionChannel.MessageListener()
{
public void onMessage(ClientSessionChannel channel, Message message)
{
events.add(channel.getSession().getId());
events.add(message.getData().toString());
}
};
session0.getChannel("/foo/bar").subscribe(listener);
session0.getChannel("/foo/bar").subscribe(listener);
session1.getChannel("/foo/bar").subscribe(listener);
session2.getChannel("/foo/bar").subscribe(listener);
Assert.assertEquals(3,_bayeux.getChannel("/foo/bar").getSubscribers().size());
session0.getChannel("/foo/bar").unsubscribe(listener);
Assert.assertEquals(3,_bayeux.getChannel("/foo/bar").getSubscribers().size());
session0.getChannel("/foo/bar").unsubscribe(listener);
Assert.assertEquals(2,_bayeux.getChannel("/foo/bar").getSubscribers().size());
ClientSessionChannel foobar0=session0.getChannel("/foo/bar");
foobar0.subscribe(listener);
foobar0.subscribe(listener);
ClientSessionChannel foostar0=session0.getChannel("/foo/*");
foostar0.subscribe(listener);
Assert.assertEquals(3,_bayeux.getChannel("/foo/bar").getSubscribers().size());
Assert.assertEquals(session0,foobar0.getSession());
Assert.assertEquals("/foo/bar",foobar0.getId());
Assert.assertEquals(false,foobar0.isDeepWild());
Assert.assertEquals(false,foobar0.isWild());
Assert.assertEquals(false,foobar0.isMeta());
Assert.assertEquals(false,foobar0.isService());
foobar0.publish("hello");
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session2.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
foostar0.unsubscribe(listener);
session1.batch(new Runnable()
{
public void run()
{
ClientSessionChannel foobar1=session1.getChannel("/foo/bar");
foobar1.publish("part1");
Assert.assertEquals(null,events.poll());
foobar1.publish("part2");
}
});
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session2.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
Assert.assertEquals(session2.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
foobar0.unsubscribe();
Assert.assertEquals(2,_bayeux.getChannel("/foo/bar").getSubscribers().size());
Assert.assertTrue(session0.isConnected());
Assert.assertTrue(session1.isConnected());
Assert.assertTrue(session2.isConnected());
ServerSession ss0=session0.getServerSession();
ServerSession ss1=session1.getServerSession();
ServerSession ss2=session2.getServerSession();
Assert.assertTrue(ss0.isConnected());
Assert.assertTrue(ss1.isConnected());
Assert.assertTrue(ss2.isConnected());
session0.disconnect();
Assert.assertFalse(session0.isConnected());
Assert.assertFalse(ss0.isConnected());
session1.getServerSession().disconnect();
Assert.assertFalse(session1.isConnected());
Assert.assertFalse(ss1.isConnected());
session2.getServerSession().disconnect();
Assert.assertFalse(session2.isConnected());
Assert.assertFalse(ss2.isConnected());
}
@Test
public void testExtensions() throws Exception
{
final Queue<String> events = new ConcurrentLinkedQueue<String>();
_bayeux.addExtension(new BayeuxServer.Extension.Adapter()
{
@Override
public boolean send(ServerSession from, ServerSession to, Mutable message)
{
if ("three".equals(message.getData()))
message.setData("four");
return !"ignoreSend".equals(message.getData());
}
@Override
public boolean rcv(ServerSession from, Mutable message)
{
if ("one".equals(message.getData()))
message.setData("two");
return !"ignoreRcv".equals(message.getData());
}
});
final LocalSession session0 = _bayeux.newLocalSession("s0");
session0.handshake();
//final LocalSession session1 = _bayeux.newLocalSession("s1");
//session1.handshake();
session0.addExtension(new ClientSession.Extension.Adapter()
{
@Override
public boolean send(ClientSession session, org.cometd.bayeux.Message.Mutable message)
{
if ("zero".equals(message.getData()))
message.setData("one");
return true;
}
@Override
public boolean rcv(ClientSession session, org.cometd.bayeux.Message.Mutable message)
{
if ("five".equals(message.getData()))
message.setData("six");
return true;
}
});
session0.getServerSession().addExtension(new ServerSession.Extension.Adapter()
{
@Override
public boolean rcv(ServerSession from, Mutable message)
{
if ("two".equals(message.getData()))
message.setData("three");
return true;
}
@Override
public ServerMessage send(ServerSession to, ServerMessage message)
{
if (message.isMeta())
new Throwable().printStackTrace();
if ("four".equals(message.getData()))
{
ServerMessage.Mutable cloned=_bayeux.newMessage(message);
cloned.setData("five");
return cloned;
}
return message;
}
});
ClientSessionChannel.MessageListener listener = new ClientSessionChannel.MessageListener()
{
public void onMessage(ClientSessionChannel channel, Message message)
{
events.add(channel.getSession().getId());
events.add(message.getData().toString());
}
};
session0.getChannel("/foo/bar").subscribe(listener);
// session1.getChannel("/foo/bar").subscribe(listener);
session0.getChannel("/foo/bar").publish("zero");
session0.getChannel("/foo/bar").publish("ignoreSend");
session0.getChannel("/foo/bar").publish("ignoreRcv");
Thread.sleep(100);
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("six",events.poll());
/*
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("four",events.poll());
Assert.assertEquals(null,events.poll());
*/
}
class CListener implements BayeuxServer.ChannelListener
{
public void configureChannel(ConfigurableServerChannel channel)
{
}
public void channelAdded(ServerChannel channel)
{
_events.add("channelAdded");
_events.add(channel);
}
public void channelRemoved(String channelId)
{
_events.add("channelRemoved");
_events.add(channelId);
}
}
class SessListener implements BayeuxServer.SessionListener
{
public void sessionAdded(ServerSession session)
{
_events.add("sessionAdded");
_events.add(session);
}
public void sessionRemoved(ServerSession session, boolean timedout)
{
_events.add("sessionRemoved");
_events.add(session);
_events.add(timedout);
}
}
class SubListener implements BayeuxServer.SubscriptionListener
{
public void subscribed(ServerSession session, ServerChannel channel)
{
_events.add("subscribed");
_events.add(session);
_events.add(channel);
}
public void unsubscribed(ServerSession session, ServerChannel channel)
{
_events.add("unsubscribed");
_events.add(session);
_events.add(channel);
}
}
}
| false | true | public void testLocalSessions() throws Exception
{
LocalSession session0 = _bayeux.newLocalSession("s0");
Assert.assertTrue(session0.toString().indexOf("s0?")>=0);
session0.handshake();
Assert.assertTrue(session0.toString().indexOf("s0_")>=0);
final LocalSession session1 = _bayeux.newLocalSession("s1");
session1.handshake();
final LocalSession session2 = _bayeux.newLocalSession("s2");
session2.handshake();
final Queue<String> events = new ConcurrentLinkedQueue<String>();
ClientSessionChannel.MessageListener listener = new ClientSessionChannel.MessageListener()
{
public void onMessage(ClientSessionChannel channel, Message message)
{
events.add(channel.getSession().getId());
events.add(message.getData().toString());
}
};
session0.getChannel("/foo/bar").subscribe(listener);
session0.getChannel("/foo/bar").subscribe(listener);
session1.getChannel("/foo/bar").subscribe(listener);
session2.getChannel("/foo/bar").subscribe(listener);
Assert.assertEquals(3,_bayeux.getChannel("/foo/bar").getSubscribers().size());
session0.getChannel("/foo/bar").unsubscribe(listener);
Assert.assertEquals(3,_bayeux.getChannel("/foo/bar").getSubscribers().size());
session0.getChannel("/foo/bar").unsubscribe(listener);
Assert.assertEquals(2,_bayeux.getChannel("/foo/bar").getSubscribers().size());
ClientSessionChannel foobar0=session0.getChannel("/foo/bar");
foobar0.subscribe(listener);
foobar0.subscribe(listener);
ClientSessionChannel foostar0=session0.getChannel("/foo/*");
foostar0.subscribe(listener);
Assert.assertEquals(3,_bayeux.getChannel("/foo/bar").getSubscribers().size());
Assert.assertEquals(session0,foobar0.getSession());
Assert.assertEquals("/foo/bar",foobar0.getId());
Assert.assertEquals(false,foobar0.isDeepWild());
Assert.assertEquals(false,foobar0.isWild());
Assert.assertEquals(false,foobar0.isMeta());
Assert.assertEquals(false,foobar0.isService());
foobar0.publish("hello");
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session2.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
foostar0.unsubscribe(listener);
session1.batch(new Runnable()
{
public void run()
{
ClientSessionChannel foobar1=session1.getChannel("/foo/bar");
foobar1.publish("part1");
Assert.assertEquals(null,events.poll());
foobar1.publish("part2");
}
});
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session2.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
Assert.assertEquals(session2.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
foobar0.unsubscribe();
Assert.assertEquals(2,_bayeux.getChannel("/foo/bar").getSubscribers().size());
Assert.assertTrue(session0.isConnected());
Assert.assertTrue(session1.isConnected());
Assert.assertTrue(session2.isConnected());
ServerSession ss0=session0.getServerSession();
ServerSession ss1=session1.getServerSession();
ServerSession ss2=session2.getServerSession();
Assert.assertTrue(ss0.isConnected());
Assert.assertTrue(ss1.isConnected());
Assert.assertTrue(ss2.isConnected());
session0.disconnect();
Assert.assertFalse(session0.isConnected());
Assert.assertFalse(ss0.isConnected());
session1.getServerSession().disconnect();
Assert.assertFalse(session1.isConnected());
Assert.assertFalse(ss1.isConnected());
session2.getServerSession().disconnect();
Assert.assertFalse(session2.isConnected());
Assert.assertFalse(ss2.isConnected());
}
| public void testLocalSessions() throws Exception
{
LocalSession session0 = _bayeux.newLocalSession("s0");
Assert.assertEquals("L:s0_", session0.toString());
session0.handshake();
Assert.assertNotEquals("L:s0_", session0.toString());
Assert.assertTrue(session0.toString().startsWith("L:s0_"));
final LocalSession session1 = _bayeux.newLocalSession("s1");
session1.handshake();
final LocalSession session2 = _bayeux.newLocalSession("s2");
session2.handshake();
final Queue<String> events = new ConcurrentLinkedQueue<String>();
ClientSessionChannel.MessageListener listener = new ClientSessionChannel.MessageListener()
{
public void onMessage(ClientSessionChannel channel, Message message)
{
events.add(channel.getSession().getId());
events.add(message.getData().toString());
}
};
session0.getChannel("/foo/bar").subscribe(listener);
session0.getChannel("/foo/bar").subscribe(listener);
session1.getChannel("/foo/bar").subscribe(listener);
session2.getChannel("/foo/bar").subscribe(listener);
Assert.assertEquals(3,_bayeux.getChannel("/foo/bar").getSubscribers().size());
session0.getChannel("/foo/bar").unsubscribe(listener);
Assert.assertEquals(3,_bayeux.getChannel("/foo/bar").getSubscribers().size());
session0.getChannel("/foo/bar").unsubscribe(listener);
Assert.assertEquals(2,_bayeux.getChannel("/foo/bar").getSubscribers().size());
ClientSessionChannel foobar0=session0.getChannel("/foo/bar");
foobar0.subscribe(listener);
foobar0.subscribe(listener);
ClientSessionChannel foostar0=session0.getChannel("/foo/*");
foostar0.subscribe(listener);
Assert.assertEquals(3,_bayeux.getChannel("/foo/bar").getSubscribers().size());
Assert.assertEquals(session0,foobar0.getSession());
Assert.assertEquals("/foo/bar",foobar0.getId());
Assert.assertEquals(false,foobar0.isDeepWild());
Assert.assertEquals(false,foobar0.isWild());
Assert.assertEquals(false,foobar0.isMeta());
Assert.assertEquals(false,foobar0.isService());
foobar0.publish("hello");
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
Assert.assertEquals(session2.getId(),events.poll());
Assert.assertEquals("hello",events.poll());
foostar0.unsubscribe(listener);
session1.batch(new Runnable()
{
public void run()
{
ClientSessionChannel foobar1=session1.getChannel("/foo/bar");
foobar1.publish("part1");
Assert.assertEquals(null,events.poll());
foobar1.publish("part2");
}
});
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session2.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part1",events.poll());
Assert.assertEquals(session1.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
Assert.assertEquals(session2.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
Assert.assertEquals(session0.getId(),events.poll());
Assert.assertEquals("part2",events.poll());
foobar0.unsubscribe();
Assert.assertEquals(2,_bayeux.getChannel("/foo/bar").getSubscribers().size());
Assert.assertTrue(session0.isConnected());
Assert.assertTrue(session1.isConnected());
Assert.assertTrue(session2.isConnected());
ServerSession ss0=session0.getServerSession();
ServerSession ss1=session1.getServerSession();
ServerSession ss2=session2.getServerSession();
Assert.assertTrue(ss0.isConnected());
Assert.assertTrue(ss1.isConnected());
Assert.assertTrue(ss2.isConnected());
session0.disconnect();
Assert.assertFalse(session0.isConnected());
Assert.assertFalse(ss0.isConnected());
session1.getServerSession().disconnect();
Assert.assertFalse(session1.isConnected());
Assert.assertFalse(ss1.isConnected());
session2.getServerSession().disconnect();
Assert.assertFalse(session2.isConnected());
Assert.assertFalse(ss2.isConnected());
}
|
diff --git a/test-integration-ui/src/main/java/org/apache/directory/studio/test/integration/ui/bots/ModificationLogsViewBot.java b/test-integration-ui/src/main/java/org/apache/directory/studio/test/integration/ui/bots/ModificationLogsViewBot.java
index d5f5f62ef..3d58356d8 100644
--- a/test-integration-ui/src/main/java/org/apache/directory/studio/test/integration/ui/bots/ModificationLogsViewBot.java
+++ b/test-integration-ui/src/main/java/org/apache/directory/studio/test/integration/ui/bots/ModificationLogsViewBot.java
@@ -1,63 +1,63 @@
/*
* 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.studio.test.integration.ui.bots;
import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.allOf;
import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.widgetOfType;
import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.withStyle;
import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.withTooltip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotToolbarButton;
import org.hamcrest.Matcher;
public class ModificationLogsViewBot
{
private SWTBotView view;
public ModificationLogsViewBot()
{
view = new SWTWorkbenchBot().viewByTitle( "Modification Logs" );
}
- public String getSearchLogsText()
+ public String getModificationLogsText()
{
view.show();
//view.toolbarButton( "Refresh" ).click();
// just a workaround till view.toolbarButton() is fixed
Matcher matcher = allOf( widgetOfType( ToolItem.class ), withTooltip( "Refresh" ), withStyle( SWT.PUSH,
"SWT.PUSH" ) );
SWTBotToolbarButton button = new SWTBotToolbarButton( ( ToolItem ) new SWTWorkbenchBot().widget( matcher, 0 ),
matcher );
button.click();
return view.bot().styledText().getText();
}
}
| true | true | public String getSearchLogsText()
{
view.show();
//view.toolbarButton( "Refresh" ).click();
// just a workaround till view.toolbarButton() is fixed
Matcher matcher = allOf( widgetOfType( ToolItem.class ), withTooltip( "Refresh" ), withStyle( SWT.PUSH,
"SWT.PUSH" ) );
SWTBotToolbarButton button = new SWTBotToolbarButton( ( ToolItem ) new SWTWorkbenchBot().widget( matcher, 0 ),
matcher );
button.click();
return view.bot().styledText().getText();
}
| public String getModificationLogsText()
{
view.show();
//view.toolbarButton( "Refresh" ).click();
// just a workaround till view.toolbarButton() is fixed
Matcher matcher = allOf( widgetOfType( ToolItem.class ), withTooltip( "Refresh" ), withStyle( SWT.PUSH,
"SWT.PUSH" ) );
SWTBotToolbarButton button = new SWTBotToolbarButton( ( ToolItem ) new SWTWorkbenchBot().widget( matcher, 0 ),
matcher );
button.click();
return view.bot().styledText().getText();
}
|
diff --git a/src/java/se/idega/idegaweb/commune/school/business/CentralPlacementBusinessBean.java b/src/java/se/idega/idegaweb/commune/school/business/CentralPlacementBusinessBean.java
index c9f39217..85c5c451 100644
--- a/src/java/se/idega/idegaweb/commune/school/business/CentralPlacementBusinessBean.java
+++ b/src/java/se/idega/idegaweb/commune/school/business/CentralPlacementBusinessBean.java
@@ -1,371 +1,370 @@
/*
* Created on 2003-okt-08
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package se.idega.idegaweb.commune.school.business;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import javax.ejb.FinderException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import se.idega.idegaweb.commune.accounting.invoice.business.RegularPaymentBusiness;
import se.idega.idegaweb.commune.accounting.invoice.data.RegularPaymentEntry;
import se.idega.idegaweb.commune.accounting.resource.business.ResourceBusiness;
import se.idega.idegaweb.commune.accounting.resource.data.ResourceClassMember;
import se.idega.idegaweb.commune.business.CommuneUserBusiness;
import se.idega.idegaweb.commune.school.presentation.CentralPlacementEditor;
import com.idega.block.school.business.SchoolBusiness;
import com.idega.block.school.data.School;
import com.idega.block.school.data.SchoolCategory;
import com.idega.block.school.data.SchoolCategoryHome;
import com.idega.block.school.data.SchoolClassMember;
import com.idega.block.school.data.SchoolClassMemberHome;
import com.idega.business.IBOServiceBean;
import com.idega.data.IDOLookup;
import com.idega.presentation.IWContext;
import com.idega.user.business.UserBusiness;
import com.idega.user.data.User;
import com.idega.util.IWTimestamp;
/**
* @author G�ran Borgman
*
* Business object with helper methods for CentralPlacementEditor
*/
public class CentralPlacementBusinessBean extends IBOServiceBean implements CentralPlacementBusiness {
// Keys for error messages
private static final String KP = "central_placement_business.";
private static final String KEY_ERROR_CHILD_ID = KP + "error.child_id";
private static final String KEY_ERROR_CATEGORY_ID = KP + "error.category_id";
private static final String KEY_ERROR_PROVIDER_ID = KP + "error.provider_id";
private static final String KEY_ERROR_PLACEMENT_DATE = KP + "error.placement_date";
private static final String KEY_ERROR_LATEST_REMOVED_DATE = KP + "error.latest_removed_date";
private static final String KEY_ERROR_SCHOOL_TYPE = KP + "error.school_type";
private static final String KEY_ERROR_SCHOOL_YEAR = KP + "error.school_year";
private static final String KEY_ERROR_SCHOOL_GROUP = KP + "error.school_group";
private static final String KEY_ERROR_STORING_PLACEMENT = KP + "error.saving_placement";
/**
* Stores a new placement(SchoolClassMember) with resources and ends the current placement
*/
public SchoolClassMember storeSchoolClassMember(IWContext iwc, int childID)
throws RemoteException, CentralPlacementException {
int studentID = -1;
User student = null;
int schoolClassID = -1;
int schoolYearID = -1;
int schoolTypeID = -1;
int registrator = -1;
String placementDateStr = "-1";
Timestamp registerStamp = null;
java.sql.Date registerDate = null;
Timestamp dayBeforeRegStamp = null;
Date dayBeforeRegDate = null;
java.sql.Date dayBeforeSqlDate = null;
//String seeDayBeforeDate = null;
String notes = null;
SchoolClassMember newPlacement = null;
//SchoolClassMember currentPlacement = null;
SchoolClassMember latestPlacement = null;
int newPlacementID = -1;
// *** START - Check in params ***
// pupil
if (childID == -1) {
throw new CentralPlacementException(KEY_ERROR_CHILD_ID, "No valid pupil found");
} else {
studentID = childID;
student = getUserBusiness().getUser(studentID);
if (student == null)
throw new CentralPlacementException(KEY_ERROR_CHILD_ID, "No valid pupil found");
latestPlacement = getLatestPlacementLatestFromElemAndHighSchool(student);
}
// operational field
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_CATEGORY)) {
String categoryID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_CATEGORY);
if (categoryID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_CATEGORY_ID,
"You must chose an operational field for the placement");
}
}
// provider
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PROVIDER)) {
String providerID = iwc.getParameter(CentralPlacementEditor.PARAM_PROVIDER);
if (providerID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_PROVIDER_ID,
"You must chose a school for the placement");
}
}
// school type
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_TYPE)) {
String typeID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_TYPE);
if (typeID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_SCHOOL_TYPE,
"You must chose a school type");
} else {
schoolTypeID = Integer.parseInt(typeID);
}
}
// school year
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_YEAR)) {
String yearID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_YEAR);
if (yearID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_SCHOOL_YEAR,
"You must chose a school year");
} else {
schoolYearID = Integer.parseInt(yearID);
}
}
// school group
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_GROUP)) {
String groupID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_GROUP);
if (groupID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_SCHOOL_GROUP,
"You must chose a school group");
} else {
schoolClassID = Integer.parseInt(groupID);
}
}
// registerDate
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PLACEMENT_DATE)) {
//IWTimestamp today = IWTimestamp.RightNow();
//today.setAsDate();
IWTimestamp placeStamp;
String placeDateStr = iwc.getParameter(CentralPlacementEditor.PARAM_PLACEMENT_DATE);
if (!placeDateStr.equals("")) {
placeStamp= new IWTimestamp(placeDateStr);
placeStamp.setAsDate();
// Get dayBeforeRegDate for further use
IWTimestamp dayBeforeStamp = new IWTimestamp(placeStamp.getDate());
dayBeforeStamp.addDays(-1);
dayBeforeRegStamp = dayBeforeStamp.getTimestamp();
dayBeforeRegDate = dayBeforeStamp.getDate();
dayBeforeSqlDate = new java.sql.Date(dayBeforeRegDate.getTime());
/* Below *** Removed check if earlier than today ***/
/*if (placeStamp.isEarlierThan(today)) {
throw new CentralPlacementException(KEY_ERROR_PLACEMENT_DATE,
"Placement date must be set and cannot be earlier than today");
} else {
*/
// Check latest placement, if new removed date is before registerdate, throw exception.
if (latestPlacement != null) {
Timestamp latestRegDateStamp = latestPlacement.getRegisterDate();
IWTimestamp latestRegDate = new IWTimestamp(latestRegDateStamp);
latestRegDate.setAsDate();
dayBeforeStamp.setAsDate();
if (dayBeforeStamp.isEarlierThan(latestRegDate)) {
throw new CentralPlacementException(KEY_ERROR_LATEST_REMOVED_DATE,
- "End date of latest placement, cannot be earlier than its start date. "
- + "Delete the latest placement or change its end date");
+ "End date of latest placement, cannot be earlier than its start date");
}
}
registerStamp = placeStamp.getTimestamp();
registerDate = new java.sql.Date(placeStamp.getDate().getTime());
//}
} else {
throw new CentralPlacementException(KEY_ERROR_PLACEMENT_DATE,
"Placement date must be set");
}
placementDateStr = placeDateStr;
} else {
throw new CentralPlacementException(KEY_ERROR_PLACEMENT_DATE,
"Placement date must be set");
}
// registrator
int currentUser = iwc.getCurrentUserId();
registrator = currentUser;
// *** END - Check in params ***
// *** START - Store new placement and end current placement ***
UserTransaction trans = getSessionContext().getUserTransaction();
try {
// Start transaction
trans.begin();
// Create new placement
newPlacement = getSchoolBusiness().storeNewSchoolClassMember(studentID, schoolClassID,
schoolYearID, schoolTypeID, registerStamp, registrator, notes);
if (newPlacement != null) {
// *** START - Store the rest of the parameters ***
newPlacementID = ((Integer) newPlacement.getPrimaryKey()).intValue(); // test
// Compensation by agreement
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PAYMENT_BY_AGREEMENT) &&
!iwc.getParameter(CentralPlacementEditor.PARAM_PAYMENT_BY_AGREEMENT).
equals("-1")) {
String value =
iwc.getParameter(CentralPlacementEditor.PARAM_PAYMENT_BY_AGREEMENT);
if (value.equals(CentralPlacementEditor.KEY_DROPDOWN_YES)) {
newPlacement.setHasCompensationByAgreement(true);
} else if (value.equals(CentralPlacementEditor.KEY_DROPDOWN_NO)) {
newPlacement.setHasCompensationByAgreement(false);
}
}
// Placement paragraph
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PLACEMENT_PARAGRAPH)) {
newPlacement.setPlacementParagraph(
iwc.getParameter(CentralPlacementEditor.PARAM_PLACEMENT_PARAGRAPH));
}
// Invoice interval
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_INVOICE_INTERVAL)) {
newPlacement.setInvoiceInterval(
iwc.getParameter(CentralPlacementEditor.PARAM_INVOICE_INTERVAL));
}
// Study path
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_STUDY_PATH)) {
String studyPathIDStr = iwc.getParameter(CentralPlacementEditor.PARAM_STUDY_PATH);
if (!studyPathIDStr.equals("-1")) {
int pK = Integer.parseInt(
iwc.getParameter(CentralPlacementEditor.PARAM_STUDY_PATH));
newPlacement.setStudyPathId(pK);
}
}
// Latest invoice date
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_LATEST_INVOICE_DATE)) {
IWTimestamp stamp = new IWTimestamp(iwc.getParameter(
CentralPlacementEditor.PARAM_LATEST_INVOICE_DATE));
newPlacement.setLatestInvoiceDate(stamp.getTimestamp());
}
// Resources
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_RESOURCES)) {
String [] arr = iwc.getParameterValues(CentralPlacementEditor.PARAM_RESOURCES);
for (int i = 0; i < arr.length; i++) {
int rscPK = Integer.parseInt(arr[i]);
/*ResourceClassMember rscPlace =*/ getResourceBusiness()
.createResourcePlacement(rscPK, newPlacementID, placementDateStr);
// Integer rscPlPK = (Integer) rscPlace.getPrimaryKey();
// int intPK = rscPlPK.intValue();
}
}
// Store newPlacement
newPlacement.store();
// *** END - Store the rest of the parameters ***
}
// End old placement
if (latestPlacement != null) {
// Set removed date
latestPlacement.setRemovedDate(dayBeforeRegStamp);
latestPlacement.store();
// finish old resource placements
Collection rscPlaces = getResourceBusiness().getResourcePlacementsByMemberId(
(Integer) latestPlacement.getPrimaryKey());
for (Iterator iter = rscPlaces.iterator(); iter.hasNext();) {
ResourceClassMember rscPlace = (ResourceClassMember) iter.next();
rscPlace.setEndDate(dayBeforeRegDate);
//String seeDate = seeDayBeforeDate;
rscPlace.store();
}
// Finish ongoing regular payments
School provider = latestPlacement.getSchoolClass().getSchool();
Collection regPayEntries = getRegularPaymentBusiness()
.findOngoingRegularPaymentsForUserAndSchoolByDate(
student, provider, registerDate);
for (Iterator iter = regPayEntries.iterator(); iter.hasNext();) {
RegularPaymentEntry regPay = (RegularPaymentEntry) iter.next();
regPay.setTo(dayBeforeSqlDate);
}
}
trans.commit();
} catch (Exception e) {
try {
trans.rollback();
e.printStackTrace();
throw new CentralPlacementException(KEY_ERROR_STORING_PLACEMENT,
"Error storing new placement. Transaction is rolled back.");
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (SystemException e1) {
e1.printStackTrace();
}
}
// *** END - Store new placement and end current placement ***
// int studentID, int schoolClassID, Timestamp registerDate, int registrator, String notes
return newPlacement;
}
public SchoolClassMember getLatestPlacementLatestFromElemAndHighSchool(User pupil) throws RemoteException {
SchoolClassMember mbr = null;
try {
if (pupil != null) {
mbr = getSchoolClassMemberHome().findLatestFromElemAndHighSchoolByUser(pupil);
}
} catch (FinderException fe1) {}
return mbr;
}
public String getDateString(Timestamp stamp, String pattern) {
IWTimestamp iwts = null;
String dateStr = "";
if (stamp != null) {
iwts = new IWTimestamp(stamp);
dateStr = iwts.getDateString(pattern);
}
return dateStr;
}
public CommuneUserBusiness getCommuneUserBusiness() throws RemoteException {
return (CommuneUserBusiness) getServiceInstance(CommuneUserBusiness.class);
}
public UserBusiness getUserBusiness() throws RemoteException {
return (UserBusiness) getServiceInstance(UserBusiness.class);
}
private SchoolBusiness getSchoolBusiness() throws RemoteException {
return (SchoolBusiness) getServiceInstance(SchoolBusiness.class);
}
private ResourceBusiness getResourceBusiness() throws RemoteException {
return (ResourceBusiness) getServiceInstance(ResourceBusiness.class);
}
private RegularPaymentBusiness getRegularPaymentBusiness() throws RemoteException {
return (RegularPaymentBusiness) getServiceInstance(RegularPaymentBusiness.class);
}
private SchoolClassMemberHome getSchoolClassMemberHome() throws RemoteException {
return (SchoolClassMemberHome) IDOLookup.getHome(SchoolClassMember.class);
}
public SchoolCategoryHome getSchoolCategoryHome() throws RemoteException {
return (SchoolCategoryHome) IDOLookup.getHome(SchoolCategory.class);
}
}
| true | true | public SchoolClassMember storeSchoolClassMember(IWContext iwc, int childID)
throws RemoteException, CentralPlacementException {
int studentID = -1;
User student = null;
int schoolClassID = -1;
int schoolYearID = -1;
int schoolTypeID = -1;
int registrator = -1;
String placementDateStr = "-1";
Timestamp registerStamp = null;
java.sql.Date registerDate = null;
Timestamp dayBeforeRegStamp = null;
Date dayBeforeRegDate = null;
java.sql.Date dayBeforeSqlDate = null;
//String seeDayBeforeDate = null;
String notes = null;
SchoolClassMember newPlacement = null;
//SchoolClassMember currentPlacement = null;
SchoolClassMember latestPlacement = null;
int newPlacementID = -1;
// *** START - Check in params ***
// pupil
if (childID == -1) {
throw new CentralPlacementException(KEY_ERROR_CHILD_ID, "No valid pupil found");
} else {
studentID = childID;
student = getUserBusiness().getUser(studentID);
if (student == null)
throw new CentralPlacementException(KEY_ERROR_CHILD_ID, "No valid pupil found");
latestPlacement = getLatestPlacementLatestFromElemAndHighSchool(student);
}
// operational field
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_CATEGORY)) {
String categoryID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_CATEGORY);
if (categoryID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_CATEGORY_ID,
"You must chose an operational field for the placement");
}
}
// provider
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PROVIDER)) {
String providerID = iwc.getParameter(CentralPlacementEditor.PARAM_PROVIDER);
if (providerID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_PROVIDER_ID,
"You must chose a school for the placement");
}
}
// school type
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_TYPE)) {
String typeID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_TYPE);
if (typeID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_SCHOOL_TYPE,
"You must chose a school type");
} else {
schoolTypeID = Integer.parseInt(typeID);
}
}
// school year
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_YEAR)) {
String yearID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_YEAR);
if (yearID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_SCHOOL_YEAR,
"You must chose a school year");
} else {
schoolYearID = Integer.parseInt(yearID);
}
}
// school group
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_GROUP)) {
String groupID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_GROUP);
if (groupID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_SCHOOL_GROUP,
"You must chose a school group");
} else {
schoolClassID = Integer.parseInt(groupID);
}
}
// registerDate
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PLACEMENT_DATE)) {
//IWTimestamp today = IWTimestamp.RightNow();
//today.setAsDate();
IWTimestamp placeStamp;
String placeDateStr = iwc.getParameter(CentralPlacementEditor.PARAM_PLACEMENT_DATE);
if (!placeDateStr.equals("")) {
placeStamp= new IWTimestamp(placeDateStr);
placeStamp.setAsDate();
// Get dayBeforeRegDate for further use
IWTimestamp dayBeforeStamp = new IWTimestamp(placeStamp.getDate());
dayBeforeStamp.addDays(-1);
dayBeforeRegStamp = dayBeforeStamp.getTimestamp();
dayBeforeRegDate = dayBeforeStamp.getDate();
dayBeforeSqlDate = new java.sql.Date(dayBeforeRegDate.getTime());
/* Below *** Removed check if earlier than today ***/
/*if (placeStamp.isEarlierThan(today)) {
throw new CentralPlacementException(KEY_ERROR_PLACEMENT_DATE,
"Placement date must be set and cannot be earlier than today");
} else {
*/
// Check latest placement, if new removed date is before registerdate, throw exception.
if (latestPlacement != null) {
Timestamp latestRegDateStamp = latestPlacement.getRegisterDate();
IWTimestamp latestRegDate = new IWTimestamp(latestRegDateStamp);
latestRegDate.setAsDate();
dayBeforeStamp.setAsDate();
if (dayBeforeStamp.isEarlierThan(latestRegDate)) {
throw new CentralPlacementException(KEY_ERROR_LATEST_REMOVED_DATE,
"End date of latest placement, cannot be earlier than its start date. "
+ "Delete the latest placement or change its end date");
}
}
registerStamp = placeStamp.getTimestamp();
registerDate = new java.sql.Date(placeStamp.getDate().getTime());
//}
} else {
throw new CentralPlacementException(KEY_ERROR_PLACEMENT_DATE,
"Placement date must be set");
}
placementDateStr = placeDateStr;
} else {
throw new CentralPlacementException(KEY_ERROR_PLACEMENT_DATE,
"Placement date must be set");
}
// registrator
int currentUser = iwc.getCurrentUserId();
registrator = currentUser;
// *** END - Check in params ***
// *** START - Store new placement and end current placement ***
UserTransaction trans = getSessionContext().getUserTransaction();
try {
// Start transaction
trans.begin();
// Create new placement
newPlacement = getSchoolBusiness().storeNewSchoolClassMember(studentID, schoolClassID,
schoolYearID, schoolTypeID, registerStamp, registrator, notes);
if (newPlacement != null) {
// *** START - Store the rest of the parameters ***
newPlacementID = ((Integer) newPlacement.getPrimaryKey()).intValue(); // test
// Compensation by agreement
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PAYMENT_BY_AGREEMENT) &&
!iwc.getParameter(CentralPlacementEditor.PARAM_PAYMENT_BY_AGREEMENT).
equals("-1")) {
String value =
iwc.getParameter(CentralPlacementEditor.PARAM_PAYMENT_BY_AGREEMENT);
if (value.equals(CentralPlacementEditor.KEY_DROPDOWN_YES)) {
newPlacement.setHasCompensationByAgreement(true);
} else if (value.equals(CentralPlacementEditor.KEY_DROPDOWN_NO)) {
newPlacement.setHasCompensationByAgreement(false);
}
}
// Placement paragraph
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PLACEMENT_PARAGRAPH)) {
newPlacement.setPlacementParagraph(
iwc.getParameter(CentralPlacementEditor.PARAM_PLACEMENT_PARAGRAPH));
}
// Invoice interval
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_INVOICE_INTERVAL)) {
newPlacement.setInvoiceInterval(
iwc.getParameter(CentralPlacementEditor.PARAM_INVOICE_INTERVAL));
}
// Study path
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_STUDY_PATH)) {
String studyPathIDStr = iwc.getParameter(CentralPlacementEditor.PARAM_STUDY_PATH);
if (!studyPathIDStr.equals("-1")) {
int pK = Integer.parseInt(
iwc.getParameter(CentralPlacementEditor.PARAM_STUDY_PATH));
newPlacement.setStudyPathId(pK);
}
}
// Latest invoice date
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_LATEST_INVOICE_DATE)) {
IWTimestamp stamp = new IWTimestamp(iwc.getParameter(
CentralPlacementEditor.PARAM_LATEST_INVOICE_DATE));
newPlacement.setLatestInvoiceDate(stamp.getTimestamp());
}
// Resources
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_RESOURCES)) {
String [] arr = iwc.getParameterValues(CentralPlacementEditor.PARAM_RESOURCES);
for (int i = 0; i < arr.length; i++) {
int rscPK = Integer.parseInt(arr[i]);
/*ResourceClassMember rscPlace =*/ getResourceBusiness()
.createResourcePlacement(rscPK, newPlacementID, placementDateStr);
// Integer rscPlPK = (Integer) rscPlace.getPrimaryKey();
// int intPK = rscPlPK.intValue();
}
}
// Store newPlacement
newPlacement.store();
// *** END - Store the rest of the parameters ***
}
// End old placement
if (latestPlacement != null) {
// Set removed date
latestPlacement.setRemovedDate(dayBeforeRegStamp);
latestPlacement.store();
// finish old resource placements
Collection rscPlaces = getResourceBusiness().getResourcePlacementsByMemberId(
(Integer) latestPlacement.getPrimaryKey());
for (Iterator iter = rscPlaces.iterator(); iter.hasNext();) {
ResourceClassMember rscPlace = (ResourceClassMember) iter.next();
rscPlace.setEndDate(dayBeforeRegDate);
//String seeDate = seeDayBeforeDate;
rscPlace.store();
}
// Finish ongoing regular payments
School provider = latestPlacement.getSchoolClass().getSchool();
Collection regPayEntries = getRegularPaymentBusiness()
.findOngoingRegularPaymentsForUserAndSchoolByDate(
student, provider, registerDate);
for (Iterator iter = regPayEntries.iterator(); iter.hasNext();) {
RegularPaymentEntry regPay = (RegularPaymentEntry) iter.next();
regPay.setTo(dayBeforeSqlDate);
}
}
trans.commit();
} catch (Exception e) {
try {
trans.rollback();
e.printStackTrace();
throw new CentralPlacementException(KEY_ERROR_STORING_PLACEMENT,
"Error storing new placement. Transaction is rolled back.");
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (SystemException e1) {
e1.printStackTrace();
}
}
// *** END - Store new placement and end current placement ***
// int studentID, int schoolClassID, Timestamp registerDate, int registrator, String notes
return newPlacement;
}
| public SchoolClassMember storeSchoolClassMember(IWContext iwc, int childID)
throws RemoteException, CentralPlacementException {
int studentID = -1;
User student = null;
int schoolClassID = -1;
int schoolYearID = -1;
int schoolTypeID = -1;
int registrator = -1;
String placementDateStr = "-1";
Timestamp registerStamp = null;
java.sql.Date registerDate = null;
Timestamp dayBeforeRegStamp = null;
Date dayBeforeRegDate = null;
java.sql.Date dayBeforeSqlDate = null;
//String seeDayBeforeDate = null;
String notes = null;
SchoolClassMember newPlacement = null;
//SchoolClassMember currentPlacement = null;
SchoolClassMember latestPlacement = null;
int newPlacementID = -1;
// *** START - Check in params ***
// pupil
if (childID == -1) {
throw new CentralPlacementException(KEY_ERROR_CHILD_ID, "No valid pupil found");
} else {
studentID = childID;
student = getUserBusiness().getUser(studentID);
if (student == null)
throw new CentralPlacementException(KEY_ERROR_CHILD_ID, "No valid pupil found");
latestPlacement = getLatestPlacementLatestFromElemAndHighSchool(student);
}
// operational field
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_CATEGORY)) {
String categoryID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_CATEGORY);
if (categoryID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_CATEGORY_ID,
"You must chose an operational field for the placement");
}
}
// provider
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PROVIDER)) {
String providerID = iwc.getParameter(CentralPlacementEditor.PARAM_PROVIDER);
if (providerID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_PROVIDER_ID,
"You must chose a school for the placement");
}
}
// school type
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_TYPE)) {
String typeID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_TYPE);
if (typeID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_SCHOOL_TYPE,
"You must chose a school type");
} else {
schoolTypeID = Integer.parseInt(typeID);
}
}
// school year
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_YEAR)) {
String yearID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_YEAR);
if (yearID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_SCHOOL_YEAR,
"You must chose a school year");
} else {
schoolYearID = Integer.parseInt(yearID);
}
}
// school group
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_SCHOOL_GROUP)) {
String groupID = iwc.getParameter(CentralPlacementEditor.PARAM_SCHOOL_GROUP);
if (groupID.equals("-1")) {
throw new CentralPlacementException(KEY_ERROR_SCHOOL_GROUP,
"You must chose a school group");
} else {
schoolClassID = Integer.parseInt(groupID);
}
}
// registerDate
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PLACEMENT_DATE)) {
//IWTimestamp today = IWTimestamp.RightNow();
//today.setAsDate();
IWTimestamp placeStamp;
String placeDateStr = iwc.getParameter(CentralPlacementEditor.PARAM_PLACEMENT_DATE);
if (!placeDateStr.equals("")) {
placeStamp= new IWTimestamp(placeDateStr);
placeStamp.setAsDate();
// Get dayBeforeRegDate for further use
IWTimestamp dayBeforeStamp = new IWTimestamp(placeStamp.getDate());
dayBeforeStamp.addDays(-1);
dayBeforeRegStamp = dayBeforeStamp.getTimestamp();
dayBeforeRegDate = dayBeforeStamp.getDate();
dayBeforeSqlDate = new java.sql.Date(dayBeforeRegDate.getTime());
/* Below *** Removed check if earlier than today ***/
/*if (placeStamp.isEarlierThan(today)) {
throw new CentralPlacementException(KEY_ERROR_PLACEMENT_DATE,
"Placement date must be set and cannot be earlier than today");
} else {
*/
// Check latest placement, if new removed date is before registerdate, throw exception.
if (latestPlacement != null) {
Timestamp latestRegDateStamp = latestPlacement.getRegisterDate();
IWTimestamp latestRegDate = new IWTimestamp(latestRegDateStamp);
latestRegDate.setAsDate();
dayBeforeStamp.setAsDate();
if (dayBeforeStamp.isEarlierThan(latestRegDate)) {
throw new CentralPlacementException(KEY_ERROR_LATEST_REMOVED_DATE,
"End date of latest placement, cannot be earlier than its start date");
}
}
registerStamp = placeStamp.getTimestamp();
registerDate = new java.sql.Date(placeStamp.getDate().getTime());
//}
} else {
throw new CentralPlacementException(KEY_ERROR_PLACEMENT_DATE,
"Placement date must be set");
}
placementDateStr = placeDateStr;
} else {
throw new CentralPlacementException(KEY_ERROR_PLACEMENT_DATE,
"Placement date must be set");
}
// registrator
int currentUser = iwc.getCurrentUserId();
registrator = currentUser;
// *** END - Check in params ***
// *** START - Store new placement and end current placement ***
UserTransaction trans = getSessionContext().getUserTransaction();
try {
// Start transaction
trans.begin();
// Create new placement
newPlacement = getSchoolBusiness().storeNewSchoolClassMember(studentID, schoolClassID,
schoolYearID, schoolTypeID, registerStamp, registrator, notes);
if (newPlacement != null) {
// *** START - Store the rest of the parameters ***
newPlacementID = ((Integer) newPlacement.getPrimaryKey()).intValue(); // test
// Compensation by agreement
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PAYMENT_BY_AGREEMENT) &&
!iwc.getParameter(CentralPlacementEditor.PARAM_PAYMENT_BY_AGREEMENT).
equals("-1")) {
String value =
iwc.getParameter(CentralPlacementEditor.PARAM_PAYMENT_BY_AGREEMENT);
if (value.equals(CentralPlacementEditor.KEY_DROPDOWN_YES)) {
newPlacement.setHasCompensationByAgreement(true);
} else if (value.equals(CentralPlacementEditor.KEY_DROPDOWN_NO)) {
newPlacement.setHasCompensationByAgreement(false);
}
}
// Placement paragraph
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_PLACEMENT_PARAGRAPH)) {
newPlacement.setPlacementParagraph(
iwc.getParameter(CentralPlacementEditor.PARAM_PLACEMENT_PARAGRAPH));
}
// Invoice interval
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_INVOICE_INTERVAL)) {
newPlacement.setInvoiceInterval(
iwc.getParameter(CentralPlacementEditor.PARAM_INVOICE_INTERVAL));
}
// Study path
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_STUDY_PATH)) {
String studyPathIDStr = iwc.getParameter(CentralPlacementEditor.PARAM_STUDY_PATH);
if (!studyPathIDStr.equals("-1")) {
int pK = Integer.parseInt(
iwc.getParameter(CentralPlacementEditor.PARAM_STUDY_PATH));
newPlacement.setStudyPathId(pK);
}
}
// Latest invoice date
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_LATEST_INVOICE_DATE)) {
IWTimestamp stamp = new IWTimestamp(iwc.getParameter(
CentralPlacementEditor.PARAM_LATEST_INVOICE_DATE));
newPlacement.setLatestInvoiceDate(stamp.getTimestamp());
}
// Resources
if (iwc.isParameterSet(CentralPlacementEditor.PARAM_RESOURCES)) {
String [] arr = iwc.getParameterValues(CentralPlacementEditor.PARAM_RESOURCES);
for (int i = 0; i < arr.length; i++) {
int rscPK = Integer.parseInt(arr[i]);
/*ResourceClassMember rscPlace =*/ getResourceBusiness()
.createResourcePlacement(rscPK, newPlacementID, placementDateStr);
// Integer rscPlPK = (Integer) rscPlace.getPrimaryKey();
// int intPK = rscPlPK.intValue();
}
}
// Store newPlacement
newPlacement.store();
// *** END - Store the rest of the parameters ***
}
// End old placement
if (latestPlacement != null) {
// Set removed date
latestPlacement.setRemovedDate(dayBeforeRegStamp);
latestPlacement.store();
// finish old resource placements
Collection rscPlaces = getResourceBusiness().getResourcePlacementsByMemberId(
(Integer) latestPlacement.getPrimaryKey());
for (Iterator iter = rscPlaces.iterator(); iter.hasNext();) {
ResourceClassMember rscPlace = (ResourceClassMember) iter.next();
rscPlace.setEndDate(dayBeforeRegDate);
//String seeDate = seeDayBeforeDate;
rscPlace.store();
}
// Finish ongoing regular payments
School provider = latestPlacement.getSchoolClass().getSchool();
Collection regPayEntries = getRegularPaymentBusiness()
.findOngoingRegularPaymentsForUserAndSchoolByDate(
student, provider, registerDate);
for (Iterator iter = regPayEntries.iterator(); iter.hasNext();) {
RegularPaymentEntry regPay = (RegularPaymentEntry) iter.next();
regPay.setTo(dayBeforeSqlDate);
}
}
trans.commit();
} catch (Exception e) {
try {
trans.rollback();
e.printStackTrace();
throw new CentralPlacementException(KEY_ERROR_STORING_PLACEMENT,
"Error storing new placement. Transaction is rolled back.");
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (SystemException e1) {
e1.printStackTrace();
}
}
// *** END - Store new placement and end current placement ***
// int studentID, int schoolClassID, Timestamp registerDate, int registrator, String notes
return newPlacement;
}
|
diff --git a/src/test/java/examples/TreeMap_Composite_Key.java b/src/test/java/examples/TreeMap_Composite_Key.java
index 9c7b4f61..6fcb194f 100644
--- a/src/test/java/examples/TreeMap_Composite_Key.java
+++ b/src/test/java/examples/TreeMap_Composite_Key.java
@@ -1,105 +1,105 @@
package examples;
import org.mapdb.BTreeKeySerializer;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Fun;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentNavigableMap;
/**
* Demonstrates how-to use multi value keys in BTree.
* <p/>
* MapDB has `sortable tuples`. They allow multi value keys in ordinary TreeMap.
* Values are sorted hierarchically,
* fully indexed query must start on first value and continue on second, third and so on.
*/
public class TreeMap_Composite_Key {
/**
* In this example we demonstrate spatial queries on a Map
* filled with Address > Income pairs.
* <p/>
* Address is represented as three-value-tuple.
* First value is Town, second is Street and
* third value is House number
* <p/>
* Java Generics are buggy, so we left out some type annotations for simplicity.
* I would recommend more civilized language with type inference such as Kotlin or Scala.
*/
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
//initial values
String[] towns = {"Galway", "Ennis", "Gort", "Cong", "Tuam"};
- String[] streets = {"Main street", "Shop street", "Second street", "Silver Strands"};
+ String[] streets = {"Main Street", "Shop Street", "Second Street", "Silver Strands"};
int[] houseNums = {1,2,3,4,5,6,7,8,9,10};
DB db = DBMaker.newMemoryDB().make();
//initialize map
// note that it uses BTreeKeySerializer.TUPLE3 to minimise disk space used by Map
ConcurrentNavigableMap<Fun.Tuple3, Integer> map =
db.createTreeMap("test").keySerializer(BTreeKeySerializer.TUPLE3).make();
//fill with values, use simple permutation so we dont have to include large test data.
Random r = new Random(41);
for(String town:towns)
for(String street:streets)
for(int houseNum:houseNums){
Fun.Tuple3<String, String, Integer> address = Fun.t3(town, street, houseNum);
int income = r.nextInt(50000);
map.put(address, income);
}
System.out.println("There are "+map.size()+ " houses in total"); //NOTE: map.size() traverses entire map
//Lets get all houses in Cong
//Values are sorted so we can query sub-range (values between lower and upper bound)
Map<Fun.Tuple3, Integer>
housesInCong = map.subMap(
Fun.t3("Cong", null, null), //null is 'negative infinity'; everything else is larger than null
Fun.t3("Cong", Fun.HI, Fun.HI) // 'HI' is 'positive infinity'; everything else is smaller then 'HI'
);
System.out.println("There are "+housesInCong.size()+ " houses in Cong");
//lets make sum of all salary in Cong
int total = 0;
for(Integer salary:housesInCong.values()){
total+=salary;
}
System.out.println("Salary sum for Cong is: "+total);
//Now different query, lets get total salary for all living in town center on 'Main Street', including all towns
//We could iterate over entire map to get this information, but there is more efficient way.
//Lets iterate over 'Main Street' in all towns.
total = 0;
for(String town:towns){
Map<Fun.Tuple3, Integer> mainStreetHouses =
map.subMap(
Fun.t3(town, "Main Street", null), //use null as LOWEST boundary for house number
Fun.t3(town, "Main Street", Fun.HI)
);
for(Integer salary:mainStreetHouses.values()){
total+=salary;
}
}
System.out.println("Salary sum for all Main Streets is: "+total);
//other example, lets remove Ennis/Shop Street from our DB
map.subMap(
Fun.t3("Ennis", "Shop Street", null),
Fun.t3("Ennis", "Shop Street", Fun.HI))
.clear();
}
}
| true | true | public static void main(String[] args) {
//initial values
String[] towns = {"Galway", "Ennis", "Gort", "Cong", "Tuam"};
String[] streets = {"Main street", "Shop street", "Second street", "Silver Strands"};
int[] houseNums = {1,2,3,4,5,6,7,8,9,10};
DB db = DBMaker.newMemoryDB().make();
//initialize map
// note that it uses BTreeKeySerializer.TUPLE3 to minimise disk space used by Map
ConcurrentNavigableMap<Fun.Tuple3, Integer> map =
db.createTreeMap("test").keySerializer(BTreeKeySerializer.TUPLE3).make();
//fill with values, use simple permutation so we dont have to include large test data.
Random r = new Random(41);
for(String town:towns)
for(String street:streets)
for(int houseNum:houseNums){
Fun.Tuple3<String, String, Integer> address = Fun.t3(town, street, houseNum);
int income = r.nextInt(50000);
map.put(address, income);
}
System.out.println("There are "+map.size()+ " houses in total"); //NOTE: map.size() traverses entire map
//Lets get all houses in Cong
//Values are sorted so we can query sub-range (values between lower and upper bound)
Map<Fun.Tuple3, Integer>
housesInCong = map.subMap(
Fun.t3("Cong", null, null), //null is 'negative infinity'; everything else is larger than null
Fun.t3("Cong", Fun.HI, Fun.HI) // 'HI' is 'positive infinity'; everything else is smaller then 'HI'
);
System.out.println("There are "+housesInCong.size()+ " houses in Cong");
//lets make sum of all salary in Cong
int total = 0;
for(Integer salary:housesInCong.values()){
total+=salary;
}
System.out.println("Salary sum for Cong is: "+total);
//Now different query, lets get total salary for all living in town center on 'Main Street', including all towns
//We could iterate over entire map to get this information, but there is more efficient way.
//Lets iterate over 'Main Street' in all towns.
total = 0;
for(String town:towns){
Map<Fun.Tuple3, Integer> mainStreetHouses =
map.subMap(
Fun.t3(town, "Main Street", null), //use null as LOWEST boundary for house number
Fun.t3(town, "Main Street", Fun.HI)
);
for(Integer salary:mainStreetHouses.values()){
total+=salary;
}
}
System.out.println("Salary sum for all Main Streets is: "+total);
//other example, lets remove Ennis/Shop Street from our DB
map.subMap(
Fun.t3("Ennis", "Shop Street", null),
Fun.t3("Ennis", "Shop Street", Fun.HI))
.clear();
}
| public static void main(String[] args) {
//initial values
String[] towns = {"Galway", "Ennis", "Gort", "Cong", "Tuam"};
String[] streets = {"Main Street", "Shop Street", "Second Street", "Silver Strands"};
int[] houseNums = {1,2,3,4,5,6,7,8,9,10};
DB db = DBMaker.newMemoryDB().make();
//initialize map
// note that it uses BTreeKeySerializer.TUPLE3 to minimise disk space used by Map
ConcurrentNavigableMap<Fun.Tuple3, Integer> map =
db.createTreeMap("test").keySerializer(BTreeKeySerializer.TUPLE3).make();
//fill with values, use simple permutation so we dont have to include large test data.
Random r = new Random(41);
for(String town:towns)
for(String street:streets)
for(int houseNum:houseNums){
Fun.Tuple3<String, String, Integer> address = Fun.t3(town, street, houseNum);
int income = r.nextInt(50000);
map.put(address, income);
}
System.out.println("There are "+map.size()+ " houses in total"); //NOTE: map.size() traverses entire map
//Lets get all houses in Cong
//Values are sorted so we can query sub-range (values between lower and upper bound)
Map<Fun.Tuple3, Integer>
housesInCong = map.subMap(
Fun.t3("Cong", null, null), //null is 'negative infinity'; everything else is larger than null
Fun.t3("Cong", Fun.HI, Fun.HI) // 'HI' is 'positive infinity'; everything else is smaller then 'HI'
);
System.out.println("There are "+housesInCong.size()+ " houses in Cong");
//lets make sum of all salary in Cong
int total = 0;
for(Integer salary:housesInCong.values()){
total+=salary;
}
System.out.println("Salary sum for Cong is: "+total);
//Now different query, lets get total salary for all living in town center on 'Main Street', including all towns
//We could iterate over entire map to get this information, but there is more efficient way.
//Lets iterate over 'Main Street' in all towns.
total = 0;
for(String town:towns){
Map<Fun.Tuple3, Integer> mainStreetHouses =
map.subMap(
Fun.t3(town, "Main Street", null), //use null as LOWEST boundary for house number
Fun.t3(town, "Main Street", Fun.HI)
);
for(Integer salary:mainStreetHouses.values()){
total+=salary;
}
}
System.out.println("Salary sum for all Main Streets is: "+total);
//other example, lets remove Ennis/Shop Street from our DB
map.subMap(
Fun.t3("Ennis", "Shop Street", null),
Fun.t3("Ennis", "Shop Street", Fun.HI))
.clear();
}
|
diff --git a/src/main/java/me/eccentric_nz/TARDIS/rooms/TARDISRoomRunnable.java b/src/main/java/me/eccentric_nz/TARDIS/rooms/TARDISRoomRunnable.java
index 181bca3b4..268de6bd3 100644
--- a/src/main/java/me/eccentric_nz/TARDIS/rooms/TARDISRoomRunnable.java
+++ b/src/main/java/me/eccentric_nz/TARDIS/rooms/TARDISRoomRunnable.java
@@ -1,375 +1,375 @@
/*
* Copyright (C) 2013 eccentric_nz
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.eccentric_nz.TARDIS.rooms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.eccentric_nz.TARDIS.TARDIS;
import me.eccentric_nz.TARDIS.TARDISConstants;
import me.eccentric_nz.TARDIS.TARDISConstants.COMPASS;
import me.eccentric_nz.TARDIS.database.QueryFactory;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
/**
* The TARDIS had a swimming pool. After the TARDIS' crash following the
* Doctor's tenth regeneration, the pool's water - or perhaps the pool itself -
* fell into the library. After the TARDIS had fixed itself, the swimming pool
* was restored but the Doctor did not know where it was.
*
* @author eccentric_nz
*/
public class TARDISRoomRunnable implements Runnable {
private final TARDIS plugin;
private Location l;
String[][][] s;
short[] dim;
private int id, task, level, row, col, h, w, c, middle_id, floor_id, startx, starty, startz, resetx, resetz, x, z, tardis_id;
byte data, middle_data, floor_data;
Block b;
COMPASS d;
String room;
String grammar;
private boolean running;
Player p;
World world;
List<Chunk> chunkList = new ArrayList<Chunk>();
List<Block> iceblocks = new ArrayList<Block>();
List<Block> lampblocks = new ArrayList<Block>();
List<Block> caneblocks = new ArrayList<Block>();
HashMap<Block, Byte> cocoablocks = new HashMap<Block, Byte>();
public TARDISRoomRunnable(TARDIS plugin, TARDISRoomData roomData, Player p) {
this.plugin = plugin;
this.l = roomData.getLocation();
this.s = roomData.getSchematic();
this.dim = roomData.getDimensions();
this.x = roomData.getX();
this.z = roomData.getZ();
this.b = roomData.getBlock();
this.d = roomData.getDirection();
this.middle_id = roomData.getMiddle_id();
this.middle_data = roomData.getMiddle_data();
this.floor_id = roomData.getFloor_id();
this.floor_data = roomData.getFloor_data();
this.room = roomData.getRoom();
this.tardis_id = roomData.getTardis_id();
this.running = false;
this.p = p;
}
/**
* A runnable task that builds TARDIS rooms block by block.
*/
@Override
public void run() {
// initialise
if (!running) {
level = 0;
row = 0;
col = 0;
h = dim[0] - 1;
w = dim[1] - 1;
c = dim[2];
startx = l.getBlockX();
starty = l.getBlockY();
startz = l.getBlockZ();
resetx = startx;
resetz = startz;
world = l.getWorld();
running = true;
grammar = (TARDISConstants.vowels.contains(room.substring(0, 1))) ? "an " + room : "a " + room;
if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) {
grammar += " WELL";
}
p.sendMessage(plugin.pluginName + "Started growing " + grammar + "...");
}
String tmp;
if (level == h && row == w && col == (c - 1)) {
// the entire schematic has been read :)
if (!room.equals("GRAVITY") && !room.equals("ANTIGRAVITY")) {
byte door_data;
switch (d) {
case NORTH:
door_data = 1;
break;
case WEST:
door_data = 0;
break;
case SOUTH:
door_data = 3;
break;
default:
door_data = 2;
break;
}
// put door on
b.setTypeIdAndData(64, door_data, true);
b.getRelative(BlockFace.UP).setTypeIdAndData(64, (byte) 8, true);
}
if (iceblocks.size() > 0) {
p.sendMessage(plugin.pluginName + "Melting the ice!");
// set all the ice to water
for (Block ice : iceblocks) {
ice.setTypeId(9);
}
iceblocks.clear();
}
if (room.equals("GREENHOUSE")) {
// plant the sugar cane
for (Block cane : caneblocks) {
cane.setTypeId(83);
}
caneblocks.clear();
// attach the cocoa
for (Map.Entry<Block, Byte> entry : cocoablocks.entrySet()) {
entry.getKey().setTypeIdAndData(127, entry.getValue(), true);
}
cocoablocks.clear();
}
// update lamp block states
p.sendMessage(plugin.pluginName + "Turning on the lights!");
for (Block lamp : lampblocks) {
lamp.setType(Material.REDSTONE_LAMP_ON);
}
lampblocks.clear();
// remove the chunks, so they can unload as normal again
if (chunkList.size() > 0) {
for (Chunk ch : chunkList) {
plugin.roomChunkList.remove(ch);
}
}
// cancel the task
plugin.getServer().getScheduler().cancelTask(task);
task = 0;
String rname = (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) ? room + " WELL" : room;
p.sendMessage(plugin.pluginName + "Finished growing the " + rname + "!");
} else {
// place one block
tmp = s[level][row][col];
String[] iddata = tmp.split(":");
id = plugin.utils.parseNum(iddata[0]);
if (TARDISConstants.PROBLEM_BLOCKS.contains(Integer.valueOf(id)) && (d.equals(COMPASS.NORTH) || d.equals(COMPASS.WEST))) {
data = TARDISDataRecalculator.calculateData(id, Byte.parseByte(iddata[1]));
} else {
data = Byte.parseByte(iddata[1]);
}
if (id == 35 && data == 1) {
if (middle_id == 35 && middle_data == 1 && plugin.getConfig().getBoolean("use_clay")) {
id = 159;
} else {
id = middle_id;
}
data = middle_data;
}
if (id == 35 && data == 8) {
if (floor_id == 35 && floor_data == 8 && plugin.getConfig().getBoolean("use_clay")) {
id = 159;
} else {
id = floor_id;
}
data = floor_data;
}
QueryFactory qf = new QueryFactory(plugin);
// set condenser
if (id == 54 && room.equals("HARMONY")) {
HashMap<String, Object> setc = new HashMap<String, Object>();
setc.put("condenser", world.getName() + ":" + startx + ":" + starty + ":" + startz);
HashMap<String, Object> wherec = new HashMap<String, Object>();
wherec.put("tardis_id", tardis_id);
qf.doUpdate("tardis", setc, wherec);
}
// set farm
if (id == 52 && room.equals("FARM")) {
HashMap<String, Object> setf = new HashMap<String, Object>();
setf.put("farm", world.getName() + ":" + startx + ":" + starty + ":" + startz);
HashMap<String, Object> wheref = new HashMap<String, Object>();
wheref.put("tardis_id", tardis_id);
qf.doUpdate("tardis", setf, wheref);
// replace with floor material
- id = floor_id;
+ id = (floor_id == 35 && floor_data == 8 && plugin.getConfig().getBoolean("use_clay")) ? 159 : floor_id;
data = floor_data;
}
// set stable
if (id == 88 && room.equals("STABLE")) {
HashMap<String, Object> sets = new HashMap<String, Object>();
sets.put("stable", world.getName() + ":" + startx + ":" + starty + ":" + startz);
HashMap<String, Object> wheres = new HashMap<String, Object>();
wheres.put("tardis_id", tardis_id);
qf.doUpdate("tardis", sets, wheres);
// replace with grass
id = 2;
data = 0;
}
// set farmland hydrated
if (id == 60 && data == 0) {
data = (byte) 4;
}
if (room.equals("GREENHOUSE")) {
// remember sugar cane
if (id == 83) {
Block cane = world.getBlockAt(startx, starty, startz);
caneblocks.add(cane);
}
// remember cocoa
if (id == 127) {
Block cocoa = world.getBlockAt(startx, starty, startz);
cocoablocks.put(cocoa, data);
}
}
if (room.equals("RAIL") && id == 85) {
// remember fence location so we can teleport the storage minecart
String loc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("rail", loc);
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", tardis_id);
qf.doUpdate("tardis", set, where);
}
// always remove sponge
if (id == 19) {
id = 0;
data = (byte) 0;
} else {
Block existing = world.getBlockAt(startx, starty, startz);
if (existing.getTypeId() != 0) {
if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) {
switch (id) {
case 20:
case 35:
case 98:
break;
default:
id = existing.getTypeId();
data = existing.getData();
break;
}
} else {
id = existing.getTypeId();
data = existing.getData();
}
}
}
Chunk thisChunk = world.getChunkAt(world.getBlockAt(startx, starty, startz));
if (!plugin.roomChunkList.contains(thisChunk)) {
plugin.roomChunkList.add(thisChunk);
chunkList.add(thisChunk);
}
if (id != 83 && id != 127) {
plugin.utils.setBlock(world, startx, starty, startz, id, data);
}
// remember ice blocks
if (id == 79) {
Block icy = world.getBlockAt(startx, starty, startz);
iceblocks.add(icy);
}
// remember lamp blocks
if (id == 124) {
Block lamp = world.getBlockAt(startx, starty, startz);
lampblocks.add(lamp);
}
if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) {
String loc;
if (id == 35 && data == 6) {
// pink wool - gravity well down
loc = new Location(world, startx, starty, startz).toString();
HashMap<String, Object> setd = new HashMap<String, Object>();
setd.put("tardis_id", tardis_id);
setd.put("location", loc);
setd.put("direction", 0);
setd.put("distance", 0);
setd.put("velocity", 0);
qf.doInsert("gravity_well", setd);
plugin.gravityDownList.add(loc);
}
if (id == 35 && data == 5) {
// light green wool - gravity well up
loc = new Location(world, startx, starty, startz).toString();
HashMap<String, Object> setu = new HashMap<String, Object>();
setu.put("tardis_id", tardis_id);
setu.put("location", loc);
setu.put("direction", 1);
setu.put("distance", 11);
setu.put("velocity", 0.5);
qf.doInsert("gravity_well", setu);
Double[] values = new Double[]{1D, 11D, 0.5D};
plugin.gravityUpList.put(loc, values);
}
}
if (room.equals("BAKER") || room.equals("WOOD")) {
// remember the controls
int secondary = (room.equals("BAKER")) ? 1 : 2;
int r = 2;
int type;
String loc_str;
List<Integer> controls = Arrays.asList(new Integer[]{69, 77, 92, 143, -113});
if (controls.contains(Integer.valueOf(id))) {
switch (id) {
case 77: // stone button - random
type = 1;
loc_str = plugin.utils.makeLocationStr(world, startx, starty, startz);
break;
case 93: // repeater
type = r;
loc_str = world.getName() + ":" + startx + ":" + starty + ":" + startz;
r++;
break;
case -113: // wood button - artron
case 143:
type = 6;
loc_str = plugin.utils.makeLocationStr(world, startx, starty, startz);
break;
default: // cake - handbrake
type = 0;
loc_str = plugin.utils.makeLocationStr(world, startx, starty, startz);
}
qf.insertControl(tardis_id, type, loc_str, secondary);
}
}
startx += x;
col++;
if (col == c && row < w) {
col = 0;
startx = resetx;
startz += z;
row++;
}
if (col == c && row == w && level < h) {
col = 0;
row = 0;
startx = resetx;
startz = resetz;
starty += 1;
level++;
}
}
}
public void setTask(int task) {
this.task = task;
}
}
| true | true | public void run() {
// initialise
if (!running) {
level = 0;
row = 0;
col = 0;
h = dim[0] - 1;
w = dim[1] - 1;
c = dim[2];
startx = l.getBlockX();
starty = l.getBlockY();
startz = l.getBlockZ();
resetx = startx;
resetz = startz;
world = l.getWorld();
running = true;
grammar = (TARDISConstants.vowels.contains(room.substring(0, 1))) ? "an " + room : "a " + room;
if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) {
grammar += " WELL";
}
p.sendMessage(plugin.pluginName + "Started growing " + grammar + "...");
}
String tmp;
if (level == h && row == w && col == (c - 1)) {
// the entire schematic has been read :)
if (!room.equals("GRAVITY") && !room.equals("ANTIGRAVITY")) {
byte door_data;
switch (d) {
case NORTH:
door_data = 1;
break;
case WEST:
door_data = 0;
break;
case SOUTH:
door_data = 3;
break;
default:
door_data = 2;
break;
}
// put door on
b.setTypeIdAndData(64, door_data, true);
b.getRelative(BlockFace.UP).setTypeIdAndData(64, (byte) 8, true);
}
if (iceblocks.size() > 0) {
p.sendMessage(plugin.pluginName + "Melting the ice!");
// set all the ice to water
for (Block ice : iceblocks) {
ice.setTypeId(9);
}
iceblocks.clear();
}
if (room.equals("GREENHOUSE")) {
// plant the sugar cane
for (Block cane : caneblocks) {
cane.setTypeId(83);
}
caneblocks.clear();
// attach the cocoa
for (Map.Entry<Block, Byte> entry : cocoablocks.entrySet()) {
entry.getKey().setTypeIdAndData(127, entry.getValue(), true);
}
cocoablocks.clear();
}
// update lamp block states
p.sendMessage(plugin.pluginName + "Turning on the lights!");
for (Block lamp : lampblocks) {
lamp.setType(Material.REDSTONE_LAMP_ON);
}
lampblocks.clear();
// remove the chunks, so they can unload as normal again
if (chunkList.size() > 0) {
for (Chunk ch : chunkList) {
plugin.roomChunkList.remove(ch);
}
}
// cancel the task
plugin.getServer().getScheduler().cancelTask(task);
task = 0;
String rname = (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) ? room + " WELL" : room;
p.sendMessage(plugin.pluginName + "Finished growing the " + rname + "!");
} else {
// place one block
tmp = s[level][row][col];
String[] iddata = tmp.split(":");
id = plugin.utils.parseNum(iddata[0]);
if (TARDISConstants.PROBLEM_BLOCKS.contains(Integer.valueOf(id)) && (d.equals(COMPASS.NORTH) || d.equals(COMPASS.WEST))) {
data = TARDISDataRecalculator.calculateData(id, Byte.parseByte(iddata[1]));
} else {
data = Byte.parseByte(iddata[1]);
}
if (id == 35 && data == 1) {
if (middle_id == 35 && middle_data == 1 && plugin.getConfig().getBoolean("use_clay")) {
id = 159;
} else {
id = middle_id;
}
data = middle_data;
}
if (id == 35 && data == 8) {
if (floor_id == 35 && floor_data == 8 && plugin.getConfig().getBoolean("use_clay")) {
id = 159;
} else {
id = floor_id;
}
data = floor_data;
}
QueryFactory qf = new QueryFactory(plugin);
// set condenser
if (id == 54 && room.equals("HARMONY")) {
HashMap<String, Object> setc = new HashMap<String, Object>();
setc.put("condenser", world.getName() + ":" + startx + ":" + starty + ":" + startz);
HashMap<String, Object> wherec = new HashMap<String, Object>();
wherec.put("tardis_id", tardis_id);
qf.doUpdate("tardis", setc, wherec);
}
// set farm
if (id == 52 && room.equals("FARM")) {
HashMap<String, Object> setf = new HashMap<String, Object>();
setf.put("farm", world.getName() + ":" + startx + ":" + starty + ":" + startz);
HashMap<String, Object> wheref = new HashMap<String, Object>();
wheref.put("tardis_id", tardis_id);
qf.doUpdate("tardis", setf, wheref);
// replace with floor material
id = floor_id;
data = floor_data;
}
// set stable
if (id == 88 && room.equals("STABLE")) {
HashMap<String, Object> sets = new HashMap<String, Object>();
sets.put("stable", world.getName() + ":" + startx + ":" + starty + ":" + startz);
HashMap<String, Object> wheres = new HashMap<String, Object>();
wheres.put("tardis_id", tardis_id);
qf.doUpdate("tardis", sets, wheres);
// replace with grass
id = 2;
data = 0;
}
// set farmland hydrated
if (id == 60 && data == 0) {
data = (byte) 4;
}
if (room.equals("GREENHOUSE")) {
// remember sugar cane
if (id == 83) {
Block cane = world.getBlockAt(startx, starty, startz);
caneblocks.add(cane);
}
// remember cocoa
if (id == 127) {
Block cocoa = world.getBlockAt(startx, starty, startz);
cocoablocks.put(cocoa, data);
}
}
if (room.equals("RAIL") && id == 85) {
// remember fence location so we can teleport the storage minecart
String loc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("rail", loc);
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", tardis_id);
qf.doUpdate("tardis", set, where);
}
// always remove sponge
if (id == 19) {
id = 0;
data = (byte) 0;
} else {
Block existing = world.getBlockAt(startx, starty, startz);
if (existing.getTypeId() != 0) {
if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) {
switch (id) {
case 20:
case 35:
case 98:
break;
default:
id = existing.getTypeId();
data = existing.getData();
break;
}
} else {
id = existing.getTypeId();
data = existing.getData();
}
}
}
Chunk thisChunk = world.getChunkAt(world.getBlockAt(startx, starty, startz));
if (!plugin.roomChunkList.contains(thisChunk)) {
plugin.roomChunkList.add(thisChunk);
chunkList.add(thisChunk);
}
if (id != 83 && id != 127) {
plugin.utils.setBlock(world, startx, starty, startz, id, data);
}
// remember ice blocks
if (id == 79) {
Block icy = world.getBlockAt(startx, starty, startz);
iceblocks.add(icy);
}
// remember lamp blocks
if (id == 124) {
Block lamp = world.getBlockAt(startx, starty, startz);
lampblocks.add(lamp);
}
if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) {
String loc;
if (id == 35 && data == 6) {
// pink wool - gravity well down
loc = new Location(world, startx, starty, startz).toString();
HashMap<String, Object> setd = new HashMap<String, Object>();
setd.put("tardis_id", tardis_id);
setd.put("location", loc);
setd.put("direction", 0);
setd.put("distance", 0);
setd.put("velocity", 0);
qf.doInsert("gravity_well", setd);
plugin.gravityDownList.add(loc);
}
if (id == 35 && data == 5) {
// light green wool - gravity well up
loc = new Location(world, startx, starty, startz).toString();
HashMap<String, Object> setu = new HashMap<String, Object>();
setu.put("tardis_id", tardis_id);
setu.put("location", loc);
setu.put("direction", 1);
setu.put("distance", 11);
setu.put("velocity", 0.5);
qf.doInsert("gravity_well", setu);
Double[] values = new Double[]{1D, 11D, 0.5D};
plugin.gravityUpList.put(loc, values);
}
}
if (room.equals("BAKER") || room.equals("WOOD")) {
// remember the controls
int secondary = (room.equals("BAKER")) ? 1 : 2;
int r = 2;
int type;
String loc_str;
List<Integer> controls = Arrays.asList(new Integer[]{69, 77, 92, 143, -113});
if (controls.contains(Integer.valueOf(id))) {
switch (id) {
case 77: // stone button - random
type = 1;
loc_str = plugin.utils.makeLocationStr(world, startx, starty, startz);
break;
case 93: // repeater
type = r;
loc_str = world.getName() + ":" + startx + ":" + starty + ":" + startz;
r++;
break;
case -113: // wood button - artron
case 143:
type = 6;
loc_str = plugin.utils.makeLocationStr(world, startx, starty, startz);
break;
default: // cake - handbrake
type = 0;
loc_str = plugin.utils.makeLocationStr(world, startx, starty, startz);
}
qf.insertControl(tardis_id, type, loc_str, secondary);
}
}
startx += x;
col++;
if (col == c && row < w) {
col = 0;
startx = resetx;
startz += z;
row++;
}
if (col == c && row == w && level < h) {
col = 0;
row = 0;
startx = resetx;
startz = resetz;
starty += 1;
level++;
}
}
}
| public void run() {
// initialise
if (!running) {
level = 0;
row = 0;
col = 0;
h = dim[0] - 1;
w = dim[1] - 1;
c = dim[2];
startx = l.getBlockX();
starty = l.getBlockY();
startz = l.getBlockZ();
resetx = startx;
resetz = startz;
world = l.getWorld();
running = true;
grammar = (TARDISConstants.vowels.contains(room.substring(0, 1))) ? "an " + room : "a " + room;
if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) {
grammar += " WELL";
}
p.sendMessage(plugin.pluginName + "Started growing " + grammar + "...");
}
String tmp;
if (level == h && row == w && col == (c - 1)) {
// the entire schematic has been read :)
if (!room.equals("GRAVITY") && !room.equals("ANTIGRAVITY")) {
byte door_data;
switch (d) {
case NORTH:
door_data = 1;
break;
case WEST:
door_data = 0;
break;
case SOUTH:
door_data = 3;
break;
default:
door_data = 2;
break;
}
// put door on
b.setTypeIdAndData(64, door_data, true);
b.getRelative(BlockFace.UP).setTypeIdAndData(64, (byte) 8, true);
}
if (iceblocks.size() > 0) {
p.sendMessage(plugin.pluginName + "Melting the ice!");
// set all the ice to water
for (Block ice : iceblocks) {
ice.setTypeId(9);
}
iceblocks.clear();
}
if (room.equals("GREENHOUSE")) {
// plant the sugar cane
for (Block cane : caneblocks) {
cane.setTypeId(83);
}
caneblocks.clear();
// attach the cocoa
for (Map.Entry<Block, Byte> entry : cocoablocks.entrySet()) {
entry.getKey().setTypeIdAndData(127, entry.getValue(), true);
}
cocoablocks.clear();
}
// update lamp block states
p.sendMessage(plugin.pluginName + "Turning on the lights!");
for (Block lamp : lampblocks) {
lamp.setType(Material.REDSTONE_LAMP_ON);
}
lampblocks.clear();
// remove the chunks, so they can unload as normal again
if (chunkList.size() > 0) {
for (Chunk ch : chunkList) {
plugin.roomChunkList.remove(ch);
}
}
// cancel the task
plugin.getServer().getScheduler().cancelTask(task);
task = 0;
String rname = (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) ? room + " WELL" : room;
p.sendMessage(plugin.pluginName + "Finished growing the " + rname + "!");
} else {
// place one block
tmp = s[level][row][col];
String[] iddata = tmp.split(":");
id = plugin.utils.parseNum(iddata[0]);
if (TARDISConstants.PROBLEM_BLOCKS.contains(Integer.valueOf(id)) && (d.equals(COMPASS.NORTH) || d.equals(COMPASS.WEST))) {
data = TARDISDataRecalculator.calculateData(id, Byte.parseByte(iddata[1]));
} else {
data = Byte.parseByte(iddata[1]);
}
if (id == 35 && data == 1) {
if (middle_id == 35 && middle_data == 1 && plugin.getConfig().getBoolean("use_clay")) {
id = 159;
} else {
id = middle_id;
}
data = middle_data;
}
if (id == 35 && data == 8) {
if (floor_id == 35 && floor_data == 8 && plugin.getConfig().getBoolean("use_clay")) {
id = 159;
} else {
id = floor_id;
}
data = floor_data;
}
QueryFactory qf = new QueryFactory(plugin);
// set condenser
if (id == 54 && room.equals("HARMONY")) {
HashMap<String, Object> setc = new HashMap<String, Object>();
setc.put("condenser", world.getName() + ":" + startx + ":" + starty + ":" + startz);
HashMap<String, Object> wherec = new HashMap<String, Object>();
wherec.put("tardis_id", tardis_id);
qf.doUpdate("tardis", setc, wherec);
}
// set farm
if (id == 52 && room.equals("FARM")) {
HashMap<String, Object> setf = new HashMap<String, Object>();
setf.put("farm", world.getName() + ":" + startx + ":" + starty + ":" + startz);
HashMap<String, Object> wheref = new HashMap<String, Object>();
wheref.put("tardis_id", tardis_id);
qf.doUpdate("tardis", setf, wheref);
// replace with floor material
id = (floor_id == 35 && floor_data == 8 && plugin.getConfig().getBoolean("use_clay")) ? 159 : floor_id;
data = floor_data;
}
// set stable
if (id == 88 && room.equals("STABLE")) {
HashMap<String, Object> sets = new HashMap<String, Object>();
sets.put("stable", world.getName() + ":" + startx + ":" + starty + ":" + startz);
HashMap<String, Object> wheres = new HashMap<String, Object>();
wheres.put("tardis_id", tardis_id);
qf.doUpdate("tardis", sets, wheres);
// replace with grass
id = 2;
data = 0;
}
// set farmland hydrated
if (id == 60 && data == 0) {
data = (byte) 4;
}
if (room.equals("GREENHOUSE")) {
// remember sugar cane
if (id == 83) {
Block cane = world.getBlockAt(startx, starty, startz);
caneblocks.add(cane);
}
// remember cocoa
if (id == 127) {
Block cocoa = world.getBlockAt(startx, starty, startz);
cocoablocks.put(cocoa, data);
}
}
if (room.equals("RAIL") && id == 85) {
// remember fence location so we can teleport the storage minecart
String loc = world.getName() + ":" + startx + ":" + starty + ":" + startz;
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("rail", loc);
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", tardis_id);
qf.doUpdate("tardis", set, where);
}
// always remove sponge
if (id == 19) {
id = 0;
data = (byte) 0;
} else {
Block existing = world.getBlockAt(startx, starty, startz);
if (existing.getTypeId() != 0) {
if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) {
switch (id) {
case 20:
case 35:
case 98:
break;
default:
id = existing.getTypeId();
data = existing.getData();
break;
}
} else {
id = existing.getTypeId();
data = existing.getData();
}
}
}
Chunk thisChunk = world.getChunkAt(world.getBlockAt(startx, starty, startz));
if (!plugin.roomChunkList.contains(thisChunk)) {
plugin.roomChunkList.add(thisChunk);
chunkList.add(thisChunk);
}
if (id != 83 && id != 127) {
plugin.utils.setBlock(world, startx, starty, startz, id, data);
}
// remember ice blocks
if (id == 79) {
Block icy = world.getBlockAt(startx, starty, startz);
iceblocks.add(icy);
}
// remember lamp blocks
if (id == 124) {
Block lamp = world.getBlockAt(startx, starty, startz);
lampblocks.add(lamp);
}
if (room.equals("GRAVITY") || room.equals("ANTIGRAVITY")) {
String loc;
if (id == 35 && data == 6) {
// pink wool - gravity well down
loc = new Location(world, startx, starty, startz).toString();
HashMap<String, Object> setd = new HashMap<String, Object>();
setd.put("tardis_id", tardis_id);
setd.put("location", loc);
setd.put("direction", 0);
setd.put("distance", 0);
setd.put("velocity", 0);
qf.doInsert("gravity_well", setd);
plugin.gravityDownList.add(loc);
}
if (id == 35 && data == 5) {
// light green wool - gravity well up
loc = new Location(world, startx, starty, startz).toString();
HashMap<String, Object> setu = new HashMap<String, Object>();
setu.put("tardis_id", tardis_id);
setu.put("location", loc);
setu.put("direction", 1);
setu.put("distance", 11);
setu.put("velocity", 0.5);
qf.doInsert("gravity_well", setu);
Double[] values = new Double[]{1D, 11D, 0.5D};
plugin.gravityUpList.put(loc, values);
}
}
if (room.equals("BAKER") || room.equals("WOOD")) {
// remember the controls
int secondary = (room.equals("BAKER")) ? 1 : 2;
int r = 2;
int type;
String loc_str;
List<Integer> controls = Arrays.asList(new Integer[]{69, 77, 92, 143, -113});
if (controls.contains(Integer.valueOf(id))) {
switch (id) {
case 77: // stone button - random
type = 1;
loc_str = plugin.utils.makeLocationStr(world, startx, starty, startz);
break;
case 93: // repeater
type = r;
loc_str = world.getName() + ":" + startx + ":" + starty + ":" + startz;
r++;
break;
case -113: // wood button - artron
case 143:
type = 6;
loc_str = plugin.utils.makeLocationStr(world, startx, starty, startz);
break;
default: // cake - handbrake
type = 0;
loc_str = plugin.utils.makeLocationStr(world, startx, starty, startz);
}
qf.insertControl(tardis_id, type, loc_str, secondary);
}
}
startx += x;
col++;
if (col == c && row < w) {
col = 0;
startx = resetx;
startz += z;
row++;
}
if (col == c && row == w && level < h) {
col = 0;
row = 0;
startx = resetx;
startz = resetz;
starty += 1;
level++;
}
}
}
|
diff --git a/src/org/nutz/dao/impl/link/DoInsertLinkVisitor.java b/src/org/nutz/dao/impl/link/DoInsertLinkVisitor.java
index 59a374ce5..1d2a5abcb 100644
--- a/src/org/nutz/dao/impl/link/DoInsertLinkVisitor.java
+++ b/src/org/nutz/dao/impl/link/DoInsertLinkVisitor.java
@@ -1,52 +1,54 @@
package org.nutz.dao.impl.link;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.LinkField;
import org.nutz.dao.impl.AbstractLinkVisitor;
import org.nutz.dao.sql.Pojo;
import org.nutz.dao.sql.PojoCallback;
import org.nutz.dao.util.Pojos;
import org.nutz.lang.Each;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;
public class DoInsertLinkVisitor extends AbstractLinkVisitor {
public void visit(final Object obj, final LinkField lnk) {
final Object value = lnk.getValue(obj);
if (Lang.length(value) == 0)
return;
// 从宿主对象更新关联对象
opt.add(Pojos.createRun(new PojoCallback() {
public Object invoke(Connection conn, ResultSet rs, Pojo pojo) throws SQLException {
lnk.updateLinkedField(obj, value);
return pojo.getOperatingObject();
}
}).setOperatingObject(obj));
// 为其循环生成插入语句 : holder.getEntityBy 会考虑到集合和数组的情况的
final Entity<?> en = lnk.getLinkedEntity();
Lang.each(value, new Each<Object>() {
public void invoke(int i, Object ele, int length) throws ExitLoop, LoopException {
+ if (ele == null)
+ throw new NullPointerException("null ele in linked field!!");
// 执行插入
opt.addInsert(en, ele);
// 更新字段
opt.add(Pojos.createRun(new PojoCallback() {
public Object invoke(Connection conn, ResultSet rs, Pojo pojo)
throws SQLException {
lnk.saveLinkedField(obj, pojo.getOperatingObject());
return pojo.getOperatingObject();
}
}).setOperatingObject(ele));
}
});
}
}
| true | true | public void visit(final Object obj, final LinkField lnk) {
final Object value = lnk.getValue(obj);
if (Lang.length(value) == 0)
return;
// 从宿主对象更新关联对象
opt.add(Pojos.createRun(new PojoCallback() {
public Object invoke(Connection conn, ResultSet rs, Pojo pojo) throws SQLException {
lnk.updateLinkedField(obj, value);
return pojo.getOperatingObject();
}
}).setOperatingObject(obj));
// 为其循环生成插入语句 : holder.getEntityBy 会考虑到集合和数组的情况的
final Entity<?> en = lnk.getLinkedEntity();
Lang.each(value, new Each<Object>() {
public void invoke(int i, Object ele, int length) throws ExitLoop, LoopException {
// 执行插入
opt.addInsert(en, ele);
// 更新字段
opt.add(Pojos.createRun(new PojoCallback() {
public Object invoke(Connection conn, ResultSet rs, Pojo pojo)
throws SQLException {
lnk.saveLinkedField(obj, pojo.getOperatingObject());
return pojo.getOperatingObject();
}
}).setOperatingObject(ele));
}
});
}
| public void visit(final Object obj, final LinkField lnk) {
final Object value = lnk.getValue(obj);
if (Lang.length(value) == 0)
return;
// 从宿主对象更新关联对象
opt.add(Pojos.createRun(new PojoCallback() {
public Object invoke(Connection conn, ResultSet rs, Pojo pojo) throws SQLException {
lnk.updateLinkedField(obj, value);
return pojo.getOperatingObject();
}
}).setOperatingObject(obj));
// 为其循环生成插入语句 : holder.getEntityBy 会考虑到集合和数组的情况的
final Entity<?> en = lnk.getLinkedEntity();
Lang.each(value, new Each<Object>() {
public void invoke(int i, Object ele, int length) throws ExitLoop, LoopException {
if (ele == null)
throw new NullPointerException("null ele in linked field!!");
// 执行插入
opt.addInsert(en, ele);
// 更新字段
opt.add(Pojos.createRun(new PojoCallback() {
public Object invoke(Connection conn, ResultSet rs, Pojo pojo)
throws SQLException {
lnk.saveLinkedField(obj, pojo.getOperatingObject());
return pojo.getOperatingObject();
}
}).setOperatingObject(ele));
}
});
}
|
diff --git a/BigInteger1.java b/BigInteger1.java
index 8d3e529..5039b94 100644
--- a/BigInteger1.java
+++ b/BigInteger1.java
@@ -1,25 +1,25 @@
import java.math.BigInteger;
public class BigInteger1 {
public static void main(String[] args) {
BigInteger two = new BigInteger("2");
BigInteger bigint = two.pow(256);
System.out.println(bigint);
BigInteger bigint2 = bigint.multiply(two);
System.out.println(bigint2);
BigInteger bigint3 = bigint.divide(two);
System.out.println(bigint3);
- System.out.format("0x%s%n", bigint3.toString(16));
+ System.out.format("%#x%n", bigint3);
// Is bigint2 larger than bigint3?
System.out.println(bigint2.compareTo(bigint3) > 0);
// Really?
System.out.println(bigint3.compareTo(bigint2) < 0);
// compareTo() uses the operators you expect between the method call
// and the zero.
System.out.println(bigint2.compareTo(bigint3) == 0);
System.out.println(bigint2.compareTo(bigint3) != 0);
}
}
| true | true | public static void main(String[] args) {
BigInteger two = new BigInteger("2");
BigInteger bigint = two.pow(256);
System.out.println(bigint);
BigInteger bigint2 = bigint.multiply(two);
System.out.println(bigint2);
BigInteger bigint3 = bigint.divide(two);
System.out.println(bigint3);
System.out.format("0x%s%n", bigint3.toString(16));
// Is bigint2 larger than bigint3?
System.out.println(bigint2.compareTo(bigint3) > 0);
// Really?
System.out.println(bigint3.compareTo(bigint2) < 0);
// compareTo() uses the operators you expect between the method call
// and the zero.
System.out.println(bigint2.compareTo(bigint3) == 0);
System.out.println(bigint2.compareTo(bigint3) != 0);
}
| public static void main(String[] args) {
BigInteger two = new BigInteger("2");
BigInteger bigint = two.pow(256);
System.out.println(bigint);
BigInteger bigint2 = bigint.multiply(two);
System.out.println(bigint2);
BigInteger bigint3 = bigint.divide(two);
System.out.println(bigint3);
System.out.format("%#x%n", bigint3);
// Is bigint2 larger than bigint3?
System.out.println(bigint2.compareTo(bigint3) > 0);
// Really?
System.out.println(bigint3.compareTo(bigint2) < 0);
// compareTo() uses the operators you expect between the method call
// and the zero.
System.out.println(bigint2.compareTo(bigint3) == 0);
System.out.println(bigint2.compareTo(bigint3) != 0);
}
|
diff --git a/WorldWindRad/src/settings/SettingsDialog.java b/WorldWindRad/src/settings/SettingsDialog.java
index ea0210e6..b34a3bf4 100644
--- a/WorldWindRad/src/settings/SettingsDialog.java
+++ b/WorldWindRad/src/settings/SettingsDialog.java
@@ -1,533 +1,534 @@
package settings;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import settings.Settings.ProjectionMode;
import settings.Settings.StereoMode;
public class SettingsDialog extends JDialog
{
private final static Logger logger = Logger.getLogger(SettingsDialog.class
.getName());
private final static int SPACING = 5;
private static Rectangle oldBounds;
private Settings settings;
private JCheckBox stereoEnabledCheck;
private JCheckBox stereoSwapCheck;
private JLabel stereoModeLabel;
private JComboBox stereoModeCombo;
private JLabel projectionModeLabel;
private JComboBox projectionModeCombo;
private JLabel eyeSeparationLabel;
private JSpinner eyeSeparationSpinner;
private JLabel focalLengthLabel;
private JSpinner focalLengthSpinner;
private JCheckBox stereoCursorCheck;
private JCheckBox proxyEnabledCheck;
private JLabel proxyHostLabel;
private JTextField proxyHostText;
private JLabel proxyPortLabel;
private JIntegerField proxyPortText;
private JLabel nonProxyHostsLabel;
private JTextField nonProxyHostsText;
public SettingsDialog(JFrame frame)
{
super(frame, "Settings", true);
settings = Settings.get();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
cancel();
}
});
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel optionsPanel = new JPanel(new BorderLayout());
JPanel buttonsPanel = new JPanel(new FlowLayout());
mainPanel.add(optionsPanel, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(mainPanel);
optionsPanel.add(createTabs());
JButton ok = new JButton("Ok");
JButton cancel = new JButton("Cancel");
buttonsPanel.add(ok);
buttonsPanel.add(cancel);
ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (verifyAndSave())
{
dispose();
}
}
});
cancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
cancel();
}
});
pack();
//setResizable(false);
if (oldBounds != null)
{
setBounds(oldBounds);
}
else
{
setLocationRelativeTo(frame);
}
addComponentListener(new ComponentAdapter()
{
@Override
public void componentMoved(ComponentEvent e)
{
oldBounds = getBounds();
}
@Override
public void componentResized(ComponentEvent e)
{
oldBounds = getBounds();
}
});
}
private void cancel()
{
dispose();
}
private boolean verifyAndSave()
{
boolean proxyValid = true;
boolean stereoEnabled = stereoEnabledCheck.isSelected();
boolean stereoSwap = stereoSwapCheck.isSelected();
StereoMode stereoMode = (StereoMode) stereoModeCombo.getSelectedItem();
ProjectionMode projectionMode = (ProjectionMode) projectionModeCombo
.getSelectedItem();
double eyeSeparation = (Double) eyeSeparationSpinner.getValue();
double focalLength = (Double) focalLengthSpinner.getValue();
boolean stereoCursor = stereoCursorCheck.isSelected();
boolean proxyEnabled = proxyEnabledCheck.isSelected();
String proxyHost = proxyHostText.getText();
int proxyPort = proxyPortText.getValue();
String nonProxyHostsString = nonProxyHostsText.getText();
String[] nph = nonProxyHostsString.split(",");
String nonProxyHosts = "";
for (String str : nph)
{
String trim = str.trim();
if (trim.length() > 0)
{
nonProxyHosts += "|" + trim;
}
}
nonProxyHosts = nonProxyHosts.length() == 0 ? nonProxyHosts
: nonProxyHosts.substring(1);
if (proxyEnabled)
{
if (proxyHost.length() == 0 || proxyPort <= 0)
{
proxyValid = false;
showError(this, "Proxy values you entered are invalid.");
}
}
boolean valid = proxyValid;
if (valid)
{
try
{
settings.setStereoEnabled(stereoEnabled);
settings.setStereoSwap(stereoSwap);
settings.setStereoMode(stereoMode);
settings.setProjectionMode(projectionMode);
settings.setEyeSeparation(eyeSeparation);
settings.setFocalLength(focalLength);
settings.setStereoCursor(stereoCursor);
settings.setProxyEnabled(proxyEnabled);
settings.setProxyHost(proxyHost);
settings.setProxyPort(proxyPort);
settings.setNonProxyHosts(nonProxyHosts);
settings.save();
}
catch (BackingStoreException e)
{
logger.severe("Error saving settings: " + e.toString());
}
}
return valid;
}
private static void showError(Component parent, String message)
{
JOptionPane.showMessageDialog(parent, message, "Error",
JOptionPane.ERROR_MESSAGE);
}
@SuppressWarnings("unused")
private static void showInfo(Component parent, String message)
{
JOptionPane.showMessageDialog(parent, message, "Info",
JOptionPane.INFORMATION_MESSAGE);
}
private JTabbedPane createTabs()
{
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Renderer", createRenderer());
tabbedPane.addTab("Network", createNetwork());
tabbedPane.validate();
return tabbedPane;
}
private Component createRenderer()
{
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEtchedBorder());
GridBagConstraints c;
JComponent stereo = createStereo();
stereo.setBorder(BorderFactory.createTitledBorder("Stereo"));
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
c.weightx = 1;
c.weighty = 1;
c.insets = new Insets(SPACING, SPACING, SPACING, SPACING);
panel.add(stereo, c);
enableStereoSettings();
return panel;
}
private JComponent createNetwork()
{
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEtchedBorder());
GridBagConstraints c;
JComponent proxy = createProxy();
proxy.setBorder(BorderFactory.createTitledBorder("Proxy"));
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
c.weightx = 1;
c.weighty = 1;
c.insets = new Insets(SPACING, SPACING, SPACING, SPACING);
panel.add(proxy, c);
return panel;
}
private JComponent createStereo()
{
GridBagConstraints c;
JPanel panel = new JPanel(new GridBagLayout());
JPanel checks = new JPanel(new GridLayout(0, 2));
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(checks, c);
stereoEnabledCheck = new JCheckBox("Enable stereo");
stereoEnabledCheck.setSelected(settings.isStereoEnabled());
stereoEnabledCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
enableStereoSettings();
}
});
checks.add(stereoEnabledCheck);
stereoSwapCheck = new JCheckBox("Swap eyes");
stereoSwapCheck.setSelected(settings.isStereoSwap());
checks.add(stereoSwapCheck);
stereoModeLabel = new JLabel("Stereo mode:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(stereoModeLabel, c);
stereoModeCombo = new JComboBox(StereoMode.values());
stereoModeCombo.setSelectedItem(settings.getStereoMode());
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.weightx = 1;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(stereoModeCombo, c);
if (!Settings.get().isStereoSupported())
{
stereoModeCombo.removeItem(StereoMode.STEREOBUFFER);
}
projectionModeLabel = new JLabel("Projection mode:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(projectionModeLabel, c);
projectionModeCombo = new JComboBox(ProjectionMode.values());
projectionModeCombo.setSelectedItem(settings.getProjectionMode());
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.weightx = 1;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(projectionModeCombo, c);
projectionModeCombo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
enableStereoSettings();
}
});
eyeSeparationLabel = new JLabel("Eye separation:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(eyeSeparationLabel, c);
SpinnerModel eyeSeparationModel = new SpinnerNumberModel(settings
.getEyeSeparation(), 0, 10, 0.1);
eyeSeparationSpinner = new JSpinner(eyeSeparationModel);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(eyeSeparationSpinner, c);
focalLengthLabel = new JLabel("Focal length:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 4;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(focalLengthLabel, c);
SpinnerModel focalLengthModel = new SpinnerNumberModel(settings
- .getFocalLength(), 0, 1000, 1);
+ .getFocalLength(), 0, 10000, 1);
focalLengthSpinner = new JSpinner(focalLengthModel);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 4;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(focalLengthSpinner, c);
stereoCursorCheck = new JCheckBox("Stereo mouse cursor");
+ stereoCursorCheck.setSelected(settings.isStereoCursor());
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 5;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, SPACING, SPACING);
panel.add(stereoCursorCheck, c);
return panel;
}
private JComponent createProxy()
{
GridBagConstraints c;
JPanel panel = new JPanel(new GridBagLayout());
proxyEnabledCheck = new JCheckBox("Enable proxy");
proxyEnabledCheck.setSelected(settings.isProxyEnabled());
proxyEnabledCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
enableProxySettings();
}
});
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(proxyEnabledCheck, c);
proxyHostLabel = new JLabel("Host:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(proxyHostLabel, c);
proxyHostText = new JTextField(settings.getProxyHost());
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(proxyHostText, c);
proxyPortLabel = new JLabel("Port:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(proxyPortLabel, c);
proxyPortText = new JIntegerField(settings.getProxyPort());
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(proxyPortText, c);
nonProxyHostsLabel = new JLabel("Non-proxy hosts:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(nonProxyHostsLabel, c);
String[] nph = settings.getNonProxyHosts().split("\\|");
String nonProxyHosts = "";
for (String str : nph)
{
String trim = str.trim();
if (trim.length() > 0)
{
nonProxyHosts += "," + trim;
}
}
nonProxyHosts = nonProxyHosts.length() == 0 ? nonProxyHosts
: nonProxyHosts.substring(1);
nonProxyHostsText = new JTextField(nonProxyHosts);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, SPACING, SPACING);
panel.add(nonProxyHostsText, c);
enableProxySettings();
return panel;
}
private void enableProxySettings()
{
boolean enabled = proxyEnabledCheck.isSelected();
proxyHostLabel.setEnabled(enabled);
proxyHostText.setEnabled(enabled);
proxyPortLabel.setEnabled(enabled);
proxyPortText.setEnabled(enabled);
nonProxyHostsLabel.setEnabled(enabled);
nonProxyHostsText.setEnabled(enabled);
}
private void enableStereoSettings()
{
boolean enabled = stereoEnabledCheck.isSelected();
stereoModeLabel.setEnabled(enabled);
stereoModeCombo.setEnabled(enabled);
stereoSwapCheck.setEnabled(enabled);
projectionModeLabel.setEnabled(enabled);
projectionModeCombo.setEnabled(enabled);
eyeSeparationLabel.setEnabled(enabled);
eyeSeparationSpinner.setEnabled(enabled);
stereoCursorCheck.setEnabled(enabled);
boolean focalLengthEnabled = enabled
&& projectionModeCombo.getSelectedItem() == ProjectionMode.ASYMMETRIC_FRUSTUM;
focalLengthLabel.setEnabled(focalLengthEnabled);
focalLengthSpinner.setEnabled(focalLengthEnabled);
}
}
| false | true | private JComponent createStereo()
{
GridBagConstraints c;
JPanel panel = new JPanel(new GridBagLayout());
JPanel checks = new JPanel(new GridLayout(0, 2));
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(checks, c);
stereoEnabledCheck = new JCheckBox("Enable stereo");
stereoEnabledCheck.setSelected(settings.isStereoEnabled());
stereoEnabledCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
enableStereoSettings();
}
});
checks.add(stereoEnabledCheck);
stereoSwapCheck = new JCheckBox("Swap eyes");
stereoSwapCheck.setSelected(settings.isStereoSwap());
checks.add(stereoSwapCheck);
stereoModeLabel = new JLabel("Stereo mode:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(stereoModeLabel, c);
stereoModeCombo = new JComboBox(StereoMode.values());
stereoModeCombo.setSelectedItem(settings.getStereoMode());
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.weightx = 1;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(stereoModeCombo, c);
if (!Settings.get().isStereoSupported())
{
stereoModeCombo.removeItem(StereoMode.STEREOBUFFER);
}
projectionModeLabel = new JLabel("Projection mode:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(projectionModeLabel, c);
projectionModeCombo = new JComboBox(ProjectionMode.values());
projectionModeCombo.setSelectedItem(settings.getProjectionMode());
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.weightx = 1;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(projectionModeCombo, c);
projectionModeCombo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
enableStereoSettings();
}
});
eyeSeparationLabel = new JLabel("Eye separation:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(eyeSeparationLabel, c);
SpinnerModel eyeSeparationModel = new SpinnerNumberModel(settings
.getEyeSeparation(), 0, 10, 0.1);
eyeSeparationSpinner = new JSpinner(eyeSeparationModel);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(eyeSeparationSpinner, c);
focalLengthLabel = new JLabel("Focal length:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 4;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(focalLengthLabel, c);
SpinnerModel focalLengthModel = new SpinnerNumberModel(settings
.getFocalLength(), 0, 1000, 1);
focalLengthSpinner = new JSpinner(focalLengthModel);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 4;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(focalLengthSpinner, c);
stereoCursorCheck = new JCheckBox("Stereo mouse cursor");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 5;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, SPACING, SPACING);
panel.add(stereoCursorCheck, c);
return panel;
}
| private JComponent createStereo()
{
GridBagConstraints c;
JPanel panel = new JPanel(new GridBagLayout());
JPanel checks = new JPanel(new GridLayout(0, 2));
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(checks, c);
stereoEnabledCheck = new JCheckBox("Enable stereo");
stereoEnabledCheck.setSelected(settings.isStereoEnabled());
stereoEnabledCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
enableStereoSettings();
}
});
checks.add(stereoEnabledCheck);
stereoSwapCheck = new JCheckBox("Swap eyes");
stereoSwapCheck.setSelected(settings.isStereoSwap());
checks.add(stereoSwapCheck);
stereoModeLabel = new JLabel("Stereo mode:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(stereoModeLabel, c);
stereoModeCombo = new JComboBox(StereoMode.values());
stereoModeCombo.setSelectedItem(settings.getStereoMode());
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
c.weightx = 1;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(stereoModeCombo, c);
if (!Settings.get().isStereoSupported())
{
stereoModeCombo.removeItem(StereoMode.STEREOBUFFER);
}
projectionModeLabel = new JLabel("Projection mode:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(projectionModeLabel, c);
projectionModeCombo = new JComboBox(ProjectionMode.values());
projectionModeCombo.setSelectedItem(settings.getProjectionMode());
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 2;
c.weightx = 1;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(projectionModeCombo, c);
projectionModeCombo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
enableStereoSettings();
}
});
eyeSeparationLabel = new JLabel("Eye separation:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(eyeSeparationLabel, c);
SpinnerModel eyeSeparationModel = new SpinnerNumberModel(settings
.getEyeSeparation(), 0, 10, 0.1);
eyeSeparationSpinner = new JSpinner(eyeSeparationModel);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(eyeSeparationSpinner, c);
focalLengthLabel = new JLabel("Focal length:");
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 4;
c.anchor = GridBagConstraints.EAST;
c.insets = new Insets(SPACING, SPACING, 0, 0);
panel.add(focalLengthLabel, c);
SpinnerModel focalLengthModel = new SpinnerNumberModel(settings
.getFocalLength(), 0, 10000, 1);
focalLengthSpinner = new JSpinner(focalLengthModel);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 4;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, 0, SPACING);
panel.add(focalLengthSpinner, c);
stereoCursorCheck = new JCheckBox("Stereo mouse cursor");
stereoCursorCheck.setSelected(settings.isStereoCursor());
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 5;
c.gridwidth = 4;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(SPACING, SPACING, SPACING, SPACING);
panel.add(stereoCursorCheck, c);
return panel;
}
|
diff --git a/src/org/jacorb/orb/util/FixIOR.java b/src/org/jacorb/orb/util/FixIOR.java
index 77a07b1b9..667f452ce 100644
--- a/src/org/jacorb/orb/util/FixIOR.java
+++ b/src/org/jacorb/orb/util/FixIOR.java
@@ -1,143 +1,145 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2002 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.jacorb.orb.util;
import org.jacorb.orb.connection.CodeSet;
import org.jacorb.orb.ParsedIOR;
import org.jacorb.orb.*;
import org.omg.IOP.*;
import org.omg.GIOP.*;
import org.omg.IIOP.*;
import org.omg.SSLIOP.*;
import org.omg.CSIIOP.*;
import org.omg.CONV_FRAME.*;
import java.io.*;
/**
* Utility class to patch host and port information into an IOR.
*
* @author Steve Osselton
*/
public class FixIOR
{
public static void main (String args[])
throws Exception
{
org.omg.CORBA.ORB orb;
String iorString;
String host;
BufferedReader br;
BufferedWriter bw;
CDRInputStream is;
CDROutputStream os;
ParsedIOR pior;
IOR ior;
TaggedProfile[] profiles;
ProfileBody_1_0 body10;
ProfileBody_1_1 body11;
short port;
int iport;
if (args.length != 4)
{
System.err.println ("Usage: FixIOR ior_file ior_out_file host port");
System.exit( 1 );
}
host = args[2];
orb = org.omg.CORBA.ORB.init (args, null);
// Read in IOR from file
br = new BufferedReader (new FileReader (args[0]));
iorString = br.readLine ();
br.close ();
if (! iorString.startsWith ("IOR:"))
{
- System.err.println ("IOR must be in the standard IOR URL scheme");
+ System.err.println ("IOR must be in the standard IOR URL format");
System.exit (1);
}
iport = Integer.parseInt (args[3]);
if (iport > 32767)
{
iport = iport - 65536;
}
port = (short) iport;
// Parse IOR
pior = new ParsedIOR (iorString);
ior = pior.getIOR ();
// Iterate through IIOP profiles setting host and port
profiles = ior.profiles;
for (int i = 0; i < profiles.length; i++)
{
if (profiles[i].tag == TAG_INTERNET_IOP.value)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
+ is.openEncapsulatedArray ();
body10 = ProfileBody_1_0Helper.read (is);
is.close ();
os = new CDROutputStream ();
os.beginEncapsulatedArray ();
if (body10.iiop_version.minor > 0)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
+ is.openEncapsulatedArray ();
body11 = ProfileBody_1_1Helper.read (is);
is.close ();
body11.host = host;
body11.port = port;
ProfileBody_1_1Helper.write (os, body11);
}
else
{
body10.host = host;
body10.port = port;
ProfileBody_1_0Helper.write (os, body10);
}
profiles[i].profile_data = os.getBufferCopy ();
}
}
pior = new ParsedIOR (ior);
// Write out new IOR to file
bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (args[1])));
bw.write (pior.getIORString ());
bw.close ();
}
private FixIOR ()
{
}
}
| false | true | public static void main (String args[])
throws Exception
{
org.omg.CORBA.ORB orb;
String iorString;
String host;
BufferedReader br;
BufferedWriter bw;
CDRInputStream is;
CDROutputStream os;
ParsedIOR pior;
IOR ior;
TaggedProfile[] profiles;
ProfileBody_1_0 body10;
ProfileBody_1_1 body11;
short port;
int iport;
if (args.length != 4)
{
System.err.println ("Usage: FixIOR ior_file ior_out_file host port");
System.exit( 1 );
}
host = args[2];
orb = org.omg.CORBA.ORB.init (args, null);
// Read in IOR from file
br = new BufferedReader (new FileReader (args[0]));
iorString = br.readLine ();
br.close ();
if (! iorString.startsWith ("IOR:"))
{
System.err.println ("IOR must be in the standard IOR URL scheme");
System.exit (1);
}
iport = Integer.parseInt (args[3]);
if (iport > 32767)
{
iport = iport - 65536;
}
port = (short) iport;
// Parse IOR
pior = new ParsedIOR (iorString);
ior = pior.getIOR ();
// Iterate through IIOP profiles setting host and port
profiles = ior.profiles;
for (int i = 0; i < profiles.length; i++)
{
if (profiles[i].tag == TAG_INTERNET_IOP.value)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
body10 = ProfileBody_1_0Helper.read (is);
is.close ();
os = new CDROutputStream ();
os.beginEncapsulatedArray ();
if (body10.iiop_version.minor > 0)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
body11 = ProfileBody_1_1Helper.read (is);
is.close ();
body11.host = host;
body11.port = port;
ProfileBody_1_1Helper.write (os, body11);
}
else
{
body10.host = host;
body10.port = port;
ProfileBody_1_0Helper.write (os, body10);
}
profiles[i].profile_data = os.getBufferCopy ();
}
}
pior = new ParsedIOR (ior);
// Write out new IOR to file
bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (args[1])));
bw.write (pior.getIORString ());
bw.close ();
}
| public static void main (String args[])
throws Exception
{
org.omg.CORBA.ORB orb;
String iorString;
String host;
BufferedReader br;
BufferedWriter bw;
CDRInputStream is;
CDROutputStream os;
ParsedIOR pior;
IOR ior;
TaggedProfile[] profiles;
ProfileBody_1_0 body10;
ProfileBody_1_1 body11;
short port;
int iport;
if (args.length != 4)
{
System.err.println ("Usage: FixIOR ior_file ior_out_file host port");
System.exit( 1 );
}
host = args[2];
orb = org.omg.CORBA.ORB.init (args, null);
// Read in IOR from file
br = new BufferedReader (new FileReader (args[0]));
iorString = br.readLine ();
br.close ();
if (! iorString.startsWith ("IOR:"))
{
System.err.println ("IOR must be in the standard IOR URL format");
System.exit (1);
}
iport = Integer.parseInt (args[3]);
if (iport > 32767)
{
iport = iport - 65536;
}
port = (short) iport;
// Parse IOR
pior = new ParsedIOR (iorString);
ior = pior.getIOR ();
// Iterate through IIOP profiles setting host and port
profiles = ior.profiles;
for (int i = 0; i < profiles.length; i++)
{
if (profiles[i].tag == TAG_INTERNET_IOP.value)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
is.openEncapsulatedArray ();
body10 = ProfileBody_1_0Helper.read (is);
is.close ();
os = new CDROutputStream ();
os.beginEncapsulatedArray ();
if (body10.iiop_version.minor > 0)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
is.openEncapsulatedArray ();
body11 = ProfileBody_1_1Helper.read (is);
is.close ();
body11.host = host;
body11.port = port;
ProfileBody_1_1Helper.write (os, body11);
}
else
{
body10.host = host;
body10.port = port;
ProfileBody_1_0Helper.write (os, body10);
}
profiles[i].profile_data = os.getBufferCopy ();
}
}
pior = new ParsedIOR (ior);
// Write out new IOR to file
bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (args[1])));
bw.write (pior.getIORString ());
bw.close ();
}
|
diff --git a/edu/wisc/ssec/mcidasv/chooser/adde/AddeImageParameterChooser.java b/edu/wisc/ssec/mcidasv/chooser/adde/AddeImageParameterChooser.java
index 6c59b0654..38b64b0a1 100644
--- a/edu/wisc/ssec/mcidasv/chooser/adde/AddeImageParameterChooser.java
+++ b/edu/wisc/ssec/mcidasv/chooser/adde/AddeImageParameterChooser.java
@@ -1,347 +1,347 @@
/*
* $Id$
*
* This file is part of McIDAS-V
*
* Copyright 2007-2011
* Space Science and Engineering Center (SSEC)
* University of Wisconsin - Madison
* 1225 W. Dayton Street, Madison, WI 53706, USA
* http://www.ssec.wisc.edu/mcidas
*
* All Rights Reserved
*
* McIDAS-V is built on Unidata's IDV and SSEC's VisAD libraries, and
* some McIDAS-V source code is based on IDV and VisAD source code.
*
* McIDAS-V is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* McIDAS-V 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package edu.wisc.ssec.mcidasv.chooser.adde;
import static javax.swing.GroupLayout.DEFAULT_SIZE;
import static javax.swing.GroupLayout.PREFERRED_SIZE;
import static javax.swing.GroupLayout.Alignment.BASELINE;
import static javax.swing.GroupLayout.Alignment.LEADING;
import static javax.swing.LayoutStyle.ComponentPlacement.RELATED;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Hashtable;
import java.util.List;
import javax.swing.GroupLayout;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.w3c.dom.Element;
import edu.wisc.ssec.mcidas.AreaDirectory;
import ucar.unidata.data.imagery.BandInfo;
import ucar.unidata.idv.chooser.IdvChooserManager;
import ucar.unidata.util.TwoFacedObject;
import ucar.unidata.xml.XmlObjectStore;
import edu.wisc.ssec.mcidasv.Constants;
import edu.wisc.ssec.mcidasv.util.McVGuiUtils;
/**
* Widget to select images from a remote ADDE server
* Displays a list of the descriptors (names) of the image datasets
* available for a particular ADDE group on the remote server.
*
* @author Don Murray
*/
public class AddeImageParameterChooser extends AddeImageChooser implements Constants {
/**
* Public keys for server, group, dataset, user, project.
*/
public final static String SIZE_KEY = "size";
public final static String BAND_KEY = "band";
public final static String PLACE_KEY = "place";
public final static String LATLON_KEY = "latlon";
public final static String LINELE_KEY = "linele";
public final static String MAG_KEY = "mag";
public final static String UNIT_KEY = "unit";
public final static String PREVIEW_KEY = "preview";
/** Property for image default value unit */
protected static final String PROP_NAV = "NAV";
/** Property for image default value unit */
protected static final String PROP_UNIT = "UNIT";
/** Property for image default value band */
protected static final String PROP_BAND = "BAND";
/** Xml attr name for the defaults */
private static final String ATTR_NAV = "NAV";
private static final String ATTR_UNIT = "UNIT";
private static final String ATTR_BAND = "BAND";
private static final String ATTR_PLACE = "PLACE";
private static final String ATTR_SIZE = "SIZE";
private static final String ATTR_MAG = "MAG";
private static final String ATTR_LATLON = "LATLON";
private static final String ATTR_LINELE = "LINELE";
/** string for ALL */
private static final String ALL = "ALL";
private static JCheckBox previewBox = null;
/**
* Construct an Adde image selection widget
*
*
* @param mgr The chooser manager
* @param root The chooser.xml node
*/
public AddeImageParameterChooser(IdvChooserManager mgr, Element root) {
super(mgr, root);
//DAVEP: Hiding parameter set picker for now... revisit after 1.0
// showParameterButton();
}
/**
* Return the parameter type associated with this chooser. Override!
*/
@Override
protected String getParameterSetType() {
return "addeimagery";
}
/**
* Return the data source ID. Used by extending classes.
*/
@Override
protected String getDataSourceId() {
return "ADDE.IMAGE.V";
}
/**
* Restore the selected parameter set using element attributes
*
* @param restoreElement
* @return
*/
@Override
protected boolean restoreParameterSet(Element restoreElement) {
boolean okay = super.restoreParameterSet(restoreElement);
if (!okay) return okay;
// Imagery specific restore
// Restore nav
if (restoreElement.hasAttribute(ATTR_NAV)) {
String nav = restoreElement.getAttribute(ATTR_NAV);
TwoFacedObject tfo = new TwoFacedObject("Default", "X");
navComboBox.setSelectedItem((Object)tfo);
if (nav.toUpperCase().equals("LALO")) {
tfo = new TwoFacedObject("Lat/Lon", "LALO");
}
navComboBox.setSelectedItem((Object)tfo);
}
return true;
}
/**
* Get the list of BandInfos for the current selected images
* @return list of BandInfos
*/
public List<BandInfo> getSelectedBandInfos() {
return super.getBandInfos();
}
/**
* Get the value for the given property. This can either be the value
* supplied by the end user through the advanced GUI or is the default
*
* @param prop The property
* @param ad The AreaDirectory
*
* @return The value of the property to use in the request string
*/
@Override
protected String getPropValue(String prop, AreaDirectory ad) {
String propValue = super.getPropValue(prop, ad);
if (prop.equals(PROP_NAV)) {
propValue = TwoFacedObject.getIdString(navComboBox.getSelectedItem());
}
return propValue;
}
/**
* Optionally override any defaults per parameter chooser
* @param property
* @return
*/
@Override
protected String getDefault(String property, String dflt) {
String paramDefault = super.getDefault(property, dflt);
if (property.equals(PROP_NAV)) {
if (restoreElement != null) {
paramDefault = restoreElement.getAttribute(ATTR_NAV);
}
} else if (property.equals(PROP_UNIT)) {
paramDefault = "";
} else if (property.equals(PROP_BAND)) {
paramDefault = ALL;
} else if (property.equals(PROP_PLACE)) {
paramDefault = "";
}
return paramDefault;
}
/**
* Get the DataSource properties
*
* @param ht
* Hashtable of properties
*/
@Override
protected void getDataSourceProperties(Hashtable ht) {
super.getDataSourceProperties(ht);
if (restoreElement != null) {
if (restoreElement.hasAttribute(ATTR_BAND)) {
ht.put(BAND_KEY, (Object)(restoreElement.getAttribute(ATTR_BAND)));
}
if (restoreElement.hasAttribute(ATTR_LATLON)) {
ht.put(LATLON_KEY, (Object)(restoreElement.getAttribute(ATTR_LATLON)));
}
if (restoreElement.hasAttribute(ATTR_LINELE)) {
ht.put(LINELE_KEY, (Object)(restoreElement.getAttribute(ATTR_LINELE)));
}
if (restoreElement.hasAttribute(ATTR_MAG)) {
ht.put(MAG_KEY, (Object)(restoreElement.getAttribute(ATTR_MAG)));
}
if (restoreElement.hasAttribute(ATTR_PLACE)) {
ht.put(PLACE_KEY, (Object)(restoreElement.getAttribute(ATTR_PLACE)));
}
if (restoreElement.hasAttribute(ATTR_SIZE)) {
ht.put(SIZE_KEY, (Object)(restoreElement.getAttribute(ATTR_SIZE)));
}
if (restoreElement.hasAttribute(ATTR_UNIT)) {
ht.put(UNIT_KEY, (Object)(restoreElement.getAttribute(ATTR_UNIT)));
}
}
ht.put(PREVIEW_KEY, (Object)previewBox.isSelected());
}
/**
* Should we use the user supplied property
*
* @param propId
* The property
*
* @return Should use the value from the advanced widget
*/
protected boolean usePropFromUser(String propId) {
boolean fromSuper = super.usePropFromUser(propId);
if (propId.equals(PROP_UNIT)) fromSuper = false;
else if (propId.equals(PROP_BAND)) fromSuper = false;
return fromSuper;
}
/**
* Make the UI for this selector.
*
* @return The gui
*/
@Override
public JComponent doMakeContents() {
JPanel myPanel = new JPanel();
JLabel timesLabel = McVGuiUtils.makeLabelRight("Times:");
addDescComp(timesLabel);
JPanel timesPanel = makeTimesPanel();
timesPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
addDescComp(timesPanel);
- JLabel navigationLabel = McVGuiUtils.makeLabelRight("Navegation:");
+ JLabel navigationLabel = McVGuiUtils.makeLabelRight("Navigation:");
addDescComp(navigationLabel);
// Use processPropertyComponents to build combo boxes that we rely on
processPropertyComponents();
addDescComp(navComboBox);
McVGuiUtils.setComponentWidth(navComboBox, McVGuiUtils.Width.DOUBLE);
// Preview checkbox
JLabel previewLabel = McVGuiUtils.makeLabelRight("Preview:");
addDescComp(previewLabel);
XmlObjectStore store = getIdv().getStore();
previewBox = new JCheckBox("Create preview image", store.get(Constants.PREF_IMAGE_PREVIEW, true));
previewBox.setToolTipText("Creating preview images takes extra time and network bandwidth");
previewBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
XmlObjectStore store = getIdv().getStore();
store.put(Constants.PREF_IMAGE_PREVIEW, e.getStateChange());
store.save();
}
});
addDescComp(previewBox);
GroupLayout layout = new GroupLayout(myPanel);
myPanel.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(descriptorLabel)
.addGap(GAP_RELATED)
.addComponent(descriptorComboBox))
.addGroup(layout.createSequentialGroup()
.addComponent(timesLabel)
.addGap(GAP_RELATED)
.addComponent(timesPanel, PREFERRED_SIZE, DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(navigationLabel)
.addGap(GAP_RELATED)
.addComponent(navComboBox))
.addGroup(layout.createSequentialGroup()
.addComponent(previewLabel)
.addGap(GAP_RELATED)
.addComponent(previewBox))))
);
layout.setVerticalGroup(
layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(BASELINE)
.addComponent(descriptorLabel)
.addComponent(descriptorComboBox))
.addPreferredGap(RELATED)
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(timesLabel)
.addComponent(timesPanel, PREFERRED_SIZE, DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(RELATED)
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(navigationLabel)
.addComponent(navComboBox))
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(previewLabel)
.addComponent(previewBox)))
);
setInnerPanel(myPanel);
return super.doMakeContents(true);
}
}
| true | true | public JComponent doMakeContents() {
JPanel myPanel = new JPanel();
JLabel timesLabel = McVGuiUtils.makeLabelRight("Times:");
addDescComp(timesLabel);
JPanel timesPanel = makeTimesPanel();
timesPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
addDescComp(timesPanel);
JLabel navigationLabel = McVGuiUtils.makeLabelRight("Navegation:");
addDescComp(navigationLabel);
// Use processPropertyComponents to build combo boxes that we rely on
processPropertyComponents();
addDescComp(navComboBox);
McVGuiUtils.setComponentWidth(navComboBox, McVGuiUtils.Width.DOUBLE);
// Preview checkbox
JLabel previewLabel = McVGuiUtils.makeLabelRight("Preview:");
addDescComp(previewLabel);
XmlObjectStore store = getIdv().getStore();
previewBox = new JCheckBox("Create preview image", store.get(Constants.PREF_IMAGE_PREVIEW, true));
previewBox.setToolTipText("Creating preview images takes extra time and network bandwidth");
previewBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
XmlObjectStore store = getIdv().getStore();
store.put(Constants.PREF_IMAGE_PREVIEW, e.getStateChange());
store.save();
}
});
addDescComp(previewBox);
GroupLayout layout = new GroupLayout(myPanel);
myPanel.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(descriptorLabel)
.addGap(GAP_RELATED)
.addComponent(descriptorComboBox))
.addGroup(layout.createSequentialGroup()
.addComponent(timesLabel)
.addGap(GAP_RELATED)
.addComponent(timesPanel, PREFERRED_SIZE, DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(navigationLabel)
.addGap(GAP_RELATED)
.addComponent(navComboBox))
.addGroup(layout.createSequentialGroup()
.addComponent(previewLabel)
.addGap(GAP_RELATED)
.addComponent(previewBox))))
);
layout.setVerticalGroup(
layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(BASELINE)
.addComponent(descriptorLabel)
.addComponent(descriptorComboBox))
.addPreferredGap(RELATED)
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(timesLabel)
.addComponent(timesPanel, PREFERRED_SIZE, DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(RELATED)
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(navigationLabel)
.addComponent(navComboBox))
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(previewLabel)
.addComponent(previewBox)))
);
setInnerPanel(myPanel);
return super.doMakeContents(true);
}
| public JComponent doMakeContents() {
JPanel myPanel = new JPanel();
JLabel timesLabel = McVGuiUtils.makeLabelRight("Times:");
addDescComp(timesLabel);
JPanel timesPanel = makeTimesPanel();
timesPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
addDescComp(timesPanel);
JLabel navigationLabel = McVGuiUtils.makeLabelRight("Navigation:");
addDescComp(navigationLabel);
// Use processPropertyComponents to build combo boxes that we rely on
processPropertyComponents();
addDescComp(navComboBox);
McVGuiUtils.setComponentWidth(navComboBox, McVGuiUtils.Width.DOUBLE);
// Preview checkbox
JLabel previewLabel = McVGuiUtils.makeLabelRight("Preview:");
addDescComp(previewLabel);
XmlObjectStore store = getIdv().getStore();
previewBox = new JCheckBox("Create preview image", store.get(Constants.PREF_IMAGE_PREVIEW, true));
previewBox.setToolTipText("Creating preview images takes extra time and network bandwidth");
previewBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
XmlObjectStore store = getIdv().getStore();
store.put(Constants.PREF_IMAGE_PREVIEW, e.getStateChange());
store.save();
}
});
addDescComp(previewBox);
GroupLayout layout = new GroupLayout(myPanel);
myPanel.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(descriptorLabel)
.addGap(GAP_RELATED)
.addComponent(descriptorComboBox))
.addGroup(layout.createSequentialGroup()
.addComponent(timesLabel)
.addGap(GAP_RELATED)
.addComponent(timesPanel, PREFERRED_SIZE, DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(navigationLabel)
.addGap(GAP_RELATED)
.addComponent(navComboBox))
.addGroup(layout.createSequentialGroup()
.addComponent(previewLabel)
.addGap(GAP_RELATED)
.addComponent(previewBox))))
);
layout.setVerticalGroup(
layout.createParallelGroup(LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(BASELINE)
.addComponent(descriptorLabel)
.addComponent(descriptorComboBox))
.addPreferredGap(RELATED)
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(timesLabel)
.addComponent(timesPanel, PREFERRED_SIZE, DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(RELATED)
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(navigationLabel)
.addComponent(navComboBox))
.addGroup(layout.createParallelGroup(LEADING)
.addComponent(previewLabel)
.addComponent(previewBox)))
);
setInnerPanel(myPanel);
return super.doMakeContents(true);
}
|
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxToBound.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxToBound.java
index cfaf9c2ee..d7bf4d6a9 100755
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxToBound.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxToBound.java
@@ -1,1896 +1,1896 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import com.sun.javafx.api.JavafxBindStatus;
import com.sun.javafx.api.tree.SequenceSliceTree;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javafx.code.FunctionType;
import com.sun.tools.javafx.comp.JavafxToJava.DurationOperationTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.UseSequenceBuilder;
import com.sun.tools.javafx.comp.JavafxToJava.Translator;
import com.sun.tools.javafx.comp.JavafxToJava.FunctionCallTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.InstanciateTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.InterpolateValueTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.StringExpressionTranslator;
import com.sun.tools.javafx.comp.JavafxToJava.Locationness;
import static com.sun.tools.javafx.code.JavafxVarSymbol.*;
import static com.sun.tools.javafx.comp.JavafxDefs.*;
import com.sun.tools.javafx.comp.JavafxTypeMorpher.TypeMorphInfo;
import com.sun.tools.javafx.comp.JavafxTypeMorpher.VarMorphInfo;
import com.sun.tools.javafx.tree.*;
import com.sun.tools.javafx.util.MsgSym;
import static com.sun.tools.javac.code.TypeTags.*;
public class JavafxToBound extends JavafxTranslationSupport implements JavafxVisitor {
protected static final Context.Key<JavafxToBound> jfxToBoundKey =
new Context.Key<JavafxToBound>();
enum ArgKind { BOUND, DEPENDENT, FREE };
/*
* modules imported by context
*/
private final JavafxToJava toJava;
private final JavafxOptimizationStatistics optStat;
/*
* other instance information
*/
private final Name computeElementsName;
/*
* State
*/
private ListBuffer<BindingExpressionClosureTranslator> bects;
private TypeMorphInfo tmiTarget = null;
private JavafxBindStatus bindStatus = null; // should never be accessed before set
/*
* static information
*/
private static final String cBoundSequences = sequencePackageNameString + ".BoundSequences";
private static final String cBoundOperators = locationPackageNameString + ".BoundOperators";
private static final String cLocations = locationPackageNameString + ".Locations";
private static final String cFunction0 = functionsPackageNameString + ".Function0";
private static final String cFunction1 = functionsPackageNameString + ".Function1";
private static final String cOperator = cBoundOperators + ".Operator";
private static final String opPLUS = cOperator + ".PLUS";
private static final String opMINUS = cOperator + ".MINUS";
private static final String opTIMES = cOperator + ".TIMES";
private static final String opDIVIDE = cOperator + ".DIVIDE";
private static final String opMODULO = cOperator + ".MODULO";
private static final String opLT = cOperator + ".CMP_LT";
private static final String opLE = cOperator + ".CMP_LE";
private static final String opGT = cOperator + ".CMP_GT";
private static final String opGE = cOperator + ".CMP_GE";
private static final String opEQ = cOperator + ".CMP_EQ";
private static final String opNE = cOperator + ".CMP_NE";
private static final String opNEGATE = cOperator + ".NEGATE";
private static final String opNOT = cOperator + ".NOT";
public static JavafxToBound instance(Context context) {
JavafxToBound instance = context.get(jfxToBoundKey);
if (instance == null)
instance = new JavafxToBound(context);
return instance;
}
protected JavafxToBound(Context context) {
super(context);
context.put(jfxToBoundKey, this);
toJava = JavafxToJava.instance(context);
optStat = JavafxOptimizationStatistics.instance(context);
computeElementsName = names.fromString("computeElements$");
}
/*** External entry points ***/
JCExpression translate(JFXExpression tree, JavafxBindStatus bindStatus, TypeMorphInfo tmi) {
JavafxBindStatus prevBindStatus = this.bindStatus;
this.bindStatus = bindStatus;
JCExpression res = translateGeneric(tree, tmi);
this.bindStatus = prevBindStatus;
return res;
}
JCExpression translate(JFXExpression tree, JavafxBindStatus bindStatus, Type type) {
JavafxBindStatus prevBindStatus = this.bindStatus;
this.bindStatus = bindStatus;
JCExpression res = translateGeneric(tree, type);
this.bindStatus = prevBindStatus;
return res;
}
// only for re-entry use by SequenceBuilder
JCExpression translate(JFXExpression tree) {
return translateGeneric(tree);
}
private JCExpression translate(JFXExpression tree, TypeMorphInfo tmi) {
return translateGeneric(tree, tmi);
}
JCExpression translate(JFXExpression tree, Type type) {
return translateGeneric(tree, type);
}
/** Visitor method: Translate a single node.
*/
@SuppressWarnings("unchecked")
private <TFX extends JFXExpression, TC extends JCTree> TC translateGeneric(TFX tree, TypeMorphInfo tmi) {
TypeMorphInfo tmiPrevTarget = tmiTarget;
this.tmiTarget = tmi;
TC ret;
if (tree == null) {
ret = null;
} else {
JFXTree prevWhere = toJava.attrEnv.where;
toJava.attrEnv.where = tree;
tree.accept(this);
toJava.attrEnv.where = prevWhere;
ret = (TC) this.result;
this.result = null;
}
this.tmiTarget = tmiPrevTarget;
return ret;
}
private <TFX extends JFXExpression, TC extends JCTree> TC translateGeneric(TFX tree, Type type) {
return translateGeneric(tree, typeMorpher.typeMorphInfo(type));
}
private <TFX extends JFXExpression, TC extends JCTree> TC translateGeneric(TFX tree) {
return translateGeneric(tree, (TypeMorphInfo) null);
}
private List<JCExpression> translate(List<JFXExpression> trees, Type methType, boolean usesVarArgs) {
return translateGeneric(trees, methType, usesVarArgs);
}
private <TFX extends JFXExpression, TC extends JCExpression> List<TC> translateGeneric(List<TFX> trees, Type methType, boolean usesVarArgs) {
ListBuffer<TC> translated = ListBuffer.lb();
boolean handlingVarargs = false;
Type formal = null;
List<Type> t = methType.getParameterTypes();
for (List<TFX> l = trees; l.nonEmpty(); l = l.tail) {
if (!handlingVarargs) {
formal = t.head;
t = t.tail;
if (usesVarArgs && t.isEmpty()) {
formal = types.elemtype(formal);
handlingVarargs = true;
}
}
TC tree = translateGeneric(l.head, formal);
if (tree != null) {
if (tree.type == null) { // if not set by convert()
tree.type = formal; // mark the type to declare the holder of this arg
}
translated.append(tree);
}
}
List<TC> args = translated.toList();
return args;
}
private JCExpression convert(Type inType, JCExpression tree) {
if (tmiTarget == null) {
tree.type = inType;
return tree;
}
Type targetType = tmiTarget.getRealType();
return convert(inType, tree, targetType);
}
private JCExpression convert(Type inType, JCExpression tree, Type targetType) {
DiagnosticPosition diagPos = tree.pos();
if (!types.isSameType(inType, targetType)) {
if (types.isSequence(targetType)) {
Type targetElementType = types.elementType(targetType);
if (targetElementType == null) { // runtime classes written in Java do this
tree.type = inType;
return tree;
}
if (!types.isSequence(inType)) {
JCExpression targetTypeInfo = makeTypeInfo(diagPos, targetElementType);
tree = runtime(diagPos,
cBoundSequences,
"singleton",
List.of(targetTypeInfo, convert(inType, tree, targetElementType)));
} else {
// this additional test is needed because wildcards compare as different
Type sourceElementType = types.elementType(inType);
if (!types.isSameType(sourceElementType, targetElementType)) {
if (types.isNumeric(sourceElementType) && types.isNumeric(targetElementType)) {
tree = convertNumericSequence(diagPos,
cBoundSequences,
tree,
sourceElementType,
targetElementType);
} else {
JCExpression targetTypeInfo = makeTypeInfo(diagPos, targetElementType);
tree = runtime(diagPos, cBoundSequences, "upcast", List.of(targetTypeInfo, tree));
}
}
}
} else if (targetType.isPrimitive()) {
if (inType.isPrimitive()) {
JCExpression classTypeExpr = makeIdentifier(diagPos, cLocations + "." + "NumericTo" + primitiveTypePrefix(targetType) + "LocationConversionWrapper");
JavafxTypeMorpher.TypeMorphInfo tmi = typeMorpher.typeMorphInfo(inType);
JCExpression locationType = makeTypeTree(diagPos, tmi.getLocationType());
JCExpression boxType = makeTypeTree(diagPos, syms.boxIfNeeded(inType));
tree = make.NewClass(null, List.of(locationType, boxType), classTypeExpr,
List.of(tree, makeTypeInfo(diagPos, inType)),
null);
}
//TODO: boxed inType
} else {
List<JCExpression> typeArgs = List.of(makeTypeTree(diagPos, targetType, true),
makeTypeTree(diagPos, syms.boxIfNeeded(inType), true));
Type inRealType = typeMorpher.typeMorphInfo(inType).getRealType();
JCExpression inClass = makeTypeInfo(diagPos, inRealType);
tree = runtime(diagPos, cLocations, "upcast", typeArgs, List.of(inClass, tree));
}
}
tree.type = targetType; // as a way of passing it to methods which needs to know the target type
return tree;
}
//where
private String primitiveTypePrefix(Type type) {
switch (type.tag) {
case BYTE:
return "Byte";
case SHORT:
return "Short";
case INT:
return "Int";
case LONG:
return "Long";
case FLOAT:
return "Float";
case DOUBLE:
return "Double";
}
assert false : "Should not reach here";
return "Unknown";
}
/**
*
* @param diagPos
* @return a boolean expression indicating if the bind is lazy
*/
private JCExpression makeLaziness(DiagnosticPosition diagPos) {
return makeLaziness(diagPos, bindStatus);
}
private Type targetType(Type type) {
return tmiTarget!=null? tmiTarget.getRealType() : type;
}
private JCVariableDecl translateVar(JFXVar tree) {
DiagnosticPosition diagPos = tree.pos();
JFXModifiers mods = tree.getModifiers();
long modFlags = mods == null ? 0L : mods.flags;
modFlags |= Flags.FINAL; // Locations are never overwritten
JCModifiers tmods = make.at(diagPos).Modifiers(modFlags);
VarMorphInfo vmi = typeMorpher.varMorphInfo(tree.sym);
JCExpression typeExpression = makeTypeTree( diagPos,vmi.getLocationType(), true);
//TODO: handle array initializers (but, really, shouldn't that be somewhere else?)
JCExpression init;
if (tree.init == null) {
init = makeLocationAttributeVariable(vmi, diagPos);
} else {
init = translate(tree.init, vmi.getRealFXType());
}
return make.at(diagPos).VarDef(tmods, tree.name, typeExpression, init);
}
private abstract class ClosureTranslator extends Translator {
protected final TypeMorphInfo tmiResult;
protected final int typeKindResult;
protected final Type elementTypeResult;
// these only used when fields are built
ListBuffer<JCTree> members = ListBuffer.lb();
ListBuffer<JCStatement> fieldInits = ListBuffer.lb();
int dependents = 0;
ListBuffer<JCExpression> callArgs = ListBuffer.lb();
int argNum = 0;
ClosureTranslator(DiagnosticPosition diagPos, Type resultType) {
this(diagPos, JavafxToBound.this.toJava, (tmiTarget != null) ? tmiTarget : typeMorpher.typeMorphInfo(resultType));
}
private ClosureTranslator(DiagnosticPosition diagPos, JavafxToJava toJava, TypeMorphInfo tmiResult) {
super(diagPos, toJava);
this.tmiResult = tmiResult;
typeKindResult = tmiResult.getTypeKind();
elementTypeResult = boxedElementType(tmiResult.getLocationType()); // want boxed, JavafxTypes version won't work
}
/**
* Make a method paramter
*/
protected JCVariableDecl makeParam(Type type, Name name) {
return make.at(diagPos).VarDef(
m().Modifiers(Flags.PARAMETER | Flags.FINAL),
name,
makeExpression(type),
null);
}
protected JCTree makeClosureMethod(Name methName, JCExpression expr, List<JCVariableDecl> params, Type returnType, long flags) {
return toJava.makeMethod(diagPos, methName, List.<JCStatement>of((returnType == syms.voidType) ? m().Exec(expr) : m().Return(expr)), params, returnType, flags);
}
protected abstract List<JCTree> makeBody();
protected abstract JCExpression makeBaseClass();
protected JCExpression makeBaseClass(Type clazzType, Type additionTypeParamOrNull) {
JCExpression clazz = makeExpression(types.erasure(clazzType)); // type params added below, so erase formals
ListBuffer<JCExpression> typeParams = ListBuffer.lb();
if (typeKindResult == TYPE_KIND_OBJECT || typeKindResult == TYPE_KIND_SEQUENCE) {
typeParams.append(makeExpression(elementTypeResult));
}
if (additionTypeParamOrNull != null) {
typeParams.append(makeExpression(additionTypeParamOrNull));
}
return typeParams.isEmpty()? clazz : m().TypeApply(clazz, typeParams.toList());
}
protected abstract List<JCExpression> makeConstructorArgs();
protected JCExpression buildClosure() {
List<JCTree> body = makeBody();
JCClassDecl classDecl = body==null? null : m().AnonymousClassDef(m().Modifiers(0L), body);
List<JCExpression> typeArgs = List.nil();
return m().NewClass(null/*encl*/, typeArgs, makeBaseClass(), makeConstructorArgs(), classDecl);
}
protected JCExpression doit() {
return buildClosure();
}
// field building support
protected List<JCTree> completeMembers() {
members.append(m().Block(0L, fieldInits.toList()));
return members.toList();
}
protected JCExpression makeLocationGet(JCExpression locExpr, int typeKind) {
Name getMethodName = defs.locationGetMethodName[typeKind];
JCFieldAccess select = m().Select(locExpr, getMethodName);
return m().Apply(null, select, List.<JCExpression>nil());
}
class FieldInfo {
final String desc;
final int num;
final TypeMorphInfo tmi;
final boolean isLocation;
FieldInfo(Type type) {
this((String)null, type);
}
FieldInfo(Name descName, Type type) {
this(descName.toString(), type);
}
FieldInfo(Name descName, TypeMorphInfo tmi) {
this(descName.toString(), tmi);
}
FieldInfo(String desc, Type type) {
this(desc, typeMorpher.typeMorphInfo(type));
}
FieldInfo(TypeMorphInfo tmi) {
this((String)null, tmi);
}
FieldInfo(String desc, TypeMorphInfo tmi) {
this(desc, tmi, true);
}
FieldInfo(String desc, TypeMorphInfo tmi, boolean isLocation) {
this.desc = desc;
this.num = argNum++;
this.tmi = tmi;
this.isLocation = isLocation;
}
JCExpression makeGetField() {
return makeGetField(tmi.getTypeKind());
}
JCExpression makeGetField(int typeKind) {
return isLocation ? makeLocationGet(makeAccess(this), typeKind) : makeAccess(this);
}
Type type() {
return isLocation ? tmi.getLocationType() : tmi.getRealBoxedType();
}
}
private Name argAccessName(FieldInfo fieldInfo) {
return names.fromString("arg$" + fieldInfo.num);
}
JCExpression makeAccess(FieldInfo fieldInfo) {
return m().Ident(argAccessName(fieldInfo));
}
protected void makeLocationField(JCExpression targ, FieldInfo fieldInfo) {
fieldInits.append( m().Exec( m().Assign(makeAccess(fieldInfo), targ)) );
members.append(m().VarDef(
m().Modifiers(Flags.PRIVATE),
argAccessName(fieldInfo),
makeExpression(fieldInfo.type()),
null));
}
protected JCExpression buildArgField(JCExpression arg, Type type) {
return buildArgField(arg, type, ArgKind.DEPENDENT);
}
protected JCExpression buildArgField(JCExpression arg, Type type, ArgKind kind) {
return buildArgField(arg, new FieldInfo(type), kind);
}
protected JCExpression buildArgField(JCExpression arg, FieldInfo fieldInfo) {
return buildArgField(arg, fieldInfo, ArgKind.DEPENDENT);
}
protected JCExpression buildArgField(JCExpression arg, FieldInfo fieldInfo, ArgKind kind) {
// translate the method arg into a Location field of the BindingExpression
// XxxLocation arg$0 = ...;
makeLocationField(arg, fieldInfo);
// build a list of these args, for use as dependents -- arg$0, arg$1, ...
if (kind == ArgKind.BOUND) {
return makeAccess(fieldInfo);
} else {
if (fieldInfo.num > 32) {
log.error(diagPos, MsgSym.MESSAGE_BIND_TOO_COMPLEX);
}
if (kind == ArgKind.DEPENDENT) {
dependents |= 1 << fieldInfo.num;
}
// set up these arg for the call -- arg$0.getXxx()
return fieldInfo.makeGetField();
}
}
protected void buildArgFields(List<JCExpression> targs, ArgKind kind) {
for (JCExpression targ : targs) {
assert targ.type != null : "caller is supposed to decorate the translated arg with its type";
callArgs.append( buildArgField(targ, targ.type, kind) );
}
}
}
void scriptBegin() {
bects = ListBuffer.lb();
}
List<JCTree> scriptComplete(DiagnosticPosition diagPos) {
ListBuffer<JCTree> trees = ListBuffer.lb();
// Add _Bindings class
if (!bects.isEmpty()) {
ListBuffer<JCCase> cases = ListBuffer.lb();
for (BindingExpressionClosureTranslator b : bects) {
cases.append(b.makeBindingCase());
}
JCStatement swit = make.at(diagPos).Switch(make.at(diagPos).Ident(defs.bindingIdName), cases.toList());
JCTree computeMethod = makeMethod(diagPos, defs.computeMethodName, List.of(swit), null, syms.voidType, Flags.PUBLIC);
Type objectArrayType = new Type.ArrayType(syms.objectType, syms.arrayClass);
ListBuffer<JCVariableDecl> params = ListBuffer.lb();
params.append(makeParam(diagPos, defs.idName, syms.intType));
params.append(makeParam(diagPos, defs.arg0Name, syms.objectType));
params.append(makeParam(diagPos, defs.arg1Name, syms.objectType));
params.append(makeParam(diagPos, defs.moreArgsName, objectArrayType));
params.append(makeParam(diagPos, defs.dependentsName, syms.intType));
JCStatement cbody = make.Exec(make.Apply(null, make.Ident(names._super), List.<JCExpression>of(
make.Ident(defs.idName),
make.Ident(defs.arg0Name),
make.Ident(defs.arg1Name),
make.Ident(defs.moreArgsName),
make.Ident(defs.dependentsName)
)));
JCTree constr = makeMethod(diagPos, names.init, List.of(cbody), params.toList(), syms.voidType, Flags.PRIVATE);
JCClassDecl bindingClass = make.at(diagPos).ClassDef(
make.at(diagPos).Modifiers(Flags.PRIVATE | Flags.STATIC),
defs.scriptBindingClassName,
List.<JCTypeParameter>nil(),
makeQualifiedTree(diagPos, JavafxDefs.scriptBindingExpressionsString),
List.<JCExpression>nil(),
List.of(computeMethod, constr));
trees.append(bindingClass);
}
return trees.toList();
}
@Override
public void visitInstanciate(final JFXInstanciate tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
return new InstanciateTranslator(tree, toJava) {
protected void processLocalVar(JFXVar var) {
preDecls.append(translateVar(var));
}
@Override
protected List<JCExpression> translatedConstructorArgs() {
List<JFXExpression> args = tree.getArgs();
if (args != null && args.size() > 0) {
assert tree.constructor != null : "args passed on instanciation of class without constructor";
boolean usesVarArgs = (tree.constructor.flags() & Flags.VARARGS) != 0L;
buildArgFields(translate(args, tree.constructor.type, usesVarArgs), ArgKind.DEPENDENT);
return callArgs.toList();
} else {
return List.<JCExpression>nil();
}
}
@Override
void setInstanceVariable(Name instName, JavafxBindStatus bindStatus, VarSymbol vsym, JFXExpression init) {
// bind staus to use for translation needs to propagate laziness if this isn't a bound init
JavafxBindStatus translationBindStatus = bindStatus.isBound()?
bindStatus :
JavafxToBound.this.bindStatus.isLazy()?
JavafxBindStatus.LAZY_UNBOUND :
JavafxBindStatus.UNBOUND;
JCExpression initRef = buildArgField(
translate(init, translationBindStatus, vsym.type),
new FieldInfo(vsym.type),
bindStatus.isBound()? ArgKind.BOUND : ArgKind.DEPENDENT);
setInstanceVariable(init.pos(), instName, bindStatus, vsym, initRef);
}
}.doit();
}
}.doit();
}
@Override
public void visitStringExpression(final JFXStringExpression tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), syms.stringType) {
protected JCExpression makePushExpression() {
return new StringExpressionTranslator(tree, toJava) {
protected JCExpression translateArg(JFXExpression arg) {
return buildArgField(translate(arg), arg.type);
}
}.doit();
}
}.doit();
}
@Override
public void visitFunctionValue(JFXFunctionValue tree) {
JFXFunctionDefinition def = tree.definition;
result = makeConstantLocation(tree.pos(), targetType(tree.type), toJava.makeFunctionValue(make.Ident(defs.lambdaName), def, tree.pos(), (MethodType) def.type) );
}
public void visitBlockExpression(JFXBlock tree) { //done
assert (tree.type != syms.voidType) : "void block expressions should be not exist in bind expressions";
DiagnosticPosition diagPos = tree.pos();
JFXExpression value = tree.value;
ListBuffer<JCStatement> translatedVars = ListBuffer.lb();
for (JFXExpression stmt : tree.getStmts()) {
if (stmt.getFXTag() == JavafxTag.VAR_DEF) {
JFXVar var = (JFXVar) stmt;
translatedVars.append(translateVar(var));
optStat.recordLocalVar(var.sym, true, true);
} else {
assert false : "non VAR_DEF in block expression in bind context";
}
}
while (value.getFXTag() == JavafxTag.VAR_DEF) {
// for now, at least, ignore the declaration part of a terminal var decl.
//TODO: when vars can be referenced before decl (say in "var: self" replacement)
// this will need to be changed.
value = ((JFXVar)value).getInitializer();
}
assert value.getFXTag() != JavafxTag.RETURN;
result = makeBlockExpression(diagPos, //TODO tree.flags lost
translatedVars.toList(),
translate(value, tmiTarget) );
}
@Override
public void visitAssign(JFXAssign tree) {
//TODO: this should probably not be allowed
// log.error(tree.pos(), "javafx.not.allowed.in.bind.context", "=");
DiagnosticPosition diagPos = tree.pos();
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(tree.type);
int typeKind = tmi.getTypeKind();
// create a temp var to hold the RHS
JCVariableDecl varDecl = makeTmpVar(diagPos, tmi.getLocationType(), translate(tree.rhs));
// call the set method
JCStatement setStmt = callStatement(diagPos,
translate(tree.lhs),
defs.locationSetMethodName[typeKind],
callExpression(diagPos,
make.at(diagPos).Ident(varDecl.name),
defs.locationGetMethodName[typeKind]));
// bundle it all into a block-expression that looks like --
// { ObjectLocation tmp = rhs; lhs.set(tmp.get()); tmp }
result = makeBlockExpression(diagPos,
List.of(varDecl, setStmt),
make.at(diagPos).Ident(varDecl.name));
}
@Override
public void visitAssignop(JFXAssignOp tree) {
// should have caught this in attribution
assert false : "Assignment operator in bind context";
}
private JCExpression makeBoundSelect(final DiagnosticPosition diagPos,
final Type resultType,
final BindingExpressionClosureTranslator translator) {
TypeMorphInfo tmi = (tmiTarget != null) ? tmiTarget : typeMorpher.typeMorphInfo(resultType);
JCExpression bindingExpression = translator.buildClosure();
List<JCExpression> args = List.of(
makeTypeInfo(diagPos, tmi.isSequence()? tmi.getElementType() : tmi.getRealType()),
makeLaziness(diagPos),
bindingExpression);
return runtime(diagPos, cBoundOperators, tmi.isSequence()? "makeBoundSequenceSelect" : "makeBoundSelect", args);
}
@Override
public void visitSelect(final JFXSelect tree) {
if (tree.type instanceof FunctionType && tree.sym.type instanceof MethodType) {
result = convert(tree.type, toJava.translateAsLocation(tree)); //TODO -- for now punt, translate like normal case
return;
}
DiagnosticPosition diagPos = tree.pos();
Symbol owner = tree.sym.owner;
if (types.isJFXClass(owner) && typeMorpher.requiresLocation(tree.sym)) {
if (tree.sym.isStatic()) {
// if this is a static reference to an attribute, eg. MyClass.myAttribute
JCExpression classRef = makeTypeTree( diagPos,types.erasure(tree.sym.owner.type), false);
result = convert(tree.type, make.at(diagPos).Select(classRef, attributeFieldName(tree.sym)));
} else {
// this is a dynamic reference to an attribute
final JFXExpression expr = tree.getExpression();
result = makeBoundSelect(diagPos,
tree.type,
new BindingExpressionClosureTranslator(tree.pos(), typeMorpher.baseLocation.type) {
protected JCExpression makePushExpression() {
return convert(tree.type, toJava.convertVariableReference(diagPos,
m().Select(
buildArgField(
translate(expr),
new FieldInfo("selector", expr.type)),
tree.getIdentifier()),
tree.sym,
Locationness.AsLocation));
}
});
}
} else {
if (tree.sym.isStatic()) {
// This is a static reference to a Java member or elided member e.g. System.out -- do unbound translation, then wrap
result = this.makeUnboundLocation(diagPos, targetType(tree.type), toJava.translateAsUnconvertedValue(tree));
} else {
// This is a dynamic reference to a Java member or elided member
result = (new BindingExpressionClosureTranslator(diagPos, tree.type) {
private JFXExpression selector = tree.getExpression();
private TypeMorphInfo tmiSelector = typeMorpher.typeMorphInfo(selector.type);
private Name selectorName = getSyntheticName("selector");
private FieldInfo selectorField = new FieldInfo(selectorName, tmiSelector);
protected JCExpression makePushExpression() {
// create two accesses to the value of to selector field -- selector$.blip
// one for the method call and one for the nul test
JCExpression transSelector = selectorField.makeGetField();
JCExpression toTest = selectorField.makeGetField();
// construct the actual select
JCExpression selectExpr = toJava.convertVariableReference(diagPos,
m().Select(transSelector, tree.getIdentifier()),
tree.sym,
Locationness.AsValue);
// test the selector for null before attempting to select the field
// if it would dereference null, then instead give the default value
JCExpression cond = m().Binary(JCTree.NE, toTest, make.Literal(TypeTags.BOT, null));
JCExpression defaultExpr = makeDefaultValue(diagPos, actualTranslatedType);
return m().Conditional(cond, selectExpr, defaultExpr);
}
@Override
protected void buildFields() {
// translate the selector into a Location field of the BindingExpression
// XxxLocation selector$ = ...;
buildArgField(translate(selector), selectorField);
}
}).doit();
}
}
}
@Override
public void visitIdent(JFXIdent tree) { //TODO: don't use toJava
// assert (tree.sym.flags() & Flags.PARAMETER) != 0 || tree.name == names._this || tree.sym.isStatic() || toJava.requiresLocation(typeMorpher.varMorphInfo(tree.sym)) : "we are bound, so should have been marked to morph: " + tree;
JCExpression transId = toJava.translateAsLocation(tree);
result = convert(tree.type, transId );
}
@Override
public void visitSequenceExplicit(JFXSequenceExplicit tree) { //done
ListBuffer<JCStatement> stmts = ListBuffer.lb();
Type elemType = boxedElementType(targetType(tree.type));
UseSequenceBuilder builder = toJava.useBoundSequenceBuilder(tree.pos(), elemType, tree.getItems().length());
stmts.append(builder.makeBuilderVar());
for (JFXExpression item : tree.getItems()) {
stmts.append(builder.addElement( item ) );
}
result = makeBlockExpression(tree.pos(), stmts, builder.makeToSequence());
}
@Override
public void visitSequenceRange(JFXSequenceRange tree) { //done: except for step and exclusive
DiagnosticPosition diagPos = tree.pos();
Type elemType = syms.javafx_IntegerType;
int ltag = tree.getLower().type.tag;
int utag = tree.getUpper().type.tag;
int stag = tree.getStepOrNull() == null? TypeTags.INT : tree.getStepOrNull().type.tag;
if (ltag == TypeTags.FLOAT || ltag == TypeTags.DOUBLE ||
utag == TypeTags.FLOAT || utag == TypeTags.DOUBLE ||
stag == TypeTags.FLOAT || stag == TypeTags.DOUBLE) {
elemType = syms.javafx_NumberType;
}
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(elemType);
ListBuffer<JCExpression> args = ListBuffer.lb();
args.append( translate( tree.getLower(), tmi ));
args.append( translate( tree.getUpper(), tmi ));
if (tree.getStepOrNull() != null) {
args.append( translate( tree.getStepOrNull(), tmi ));
}
if (tree.isExclusive()) {
args.append( make.at(diagPos).Literal(TypeTags.BOOLEAN, 1) );
}
result = convert(types.sequenceType(elemType), runtime(diagPos, cBoundSequences, "range", args));
}
@Override
public void visitSequenceEmpty(JFXSequenceEmpty tree) { //done
DiagnosticPosition diagPos = tree.pos();
if (types.isSequence(tree.type)) {
Type elemType = types.elementType(targetType(tree.type));
result = runtime(diagPos, cBoundSequences, "empty", List.of(makeTypeInfo(diagPos, elemType)));
} else {
result = makeConstantLocation(diagPos, targetType(tree.type), makeNull(diagPos));
}
}
@Override
public void visitSequenceIndexed(JFXSequenceIndexed tree) { //done
DiagnosticPosition diagPos = tree.pos();
result = convert(tree.type, runtime(diagPos, cBoundSequences, "element",
List.of(translate(tree.getSequence()),
translate(tree.getIndex(), syms.intType))));
}
@Override
public void visitSequenceSlice(JFXSequenceSlice tree) { //done
DiagnosticPosition diagPos = tree.pos();
result = runtime(diagPos, cBoundSequences,
tree.getEndKind()==SequenceSliceTree.END_EXCLUSIVE? "sliceExclusive" : "slice",
List.of(
makeTypeInfo(diagPos, types.elementType(targetType(tree.type))),
translate(tree.getSequence()),
translate(tree.getFirstIndex()),
tree.getLastIndex()==null? makeNull(diagPos) : translate(tree.getLastIndex())
));
}
/**
* Generate this template, expanding to handle multiple in-clauses
*
* SequenceLocation<V> derived = new BoundComprehension<T,V>(..., IN_SEQUENCE, USE_INDEX) {
protected SequenceLocation<V> getMappedElement$(final ObjectLocation<T> IVAR_NAME, final IntLocation INDEXOF_IVAR_NAME) {
return SequenceVariable.make(...,
new SequenceBindingExpression<V>() {
public Sequence<V> computeValue() {
if (WHERE)
return BODY with s/indexof IVAR_NAME/INDEXOF_IVAR_NAME/;
else
return ....emptySequence;
}
}, maybe IVAR_NAME, maybe INDEXOF_IVAR_NAME);
}
};
*
* **/
@Override
public void visitForExpression(final JFXForExpression tree) {
result = (new Translator( tree.pos(), toJava ) {
private final TypeMorphInfo tmiResult = typeMorpher.typeMorphInfo(targetType(tree.type));
/**
* V
*/
private final Type resultElementType = tmiResult.getElementType();
/**
* SequenceLocation<V>
*/
private final Type resultSequenceLocationType = typeMorpher.generifyIfNeeded(typeMorpher.locationType(TYPE_KIND_SEQUENCE), tmiResult);
/**
* isSimple -- true if the for-loop is simple enough that it can use SimpleBoundComprehension
*/
private final boolean isSimple = false; //TODO
/**
* Make: V.class
*/
private JCExpression makeResultClass() {
return makeTypeInfo(diagPos, resultElementType);
}
/**
* Make a method parameter
*/
private JCVariableDecl makeParam(Type type, Name name) {
return make.at(diagPos).VarDef(
make.Modifiers(Flags.PARAMETER | Flags.FINAL),
name,
makeExpression(type),
null);
}
/**
* Starting with the body of the comprehension...
* Wrap in a singleton sequence, if not a sequence.
* Wrap in a conditional if there are where-clauses: whereClause? body : []
*/
private JCExpression makeCore() {
JCExpression body;
if (types.isSequence(tree.getBodyExpression().type)) {
// the body is a sequence, desired type is the same as for the for-loop
body = translate(tree.getBodyExpression(), tmiTarget);
} else {
// the body is not a sequence, desired type is the element tpe need for for-loop
- JCExpression single = translate(tree.getBodyExpression(), types.unboxedTypeOrType(tmiTarget.getElementType()));
+ JCExpression single = translate(tree.getBodyExpression(), types.unboxedTypeOrType(resultElementType));
List<JCExpression> args = List.of(makeResultClass(), single);
body = runtime(diagPos, cBoundSequences, "singleton", args);
}
JCExpression whereTest = null;
for (JFXForExpressionInClause clause : tree.getForExpressionInClauses()) {
JCExpression where = translate(clause.getWhereExpression());
if (where != null) {
if (whereTest == null) {
whereTest = where;
} else {
whereTest = runtime(diagPos, cBoundOperators, "and_bb", List.of(whereTest, where));
}
}
}
if (whereTest != null) {
body = makeBoundConditional(diagPos,
tree.type,
body,
runtime(diagPos, cBoundSequences, "empty", List.of(makeTypeInfo(diagPos, resultElementType))),
whereTest);
}
return body;
}
/**
* protected SequenceLocation<V> computeElements$(final ObjectLocation<T> IVAR_NAME, final IntLocation INDEXOF_IVAR_NAME) {
* return ...
* }
*/
private JCTree makeComputeElementsMethod(JFXForExpressionInClause clause, JCExpression inner, TypeMorphInfo tmiInduction) {
Type iVarType;
Type idxVarType;
Name computeName;
if (isSimple) {
iVarType = tmiInduction.getRealFXType();
idxVarType = syms.intType;
computeName = computeElementsName;
} else {
iVarType = tmiInduction.getLocationType();
idxVarType = typeMorpher.locationType(TYPE_KIND_INT);
computeName = computeElementsName;
}
ListBuffer<JCStatement> stmts = ListBuffer.lb();
Name ivarName = clause.getVar().name;
stmts.append(m().Return( inner ));
List<JCVariableDecl> params = List.of(
makeParam(iVarType, ivarName),
makeParam(idxVarType, indexVarName(clause) )
);
return m().MethodDef(
m().Modifiers(Flags.PROTECTED),
computeName,
makeExpression( resultSequenceLocationType ),
List.<JCTypeParameter>nil(),
params,
List.<JCExpression>nil(),
m().Block(0L, stmts.toList()),
null);
}
/**
* new BoundComprehension<T,V>(V.class, IN_SEQUENCE, USE_INDEX) { ... }
*/
private JCExpression makeBoundComprehension(JFXForExpressionInClause clause, JCExpression inner) {
JFXExpression seq = clause.getSequenceExpression();
TypeMorphInfo tmiSeq = typeMorpher.typeMorphInfo(seq.type);
TypeMorphInfo tmiInduction = typeMorpher.typeMorphInfo(clause.getVar().type);
JCClassDecl classDecl = m().AnonymousClassDef(
m().Modifiers(0L),
List.<JCTree>of(makeComputeElementsMethod(clause, inner, tmiInduction)));
List<JCExpression> typeArgs = List.nil();
boolean useIndex = clause.getIndexUsed();
JCExpression transSeq = translate( seq );
if (!tmiSeq.isSequence()) {
transSeq = runtime(diagPos, cBoundSequences, "singleton", List.of(makeResultClass(), transSeq));
}
List<JCExpression> constructorArgs = List.of(
makeResultClass(),
makeTypeInfo(diagPos, tmiInduction.getRealBoxedType()),
transSeq,
m().Literal(TypeTags.BOOLEAN, useIndex? 1 : 0) );
Type bcType = typeMorpher.abstractBoundComprehension.type;
JCExpression clazz = makeExpression(types.erasure(bcType)); // type params added below, so erase formals
ListBuffer<JCExpression> typeParams = ListBuffer.lb();
typeParams.append( makeExpression(tmiInduction.getRealBoxedType()) );
typeParams.append( makeExpression(tmiInduction.getLocationType()) );
typeParams.append( makeExpression(resultElementType) );
clazz = m().TypeApply(clazz, typeParams.toList());
return m().NewClass(null,
typeArgs,
clazz,
constructorArgs,
classDecl);
}
/**
* Put everything together, handle multiple in clauses -- wrap from the inner-most first
*/
public JCExpression doit() {
List<JFXForExpressionInClause> clauses = tree.getForExpressionInClauses();
// make the body of loop
JCExpression expr = makeCore();
// then wrap it in the looping constructs
for (int inx = clauses.size() - 1; inx >= 0; --inx) {
JFXForExpressionInClause clause = clauses.get(inx);
expr = makeBoundComprehension(clause, expr);
}
return expr;
}
}).doit();
}
public void visitIndexof(JFXIndexof tree) {
assert tree.clause.getIndexUsed() : "assert that index used is set correctly";
JCExpression transIndex = make.at(tree.pos()).Ident(indexVarName(tree.fname));
VarSymbol vsym = (VarSymbol)tree.clause.getVar().sym;
if (toJava.requiresLocation(vsym)) {
// from inside the bind, already a Location
result = convert(tree.type, transIndex);
} else {
// it came from outside of the bind, make it into a Location
result = makeConstantLocation(tree.pos(), targetType(tree.type), transIndex);
}
}
/**
* Build a tree for a conditional.
* @param diagPos
* @param resultType
* @param trueExpr then branch, already translated
* @param falseExpr else branch, already translated
* @param condExpr conditional expression branch, already translated
* @return
*/
private JCExpression makeBoundConditional(final DiagnosticPosition diagPos,
final Type resultType,
final JCExpression trueExpr,
final JCExpression falseExpr,
final JCExpression condExpr) {
TypeMorphInfo tmi = (tmiTarget != null) ? tmiTarget : typeMorpher.typeMorphInfo(resultType);
List<JCExpression> args = List.of(
makeLaziness(diagPos),
condExpr,
makeFunction0(resultType, trueExpr),
makeFunction0(resultType, falseExpr));
if (tmi.isSequence()) {
// prepend "Foo.class, "
args = args.prepend(makeTypeInfo(diagPos, tmi.getElementType()));
}
return runtime(diagPos, cBoundOperators, "makeBoundIf", args);
}
private JCExpression makeFunction0(
final Type resultType,
final JCExpression bodyExpr) {
return (new ClosureTranslator(bodyExpr.pos(), resultType) {
protected List<JCTree> makeBody() {
return List.<JCTree>of(
makeClosureMethod(defs.invokeName, bodyExpr, null, tmiResult.getLocationType(), Flags.PUBLIC));
}
protected JCExpression makeBaseClass() {
JCExpression objFactory = makeQualifiedTree(diagPos, cFunction0);
Type clazzType = tmiResult.getLocationType();
JCExpression clazz = makeExpression(clazzType);
return m().TypeApply(objFactory, List.of(clazz));
}
protected List<JCExpression> makeConstructorArgs() {
return List.<JCExpression>nil();
}
}).doit();
}
/*** New Version -- in process
*
private JCExpression makeBoundConditional(final DiagnosticPosition diagPos,
final Type resultType,
final JCExpression trueExpr,
final JCExpression falseExpr,
final JCExpression condExpr) {
return new BindingExpressionClosureTranslator(diagPos, resultType) {
final FieldInfo condField = new FieldInfo("condition", syms.booleanType);
final FieldInfo thenField = new FieldInfo("trueBranch", resultType);
final FieldInfo elseField = new FieldInfo("elseBranch", resultType);
JCStatement makeBranch(FieldInfo takenBranch, FieldInfo abandonedBranch) {
ListBuffer<JCStatement> stmts = ListBuffer.lb();
// stmts.append(callStatement(diagPos, makeAccess(abandonedBranch), "unbind"));
// stmts.append(callStatement(diagPos, makeAccess(takenBranch), "resetState", makeLaziness(diagPos)));
stmts.append(callStatement(diagPos, null, "pushValue", takenBranch.makeGetField()));
return m().Block(0L, stmts.toList());
}
protected JCExpression makePushExpression() {
throw new AssertionError("Should not reach here");
}
@Override
protected List<JCTree> makeBody() {
buildArgField(condExpr, condField);
buildArgField(trueExpr, thenField);
buildArgField(falseExpr, elseField);
pushStatement = m().If(
condField.makeGetField(),
makeBranch(thenField, elseField),
makeBranch(elseField, thenField));
return null;
}
}.doit();
}
private JCExpression makeBoundConditionalTT(final DiagnosticPosition diagPos,
final Type resultType,
final JCExpression trueExpr,
final JCExpression falseExpr,
final JCExpression condExpr) {
TypeMorphInfo tmi = typeMorpher.typeMorphInfo(resultType);
List<JCExpression> args = List.of(
makeTypeInfo(diagPos, tmi.isSequence()? tmi.getElementType() : resultType),
makeLaziness(diagPos),
condExpr,
makeClosure0(diagPos, trueExpr, resultType),
makeClosure0(diagPos, falseExpr, resultType));
String makeBoundIf = tmi.isSequence()? "makeBoundSequenceIf" : "makeBoundIf";
return runtime(diagPos, cBoundOperators, makeBoundIf, args);
}
private JCExpression makeClosure0(final DiagnosticPosition diagPos, final JCExpression expr, final Type resultType) {
final TypeMorphInfo tmiPrevTarget = tmiTarget;
tmiTarget = null;
try {
return new BindingExpressionClosureTranslator(diagPos, typeMorpher.baseLocation.type) {
protected JCExpression makePushExpression() {
return buildArgField(expr, resultType, ArgKind.FREE);
}
}.buildClosure();
} finally {
tmiTarget = tmiPrevTarget;
}
}
/***/
@Override
public void visitIfExpression(final JFXIfExpression tree) {
Type targetType = targetType(tree.type);
result = makeBoundConditional(tree.pos(),
targetType,
translate(tree.getTrueExpression(), targetType),
translate(tree.getFalseExpression(), targetType),
translate(tree.getCondition()) );
}
@Override
public void visitParens(JFXParens tree) { //done
JCExpression expr = translate(tree.expr);
result = make.at(tree.pos).Parens(expr);
}
@Override
public void visitInstanceOf(final JFXInstanceOf tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
Type type = tree.clazz.type;
if (type.isPrimitive())
type = types.boxedClass(type).type;
return m().TypeTest(
buildArgField(translate(tree.expr),
new FieldInfo(defs.toTestName, tree.expr.type)),
makeExpression(type) );
}
}.doit();
}
@Override
public void visitTypeCast(final JFXTypeCast tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
return makeTypeCast(tree.pos(), tree.clazz.type, tree.expr.type,
buildArgField(translate(tree.expr), new FieldInfo(defs.toBeCastName, tree.expr.type)));
}
}.doit();
}
@Override
public void visitLiteral(JFXLiteral tree) {
final DiagnosticPosition diagPos = tree.pos();
if (tree.typetag == TypeTags.BOT && types.isSequence(tree.type)) {
Type elemType = types.elementType(targetType(tree.type));
result = runtime(diagPos, cBoundSequences, "empty", List.of(makeTypeInfo(diagPos, elemType)));
} else {
Type targetType = targetType(tree.type);
JCExpression unbound = toJava.convertTranslated(make.at(diagPos).Literal(tree.typetag, tree.value), diagPos, tree.type, targetType);
result = makeConstantLocation(diagPos, targetType, unbound);
}
}
/**
* Translator for Java method and non-bound JavaFX functions.
*/
private abstract class BindingExpressionClosureTranslator extends ClosureTranslator {
final Type actualTranslatedType;
final int id;
JCStatement pushStatement;
final ListBuffer<JCExpression> argInits = ListBuffer.lb();
final ListBuffer<JCStatement> preDecls = ListBuffer.lb();
BindingExpressionClosureTranslator(DiagnosticPosition diagPos, Type resultType) {
super(diagPos, resultType);
this.id = bects.size();
this.actualTranslatedType = resultType;
bects.append(this);
}
protected abstract JCExpression makePushExpression();
protected void buildFields() {
// by default do this dynamically
}
JCCase makeBindingCase() {
return m().Case(m().Literal(id), List.<JCStatement>of(
pushStatement,
m().Break(null)));
}
@Override
JCExpression makeAccess(FieldInfo fieldInfo) {
JCExpression uncast;
if (fieldInfo.num < 2) {
// arg$0 and arg$1, use Ident
uncast = super.makeAccess(fieldInfo);
} else {
// moreArgs
uncast = m().Indexed(m().Ident(defs.moreArgsName), m().Literal(fieldInfo.num - 2));
}
// These are just "Location" -- cast to their XxxLocation type
return m().TypeCast(makeExpression(fieldInfo.type()), uncast);
}
protected List<JCTree> makeBody() {
buildFields();
// build first since this may add dependencies
JCExpression resultVal = makePushExpression();
if (tmiTarget != null && actualTranslatedType != typeMorpher.baseLocation.type) {
// If we have a target type and this isn't a Location yielding translation (which handles it's own), do any needed type conversion
resultVal = toJava.convertTranslated(resultVal, diagPos, actualTranslatedType, tmiTarget.getRealType());
}
pushStatement = callStatement(diagPos, null, "pushValue", resultVal);
return null;
}
protected JCExpression makeBaseClass() {
return m().Ident(defs.scriptBindingClassName);
}
@Override
protected void makeLocationField(JCExpression targ, FieldInfo fieldInfo) {
// We use the fields in the base class, just store to Location constructions for use in the constructor args
argInits.append(targ);
}
protected List<JCExpression> makeConstructorArgs() {
ListBuffer<JCExpression> args = ListBuffer.lb();
// arg: id
args.append(m().Literal(id));
List<JCExpression> inits = argInits.toList();
assert inits.length() == argNum : "Mismatch Args: " + argNum + ", Inits: " + inits.length();
// arg: arg$0
if (argNum > 0) {
args.append(inits.head);
inits = inits.tail;
} else {
args.append(m().Literal(TypeTags.BOT, null));
}
// arg: arg$1
if (argNum > 1) {
args.append(inits.head);
inits = inits.tail;
} else {
args.append(m().Literal(TypeTags.BOT, null));
}
// arg: moreArgs
if (argNum > 2) {
args.append(m().NewArray(makeExpression(syms.objectType), List.<JCExpression>nil(), inits));
} else {
args.append(m().Literal(TypeTags.BOT, null));
}
// arg: dependents
args.append(m().Literal(TypeTags.INT, dependents));
return args.toList();
}
@Override
protected JCExpression doit() {
ListBuffer<JCExpression> args = ListBuffer.lb();
if (tmiResult.getTypeKind() == TYPE_KIND_OBJECT) {
args.append(makeDefaultValue(diagPos, tmiResult));
}
args.append(makeLaziness(diagPos));
args.append(buildClosure());
JCExpression varResult = makeLocationLocalVariable(tmiResult, diagPos, args.toList());
if (preDecls.nonEmpty()) {
return toJava.makeBlockExpression(diagPos, preDecls, varResult);
} else {
return varResult;
}
}
}
@Override
public void visitFunctionInvocation(final JFXFunctionInvocation tree) {
//TODO: painfully in need of refactoring
result = (new FunctionCallTranslator(tree, toJava) {
final List<JCExpression> typeArgs = toJava.translateExpressions(tree.typeargs); //TODO: should, I think, be nil list
final List<JCExpression> targs = translate(tree.args, meth.type, usesVarArgs);
public JCExpression doit() {
if (callBound) {
if (selectorMutable) {
return makeBoundSelect(diagPos,
tree.type,
new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
JCExpression transSelect = buildArgField(translate(selector), new FieldInfo("selector", selector.type));
// create a field in the closure for each argument
buildArgFields(targs, ArgKind.BOUND);
// translate the method name -- e.g., foo to foo$bound
Name name = functionName(msym, false, callBound);
// selectors are always Objects
JCExpression expr = m().Apply(typeArgs,
m().Select(transSelect, name),
callArgs.toList());
return convert(tree.type, expr); // convert type, if needed
}
});
} else {
List<JCExpression> callArgs = targs;
if (superToStatic) { //TODO: should this be higher?
// This is a super call, add the receiver so that the impl is called directly
callArgs = callArgs.prepend(make.Ident(defs.receiverName));
}
return convert(tree.type, m().Apply(typeArgs, transMeth(), callArgs));
}
} else {
// call to Java method or unbound JavaFX function
//TODO: varargs
if (selectorMutable || useInvoke) {
return (new BindingExpressionClosureTranslator(diagPos, tree.type) {
private JFXExpression check = useInvoke? meth : selector;
private TypeMorphInfo tmiSelector = typeMorpher.typeMorphInfo(check.type);
private Name selectorName = getSyntheticName("selector");
private FieldInfo selectorField = new FieldInfo(selectorName, tmiSelector);
protected JCExpression makePushExpression() {
// access the selector field for the method call-- selector$.get()
// selectors are always Objects
JCExpression transSelector = selectorField.makeGetField(TYPE_KIND_OBJECT);
// construct the actual method invocation
Name methName = useInvoke? defs.invokeName : ((JFXSelect) tree.meth).name;
JCExpression callMeth = m().Select(transSelector, methName);
JCExpression call = m().Apply(typeArgs, callMeth, callArgs.toList());
if (tmiSelector.getTypeKind() == TYPE_KIND_OBJECT) {
// create another access to the selector field for the null test (below)
JCExpression toTest = selectorField.makeGetField(TYPE_KIND_OBJECT);
// test the selector for null before attempting to invoke the method
// if it would dereference null, then instead give the default value
JCExpression cond = m().Binary(JCTree.NE, toTest, make.Literal(TypeTags.BOT, null));
JCExpression defaultExpr = makeDefaultValue(diagPos, actualTranslatedType);
return m().Conditional(cond, call, defaultExpr);
} else {
return call;
}
}
@Override
protected void buildFields() {
// translate the method selector into a Location field of the BindingExpression
// XxxLocation selector$ = ...;
// Must be first, because of pre-definition of selectorField
buildArgField(translate(check), selectorField);
// create a field in the BindingExpression for each argument
buildArgFields(targs, ArgKind.DEPENDENT);
}
}).doit();
} else {
return (new BindingExpressionClosureTranslator(diagPos, tree.type) {
FieldInfo rcvrField = null;
// construct the actual value computing method (with the method call)
protected JCExpression makePushExpression() {
if (superToStatic) { //TODO: should this be higher?
// This is a super call, add the receiver so that the impl is called directly
callArgs.prepend( receiver() );
}
// result is a block expression that has the definition of receiver$ at the beginning
return m().Apply(null, translatedImmutableMethodReference(), callArgs.toList());
}
@Override
protected void buildFields() {
// create a field in the BindingExpression for each argument
buildArgFields(targs, ArgKind.DEPENDENT);
}
JCExpression receiver() {
if (rcvrField == null) {
Type rcvrType = msym.owner.type;
rcvrField = new FieldInfo(JavafxDefs.receiverNameString, typeMorpher.typeMorphInfo(rcvrType), false);
return buildArgField(toJava.makeReceiver(diagPos, msym, toJava.attrEnv.enclClass.sym), rcvrField, ArgKind.BOUND);
} else {
return rcvrField.makeGetField();
}
}
JCExpression translatedImmutableMethodReference() {
Name name = functionName(msym, superToStatic, callBound);
JCExpression stor;
if (renameToSuper) {
stor = m().Select(makeTypeTree(diagPos, toJava.attrEnv.enclClass.sym.type, false), names._super);
} else if (superCall) {
stor = m().Ident(names._super);
} else if (superToStatic || msym.isStatic()) {
stor = makeTypeTree(diagPos, types.erasure(msym.owner.type), false);
} else if (selector == null || thisCall) {
stor = receiver();
} else {
stor = makeTypeTree(diagPos, types.erasure(msym.owner.type), false);
}
return m().Select(stor, name);
}
}).doit();
}
}
}
public JCExpression transMeth() {
assert !useInvoke;
JCExpression transMeth = toJava.translateAsUnconvertedValue(meth);
if (superToStatic || callBound) {
// translate the method name -- e.g., foo to foo$bound or foo$impl
Name name = functionName(msym, superToStatic, callBound);
JCExpression expr = superToStatic ? makeTypeTree(diagPos, msym.owner.type, false) : ((JCFieldAccess) transMeth).getExpression();
transMeth = m().Select(expr, name);
}
return transMeth;
}
}).doit();
}
private class BinaryTranslator {
final JFXBinary tree;
final DiagnosticPosition diagPos;
final JFXExpression l;
final JFXExpression r;
final boolean lBoxed;
final boolean rBoxed;
final Type lType;
final Type rType;
BinaryTranslator(final JFXBinary tree) {
this.tree = tree;
this.diagPos = tree.pos();
this.l = tree.lhs;
this.r = tree.rhs;
Type tubl = types.unboxedType(tree.lhs.type);
lBoxed = tubl.tag != TypeTags.NONE;
lType = lBoxed? tubl : tree.lhs.type;
Type tubr = types.unboxedType(tree.rhs.type);
rBoxed = tubr.tag != TypeTags.NONE;
rType = rBoxed? tubr : tree.rhs.type;
}
String typeString() {
if (types.isSameType(rType, syms.doubleType) || types.isSameType(lType, syms.doubleType)) {
return "double";
}
if (types.isSameType(rType, syms.floatType) || types.isSameType(lType, syms.floatType)) {
return "float";
}
if (types.isSameType(rType, syms.longType) || types.isSameType(lType, syms.longType)) {
return "long";
}
return "int";
}
JCExpression makeBinaryOperator(String op, String prefix) {
final JCExpression lhs = translate(l);
final JCExpression rhs = translate(r);
return runtime(diagPos, cBoundOperators, prefix + typeString(), List.of(makeLaziness(diagPos), lhs, rhs, makeQualifiedTree(diagPos, op)));
}
JCExpression makeBinaryArithmeticOperator(String op) {
return makeBinaryOperator(op, "op_");
}
JCExpression makeBinaryComparisonOperator(String op) {
return makeBinaryOperator(op, "cmp_");
}
boolean isNumeric(Type opType) {
switch (opType.tag) {
case BYTE:
case CHAR:
case SHORT:
case INT:
case LONG:
case FLOAT:
case DOUBLE:
return true;
}
return false;
}
JCExpression makeBinaryEqualityOperator(String op) {
if (isNumeric(lType) && isNumeric(rType)) {
return makeBinaryComparisonOperator(op);
} else {
final JCExpression lhs = translate(l);
final JCExpression rhs = translate(r);
String methodName = (lType.tag == BOOLEAN && rType.tag == BOOLEAN) ? "op_boolean" : "cmp_other";
return runtime(diagPos, cBoundOperators, methodName, List.of(makeLaziness(diagPos), lhs, rhs, makeQualifiedTree(diagPos, op)));
}
}
JCExpression doit() {
if ((types.isSameType(lType, syms.javafx_DurationType) ||
types.isSameType(rType, syms.javafx_DurationType)) &&
(tree.getFXTag() != JavafxTag.EQ && tree.getFXTag() != JavafxTag.NE)) {
// This is a Duration operation (other than equality). Use the Duration translator
return new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
return new DurationOperationTranslator(diagPos, tree.getFXTag(),
buildArgField(translate(l), lType), buildArgField(translate(r), rType),
lType, rType, toJava).doit();
}
}.doit();
}
switch (tree.getFXTag()) {
case PLUS:
return makeBinaryArithmeticOperator(opPLUS);
case MINUS:
return makeBinaryArithmeticOperator(opMINUS);
case DIV:
return makeBinaryArithmeticOperator(opDIVIDE);
case MUL:
return makeBinaryArithmeticOperator(opTIMES);
case MOD:
return makeBinaryArithmeticOperator(opMODULO);
case LT:
return makeBinaryComparisonOperator(opLT);
case LE:
return makeBinaryComparisonOperator(opLE);
case GT:
return makeBinaryComparisonOperator(opGT);
case GE:
return makeBinaryComparisonOperator(opGE);
case EQ:
return makeBinaryEqualityOperator(opEQ);
case NE:
return makeBinaryEqualityOperator(opNE);
case AND:
return makeBoundConditional(diagPos,
syms.booleanType,
translate(r, syms.booleanType),
makeConstantLocation(diagPos, syms.booleanType, makeLit(diagPos, syms.booleanType, 0)),
translate(l, syms.booleanType));
case OR:
return makeBoundConditional(diagPos,
syms.booleanType,
makeConstantLocation(diagPos, syms.booleanType, makeLit(diagPos, syms.booleanType, 1)),
translate(r, syms.booleanType),
translate(l, syms.booleanType));
default:
assert false : "unhandled binary operator";
return translate(l);
}
}
}
@Override
public void visitBinary(final JFXBinary tree) {
result = convert(tree.type, new BinaryTranslator(tree).doit());
}
@Override
public void visitUnary(final JFXUnary tree) {
DiagnosticPosition diagPos = tree.pos();
JFXExpression expr = tree.getExpression();
JCExpression transExpr = translate(expr);
JCExpression res;
switch (tree.getFXTag()) {
case SIZEOF:
res = runtime(diagPos, cBoundSequences, "sizeof", List.of(transExpr) );
break;
case REVERSE:
if (types.isSequence(expr.type)) {
// call runtime reverse of a sequence
res = runtime(diagPos, cBoundSequences, "reverse", List.of(transExpr));
} else {
// this isn't a sequence, just make it into a sequence
res = convert(expr.type, transExpr, tree.type);
}
break;
case NOT:
res = runtime(diagPos, cBoundOperators, "op_boolean", List.of(makeLaziness(diagPos), transExpr, make.Literal(TypeTags.BOT, null), makeQualifiedTree(diagPos, opNOT)));
break;
case NEG:
if (types.isSameType(tree.type, syms.javafx_DurationType)) {
//TODO: totally wrong
res = make.at(diagPos).Apply(null,
make.at(diagPos).Select(translate(tree.arg), names.fromString("negate")), List.<JCExpression>nil());
} else {
Type t = expr.type;
Type tub = types.unboxedType(t);
if (tub.tag != TypeTags.NONE) {
t = tub;
}
String typeString = (types.isSameType(t, syms.doubleType)) ? "double" : (types.isSameType(t, syms.floatType)) ? "float" : (types.isSameType(t, syms.longType)) ? "long" : "int";
res = runtime(diagPos, cBoundOperators, "op_" + typeString, List.of(makeLaziness(diagPos), transExpr, make.Literal(TypeTags.BOT, null), makeQualifiedTree(diagPos, opNEGATE)));
}
break;
case PREINC:
case PREDEC:
case POSTINC:
case POSTDEC:
// should have caught this in attribution
assert false : "++/-- in bind context f";
res = transExpr;
break;
default:
assert false : "unhandled unary operator";
res = transExpr;
break;
}
result = convert(tree.type, res);
}
@Override
public void visitTimeLiteral(JFXTimeLiteral tree) {
//TODO: code should be something like the below, but this requires a similar change to visitInterpolateValue
/***
DiagnosticPosition diagPos = tree.pos();
JCExpression unbound = toJava.translate(tree, Wrapped.InNothing);
result = makeConstantLocation(diagPos, targetType(tree.type), unbound);
*/
// convert this time literal to a javafx.lang.Duration.valueOf() invocation
JFXFunctionInvocation duration = timeLiteralToDuration(tree);
// now convert that FX invocation to Java
visitFunctionInvocation(duration); // sets result
}
public void visitInterpolateValue(final JFXInterpolateValue tree) {
result = new BindingExpressionClosureTranslator(tree.pos(), tree.type) {
protected JCExpression makePushExpression() {
return new InterpolateValueTranslator(tree, toJava) {
@Override
void setInstanceVariable(DiagnosticPosition diagPos, Name instName, JavafxBindStatus bindStatus, VarSymbol vsym, JCExpression transInit) {
JCExpression initRef = buildArgField(
transInit,
new FieldInfo(vsym.name, vsym.type),
bindStatus.isBound()? ArgKind.BOUND : ArgKind.DEPENDENT);
super.setInstanceVariable(diagPos, instName, bindStatus, vsym, initRef);
}
@Override
protected JCExpression translateInstanceVariableInit(JFXExpression init, JavafxBindStatus bindStatus, VarSymbol vsym) {
return translate(init, bindStatus, vsym.type);
}
protected JCExpression translateTarget() {
JCExpression target = translate(tree.attribute);
JCExpression val = toJava.callExpression(diagPos, makeExpression(syms.javafx_PointerType), "make", target);
return makeConstantLocation(diagPos, syms.javafx_KeyValueTargetType, val);
}
}.doit();
}
}.doit();
}
/***********************************************************************
*
* Utilities
*s
*/
protected String getSyntheticPrefix() {
return "bfx$";
}
/***********************************************************************
*
* Moot visitors
*
*/
@Override
public void visitForExpressionInClause(JFXForExpressionInClause that) {
assert false : "should be processed by parent tree";
}
@Override
public void visitModifiers(JFXModifiers tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitSkip(JFXSkip tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitThrow(JFXThrow tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTry(JFXTry tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitWhileLoop(JFXWhileLoop tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitOnReplace(JFXOnReplace tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitScript(JFXScript tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitClassDeclaration(JFXClassDeclaration tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitInitDefinition(JFXInitDefinition tree) {
assert false : "should not be processed as part of a binding";
}
public void visitPostInitDefinition(JFXPostInitDefinition tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitFunctionDefinition(JFXFunctionDefinition tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitSequenceInsert(JFXSequenceInsert tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitSequenceDelete(JFXSequenceDelete tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitContinue(JFXContinue tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitReturn(JFXReturn tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitImport(JFXImport tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitBreak(JFXBreak tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitCatch(JFXCatch tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTypeAny(JFXTypeAny that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTypeClass(JFXTypeClass that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTypeFunctional(JFXTypeFunctional that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTypeArray(JFXTypeArray tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitTypeUnknown(JFXTypeUnknown that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitObjectLiteralPart(JFXObjectLiteralPart that) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitVarScriptInit(JFXVarScriptInit tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitVar(JFXVar tree) {
// this is handled in translarVar
assert false : "should not be processed as part of a binding";
}
@Override
public void visitKeyFrameLiteral(JFXKeyFrameLiteral tree) {
assert false : "should not be processed as part of a binding";
}
@Override
public void visitErroneous(JFXErroneous tree) {
assert false : "erroneous nodes shouldn't have gotten this far";
}
}
| true | true | public void visitForExpression(final JFXForExpression tree) {
result = (new Translator( tree.pos(), toJava ) {
private final TypeMorphInfo tmiResult = typeMorpher.typeMorphInfo(targetType(tree.type));
/**
* V
*/
private final Type resultElementType = tmiResult.getElementType();
/**
* SequenceLocation<V>
*/
private final Type resultSequenceLocationType = typeMorpher.generifyIfNeeded(typeMorpher.locationType(TYPE_KIND_SEQUENCE), tmiResult);
/**
* isSimple -- true if the for-loop is simple enough that it can use SimpleBoundComprehension
*/
private final boolean isSimple = false; //TODO
/**
* Make: V.class
*/
private JCExpression makeResultClass() {
return makeTypeInfo(diagPos, resultElementType);
}
/**
* Make a method parameter
*/
private JCVariableDecl makeParam(Type type, Name name) {
return make.at(diagPos).VarDef(
make.Modifiers(Flags.PARAMETER | Flags.FINAL),
name,
makeExpression(type),
null);
}
/**
* Starting with the body of the comprehension...
* Wrap in a singleton sequence, if not a sequence.
* Wrap in a conditional if there are where-clauses: whereClause? body : []
*/
private JCExpression makeCore() {
JCExpression body;
if (types.isSequence(tree.getBodyExpression().type)) {
// the body is a sequence, desired type is the same as for the for-loop
body = translate(tree.getBodyExpression(), tmiTarget);
} else {
// the body is not a sequence, desired type is the element tpe need for for-loop
JCExpression single = translate(tree.getBodyExpression(), types.unboxedTypeOrType(tmiTarget.getElementType()));
List<JCExpression> args = List.of(makeResultClass(), single);
body = runtime(diagPos, cBoundSequences, "singleton", args);
}
JCExpression whereTest = null;
for (JFXForExpressionInClause clause : tree.getForExpressionInClauses()) {
JCExpression where = translate(clause.getWhereExpression());
if (where != null) {
if (whereTest == null) {
whereTest = where;
} else {
whereTest = runtime(diagPos, cBoundOperators, "and_bb", List.of(whereTest, where));
}
}
}
if (whereTest != null) {
body = makeBoundConditional(diagPos,
tree.type,
body,
runtime(diagPos, cBoundSequences, "empty", List.of(makeTypeInfo(diagPos, resultElementType))),
whereTest);
}
return body;
}
/**
* protected SequenceLocation<V> computeElements$(final ObjectLocation<T> IVAR_NAME, final IntLocation INDEXOF_IVAR_NAME) {
* return ...
* }
*/
private JCTree makeComputeElementsMethod(JFXForExpressionInClause clause, JCExpression inner, TypeMorphInfo tmiInduction) {
Type iVarType;
Type idxVarType;
Name computeName;
if (isSimple) {
iVarType = tmiInduction.getRealFXType();
idxVarType = syms.intType;
computeName = computeElementsName;
} else {
iVarType = tmiInduction.getLocationType();
idxVarType = typeMorpher.locationType(TYPE_KIND_INT);
computeName = computeElementsName;
}
ListBuffer<JCStatement> stmts = ListBuffer.lb();
Name ivarName = clause.getVar().name;
stmts.append(m().Return( inner ));
List<JCVariableDecl> params = List.of(
makeParam(iVarType, ivarName),
makeParam(idxVarType, indexVarName(clause) )
);
return m().MethodDef(
m().Modifiers(Flags.PROTECTED),
computeName,
makeExpression( resultSequenceLocationType ),
List.<JCTypeParameter>nil(),
params,
List.<JCExpression>nil(),
m().Block(0L, stmts.toList()),
null);
}
/**
* new BoundComprehension<T,V>(V.class, IN_SEQUENCE, USE_INDEX) { ... }
*/
private JCExpression makeBoundComprehension(JFXForExpressionInClause clause, JCExpression inner) {
JFXExpression seq = clause.getSequenceExpression();
TypeMorphInfo tmiSeq = typeMorpher.typeMorphInfo(seq.type);
TypeMorphInfo tmiInduction = typeMorpher.typeMorphInfo(clause.getVar().type);
JCClassDecl classDecl = m().AnonymousClassDef(
m().Modifiers(0L),
List.<JCTree>of(makeComputeElementsMethod(clause, inner, tmiInduction)));
List<JCExpression> typeArgs = List.nil();
boolean useIndex = clause.getIndexUsed();
JCExpression transSeq = translate( seq );
if (!tmiSeq.isSequence()) {
transSeq = runtime(diagPos, cBoundSequences, "singleton", List.of(makeResultClass(), transSeq));
}
List<JCExpression> constructorArgs = List.of(
makeResultClass(),
makeTypeInfo(diagPos, tmiInduction.getRealBoxedType()),
transSeq,
m().Literal(TypeTags.BOOLEAN, useIndex? 1 : 0) );
Type bcType = typeMorpher.abstractBoundComprehension.type;
JCExpression clazz = makeExpression(types.erasure(bcType)); // type params added below, so erase formals
ListBuffer<JCExpression> typeParams = ListBuffer.lb();
typeParams.append( makeExpression(tmiInduction.getRealBoxedType()) );
typeParams.append( makeExpression(tmiInduction.getLocationType()) );
typeParams.append( makeExpression(resultElementType) );
clazz = m().TypeApply(clazz, typeParams.toList());
return m().NewClass(null,
typeArgs,
clazz,
constructorArgs,
classDecl);
}
/**
* Put everything together, handle multiple in clauses -- wrap from the inner-most first
*/
public JCExpression doit() {
List<JFXForExpressionInClause> clauses = tree.getForExpressionInClauses();
// make the body of loop
JCExpression expr = makeCore();
// then wrap it in the looping constructs
for (int inx = clauses.size() - 1; inx >= 0; --inx) {
JFXForExpressionInClause clause = clauses.get(inx);
expr = makeBoundComprehension(clause, expr);
}
return expr;
}
}).doit();
}
| public void visitForExpression(final JFXForExpression tree) {
result = (new Translator( tree.pos(), toJava ) {
private final TypeMorphInfo tmiResult = typeMorpher.typeMorphInfo(targetType(tree.type));
/**
* V
*/
private final Type resultElementType = tmiResult.getElementType();
/**
* SequenceLocation<V>
*/
private final Type resultSequenceLocationType = typeMorpher.generifyIfNeeded(typeMorpher.locationType(TYPE_KIND_SEQUENCE), tmiResult);
/**
* isSimple -- true if the for-loop is simple enough that it can use SimpleBoundComprehension
*/
private final boolean isSimple = false; //TODO
/**
* Make: V.class
*/
private JCExpression makeResultClass() {
return makeTypeInfo(diagPos, resultElementType);
}
/**
* Make a method parameter
*/
private JCVariableDecl makeParam(Type type, Name name) {
return make.at(diagPos).VarDef(
make.Modifiers(Flags.PARAMETER | Flags.FINAL),
name,
makeExpression(type),
null);
}
/**
* Starting with the body of the comprehension...
* Wrap in a singleton sequence, if not a sequence.
* Wrap in a conditional if there are where-clauses: whereClause? body : []
*/
private JCExpression makeCore() {
JCExpression body;
if (types.isSequence(tree.getBodyExpression().type)) {
// the body is a sequence, desired type is the same as for the for-loop
body = translate(tree.getBodyExpression(), tmiTarget);
} else {
// the body is not a sequence, desired type is the element tpe need for for-loop
JCExpression single = translate(tree.getBodyExpression(), types.unboxedTypeOrType(resultElementType));
List<JCExpression> args = List.of(makeResultClass(), single);
body = runtime(diagPos, cBoundSequences, "singleton", args);
}
JCExpression whereTest = null;
for (JFXForExpressionInClause clause : tree.getForExpressionInClauses()) {
JCExpression where = translate(clause.getWhereExpression());
if (where != null) {
if (whereTest == null) {
whereTest = where;
} else {
whereTest = runtime(diagPos, cBoundOperators, "and_bb", List.of(whereTest, where));
}
}
}
if (whereTest != null) {
body = makeBoundConditional(diagPos,
tree.type,
body,
runtime(diagPos, cBoundSequences, "empty", List.of(makeTypeInfo(diagPos, resultElementType))),
whereTest);
}
return body;
}
/**
* protected SequenceLocation<V> computeElements$(final ObjectLocation<T> IVAR_NAME, final IntLocation INDEXOF_IVAR_NAME) {
* return ...
* }
*/
private JCTree makeComputeElementsMethod(JFXForExpressionInClause clause, JCExpression inner, TypeMorphInfo tmiInduction) {
Type iVarType;
Type idxVarType;
Name computeName;
if (isSimple) {
iVarType = tmiInduction.getRealFXType();
idxVarType = syms.intType;
computeName = computeElementsName;
} else {
iVarType = tmiInduction.getLocationType();
idxVarType = typeMorpher.locationType(TYPE_KIND_INT);
computeName = computeElementsName;
}
ListBuffer<JCStatement> stmts = ListBuffer.lb();
Name ivarName = clause.getVar().name;
stmts.append(m().Return( inner ));
List<JCVariableDecl> params = List.of(
makeParam(iVarType, ivarName),
makeParam(idxVarType, indexVarName(clause) )
);
return m().MethodDef(
m().Modifiers(Flags.PROTECTED),
computeName,
makeExpression( resultSequenceLocationType ),
List.<JCTypeParameter>nil(),
params,
List.<JCExpression>nil(),
m().Block(0L, stmts.toList()),
null);
}
/**
* new BoundComprehension<T,V>(V.class, IN_SEQUENCE, USE_INDEX) { ... }
*/
private JCExpression makeBoundComprehension(JFXForExpressionInClause clause, JCExpression inner) {
JFXExpression seq = clause.getSequenceExpression();
TypeMorphInfo tmiSeq = typeMorpher.typeMorphInfo(seq.type);
TypeMorphInfo tmiInduction = typeMorpher.typeMorphInfo(clause.getVar().type);
JCClassDecl classDecl = m().AnonymousClassDef(
m().Modifiers(0L),
List.<JCTree>of(makeComputeElementsMethod(clause, inner, tmiInduction)));
List<JCExpression> typeArgs = List.nil();
boolean useIndex = clause.getIndexUsed();
JCExpression transSeq = translate( seq );
if (!tmiSeq.isSequence()) {
transSeq = runtime(diagPos, cBoundSequences, "singleton", List.of(makeResultClass(), transSeq));
}
List<JCExpression> constructorArgs = List.of(
makeResultClass(),
makeTypeInfo(diagPos, tmiInduction.getRealBoxedType()),
transSeq,
m().Literal(TypeTags.BOOLEAN, useIndex? 1 : 0) );
Type bcType = typeMorpher.abstractBoundComprehension.type;
JCExpression clazz = makeExpression(types.erasure(bcType)); // type params added below, so erase formals
ListBuffer<JCExpression> typeParams = ListBuffer.lb();
typeParams.append( makeExpression(tmiInduction.getRealBoxedType()) );
typeParams.append( makeExpression(tmiInduction.getLocationType()) );
typeParams.append( makeExpression(resultElementType) );
clazz = m().TypeApply(clazz, typeParams.toList());
return m().NewClass(null,
typeArgs,
clazz,
constructorArgs,
classDecl);
}
/**
* Put everything together, handle multiple in clauses -- wrap from the inner-most first
*/
public JCExpression doit() {
List<JFXForExpressionInClause> clauses = tree.getForExpressionInClauses();
// make the body of loop
JCExpression expr = makeCore();
// then wrap it in the looping constructs
for (int inx = clauses.size() - 1; inx >= 0; --inx) {
JFXForExpressionInClause clause = clauses.get(inx);
expr = makeBoundComprehension(clause, expr);
}
return expr;
}
}).doit();
}
|
diff --git a/src/demos/misc/GLCapsTableDemo.java b/src/demos/misc/GLCapsTableDemo.java
index 548099d..767c4d5 100755
--- a/src/demos/misc/GLCapsTableDemo.java
+++ b/src/demos/misc/GLCapsTableDemo.java
@@ -1,322 +1,322 @@
package demos.misc;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.media.opengl.*;
import javax.media.opengl.glu.*;
import javax.swing.*;
import com.sun.opengl.util.FPSAnimator;
import javax.swing.border.TitledBorder;
import javax.swing.table.TableColumn;
import demos.gears.Gears;
/*******************************************************************************
* @file GLCapsTableDemo.java
* @desc Demonstrate use of GLCapabilitiesChooser and DefaultGLCapabilities.
* Demo tabulates the available capabilities array and put the data into a
* table. Pressing respawn button displays a canvas created with the
* currently selected index corresponding to the available array. There
* are two canvas to respawn: left or right.<br>
* TODO: if the number of samples > 0, setSampleBuffer(true) and run an
* antialiased renderer?;<br>
* TODO: if pbuffer is available, enable Float, RTT, RTTRec and create a
* pbuffer for eacH?<br>
* TODO: spawn using a diff renderer option(such as ones from demo
* package) <br>
* @version Jan 22, 2006 - GLCapsTableDemo.java created at 7:17:31 PM
* @platform ATI X600SE/XP Tablet SP2/JDK5/Eclipse
* @author Kiet Le
* @legal (c) 2006 Kiet Le. Released under BSD licence.
******************************************************************************/
public class GLCapsTableDemo
extends JFrame
implements
GLCapabilitiesChooser
{
private String[] colNames =
{"Pfd", "H/W", "DblBfr", "Stereo", // index, hwaccel, double, stereo
"CBits", "cR", "cG", "cB", "cA", // color bits
"ABits", "aR", "aG", "aB", "aA", // accum bits
"Z", "S", "AA|AAS", "PBuf(Float|RTT|RTTRec)"}; // depth, stencil, n
// samples, pbuffer
private ArrayList/*<GLCapabilities>*/ available = new ArrayList/*<GLCapabilities>*/();
private ArrayList/*<Integer>*/ indices = new ArrayList/*<Integer>*/();
private Object[][] data;
private JTable capsTable;
private int desiredCapIndex; // pfd index
private int selected = desiredCapIndex;
protected JPanel pane, pane2;
private boolean updateLR;// leftright
private DefaultGLCapabilitiesChooser choiceExaminer = //
new DefaultGLCapabilitiesChooser()
{
public int chooseCapabilities(GLCapabilities desired,
GLCapabilities[] available,
int windowSystemRecommendedChoice)
{
if ( available != null )
for (int i = 0; i < available.length; i++) {
GLCapabilities c = available[i];
if (c != null) {
GLCapsTableDemo.this.available.add((GLCapabilities) c.clone());
GLCapsTableDemo.this.indices.add(new Integer(i));
}
}
desiredCapIndex = super.chooseCapabilities(desired, available,
windowSystemRecommendedChoice);
System.out.println("valid" + desiredCapIndex);
capsTable = GLCapsTableDemo.this
.tabulateTable(GLCapsTableDemo.this.available, GLCapsTableDemo.this.indices);
JScrollPane scroller = //
new JScrollPane(capsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
GLCapsTableDemo.this.getContentPane().add(scroller);
pane.setBorder(BorderFactory
.createTitledBorder(null, "" + desiredCapIndex, TitledBorder.TRAILING,
TitledBorder.DEFAULT_POSITION));
pane2.setBorder(BorderFactory
.createTitledBorder(null, "" + desiredCapIndex, TitledBorder.LEADING,
TitledBorder.DEFAULT_POSITION));
GLCapsTableDemo.this.validate();// so table'll show up
System.out.println("valid");
return desiredCapIndex;
}
};
private GraphicsDevice device = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice();
private JSplitPane canvasPane;
private GLCanvas canvas;
private GLCanvas canvas2;
private Gears topRenderer = new Gears(), bottomRenderer = new Gears();
private FPSAnimator animator;
private Dimension defdim = new Dimension(512, 256);
private String visTip = "If no gears are visible, it may be that the "
+ "current desktop color resolution doesn't match "
+ "the GLCapabilities chosen. Check CBits column.";
/**
*/
public GLCapsTableDemo()
{
super(GLCapsTableDemo.class.getName());
initComponents();
}
/**
* (non-Javadoc)
*
* @see javax.media.opengl.GLCapabilitiesChooser#chooseCapabilities(javax.media.opengl.GLCapabilities,
* javax.media.opengl.GLCapabilities[], int)
*/
public int chooseCapabilities(GLCapabilities desired,
GLCapabilities[] available,
int windowSystemRecommendedChoice)
{
int row = capsTable.getSelectedRow();
int desiredCapIndex = ((Integer) indices.get(row)).intValue();
if ( updateLR )
{
pane.setBorder(BorderFactory
.createTitledBorder(null, "" + desiredCapIndex,
TitledBorder.TRAILING,
TitledBorder.DEFAULT_POSITION));
}
else
{
pane2.setBorder(BorderFactory
.createTitledBorder(null, "" + desiredCapIndex, TitledBorder.LEADING,
TitledBorder.DEFAULT_POSITION));
}
return desiredCapIndex;
}
public void run(final String[] args)
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setSize(new Dimension((int) (d.width * 0.75), (int) (d.height * 0.75)));
setLocationRelativeTo(null);
setVisible(true);
validate();
animator.start();
}//
/**
* @param args
*/
public static void main(String[] args)
{
GLCapsTableDemo demo = new GLCapsTableDemo();
demo.run(args);
}
private void initComponents()
{
// Hack: use multisampled capabilities to pick up more detailed information on Windows
GLCapabilities multisampledCaps = new GLCapabilities();
multisampledCaps.setSampleBuffers(true);
canvas = new GLCanvas(multisampledCaps, choiceExaminer, null, device);
// initially start w/ 2 canvas of default caps
// canvas = new GLCanvas(null, choiceExaminer, null, device);
canvas.addGLEventListener(topRenderer);
canvas.setSize(defdim);
// canvas.setPreferredSize(defdim);
// canvas.setMaximumSize(defdim);
animator = new FPSAnimator(canvas, 30);
canvas2 = new GLCanvas(null, null, null, device);
canvas2.addGLEventListener(bottomRenderer);
canvas2.setSize(defdim);
// canvas2.setPreferredSize(defdim);
// canvas2.setMaximumSize(defdim);
animator.add(canvas2);
pane = new JPanel();
pane2 = new JPanel();
pane.add(canvas);
pane2.add(canvas2);
canvasPane = new JSplitPane();
canvasPane.setResizeWeight(0.5);// 50-50 division
canvasPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
canvasPane.setLeftComponent(pane);
canvasPane.setRightComponent(pane2);
getContentPane().add(canvasPane, BorderLayout.SOUTH);
getContentPane().add(buildControls(), BorderLayout.NORTH);
}
private JTable tabulateTable(ArrayList/*<GLCapabilities>*/ capabilities,
ArrayList/*<Integer>*/ indices)
{
capabilities.trimToSize();
data = new Object[capabilities.size()][colNames.length];
String t = "T", f = "F";
for (int pfd = 0; pfd < capabilities.size(); pfd++)
{
data[ pfd ][ 0 ] = indices.get(pfd);
GLCapabilities cap = (GLCapabilities) capabilities.get(pfd);
data[ pfd ][ 1 ] = "" + (cap.getHardwareAccelerated() ? f : f);
data[ pfd ][ 2 ] = "" + (cap.getDoubleBuffered() ? t : f);
data[ pfd ][ 3 ] = "" + (cap.getStereo() ? t : f);
int r = cap.getRedBits(), //
g = cap.getGreenBits(), //
b = cap.getBlueBits(), //
a = cap.getAlphaBits();
data[ pfd ][ 4 ] = "" + (r + g + b + a);
data[ pfd ][ 5 ] = new Integer(r);
data[ pfd ][ 6 ] = new Integer(g);
data[ pfd ][ 7 ] = new Integer(b);
data[ pfd ][ 8 ] = new Integer(a);
r = cap.getAccumRedBits();
g = cap.getAccumGreenBits();
b = cap.getAccumBlueBits();
a = cap.getAccumAlphaBits();
data[ pfd ][ 9 ] = "" + (r + g + b + a);
data[ pfd ][ 10 ] = new Integer(r);
data[ pfd ][ 11 ] = new Integer(g);
data[ pfd ][ 12 ] = new Integer(b);
data[ pfd ][ 13 ] = new Integer(a);
//
data[ pfd ][ 14 ] = "" + cap.getDepthBits();
data[ pfd ][ 15 ] = "" + cap.getStencilBits();
data[ pfd ][ 16 ] = "" + (cap.getSampleBuffers() ? t : f) + " | "
+ cap.getNumSamples();
// concat p buffer nfo
- String pbuf = (cap.getOffscreenFloatingPointBuffers() ? "T |" : "F |");
- pbuf += (cap.getOffscreenRenderToTexture() ? "T | " : "F | ");
- pbuf += (cap.getOffscreenRenderToTextureRectangle() ? t : f);
+ String pbuf = (cap.getPbufferFloatingPointBuffers() ? "T |" : "F |");
+ pbuf += (cap.getPbufferRenderToTexture() ? "T | " : "F | ");
+ pbuf += (cap.getPbufferRenderToTextureRectangle() ? t : f);
data[ pfd ][ 17 ] = pbuf;
}
JTable table = new JTable(data, colNames) {
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
// table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
TableColumn column = null;
for (int i = 0; i < colNames.length; i++)
{
column = table.getColumnModel().getColumn(i);
if ( i == (colNames.length - 1) )
{
column.setPreferredWidth(100); // pbuffer column is bigger
}
else column.setPreferredWidth(7);
}
table.setDoubleBuffered(true);
return table;
}
private JPanel buildControls()
{
JPanel controls = new JPanel();
final JButton spawn = new JButton("Respawn Left");
final JButton spawn2 = new JButton("Respawn Right");
ActionListener recap = new ActionListener()
{
public void actionPerformed(final ActionEvent act)
{
animator.stop();
if ( act.getSource() == spawn )
{
updateLR = true;// left
animator.remove(canvas);
pane.remove(canvas);
canvas = newCanvas(true, true);// get new canvas w/ selected index
pane.add(canvas);
animator.add(canvas);
}
else
{
updateLR = false;
animator.remove(canvas2);
pane2.remove(canvas2);
canvas2 = newCanvas(true, false);
pane2.add(canvas2);
animator.add(canvas2);
}
new Thread()
{
public void run()
{
animator.start();
}
}.start();
GLCapsTableDemo.this.validate();
}
};
spawn.setToolTipText(visTip);
spawn.addActionListener(recap);
spawn2.addActionListener(recap);
//
controls.add(spawn);
controls.add(spawn2);
return controls;
}
private GLCanvas newCanvas(boolean mycap, boolean top)
{
GLCanvas surface = null;
if ( !mycap ) surface = new GLCanvas(null, choiceExaminer, null, device);
else surface = new GLCanvas(null, this, null, device);
if ( top ) surface.addGLEventListener(topRenderer);
else surface.addGLEventListener(bottomRenderer);
surface.setSize(defdim);// otherwise, no show; mixin' light-heavy containers
// surface.setMinimumSize(defdim);
return surface;
}
private void exitRunner()
{
new Thread()
{
public void run()
{
animator.stop();
}
};
}
}//
| true | true | private JTable tabulateTable(ArrayList/*<GLCapabilities>*/ capabilities,
ArrayList/*<Integer>*/ indices)
{
capabilities.trimToSize();
data = new Object[capabilities.size()][colNames.length];
String t = "T", f = "F";
for (int pfd = 0; pfd < capabilities.size(); pfd++)
{
data[ pfd ][ 0 ] = indices.get(pfd);
GLCapabilities cap = (GLCapabilities) capabilities.get(pfd);
data[ pfd ][ 1 ] = "" + (cap.getHardwareAccelerated() ? f : f);
data[ pfd ][ 2 ] = "" + (cap.getDoubleBuffered() ? t : f);
data[ pfd ][ 3 ] = "" + (cap.getStereo() ? t : f);
int r = cap.getRedBits(), //
g = cap.getGreenBits(), //
b = cap.getBlueBits(), //
a = cap.getAlphaBits();
data[ pfd ][ 4 ] = "" + (r + g + b + a);
data[ pfd ][ 5 ] = new Integer(r);
data[ pfd ][ 6 ] = new Integer(g);
data[ pfd ][ 7 ] = new Integer(b);
data[ pfd ][ 8 ] = new Integer(a);
r = cap.getAccumRedBits();
g = cap.getAccumGreenBits();
b = cap.getAccumBlueBits();
a = cap.getAccumAlphaBits();
data[ pfd ][ 9 ] = "" + (r + g + b + a);
data[ pfd ][ 10 ] = new Integer(r);
data[ pfd ][ 11 ] = new Integer(g);
data[ pfd ][ 12 ] = new Integer(b);
data[ pfd ][ 13 ] = new Integer(a);
//
data[ pfd ][ 14 ] = "" + cap.getDepthBits();
data[ pfd ][ 15 ] = "" + cap.getStencilBits();
data[ pfd ][ 16 ] = "" + (cap.getSampleBuffers() ? t : f) + " | "
+ cap.getNumSamples();
// concat p buffer nfo
String pbuf = (cap.getOffscreenFloatingPointBuffers() ? "T |" : "F |");
pbuf += (cap.getOffscreenRenderToTexture() ? "T | " : "F | ");
pbuf += (cap.getOffscreenRenderToTextureRectangle() ? t : f);
data[ pfd ][ 17 ] = pbuf;
}
JTable table = new JTable(data, colNames) {
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
// table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
TableColumn column = null;
for (int i = 0; i < colNames.length; i++)
{
column = table.getColumnModel().getColumn(i);
if ( i == (colNames.length - 1) )
{
column.setPreferredWidth(100); // pbuffer column is bigger
}
else column.setPreferredWidth(7);
}
table.setDoubleBuffered(true);
return table;
}
| private JTable tabulateTable(ArrayList/*<GLCapabilities>*/ capabilities,
ArrayList/*<Integer>*/ indices)
{
capabilities.trimToSize();
data = new Object[capabilities.size()][colNames.length];
String t = "T", f = "F";
for (int pfd = 0; pfd < capabilities.size(); pfd++)
{
data[ pfd ][ 0 ] = indices.get(pfd);
GLCapabilities cap = (GLCapabilities) capabilities.get(pfd);
data[ pfd ][ 1 ] = "" + (cap.getHardwareAccelerated() ? f : f);
data[ pfd ][ 2 ] = "" + (cap.getDoubleBuffered() ? t : f);
data[ pfd ][ 3 ] = "" + (cap.getStereo() ? t : f);
int r = cap.getRedBits(), //
g = cap.getGreenBits(), //
b = cap.getBlueBits(), //
a = cap.getAlphaBits();
data[ pfd ][ 4 ] = "" + (r + g + b + a);
data[ pfd ][ 5 ] = new Integer(r);
data[ pfd ][ 6 ] = new Integer(g);
data[ pfd ][ 7 ] = new Integer(b);
data[ pfd ][ 8 ] = new Integer(a);
r = cap.getAccumRedBits();
g = cap.getAccumGreenBits();
b = cap.getAccumBlueBits();
a = cap.getAccumAlphaBits();
data[ pfd ][ 9 ] = "" + (r + g + b + a);
data[ pfd ][ 10 ] = new Integer(r);
data[ pfd ][ 11 ] = new Integer(g);
data[ pfd ][ 12 ] = new Integer(b);
data[ pfd ][ 13 ] = new Integer(a);
//
data[ pfd ][ 14 ] = "" + cap.getDepthBits();
data[ pfd ][ 15 ] = "" + cap.getStencilBits();
data[ pfd ][ 16 ] = "" + (cap.getSampleBuffers() ? t : f) + " | "
+ cap.getNumSamples();
// concat p buffer nfo
String pbuf = (cap.getPbufferFloatingPointBuffers() ? "T |" : "F |");
pbuf += (cap.getPbufferRenderToTexture() ? "T | " : "F | ");
pbuf += (cap.getPbufferRenderToTextureRectangle() ? t : f);
data[ pfd ][ 17 ] = pbuf;
}
JTable table = new JTable(data, colNames) {
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
// table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
TableColumn column = null;
for (int i = 0; i < colNames.length; i++)
{
column = table.getColumnModel().getColumn(i);
if ( i == (colNames.length - 1) )
{
column.setPreferredWidth(100); // pbuffer column is bigger
}
else column.setPreferredWidth(7);
}
table.setDoubleBuffered(true);
return table;
}
|
diff --git a/ui/web/KnownIdentitiesPage.java b/ui/web/KnownIdentitiesPage.java
index 0b94a756..8da21767 100644
--- a/ui/web/KnownIdentitiesPage.java
+++ b/ui/web/KnownIdentitiesPage.java
@@ -1,267 +1,267 @@
/* This code is part of WoT, a plugin for Freenet. It is distributed
* under the GNU General Public License, version 2 (or at your option
* any later version). See http://www.gnu.org/ for details of the GPL. */
package plugins.WoT.ui.web;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import plugins.WoT.Identity;
import plugins.WoT.OwnIdentity;
import plugins.WoT.Trust;
import plugins.WoT.exceptions.DuplicateScoreException;
import plugins.WoT.exceptions.DuplicateTrustException;
import plugins.WoT.exceptions.NotInTrustTreeException;
import plugins.WoT.exceptions.NotTrustedException;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import freenet.keys.FreenetURI;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
/**
* The page where users can manage others identities.
*
* @author xor ([email protected])
* @author Julien Cornuwel ([email protected])
*/
public class KnownIdentitiesPage extends WebPageImpl {
private final static SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Creates a new KnownIdentitiesPage
*
* @param myWebInterface A reference to the WebInterface which created the page, used to get resources the page needs.
* @param myRequest The request sent by the user.
*/
public KnownIdentitiesPage(WebInterface myWebInterface, HTTPRequest myRequest) {
super(myWebInterface, myRequest);
}
public void make() {
if(request.isPartSet("AddIdentity")) {
try {
wot.addIdentity(request.getPartAsString("IdentityURI", 1024));
HTMLNode successBox = addContentBox("Success");
successBox.addChild("#", "The identity was added and is now being downloaded.");
}
catch(Exception e) {
addErrorBox("Adding the identity failed", e.getMessage());
}
}
if(request.isPartSet("SetTrust")) {
String trusterID = request.getPartAsString("OwnerID", 128);
- String trusteeID = request.isPartSet("trustee") ? request.getPartAsString("Trustee", 128) : null;
+ String trusteeID = request.isPartSet("Trustee") ? request.getPartAsString("Trustee", 128) : null;
String value = request.getPartAsString("Value", 4);
String comment = request.getPartAsString("Comment", 256); /* FIXME: store max length as a constant in class identity */
try {
if(trusteeID == null) /* For AddIdentity */
trusteeID = Identity.getIDFromURI(new FreenetURI(request.getPartAsString("IdentityURI", 1024)));
if(value.trim().equals(""))
wot.removeTrust(trusterID, trusteeID);
else
wot.setTrust(trusterID, trusteeID, Byte.parseByte(value), comment);
} catch(Exception e) {
addErrorBox("Setting trust failed", e.getMessage());
}
}
OwnIdentity treeOwner = null;
ObjectContainer db = wot.getDB();
PluginRespirator pr = wot.getPluginRespirator();
int nbOwnIdentities = 1;
String ownerID = request.getPartAsString("OwnerID", 128);
if(!ownerID.equals("")) {
try {
treeOwner = wot.getOwnIdentityByID(ownerID);
} catch (Exception e) {
Logger.error(this, "Error while selecting the OwnIdentity", e);
addErrorBox("Error while selecting the OwnIdentity", e.getMessage());
}
} else {
synchronized(wot) {
ObjectSet<OwnIdentity> allOwnIdentities = wot.getAllOwnIdentities();
nbOwnIdentities = allOwnIdentities.size();
if(nbOwnIdentities == 1)
treeOwner = allOwnIdentities.next();
}
}
makeAddIdentityForm(pr, treeOwner);
if(treeOwner != null) {
try {
makeKnownIdentitiesList(treeOwner, db, pr);
} catch (Exception e) {
Logger.error(this, e.getMessage());
addErrorBox("Error: " + e.getClass(), e.getMessage());
}
} else if(nbOwnIdentities > 1)
makeSelectTreeOwnerForm(db, pr);
else
makeNoOwnIdentityWarning();
}
/**
* Makes a form where the user can enter the requestURI of an Identity he knows.
*
* @param pr a reference to the {@link PluginRespirator}
* @param treeOwner The owner of the known identity list. Not used for adding the identity but for showing the known identity list properly after adding.
*/
private void makeAddIdentityForm(PluginRespirator pr, OwnIdentity treeOwner) {
// TODO Add trust value and comment fields and make them mandatory
// The user should only add an identity he trusts
HTMLNode addBoxContent = addContentBox("Add an identity");
HTMLNode createForm = pr.addFormChild(addBoxContent, uri, "AddIdentity");
if(treeOwner != null)
createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "OwnerID", treeOwner.getID()});
createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "AddIdentity" });
createForm.addChild("span", new String[] {"title", "style"},
new String[] { "This must be a valid Freenet URI.", "border-bottom: 1px dotted; cursor: help;"} , "Identity URI: ");
createForm.addChild("input", new String[] {"type", "name", "size"}, new String[] {"text", "IdentityURI", "70"});
createForm.addChild("br");
if(treeOwner != null) {
createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "SetTrust", "true"});
createForm.addChild("span", "Trust: ")
.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "Value", "4", "" });
createForm.addChild("span", "Comment:")
.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "Comment", "20", "" });
createForm.addChild("br");
}
createForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "AddIdentity", "Add" });
}
private void makeNoOwnIdentityWarning() {
addErrorBox("No own identity found", "You should create an identity first.");
}
private void makeSelectTreeOwnerForm(ObjectContainer db, PluginRespirator pr) {
HTMLNode listBoxContent = addContentBox("Select the trust tree owner");
HTMLNode selectForm = pr.addFormChild(listBoxContent, uri, "ViewTree");
selectForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "ViewTree" });
HTMLNode selectBox = selectForm.addChild("select", "name", "OwnerID");
synchronized(wot) {
for(OwnIdentity ownIdentity : wot.getAllOwnIdentities())
selectBox.addChild("option", "value", ownIdentity.getID(), ownIdentity.getNickname());
}
selectForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "select", "View this identity's Web of Trust" });
}
/**
* Makes the list of Identities known by the tree owner.
*
* @param db a reference to the database
* @param pr a reference to the {@link PluginRespirator}
* @param treeOwner owner of the trust tree we want to display
*/
private void makeKnownIdentitiesList(OwnIdentity treeOwner, ObjectContainer db, PluginRespirator pr) throws DuplicateScoreException, DuplicateTrustException {
HTMLNode listBoxContent = addContentBox("Known Identities");
// Display the list of known identities
HTMLNode identitiesTable = listBoxContent.addChild("table", "border", "0");
HTMLNode row=identitiesTable.addChild("tr");
row.addChild("th", "Nickname");
row.addChild("th", "Fetched");
row.addChild("th", "Trustlist");
row.addChild("th", "Score (Rank)");
row.addChild("th", "Trust/Comment");
row.addChild("th", "Trusters");
row.addChild("th", "Trustees");
synchronized(wot) {
for(Identity id : wot.getAllIdentities()) {
if(id == treeOwner) continue;
row=identitiesTable.addChild("tr");
// NickName
row.addChild("td", new String[] {"title", "style"}, new String[] {id.getRequestURI().toString(), "cursor: help;"}).addChild("a", "href", "?ShowIdentity&id=" + id.getID(), id.getNickname());
Date lastFetched = id.getLastFetchedDate();
if(!lastFetched.equals(new Date(0))) {
synchronized(mDateFormat) {
mDateFormat.setTimeZone(TimeZone.getDefault());
/* SimpleDateFormat.format(Date in UTC) does convert to the configured TimeZone. Interesting, eh? */
row.addChild("td", mDateFormat.format(lastFetched));
}
}
else
row.addChild("td", "Never");
// Publish TrustList
row.addChild("td", new String[] { "align" }, new String[] { "center" } , id.doesPublishTrustList() ? "Yes" : "No");
//Score
try {
row.addChild("td", new String[] { "align" }, new String[] { "center" } , String.valueOf(wot.getScore((OwnIdentity)treeOwner, id).getScore())+" ("+wot.getScore((OwnIdentity)treeOwner, id).getRank()+")");
}
catch (NotInTrustTreeException e) {
// This only happen with identities added manually by the user
// TODO Maybe we should give the opportunity to trust it at creation time
row.addChild("td", "null");
}
// Own Trust
row.addChild(getReceivedTrustForm(treeOwner, id));
// Nb Trusters
HTMLNode trustersCell = row.addChild("td", new String[] { "align" }, new String[] { "center" });
trustersCell.addChild(new HTMLNode("a", "href", uri + "?ShowIdentity&id="+id.getID(), Long.toString(wot.getReceivedTrusts(id).size())));
// Nb Trustees
HTMLNode trusteesCell = row.addChild("td", new String[] { "align" }, new String[] { "center" });
trusteesCell.addChild(new HTMLNode("a", "href", uri + "?ShowIdentity&id="+id.getID(), Long.toString(wot.getGivenTrusts(id).size())));
}
}
}
private HTMLNode getReceivedTrustForm (OwnIdentity truster, Identity trustee) throws DuplicateTrustException {
String trustValue = "";
String trustComment = "";
Trust trust;
try {
trust = wot.getTrust(truster, trustee);
trustValue = String.valueOf(trust.getValue());
trustComment = trust.getComment();
}
catch (NotTrustedException e) {
Logger.debug(this, truster.getNickname() + " does not trust " + trustee.getNickname());
}
HTMLNode cell = new HTMLNode("td");
HTMLNode trustForm = pr.addFormChild(cell, uri, "SetTrust");
trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "page", "SetTrust" });
trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "OwnerID", truster.getID() });
trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "Trustee", trustee.getID() });
trustForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "Value", "2", trustValue });
trustForm.addChild("input", new String[] { "type", "name", "size", "value" }, new String[] { "text", "Comment", "50", trustComment });
trustForm.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "SetTrust", "Update" });
return cell;
}
}
| true | true | public void make() {
if(request.isPartSet("AddIdentity")) {
try {
wot.addIdentity(request.getPartAsString("IdentityURI", 1024));
HTMLNode successBox = addContentBox("Success");
successBox.addChild("#", "The identity was added and is now being downloaded.");
}
catch(Exception e) {
addErrorBox("Adding the identity failed", e.getMessage());
}
}
if(request.isPartSet("SetTrust")) {
String trusterID = request.getPartAsString("OwnerID", 128);
String trusteeID = request.isPartSet("trustee") ? request.getPartAsString("Trustee", 128) : null;
String value = request.getPartAsString("Value", 4);
String comment = request.getPartAsString("Comment", 256); /* FIXME: store max length as a constant in class identity */
try {
if(trusteeID == null) /* For AddIdentity */
trusteeID = Identity.getIDFromURI(new FreenetURI(request.getPartAsString("IdentityURI", 1024)));
if(value.trim().equals(""))
wot.removeTrust(trusterID, trusteeID);
else
wot.setTrust(trusterID, trusteeID, Byte.parseByte(value), comment);
} catch(Exception e) {
addErrorBox("Setting trust failed", e.getMessage());
}
}
OwnIdentity treeOwner = null;
ObjectContainer db = wot.getDB();
PluginRespirator pr = wot.getPluginRespirator();
int nbOwnIdentities = 1;
String ownerID = request.getPartAsString("OwnerID", 128);
if(!ownerID.equals("")) {
try {
treeOwner = wot.getOwnIdentityByID(ownerID);
} catch (Exception e) {
Logger.error(this, "Error while selecting the OwnIdentity", e);
addErrorBox("Error while selecting the OwnIdentity", e.getMessage());
}
} else {
synchronized(wot) {
ObjectSet<OwnIdentity> allOwnIdentities = wot.getAllOwnIdentities();
nbOwnIdentities = allOwnIdentities.size();
if(nbOwnIdentities == 1)
treeOwner = allOwnIdentities.next();
}
}
makeAddIdentityForm(pr, treeOwner);
if(treeOwner != null) {
try {
makeKnownIdentitiesList(treeOwner, db, pr);
} catch (Exception e) {
Logger.error(this, e.getMessage());
addErrorBox("Error: " + e.getClass(), e.getMessage());
}
} else if(nbOwnIdentities > 1)
makeSelectTreeOwnerForm(db, pr);
else
makeNoOwnIdentityWarning();
}
| public void make() {
if(request.isPartSet("AddIdentity")) {
try {
wot.addIdentity(request.getPartAsString("IdentityURI", 1024));
HTMLNode successBox = addContentBox("Success");
successBox.addChild("#", "The identity was added and is now being downloaded.");
}
catch(Exception e) {
addErrorBox("Adding the identity failed", e.getMessage());
}
}
if(request.isPartSet("SetTrust")) {
String trusterID = request.getPartAsString("OwnerID", 128);
String trusteeID = request.isPartSet("Trustee") ? request.getPartAsString("Trustee", 128) : null;
String value = request.getPartAsString("Value", 4);
String comment = request.getPartAsString("Comment", 256); /* FIXME: store max length as a constant in class identity */
try {
if(trusteeID == null) /* For AddIdentity */
trusteeID = Identity.getIDFromURI(new FreenetURI(request.getPartAsString("IdentityURI", 1024)));
if(value.trim().equals(""))
wot.removeTrust(trusterID, trusteeID);
else
wot.setTrust(trusterID, trusteeID, Byte.parseByte(value), comment);
} catch(Exception e) {
addErrorBox("Setting trust failed", e.getMessage());
}
}
OwnIdentity treeOwner = null;
ObjectContainer db = wot.getDB();
PluginRespirator pr = wot.getPluginRespirator();
int nbOwnIdentities = 1;
String ownerID = request.getPartAsString("OwnerID", 128);
if(!ownerID.equals("")) {
try {
treeOwner = wot.getOwnIdentityByID(ownerID);
} catch (Exception e) {
Logger.error(this, "Error while selecting the OwnIdentity", e);
addErrorBox("Error while selecting the OwnIdentity", e.getMessage());
}
} else {
synchronized(wot) {
ObjectSet<OwnIdentity> allOwnIdentities = wot.getAllOwnIdentities();
nbOwnIdentities = allOwnIdentities.size();
if(nbOwnIdentities == 1)
treeOwner = allOwnIdentities.next();
}
}
makeAddIdentityForm(pr, treeOwner);
if(treeOwner != null) {
try {
makeKnownIdentitiesList(treeOwner, db, pr);
} catch (Exception e) {
Logger.error(this, e.getMessage());
addErrorBox("Error: " + e.getClass(), e.getMessage());
}
} else if(nbOwnIdentities > 1)
makeSelectTreeOwnerForm(db, pr);
else
makeNoOwnIdentityWarning();
}
|
diff --git a/modules/plugin/arcsde/datastore/src/main/java/org/geotools/arcsde/data/ArcSDEQuery.java b/modules/plugin/arcsde/datastore/src/main/java/org/geotools/arcsde/data/ArcSDEQuery.java
index ffafbd54c..4afffef22 100644
--- a/modules/plugin/arcsde/datastore/src/main/java/org/geotools/arcsde/data/ArcSDEQuery.java
+++ b/modules/plugin/arcsde/datastore/src/main/java/org/geotools/arcsde/data/ArcSDEQuery.java
@@ -1,1155 +1,1160 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2008, Open Source Geospatial Foundation (OSGeo)
*
* 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;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package org.geotools.arcsde.data;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.geotools.arcsde.ArcSdeException;
import org.geotools.arcsde.data.versioning.ArcSdeVersionHandler;
import org.geotools.arcsde.filter.FilterToSQLSDE;
import org.geotools.arcsde.filter.GeometryEncoderException;
import org.geotools.arcsde.filter.GeometryEncoderSDE;
import org.geotools.arcsde.pool.Command;
import org.geotools.arcsde.pool.ISession;
import org.geotools.data.DataSourceException;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultQuery;
import org.geotools.data.Query;
import org.geotools.data.jdbc.FilterToSQLException;
import org.geotools.feature.SchemaException;
import org.geotools.filter.FilterAttributeExtractor;
import org.geotools.filter.visitor.PostPreProcessFilterSplittingVisitor;
import org.geotools.filter.visitor.SimplifyingFilterVisitor;
import org.geotools.filter.visitor.SimplifyingFilterVisitor.FIDValidator;
import org.geotools.util.logging.Logging;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.filter.Filter;
import com.esri.sde.sdk.client.SeConnection;
import com.esri.sde.sdk.client.SeException;
import com.esri.sde.sdk.client.SeExtent;
import com.esri.sde.sdk.client.SeFilter;
import com.esri.sde.sdk.client.SeLayer;
import com.esri.sde.sdk.client.SeQuery;
import com.esri.sde.sdk.client.SeQueryInfo;
import com.esri.sde.sdk.client.SeSqlConstruct;
import com.esri.sde.sdk.client.SeTable;
import com.vividsolutions.jts.geom.Envelope;
/**
* Wrapper class for SeQuery to hold a SeConnection until close() is called and provide utility
* methods.
*
* @author Gabriel Roldan, Axios Engineering
* @source $URL:
* http://svn.geotools.org/geotools/trunk/gt/modules/plugin/arcsde/datastore/src/main/java
* /org/geotools/arcsde/data/ArcSDEQuery.java $
* @version $Id$
*/
class ArcSDEQuery {
/** Shared package's logger */
private static final Logger LOGGER = Logging.getLogger(ArcSDEQuery.class.getName());
/**
* The connection to the ArcSDE server obtained when first created the SeQuery in
* <code>getSeQuery</code>. It is retained until <code>close()</code> is called. Do not use it
* directly, but through <code>getConnection()</code>.
* <p>
* NOTE: this member is package visible only for unit test pourposes
* </p>
*/
final ISession session;
/**
* The exact feature type this query is about to request from the arcsde server. It could have
* less attributes than the ones of the actual table schema, in which case only those attributes
* will be requested.
*/
private SimpleFeatureType schema;
/**
* The query built using the constraints given by the geotools Query. It must not be accessed
* directly, but through <code>getSeQuery()</code>, since it is lazyly created
*/
private SeQuery query;
/**
* Holds the geotools Filter that originated this query from which can parse the sql where
* clause and the set of spatial filters for the ArcSDE Java API
*/
private ArcSDEQuery.FilterSet filters;
/** The lazyly calculated result count */
private int resultCount = -1;
/** DOCUMENT ME! */
private FIDReader fidReader;
private Object[] previousRowValues;
private ArcSdeVersionHandler versioningHandler;
/**
* Creates a new SDEQuery object.
*
* @param session
* the session attached to the life cycle of this query
* @param schema
* the schema with all the attributes as expected.
* @param filterSet
* DOCUMENT ME!
* @param versioningHandler
* used to transparently set up SeQuery streams pointing to the propper version edit
* state when appropriate
* @throws DataSourceException
* DOCUMENT ME!
* @see prepareQuery
*/
private ArcSDEQuery(final ISession session, final SimpleFeatureType schema,
final FilterSet filterSet, final FIDReader fidReader,
ArcSdeVersionHandler versioningHandler) throws DataSourceException {
this.session = session;
this.schema = schema;
this.filters = filterSet;
this.fidReader = fidReader;
this.versioningHandler = versioningHandler;
}
/**
* Creates a Query to be executed over a registered ArcSDE layer (whether it is from a table or
* a spatial view).
*
* @param session
* the session the query works over. As its managed by the calling code its the
* calling code responsibility to close it when done.
* @param fullSchema
* @param query
* @param isMultiversioned
* whether the table is versioned, if so, the default version and current state will
* be used for the SeQuery
* @return
* @throws IOException
*/
public static ArcSDEQuery createQuery(final ISession session,
final SimpleFeatureType fullSchema, final Query query, final FIDReader fidReader,
final ArcSdeVersionHandler versioningHandler) throws IOException {
Filter filter = query.getFilter();
LOGGER.fine("Creating new ArcSDEQuery");
final String typeName = fullSchema.getTypeName();
final SeLayer sdeLayer = session.getLayer(typeName);
final SimpleFeatureType querySchema = getQuerySchema(query, fullSchema);
// create the set of filters to work over
final ArcSDEQuery.FilterSet filters = new ArcSDEQuery.FilterSet(sdeLayer, filter,
querySchema, null, null, fidReader);
final ArcSDEQuery sdeQuery;
sdeQuery = new ArcSDEQuery(session, querySchema, filters, fidReader, versioningHandler);
return sdeQuery;
}
/**
* Creates a query to be executed over an inprocess view (a view defined by a SQL SELECT
* statement at the datastore configuration)
*
* @return the newly created ArcSDEQuery.
* @throws IOException
* see <i>throws DataSourceException</i> bellow.
* @see ArcSDEDataStore#registerView(String, PlainSelect)
*/
public static ArcSDEQuery createInprocessViewQuery(final ISession session,
final SimpleFeatureType fullSchema, final Query query,
final SeQueryInfo definitionQuery, final PlainSelect viewSelectStatement)
throws IOException {
final Filter filter = query.getFilter();
final FIDReader fidReader = FIDReader.NULL_READER;
final SeLayer sdeLayer;
// the first table has to be the main layer
final SeSqlConstruct construct;
try {
construct = definitionQuery.getConstruct();
} catch (SeException e) {
throw new ArcSdeException("shouldn't happen: " + e.getMessage(), e);
}
final String[] tables = construct.getTables();
String layerName = tables[0];
// @REVISIT: HACK HERE!, look how to get rid of alias in
// query info, or
// better stop using queryinfo as definition query and use
// the PlainSelect,
// then construct the query info dynamically when needed?
if (layerName.indexOf(" AS") > 0) {
layerName = layerName.substring(0, layerName.indexOf(" AS"));
}
sdeLayer = session.getLayer(layerName);
final SimpleFeatureType querySchema = getQuerySchema(query, fullSchema);
// create the set of filters to work over
final ArcSDEQuery.FilterSet filters = new ArcSDEQuery.FilterSet(sdeLayer, filter,
querySchema, definitionQuery, viewSelectStatement, fidReader);
final ArcSDEQuery sdeQuery;
sdeQuery = new ArcSDEQuery(session, querySchema, filters, fidReader,
ArcSdeVersionHandler.NONVERSIONED_HANDLER);
return sdeQuery;
}
/**
* Returns a {@link SimpleFeatureType} whichs a "view" of the <code>fullSchema</code> adapted as
* per the required query property names.
*
* @param query
* the query containing the list of property names required by the output schema and
* the {@link Filter query predicate} from which to fetch required properties to be
* used at runtime filter evaluation.
* @param fullSchema
* a feature type representing an ArcSDE layer full schema.
* @return a FeatureType derived from <code>fullSchema</code> which contains the property names
* required by the <code>query</code> and the ones referenced in the query filter.
* @throws DataSourceException
*/
public static SimpleFeatureType getQuerySchema(final Query query,
final SimpleFeatureType fullSchema) throws DataSourceException {
// guess which properties need to actually be retrieved.
final List<String> queryColumns = getQueryColumns(query, fullSchema);
final String[] attNames = queryColumns.toArray(new String[queryColumns.size()]);
try {
// create the resulting feature type for the real attributes to
// retrieve
SimpleFeatureType querySchema = DataUtilities.createSubType(fullSchema, attNames);
return querySchema;
} catch (SchemaException ex) {
throw new DataSourceException(
"Some requested attributes do not match the table schema: " + ex.getMessage(),
ex);
}
}
private static List<String> getQueryColumns(Query query, final SimpleFeatureType fullSchema)
throws DataSourceException {
final List<String> columnNames = new ArrayList<String>();
final String[] queryColumns = query.getPropertyNames();
if ((queryColumns == null) || (queryColumns.length == 0)) {
final List<AttributeDescriptor> attNames = fullSchema.getAttributeDescriptors();
for (Iterator<AttributeDescriptor> it = attNames.iterator(); it.hasNext();) {
AttributeDescriptor att = it.next();
String attName = att.getLocalName();
// de namespace-ify the names
// REVISIT: this shouldnt be needed!
if (attName.indexOf(":") != -1) {
attName = attName.substring(attName.indexOf(":") + 1);
}
columnNames.add(attName);
}
} else {
columnNames.addAll(Arrays.asList(queryColumns));
}
// Ok, say we don't support the full filter natively and it references
// some properties, then they have to be retrieved in order to evaluate
// the filter at runtime
Filter f = query.getFilter();
if (f != null) {
final FilterAttributeExtractor attExtractor = new FilterAttributeExtractor(fullSchema);
f.accept(attExtractor, null);
final String[] filterAtts = attExtractor.getAttributeNames();
for (String attName : filterAtts) {
if (!columnNames.contains(attName)) {
columnNames.add(attName);
}
}
}
return columnNames;
}
/**
* Returns the FID strategy used
*
* @return DOCUMENT ME!
*/
public FIDReader getFidReader() {
return this.fidReader;
}
public static ArcSDEQuery.FilterSet createFilters(SeLayer layer, SimpleFeatureType schema,
Filter filter, SeQueryInfo qInfo, PlainSelect viewSelect, FIDReader fidReader)
throws NoSuchElementException, IOException {
ArcSDEQuery.FilterSet filters = new ArcSDEQuery.FilterSet(layer, filter, schema, qInfo,
viewSelect, fidReader);
return filters;
}
/**
* Returns the stream used to fetch rows, creating it if it was not yet created.
*
* @throws SeException
* @throws IOException
*/
private SeQuery getSeQuery() throws IOException {
if (this.query == null) {
try {
String[] propsToQuery = fidReader.getPropertiesToFetch(this.schema);
this.query = createSeQueryForFetch(propsToQuery);
} catch (SeException e) {
throw new ArcSdeException(e);
}
}
return this.query;
}
/**
* creates an SeQuery with the filters provided to the constructor and returns it. Queries
* created with this method can be used to execute and fetch results. They cannot be used for
* other operations, such as calculating layer extents, or result count.
* <p>
* Difference with {@link #createSeQueryForFetch(Session, String[])} is tha this function tells
* <code>SeQuery.setSpatialConstraints</code> to NOT return geometry based bitmasks, which are
* needed for calculating the query extent and result count, but not for fetching SeRows.
* </p>
*
* @param propertyNames
* names of attributes to build the query for, respecting order
* @return DOCUMENT ME!
* @throws SeException
* if the ArcSDE Java API throws it while creating the SeQuery or setting it the
* spatial constraints.
* @throws IOException
* DOCUMENT ME!
*/
private SeQuery createSeQueryForFetch(String[] propertyNames) throws SeException, IOException {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("constructing new sql query with connection: " + session
+ ", propnames: " + java.util.Arrays.asList(propertyNames)
+ " sqlConstruct where clause: '" + this.filters.getSeSqlConstruct().getWhere()
+ "'");
}
final SeQuery seQuery = session.createSeQuery();
setQueryVersionState(seQuery);
final SeQueryInfo qInfo = filters.getQueryInfo(propertyNames);
final SeFilter[] spatialConstraints = this.filters.getSpatialFilters();
if (LOGGER.isLoggable(Level.FINER)) {
String msg = "ArcSDE query is: " + toString(qInfo);
LOGGER.finer(msg);
}
// try {
session.issue(new Command<Void>() {
@Override
public Void execute(ISession session, SeConnection connection) throws SeException,
IOException {
seQuery.prepareQueryInfo(qInfo);
if (spatialConstraints.length > 0) {
final boolean setReturnGeometryMasks = false;
seQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, setReturnGeometryMasks,
spatialConstraints);
}
return null;
}
});
// } catch (SeException e) {
// // HACK: a DATABASE LEVEL ERROR (code -51) occurs when using
// // prepareQueryInfo but the geometry att is not required in the list
// // of properties to retrieve, and thus propertyNames contains
// // SHAPE.fid as a last resort to get a fid
// if (-51 == e.getSeError().getSdeError()) {
// seQuery.close();
// seQuery = session.createSeQuery(propertyNames,
// filters.getSeSqlConstruct());
// setQueryVersionState(seQuery);
// seQuery.prepareQuery();
// } else {
// throw new ArcSdeException(e);
// }
// }
// if (spatialConstraints.length > 0) {
// final boolean setReturnGeometryMasks = false;
// seQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE,
// setReturnGeometryMasks,
// spatialConstraints);
// }
//
return seQuery;
}
private String toString(SeQueryInfo qInfo) {
StringBuffer sb = new StringBuffer("SeQueryInfo[\n\tcolumns=");
try {
SeSqlConstruct sql = qInfo.getConstruct();
String[] tables = sql.getTables();
String[] cols = qInfo.getColumns();
String by = null;
try {
by = qInfo.getByClause();
} catch (NullPointerException npe) {
// no-op
}
String where = sql.getWhere();
for (int i = 0; cols != null && i < cols.length; i++) {
sb.append(cols[i]);
if (i < cols.length - 1)
sb.append(", ");
}
sb.append("\n\tTables=");
for (int i = 0; i < tables.length; i++) {
sb.append(tables[i]);
if (i < tables.length - 1)
sb.append(", ");
}
sb.append("\n\tWhere=");
sb.append(where);
sb.append("\n\tOrderBy=");
sb.append(by);
} catch (SeException e) {
sb.append("Exception retrieving query info properties: " + e.getMessage());
}
sb.append("]");
return sb.toString();
}
/**
* If the table being queried is multi versioned (we have a flag indicating it), retrieves the
* default version and its current version state to use for the query object
*
* @param seQuery
* @throws IOException
*/
private void setQueryVersionState(SeQuery seQuery) throws IOException {
versioningHandler.setUpStream(session, seQuery);
}
/**
* Returns the schema of the originating Query
*
* @return the schema of the originating Query
*/
public SimpleFeatureType getSchema() {
return this.schema;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public ArcSDEQuery.FilterSet getFilters() {
return this.filters;
}
/**
* Convenient method to just calculate the result count of a given query.
*/
public static int calculateResultCount(final ISession session, final FeatureTypeInfo typeInfo,
final Query query, final ArcSdeVersionHandler versioningHandler) throws IOException {
ArcSDEQuery countQuery = null;
final int count;
try {
final SimpleFeatureType fullSchema = typeInfo.getFeatureType();
if (typeInfo.isInProcessView()) {
final SeQueryInfo definitionQuery = typeInfo.getSdeDefinitionQuery();
final PlainSelect viewSelectStatement = typeInfo.getDefinitionQuery();
countQuery = createInprocessViewQuery(session, fullSchema, query, definitionQuery,
viewSelectStatement);
} else {
final FIDReader fidStrategy = typeInfo.getFidStrategy();
countQuery = createQuery(session, fullSchema, query, fidStrategy, versioningHandler);
}
count = countQuery.calculateResultCount();
} finally {
if (countQuery != null) {
countQuery.close();
}
}
return count;
}
/**
* Convenient method to just calculate the resulting bound box of a given query.
*/
public static Envelope calculateQueryExtent(final ISession session,
final FeatureTypeInfo typeInfo, final Query query,
final ArcSdeVersionHandler versioningHandler) throws IOException {
final SimpleFeatureType fullSchema = typeInfo.getFeatureType();
final String defaultGeomAttName = fullSchema.getGeometryDescriptor().getLocalName();
// we're calculating the bounds, so we'd better be sure and add the
// spatial column to the query's propertynames
final DefaultQuery realQuery = new DefaultQuery(query);
realQuery.setPropertyNames(new String[] { defaultGeomAttName });
final ArcSDEQuery boundsQuery;
if (typeInfo.isInProcessView()) {
final SeQueryInfo definitionQuery = typeInfo.getSdeDefinitionQuery();
final PlainSelect viewSelectStatement = typeInfo.getDefinitionQuery();
boundsQuery = createInprocessViewQuery(session, fullSchema, realQuery, definitionQuery,
viewSelectStatement);
} else {
boundsQuery = createQuery(session, fullSchema, realQuery, FIDReader.NULL_READER,
versioningHandler);
}
Envelope queryExtent = null;
try {
Filter unsupportedFilter = boundsQuery.getFilters().getUnsupportedFilter();
if (unsupportedFilter == Filter.INCLUDE) {
// we can only use an optimized bounds calculation if the
// query is fully supported by sde
queryExtent = boundsQuery.calculateQueryExtent();
}
} finally {
boundsQuery.close();
}
return queryExtent;
}
/**
* if the query has been parsed as just a where clause filter, or has no filter at all, the
* result count calculation is optimized by selecting a <code>count()</code> single row. If the
* filter involves any kind of spatial filter, such as BBOX, the calculation can't be optimized
* by this way, because the ArcSDE Java API throws a <code>"DATABASE LEVEL
* ERROR OCURRED"</code> exception. So, in this case, a query over the shape field is made and the result is
* traversed counting the number of rows inside a while loop
*
* @return DOCUMENT ME!
* @throws IOException
* DOCUMENT ME!
* @throws DataSourceException
* DOCUMENT ME!
*/
public int calculateResultCount() throws IOException {
final Command<Integer> countCmd = new Command<Integer>() {
@Override
public Integer execute(ISession session, SeConnection connection) throws SeException,
IOException {
final String colName = ArcSDEQuery.this.schema.getGeometryDescriptor().getName()
.getLocalPart();
final SeQueryInfo qInfo = filters.getQueryInfo(new String[] { colName });
final SeFilter[] spatialFilters = filters.getSpatialFilters();
SeQuery query = new SeQuery(connection);
try {
setQueryVersionState(query);
if (spatialFilters != null && spatialFilters.length > 0) {
query.setSpatialConstraints(SeQuery.SE_OPTIMIZE, true, spatialFilters);
}
SeTable.SeTableStats tableStats = query.calculateTableStatistics("*",
SeTable.SeTableStats.SE_COUNT_STATS, qInfo, 0);
int actualCount = tableStats.getCount();
return new Integer(actualCount);
} finally {
query.close();
}
}
};
final Integer count = session.issue(countCmd);
return count.intValue();
}
public int _calculateResultCount() throws IOException {
final Command<Integer> countCmd = new Command<Integer>() {
@Override
public Integer execute(ISession session, SeConnection connection) throws SeException,
IOException {
final String colName = ArcSDEQuery.this.schema.getGeometryDescriptor().getName()
.getLocalPart();
final SeQueryInfo queryInfo = filters.getQueryInfo(new String[] { colName });
final String[] columns = { "*" };
final SeFilter[] spatialFilters = filters.getSpatialFilters();
SeSqlConstruct sql = new SeSqlConstruct();
String[] tables = filters.getSeSqlConstruct().getTables();
sql.setTables(tables);
String whereClause = filters.getSeSqlConstruct().getWhere();
if (whereClause != null) {
sql.setWhere(whereClause);
}
SeQuery query = new SeQuery(connection, columns, sql);
setQueryVersionState(query);
SeQueryInfo qInfo = new SeQueryInfo();
qInfo.setConstruct(sql);
if (spatialFilters != null && spatialFilters.length > 0) {
query.setSpatialConstraints(SeQuery.SE_OPTIMIZE, true, spatialFilters);
}
SeTable.SeTableStats tableStats = query.calculateTableStatistics("*",
SeTable.SeTableStats.SE_COUNT_STATS, qInfo, 0);
int actualCount = tableStats.getCount();
query.close();
return new Integer(actualCount);
}
};
final Integer count = session.issue(countCmd);
return count.intValue();
}
/**
* Returns the envelope for all features within the layer that pass any SQL construct, state, or
* spatial constraints for the stream.
*
* @return DOCUMENT ME!
* @throws IOException
* DOCUMENT ME!
* @throws DataSourceException
* DOCUMENT ME!
*/
public Envelope calculateQueryExtent() throws IOException {
Envelope envelope = null;
LOGGER.fine("Building a new SeQuery to consult it's resulting envelope");
// if (LOGGER.isLoggable(Level.FINER)) {
// String msg = "ArcSDE query is: " + toString(sdeQueryInfo);
// LOGGER.finer(msg);
// }
try {
envelope = session.issue(new Command<Envelope>() {
@Override
public Envelope execute(ISession session, SeConnection connection)
throws SeException, IOException {
final String[] spatialCol = { schema.getGeometryDescriptor().getLocalName() };
- String whereClause = filters.getSeSqlConstruct().getWhere();
+ // fullConstruct may hold information about multiple tables in case of an
+ // in-process view
+ final SeSqlConstruct fullConstruct = filters.getQueryInfo(spatialCol)
+ .getConstruct();
+ String whereClause = fullConstruct.getWhere();
if (whereClause == null) {
/*
* we really need a where clause or will get a famous -51 DATABASE LEVEL
* ERROR with no other explanation on some oracle databases
*/
whereClause = "1 = 1";
}
final SeFilter[] spatialConstraints = filters.getSpatialFilters();
final SeQuery extentQuery = new SeQuery(connection);
setQueryVersionState(extentQuery);
if (spatialConstraints.length > 0) {
extentQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
spatialConstraints);
}
- SeSqlConstruct sqlCons = new SeSqlConstruct(schema.getTypeName());
+ SeSqlConstruct sqlCons = new SeSqlConstruct();
+ sqlCons.setTables(fullConstruct.getTables());
sqlCons.setWhere(whereClause);
final SeQueryInfo seQueryInfo = new SeQueryInfo();
seQueryInfo.setColumns(spatialCol);
seQueryInfo.setConstruct(sqlCons);
SeExtent extent = extentQuery.calculateLayerExtent(seQueryInfo);
Envelope envelope = new Envelope(extent.getMinX(), extent.getMaxX(), extent
.getMinY(), extent.getMaxY());
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("got extent: " + extent + ", built envelope: " + envelope);
}
return envelope;
}
});
} catch (IOException ex) {
SeSqlConstruct sqlCons = this.filters.getSeSqlConstruct();
String sql = (sqlCons == null) ? null : sqlCons.getWhere();
String tables = (sqlCons == null) ? null : Arrays.asList(sqlCons.getTables())
.toString();
if (ex.getCause() instanceof SeException) {
SeException sdeEx = (SeException) ex.getCause();
if (sdeEx.getSeError().getSdeError() == -288) {
// gah, the dreaded 'LOGFILE SYSTEM TABLES DO NOT EXIST'
// error.
// this error is worthless. Make it quiet, at least.
LOGGER.severe("ArcSDE is complaining that your 'LOGFILE SYSTEM "
+ "TABLES DO NOT EXIST'. This is an ignorable error.");
}
}
LOGGER.log(Level.SEVERE, "***********************\ntables: " + tables + "\nfilter: "
+ this.filters.getGeometryFilter() + "\nSQL: " + sql, ex);
throw ex;
}
return envelope;
}
/**
* Silently closes this query.
*
* @param query
* @throws IOException
*/
private static void close(final SeQuery query, final ISession session) throws IOException {
if (query == null) {
return;
}
session.close(query);
}
// //////////////////////////////////////////////////////////////////////
// //////////// RELEVANT METHODS WRAPPED FROM SeStreamOp ////////////////
// //////////////////////////////////////////////////////////////////////
/**
* Closes the query.
* <p>
* The {@link Session connection} used by the query is not closed by this operation as it was
* provided by the calling code and thus it is its responsibility to handle the connection life
* cycle.
* </p>
*
* @throws IOException
*/
public void close() throws IOException {
close(this.query, session);
this.query = null;
}
/**
* Tells the server to execute a stream operation.
*
* @throws IOException
* DOCUMENT ME!
* @throws DataSourceException
* DOCUMENT ME!
*/
public void execute() throws IOException {
final SeQuery seQuery = getSeQuery();
session.issue(new Command<Void>() {
@Override
public Void execute(ISession session, SeConnection connection) throws SeException,
IOException {
seQuery.execute();
return null;
}
});
}
private SdeRow currentRow;
/**
* Fetches an SeRow of data.
*
* @return DOCUMENT ME!
* @throws IOException
* (DataSourceException) if the fetching fails
* @throws IllegalStateException
* if the query was already closed or {@link #execute()} hastn't been called yet
*/
public SdeRow fetch() throws IOException, IllegalStateException {
if (this.query == null) {
throw new IllegalStateException("query closed or not yet executed");
}
final SeQuery seQuery = getSeQuery();
// commented out while SeToJTSGeometryFactory is in development
// if(currentRow == null){
// GeometryFactory geomFac = new SeToJTSGeometryFactory();
// currentRow = new SdeRow(geomFac);
// int geometryIndex = -1;
// for(int i = 0; i < schema.getAttributeCount(); i++){
// if(schema.getDescriptor(i) instanceof GeometryDescriptor){
// geometryIndex = i;
// break;
// }
// }
// currentRow.setGeometryIndex(geometryIndex);
// }
// try {
// currentRow = session.fetch(seQuery, currentRow);
try {
currentRow = session.fetch(seQuery);
} catch (IOException e) {
close();
String msg = "Error fetching row for " + this.schema.getTypeName() + "[";
msg += "\nFilter: " + filters.sourceFilter;
msg += "\n where clause sent: " + filters.sdeSqlConstruct.getWhere();
msg += "\ngeometry filter:" + filters.geometryFilter;
LOGGER.log(Level.WARNING, msg, e);
throw e;
} catch (Exception e) {
close();
LOGGER.log(Level.SEVERE, "fetching row: " + e.getMessage(), e);
throw new DataSourceException("fetching row: " + e.getMessage(), e);
}
if (currentRow != null) {
currentRow.setPreviousValues(this.previousRowValues);
previousRowValues = currentRow.getAll();
}
return currentRow;
}
/**
* Sets the spatial filters on the query using SE_OPTIMIZE as the policy for spatial index
* search
*
* @param filters
* a set of spatial constraints to filter upon
* @throws IOException
* DOCUMENT ME!
* @throws DataSourceException
* DOCUMENT ME!
*/
public void setSpatialConstraints(SeFilter[] filters) throws IOException {
try {
getSeQuery().setSpatialConstraints(SeQuery.SE_OPTIMIZE, false, filters);
} catch (SeException e) {
throw new ArcSdeException(e);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public String toString() {
return "Schema: " + this.schema.getTypeName() + ", query: " + this.query;
}
/**
* DOCUMENT ME!
*
* @author $author$
* @version $Revision: 1.9 $
*/
public static class FilterSet {
/** DOCUMENT ME! */
private SeQueryInfo definitionQuery;
private PlainSelect layerSelectStatement;
private FIDReader fidReader;
/** DOCUMENT ME! */
private final SeLayer sdeLayer;
/** DOCUMENT ME! */
private final Filter sourceFilter;
/** DOCUMENT ME! */
private Filter _sqlFilter;
/** DOCUMENT ME! */
private Filter geometryFilter;
/** DOCUMENT ME! */
private Filter unsupportedFilter;
private FilterToSQLSDE _sqlEncoder;
/**
* Holds the ArcSDE Java API definition of the geometry related filters this datastore
* implementation supports natively.
*/
private SeFilter[] sdeSpatialFilters;
/**
* Holds the ArcSDE Java API definition of the <strong>non</strong> geometry related filters
* this datastore implementation supports natively.
*/
private SeSqlConstruct sdeSqlConstruct;
private SimpleFeatureType featureType;
/**
* Creates a new FilterSet object.
*
* @param sdeLayer
* DOCUMENT ME!
* @param sourceFilter
* DOCUMENT ME!
*/
public FilterSet(SeLayer sdeLayer, Filter sourceFilter, SimpleFeatureType ft,
SeQueryInfo definitionQuery, PlainSelect layerSelectStatement, FIDReader fidReader) {
assert sdeLayer != null;
assert sourceFilter != null;
assert ft != null;
this.sdeLayer = sdeLayer;
this.sourceFilter = sourceFilter;
this.featureType = ft;
this.definitionQuery = definitionQuery;
this.layerSelectStatement = layerSelectStatement;
this.fidReader = fidReader;
createGeotoolsFilters();
}
/**
* Given the <code>Filter</code> passed to the constructor, unpacks it to three different
* filters, one for the supported SQL based filter, another for the supported Geometry based
* filter, and the last one for the unsupported filter. All of them can be retrieved from
* its corresponding getter.
*/
private void createGeotoolsFilters() {
FilterToSQLSDE sqlEncoder = getSqlEncoder();
PostPreProcessFilterSplittingVisitor unpacker = new PostPreProcessFilterSplittingVisitor(
sqlEncoder.getCapabilities(), featureType, null);
sourceFilter.accept(unpacker, null);
SimplifyingFilterVisitor filterSimplifier = new SimplifyingFilterVisitor();
final String typeName = this.featureType.getTypeName();
FIDValidator validator = new SimplifyingFilterVisitor.TypeNameDotNumberFidValidator(
typeName);
filterSimplifier.setFIDValidator(validator);
this._sqlFilter = unpacker.getFilterPre();
this._sqlFilter = (Filter) this._sqlFilter.accept(filterSimplifier, null);
if (LOGGER.isLoggable(Level.FINE) && _sqlFilter != null)
LOGGER.fine("SQL portion of SDE Query: '" + _sqlFilter + "'");
Filter remainingFilter = unpacker.getFilterPost();
unpacker = new PostPreProcessFilterSplittingVisitor(GeometryEncoderSDE
.getCapabilities(), featureType, null);
remainingFilter.accept(unpacker, null);
this.geometryFilter = unpacker.getFilterPre();
this.geometryFilter = (Filter) this.geometryFilter.accept(filterSimplifier, null);
if (LOGGER.isLoggable(Level.FINE) && geometryFilter != null)
LOGGER.fine("Spatial-Filter portion of SDE Query: '" + geometryFilter + "'");
this.unsupportedFilter = unpacker.getFilterPost();
this.unsupportedFilter = (Filter) this.unsupportedFilter.accept(filterSimplifier, null);
if (LOGGER.isLoggable(Level.FINE) && unsupportedFilter != null)
LOGGER.fine("Unsupported (and therefore ignored) portion of SDE Query: '"
+ unsupportedFilter + "'");
}
/**
* Returns an SeQueryInfo that can be used to retrieve a set of SeRows from an ArcSDE layer
* or a layer with joins. The SeQueryInfo object lacks the set of column names to fetch. It
* is the responsibility of the calling code to call setColumns(String []) on the returned
* object to specify which properties to fetch.
*
* @param unqualifiedPropertyNames
* non null, possibly empty, list of property names to fetch
* @return
* @throws IOException
*/
public SeQueryInfo getQueryInfo(final String[] unqualifiedPropertyNames) throws IOException {
assert unqualifiedPropertyNames != null;
String[] tables;
String byClause = null;
final SeSqlConstruct plainSqlConstruct = getSeSqlConstruct();
String where = plainSqlConstruct.getWhere();
try {
if (definitionQuery == null) {
tables = new String[] { this.sdeLayer.getQualifiedName() };
} else {
tables = definitionQuery.getConstruct().getTables();
String joinWhere = definitionQuery.getConstruct().getWhere();
if (where == null) {
where = joinWhere;
} else {
where = joinWhere == null ? where : (joinWhere + " AND " + where);
}
try {
byClause = definitionQuery.getByClause();
} catch (NullPointerException e) {
// no-op
}
}
final SeQueryInfo qInfo = new SeQueryInfo();
final SeSqlConstruct sqlConstruct = new SeSqlConstruct();
sqlConstruct.setTables(tables);
if (where != null && where.length() > 0) {
sqlConstruct.setWhere(where);
}
final int queriedAttCount = unqualifiedPropertyNames.length;
if (queriedAttCount > 0) {
String[] sdeAttNames = new String[queriedAttCount];
FilterToSQLSDE sqlEncoder = getSqlEncoder();
for (int i = 0; i < queriedAttCount; i++) {
String attName = unqualifiedPropertyNames[i];
String coldef = sqlEncoder.getColumnDefinition(attName);
sdeAttNames[i] = coldef;
}
qInfo.setColumns(sdeAttNames);
}
qInfo.setConstruct(sqlConstruct);
if (byClause != null) {
qInfo.setByClause(byClause);
}
return qInfo;
} catch (SeException e) {
throw new ArcSdeException(e);
}
}
/**
* DOCUMENT ME!
*
* @return the SeSqlConstruct corresponding to the given SeLayer and SQL based filter.
* Should never return null.
* @throws DataSourceException
* if an error occurs encoding the sql filter to a SQL where clause, or creating
* the SeSqlConstruct for the given layer and where clause.
*/
public SeSqlConstruct getSeSqlConstruct() throws DataSourceException {
if (this.sdeSqlConstruct == null) {
final String layerName;
try {
layerName = this.sdeLayer.getQualifiedName();
this.sdeSqlConstruct = new SeSqlConstruct(layerName);
} catch (SeException e) {
throw new ArcSdeException("Can't create SQL construct for "
+ sdeLayer.getName(), e);
}
Filter sqlFilter = getSqlFilter();
if (!Filter.INCLUDE.equals(sqlFilter)) {
String whereClause = null;
FilterToSQLSDE sqlEncoder = getSqlEncoder();
try {
whereClause = sqlEncoder.encodeToString(sqlFilter);
} catch (FilterToSQLException sqle) {
String message = "Geometry encoder error: " + sqle.getMessage();
throw new DataSourceException(message, sqle);
}
LOGGER.fine("ArcSDE where clause '" + whereClause + "'");
this.sdeSqlConstruct.setWhere(whereClause);
}
}
return this.sdeSqlConstruct;
}
/**
* Lazily creates the array of <code>SeShapeFilter</code> objects that map the corresponding
* geometry related filters included in the original <code>org.geotools.data.Query</code>
* passed to the constructor.
*
* @return an array with the spatial filters to be applied to the SeQuery, or null if none.
* @throws DataSourceException
* DOCUMENT ME!
*/
public SeFilter[] getSpatialFilters() throws DataSourceException {
if (this.sdeSpatialFilters == null) {
GeometryEncoderSDE geometryEncoder = new GeometryEncoderSDE(this.sdeLayer,
featureType);
try {
geometryEncoder.encode(getGeometryFilter());
} catch (GeometryEncoderException e) {
throw new DataSourceException("Error parsing geometry filters: "
+ e.getMessage(), e);
}
this.sdeSpatialFilters = geometryEncoder.getSpatialFilters();
}
return this.sdeSpatialFilters;
}
/**
* DOCUMENT ME!
*
* @return the subset, non geometry related, of the original filter this datastore
* implementation supports natively, or <code>Filter.INCLUDE</code> if the original
* Query does not contains non spatial filters that we can deal with at the ArcSDE
* Java API side.
*/
public Filter getSqlFilter() {
return (this._sqlFilter == null) ? Filter.INCLUDE : this._sqlFilter;
}
/**
* DOCUMENT ME!
*
* @return the geometry related subset of the original filter this datastore implementation
* supports natively, or <code>Filter.INCLUDE</code> if the original Query does not
* contains spatial filters that we can deal with at the ArcSDE Java API side.
*/
public Filter getGeometryFilter() {
return (this.geometryFilter == null) ? Filter.INCLUDE : this.geometryFilter;
}
/**
* DOCUMENT ME!
*
* @return the part of the original filter this datastore implementation does not supports
* natively, or <code>Filter.INCLUDE</code> if we support the whole Query filter.
*/
public Filter getUnsupportedFilter() {
return (this.unsupportedFilter == null) ? Filter.INCLUDE : this.unsupportedFilter;
}
private FilterToSQLSDE getSqlEncoder() {
if (_sqlEncoder == null) {
final String layerName;
try {
layerName = sdeLayer.getQualifiedName();
} catch (SeException e) {
throw (RuntimeException) new RuntimeException(
"error getting layer's qualified name").initCause(e);
}
String fidColumn = fidReader.getFidColumn();
_sqlEncoder = new FilterToSQLSDE(layerName, fidColumn, featureType,
layerSelectStatement);
}
return _sqlEncoder;
}
}
}
| false | true | public Envelope calculateQueryExtent() throws IOException {
Envelope envelope = null;
LOGGER.fine("Building a new SeQuery to consult it's resulting envelope");
// if (LOGGER.isLoggable(Level.FINER)) {
// String msg = "ArcSDE query is: " + toString(sdeQueryInfo);
// LOGGER.finer(msg);
// }
try {
envelope = session.issue(new Command<Envelope>() {
@Override
public Envelope execute(ISession session, SeConnection connection)
throws SeException, IOException {
final String[] spatialCol = { schema.getGeometryDescriptor().getLocalName() };
String whereClause = filters.getSeSqlConstruct().getWhere();
if (whereClause == null) {
/*
* we really need a where clause or will get a famous -51 DATABASE LEVEL
* ERROR with no other explanation on some oracle databases
*/
whereClause = "1 = 1";
}
final SeFilter[] spatialConstraints = filters.getSpatialFilters();
final SeQuery extentQuery = new SeQuery(connection);
setQueryVersionState(extentQuery);
if (spatialConstraints.length > 0) {
extentQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
spatialConstraints);
}
SeSqlConstruct sqlCons = new SeSqlConstruct(schema.getTypeName());
sqlCons.setWhere(whereClause);
final SeQueryInfo seQueryInfo = new SeQueryInfo();
seQueryInfo.setColumns(spatialCol);
seQueryInfo.setConstruct(sqlCons);
SeExtent extent = extentQuery.calculateLayerExtent(seQueryInfo);
Envelope envelope = new Envelope(extent.getMinX(), extent.getMaxX(), extent
.getMinY(), extent.getMaxY());
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("got extent: " + extent + ", built envelope: " + envelope);
}
return envelope;
}
});
} catch (IOException ex) {
SeSqlConstruct sqlCons = this.filters.getSeSqlConstruct();
String sql = (sqlCons == null) ? null : sqlCons.getWhere();
String tables = (sqlCons == null) ? null : Arrays.asList(sqlCons.getTables())
.toString();
if (ex.getCause() instanceof SeException) {
SeException sdeEx = (SeException) ex.getCause();
if (sdeEx.getSeError().getSdeError() == -288) {
// gah, the dreaded 'LOGFILE SYSTEM TABLES DO NOT EXIST'
// error.
// this error is worthless. Make it quiet, at least.
LOGGER.severe("ArcSDE is complaining that your 'LOGFILE SYSTEM "
+ "TABLES DO NOT EXIST'. This is an ignorable error.");
}
}
LOGGER.log(Level.SEVERE, "***********************\ntables: " + tables + "\nfilter: "
+ this.filters.getGeometryFilter() + "\nSQL: " + sql, ex);
throw ex;
}
return envelope;
}
| public Envelope calculateQueryExtent() throws IOException {
Envelope envelope = null;
LOGGER.fine("Building a new SeQuery to consult it's resulting envelope");
// if (LOGGER.isLoggable(Level.FINER)) {
// String msg = "ArcSDE query is: " + toString(sdeQueryInfo);
// LOGGER.finer(msg);
// }
try {
envelope = session.issue(new Command<Envelope>() {
@Override
public Envelope execute(ISession session, SeConnection connection)
throws SeException, IOException {
final String[] spatialCol = { schema.getGeometryDescriptor().getLocalName() };
// fullConstruct may hold information about multiple tables in case of an
// in-process view
final SeSqlConstruct fullConstruct = filters.getQueryInfo(spatialCol)
.getConstruct();
String whereClause = fullConstruct.getWhere();
if (whereClause == null) {
/*
* we really need a where clause or will get a famous -51 DATABASE LEVEL
* ERROR with no other explanation on some oracle databases
*/
whereClause = "1 = 1";
}
final SeFilter[] spatialConstraints = filters.getSpatialFilters();
final SeQuery extentQuery = new SeQuery(connection);
setQueryVersionState(extentQuery);
if (spatialConstraints.length > 0) {
extentQuery.setSpatialConstraints(SeQuery.SE_OPTIMIZE, false,
spatialConstraints);
}
SeSqlConstruct sqlCons = new SeSqlConstruct();
sqlCons.setTables(fullConstruct.getTables());
sqlCons.setWhere(whereClause);
final SeQueryInfo seQueryInfo = new SeQueryInfo();
seQueryInfo.setColumns(spatialCol);
seQueryInfo.setConstruct(sqlCons);
SeExtent extent = extentQuery.calculateLayerExtent(seQueryInfo);
Envelope envelope = new Envelope(extent.getMinX(), extent.getMaxX(), extent
.getMinY(), extent.getMaxY());
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("got extent: " + extent + ", built envelope: " + envelope);
}
return envelope;
}
});
} catch (IOException ex) {
SeSqlConstruct sqlCons = this.filters.getSeSqlConstruct();
String sql = (sqlCons == null) ? null : sqlCons.getWhere();
String tables = (sqlCons == null) ? null : Arrays.asList(sqlCons.getTables())
.toString();
if (ex.getCause() instanceof SeException) {
SeException sdeEx = (SeException) ex.getCause();
if (sdeEx.getSeError().getSdeError() == -288) {
// gah, the dreaded 'LOGFILE SYSTEM TABLES DO NOT EXIST'
// error.
// this error is worthless. Make it quiet, at least.
LOGGER.severe("ArcSDE is complaining that your 'LOGFILE SYSTEM "
+ "TABLES DO NOT EXIST'. This is an ignorable error.");
}
}
LOGGER.log(Level.SEVERE, "***********************\ntables: " + tables + "\nfilter: "
+ this.filters.getGeometryFilter() + "\nSQL: " + sql, ex);
throw ex;
}
return envelope;
}
|
diff --git a/src/lib/com/izforge/izpack/panels/UserPathSelectionPanel.java b/src/lib/com/izforge/izpack/panels/UserPathSelectionPanel.java
index 136f0478..fcd659b0 100644
--- a/src/lib/com/izforge/izpack/panels/UserPathSelectionPanel.java
+++ b/src/lib/com/izforge/izpack/panels/UserPathSelectionPanel.java
@@ -1,213 +1,213 @@
/*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2004 Klaus Bartz
*
* 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.izforge.izpack.panels;
import com.izforge.izpack.gui.ButtonFactory;
import com.izforge.izpack.gui.IzPanelConstraints;
import com.izforge.izpack.gui.IzPanelLayout;
import com.izforge.izpack.gui.LayoutConstants;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.IzPanel;
import com.izforge.izpack.installer.LayoutHelper;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* This is a sub panel which contains a text field and a browse button for path selection. This is
* NOT an IzPanel, else it is made to use in an IzPanel for any path selection. If the IzPanel
* parent implements ActionListener, the ActionPerformed method will be called, if
* PathSelectionPanel.ActionPerformed was called with a source other than the browse button. This
* can be used to perform parentFrame.navigateNext in the IzPanel parent. An example implementation
* is done in com.izforge.izpack.panels.PathInputPanel.
*
* @author Klaus Bartz
* @author Jeff Gordon
*/
public class UserPathSelectionPanel extends JPanel implements ActionListener, LayoutConstants
{
/**
*
*/
private static final long serialVersionUID = 3618700794577105718L;
/**
* The text field for the path.
*/
private JTextField textField;
/**
* The 'browse' button.
*/
private JButton browseButton;
/**
* IzPanel parent (not the InstallerFrame).
*/
private IzPanel parent;
/**
* The installer internal data.
*/
private InstallData idata;
private String targetPanel;
private String variableName;
private String defaultPanelName = "TargetPanel";
/**
* The constructor. Be aware, parent is the parent IzPanel, not the installer frame.
*
* @param parent The parent IzPanel.
* @param idata The installer internal data.
*/
public UserPathSelectionPanel(IzPanel parent, InstallData idata, String targetPanel, String variableName)
{
super();
this.parent = parent;
this.idata = idata;
this.variableName = variableName;
this.targetPanel = targetPanel;
createLayout();
}
/**
* Creates the layout for this sub panel.
*/
protected void createLayout()
{
// We woulduse the IzPanelLayout also in this "sub"panel.
// In an IzPanel there are support of this layout manager at
// more than one places. In this panel not, therefore we have
// to make all things needed.
// First create a layout helper.
LayoutHelper layoutHelper = new LayoutHelper(this);
// Start the layout.
layoutHelper.startLayout(new IzPanelLayout());
// One of the rare points we need explicit a constraints.
IzPanelConstraints ipc = IzPanelLayout.getDefaultConstraint(TEXT_CONSTRAINT);
// The text field should be stretched.
ipc.setXStretch(1.0);
- textField = new JTextField(idata.getVariable(variableName));
+ textField = new JTextField(idata.getVariable(variableName), 10);
textField.addActionListener(this);
parent.setInitialFocus(textField);
add(textField, ipc);
// We would have place between text field and button.
add(IzPanelLayout.createHorizontalFiller(3));
// No explicit constraints for the button (else implicit) because
// defaults are OK.
String buttonText = parent.getInstallerFrame().langpack.getString(targetPanel + ".browse");
if (buttonText == null)
{
buttonText = parent.getInstallerFrame().langpack.getString(defaultPanelName + ".browse");
}
browseButton = ButtonFactory.createButton(buttonText, parent.getInstallerFrame().icons.getImageIcon("open"), idata.buttonsHColor);
browseButton.addActionListener(this);
add(browseButton);
}
// There are problems with the size if no other component needs the
// full size. Sometimes directly, somtimes only after a back step.
public Dimension getMinimumSize()
{
Dimension ss = super.getPreferredSize();
Dimension retval = parent.getSize();
retval.height = ss.height;
return (retval);
}
/**
* Actions-handling method.
*
* @param e The event.
*/
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == browseButton)
{
// The user wants to browse its filesystem
// Prepares the file chooser
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new File(textField.getText()));
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
// Shows it
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
String path = fc.getSelectedFile().getAbsolutePath();
textField.setText(path);
}
}
else
{
if (parent instanceof ActionListener)
{
((ActionListener) parent).actionPerformed(e);
}
}
}
/**
* Returns the chosen path.
*
* @return the chosen path
*/
public String getPath()
{
return (textField.getText());
}
/**
* Sets the contents of the text field to the given path.
*
* @param path the path to be set
*/
public void setPath(String path)
{
textField.setText(path);
}
/**
* Returns the text input field for the path. This methode can be used to differ in a
* ActionPerformed method of the parent between the browse button and the text field.
*
* @return the text input field for the path
*/
public JTextField getPathInputField()
{
return textField;
}
/**
* Returns the browse button object for modification or for use with a different ActionListener.
*
* @return the browse button to open the JFileChooser
*/
public JButton getBrowseButton()
{
return browseButton;
}
}
| true | true | protected void createLayout()
{
// We woulduse the IzPanelLayout also in this "sub"panel.
// In an IzPanel there are support of this layout manager at
// more than one places. In this panel not, therefore we have
// to make all things needed.
// First create a layout helper.
LayoutHelper layoutHelper = new LayoutHelper(this);
// Start the layout.
layoutHelper.startLayout(new IzPanelLayout());
// One of the rare points we need explicit a constraints.
IzPanelConstraints ipc = IzPanelLayout.getDefaultConstraint(TEXT_CONSTRAINT);
// The text field should be stretched.
ipc.setXStretch(1.0);
textField = new JTextField(idata.getVariable(variableName));
textField.addActionListener(this);
parent.setInitialFocus(textField);
add(textField, ipc);
// We would have place between text field and button.
add(IzPanelLayout.createHorizontalFiller(3));
// No explicit constraints for the button (else implicit) because
// defaults are OK.
String buttonText = parent.getInstallerFrame().langpack.getString(targetPanel + ".browse");
if (buttonText == null)
{
buttonText = parent.getInstallerFrame().langpack.getString(defaultPanelName + ".browse");
}
browseButton = ButtonFactory.createButton(buttonText, parent.getInstallerFrame().icons.getImageIcon("open"), idata.buttonsHColor);
browseButton.addActionListener(this);
add(browseButton);
}
| protected void createLayout()
{
// We woulduse the IzPanelLayout also in this "sub"panel.
// In an IzPanel there are support of this layout manager at
// more than one places. In this panel not, therefore we have
// to make all things needed.
// First create a layout helper.
LayoutHelper layoutHelper = new LayoutHelper(this);
// Start the layout.
layoutHelper.startLayout(new IzPanelLayout());
// One of the rare points we need explicit a constraints.
IzPanelConstraints ipc = IzPanelLayout.getDefaultConstraint(TEXT_CONSTRAINT);
// The text field should be stretched.
ipc.setXStretch(1.0);
textField = new JTextField(idata.getVariable(variableName), 10);
textField.addActionListener(this);
parent.setInitialFocus(textField);
add(textField, ipc);
// We would have place between text field and button.
add(IzPanelLayout.createHorizontalFiller(3));
// No explicit constraints for the button (else implicit) because
// defaults are OK.
String buttonText = parent.getInstallerFrame().langpack.getString(targetPanel + ".browse");
if (buttonText == null)
{
buttonText = parent.getInstallerFrame().langpack.getString(defaultPanelName + ".browse");
}
browseButton = ButtonFactory.createButton(buttonText, parent.getInstallerFrame().icons.getImageIcon("open"), idata.buttonsHColor);
browseButton.addActionListener(this);
add(browseButton);
}
|
diff --git a/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/auth/plugins/SeamJsfSessionManager.java b/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/auth/plugins/SeamJsfSessionManager.java
index d7e6d0f1..4ab08cb9 100644
--- a/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/auth/plugins/SeamJsfSessionManager.java
+++ b/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/auth/plugins/SeamJsfSessionManager.java
@@ -1,73 +1,76 @@
/*
* (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id$
*/
package org.nuxeo.ecm.platform.ui.web.auth.plugins;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jboss.seam.Seam;
import org.jboss.seam.contexts.ServletLifecycle;
import org.jboss.seam.core.Manager;
import org.nuxeo.ecm.platform.ui.web.rest.FancyURLRequestWrapper;
public class SeamJsfSessionManager extends DefaultSessionManager {
@Override
public boolean canBypassRequest(ServletRequest request) {
return request instanceof FancyURLRequestWrapper;
}
@Override
public void onBeforeSessionInvalidate(ServletRequest request) {
try {
Seam.invalidateSession();
}
catch (Exception e) {
super.onBeforeSessionInvalidate(request);
}
}
@Override
public void onBeforeSessionReinit(ServletRequest request) {
// destroy session
// because of Seam Phase Listener we can't use Seam.invalidateSession()
// because the session would be invalidated at the end of the request !
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession(false);
if (session != null) {
- ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
- // Make long-running conversation temporary
- Manager.instance().endConversation(true);
- Manager.instance().endRequest(externalContext.getSessionMap());
- ServletLifecycle.endRequest(httpRequest);
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ if (facesContext!=null) {
+ ExternalContext externalContext = facesContext.getExternalContext();
+ // Make long-running conversation temporary
+ Manager.instance().endConversation(true);
+ Manager.instance().endRequest(externalContext.getSessionMap());
+ ServletLifecycle.endRequest(httpRequest);
+ }
}
}
@Override
public void onAfterSessionReinit(ServletRequest request) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
// reinit Seam so the afterResponseComplete does not crash
ServletLifecycle.beginRequest(httpRequest);
}
}
| true | true | public void onBeforeSessionReinit(ServletRequest request) {
// destroy session
// because of Seam Phase Listener we can't use Seam.invalidateSession()
// because the session would be invalidated at the end of the request !
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession(false);
if (session != null) {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
// Make long-running conversation temporary
Manager.instance().endConversation(true);
Manager.instance().endRequest(externalContext.getSessionMap());
ServletLifecycle.endRequest(httpRequest);
}
}
| public void onBeforeSessionReinit(ServletRequest request) {
// destroy session
// because of Seam Phase Listener we can't use Seam.invalidateSession()
// because the session would be invalidated at the end of the request !
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession(false);
if (session != null) {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext!=null) {
ExternalContext externalContext = facesContext.getExternalContext();
// Make long-running conversation temporary
Manager.instance().endConversation(true);
Manager.instance().endRequest(externalContext.getSessionMap());
ServletLifecycle.endRequest(httpRequest);
}
}
}
|
diff --git a/src/main/java/org/elasticsearch/common/util/concurrent/EsThreadPoolExecutor.java b/src/main/java/org/elasticsearch/common/util/concurrent/EsThreadPoolExecutor.java
index 86301ec8ea0..e1a27ea5186 100644
--- a/src/main/java/org/elasticsearch/common/util/concurrent/EsThreadPoolExecutor.java
+++ b/src/main/java/org/elasticsearch/common/util/concurrent/EsThreadPoolExecutor.java
@@ -1,78 +1,78 @@
/*
* Licensed to ElasticSearch and Shay Banon 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.common.util.concurrent;
import org.elasticsearch.ElasticSearchIllegalStateException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* An extension to thread pool executor, allowing (in the future) to add specific additional stats to it.
*/
public class EsThreadPoolExecutor extends ThreadPoolExecutor {
private volatile ShutdownListener listener;
private final Object monitor = new Object();
EsThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, new EsAbortPolicy());
}
EsThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, XRejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
public void shutdown(ShutdownListener listener) {
synchronized (monitor) {
if (this.listener != null) {
throw new ElasticSearchIllegalStateException("Shutdown was already called on this thread pool");
}
if (isTerminated()) {
listener.onTerminated();
} else {
this.listener = listener;
}
- shutdown();
}
+ shutdown();
}
@Override
protected synchronized void terminated() {
super.terminated();
synchronized (monitor) {
if (listener != null) {
try {
listener.onTerminated();
} finally {
listener = null;
}
}
}
}
public static interface ShutdownListener {
public void onTerminated();
}
}
| false | true | public void shutdown(ShutdownListener listener) {
synchronized (monitor) {
if (this.listener != null) {
throw new ElasticSearchIllegalStateException("Shutdown was already called on this thread pool");
}
if (isTerminated()) {
listener.onTerminated();
} else {
this.listener = listener;
}
shutdown();
}
}
| public void shutdown(ShutdownListener listener) {
synchronized (monitor) {
if (this.listener != null) {
throw new ElasticSearchIllegalStateException("Shutdown was already called on this thread pool");
}
if (isTerminated()) {
listener.onTerminated();
} else {
this.listener = listener;
}
}
shutdown();
}
|
diff --git a/continuum-core/src/main/java/org/apache/maven/continuum/buildqueue/BuildProjectTask.java b/continuum-core/src/main/java/org/apache/maven/continuum/buildqueue/BuildProjectTask.java
index 09c6899d4..364997a22 100644
--- a/continuum-core/src/main/java/org/apache/maven/continuum/buildqueue/BuildProjectTask.java
+++ b/continuum-core/src/main/java/org/apache/maven/continuum/buildqueue/BuildProjectTask.java
@@ -1,117 +1,117 @@
package org.apache.maven.continuum.buildqueue;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.codehaus.plexus.taskqueue.Task;
/**
* @author <a href="mailto:[email protected]">Trygve Laugstøl</a>
* @version $Id$
*/
public class BuildProjectTask
implements Task
{
private int projectId;
private int buildDefinitionId;
private long timestamp;
private int trigger;
private long maxExecutionTime;
private String projectName;
public BuildProjectTask( int projectId, int buildDefinitionId, int trigger, String projectName )
{
this.projectId = projectId;
this.buildDefinitionId = buildDefinitionId;
this.timestamp = System.currentTimeMillis();
this.trigger = trigger;
this.projectName = projectName;
}
public int getProjectId()
{
return projectId;
}
public int getBuildDefinitionId()
{
return buildDefinitionId;
}
public long getTimestamp()
{
return timestamp;
}
public int getTrigger()
{
return trigger;
}
public void setMaxExecutionTime( long maxExecutionTime )
{
this.maxExecutionTime = maxExecutionTime;
}
public long getMaxExecutionTime()
{
return maxExecutionTime;
}
public String getProjectName()
{
return projectName;
}
public boolean equals( Object obj )
{
if ( obj == null )
{
return false;
}
if ( obj == this )
{
- return false;
+ return true;
}
if ( !( obj instanceof BuildProjectTask ) )
{
return false;
}
BuildProjectTask buildProjectTask = (BuildProjectTask) obj;
return buildProjectTask.getBuildDefinitionId() == this.getBuildDefinitionId()
&& buildProjectTask.getProjectId() == this.getProjectId()
&& buildProjectTask.getTrigger() == this.getTrigger();
}
public int hashCode()
{
return this.getBuildDefinitionId() + this.getProjectId() + this.getTrigger();
}
}
| true | true | public boolean equals( Object obj )
{
if ( obj == null )
{
return false;
}
if ( obj == this )
{
return false;
}
if ( !( obj instanceof BuildProjectTask ) )
{
return false;
}
BuildProjectTask buildProjectTask = (BuildProjectTask) obj;
return buildProjectTask.getBuildDefinitionId() == this.getBuildDefinitionId()
&& buildProjectTask.getProjectId() == this.getProjectId()
&& buildProjectTask.getTrigger() == this.getTrigger();
}
| public boolean equals( Object obj )
{
if ( obj == null )
{
return false;
}
if ( obj == this )
{
return true;
}
if ( !( obj instanceof BuildProjectTask ) )
{
return false;
}
BuildProjectTask buildProjectTask = (BuildProjectTask) obj;
return buildProjectTask.getBuildDefinitionId() == this.getBuildDefinitionId()
&& buildProjectTask.getProjectId() == this.getProjectId()
&& buildProjectTask.getTrigger() == this.getTrigger();
}
|
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java
index 28530e6ac..eaa2fd297 100644
--- a/src/com/android/launcher3/LauncherModel.java
+++ b/src/com/android/launcher3/LauncherModel.java
@@ -1,3003 +1,3005 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3;
import android.app.SearchManager;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.*;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Parcelable;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import android.util.Pair;
import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = false;
static final String TAG = "Launcher.Model";
private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
private final boolean mAppsCanBeOnExternalStorage;
private final LauncherAppState mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private LoaderTask mLoaderTask;
private boolean mIsLoaderTaskRunning;
private volatile boolean mFlushingWorkerThread;
// Specific runnable types that are run on the main thread deferred handler, this allows us to
// clear all queued binding runnables when the Launcher activity is destroyed.
private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0;
private static final int MAIN_THREAD_BINDING_RUNNABLE = 1;
private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
static {
sWorkerThread.start();
}
private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
// We start off with everything not loaded. After that, we assume that
// our monitoring of the package manager provides all updates and we never
// need to do a requery. These are only ever touched from the loader thread.
private boolean mWorkspaceLoaded;
private boolean mAllAppsLoaded;
// When we are loading pages synchronously, we can't just post the binding of items on the side
// pages as this delays the rotation process. Instead, we wait for a callback from the first
// draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start
// a normal load, we also clear this set of Runnables.
static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>();
private WeakReference<Callbacks> mCallbacks;
// < only access in worker thread >
private AllAppsList mBgAllAppsList;
// The lock that must be acquired before referencing any static bg data structures. Unlike
// other locks, this one can generally be held long-term because we never expect any of these
// static data structures to be referenced outside of the worker thread except on the first
// load after configuration change.
static final Object sBgLock = new Object();
// sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
// LauncherModel to their ids
static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>();
// sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts
// created by LauncherModel that are directly on the home screen (however, no widgets or
// shortcuts within folders).
static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>();
// sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
// sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>();
// sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database
static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>();
// sBgWorkspaceScreens is the ordered set of workspace screens.
static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>();
// </ only access in worker thread >
private IconCache mIconCache;
private Bitmap mDefaultIcon;
private static int mCellCountX;
private static int mCellCountY;
protected int mPreviousConfigMcc;
public interface Callbacks {
public boolean setLoadOnResume();
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end,
boolean forceAnimateIcons);
public void bindScreens(ArrayList<Long> orderedScreenIds);
public void bindAddScreens(ArrayList<Long> orderedScreenIds);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems(boolean upgradePath);
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
public void bindComponentsRemoved(ArrayList<String> packageNames,
ArrayList<ApplicationInfo> appInfos,
boolean matchPackageNamesOnly);
public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts);
public void bindSearchablesChanged();
public void onPageBoundSynchronously(int page);
}
public interface ItemInfoFilter {
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn);
}
LauncherModel(LauncherAppState app, IconCache iconCache) {
final Context context = app.getContext();
mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
mApp = app;
mBgAllAppsList = new AllAppsList(iconCache);
mIconCache = iconCache;
mDefaultIcon = Utilities.createIconBitmap(
mIconCache.getFullResDefaultActivityIcon(), context);
final Resources res = context.getResources();
Configuration config = res.getConfiguration();
mPreviousConfigMcc = config.mcc;
}
/** Runs the specified runnable immediately if called from the main thread, otherwise it is
* posted on the main thread handler. */
private void runOnMainThread(Runnable r) {
runOnMainThread(r, 0);
}
private void runOnMainThread(Runnable r, int type) {
if (sWorkerThread.getThreadId() == Process.myTid()) {
// If we are on the worker thread, post onto the main handler
mHandler.post(r);
} else {
r.run();
}
}
/** Runs the specified runnable immediately if called from the worker thread, otherwise it is
* posted on the worker thread handler. */
private static void runOnWorkerThread(Runnable r) {
if (sWorkerThread.getThreadId() == Process.myTid()) {
r.run();
} else {
// If we are not on the worker thread, then post to the worker handler
sWorker.post(r);
}
}
static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy,
long screen) {
final int xCount = LauncherModel.getCellCountX();
final int yCount = LauncherModel.getCellCountY();
boolean[][] occupied = new boolean[xCount][yCount];
int cellX, cellY, spanX, spanY;
for (int i = 0; i < items.size(); ++i) {
final ItemInfo item = items.get(i);
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (item.screenId == screen) {
cellX = item.cellX;
cellY = item.cellY;
spanX = item.spanX;
spanY = item.spanY;
for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) {
for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) {
occupied[x][y] = true;
}
}
}
}
}
return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied);
}
static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name,
Intent launchIntent,
int firstScreenIndex) {
// Lock on the app so that we don't try and get the items while apps are being added
LauncherAppState app = LauncherAppState.getInstance();
LauncherModel model = app.getModel();
boolean found = false;
synchronized (app) {
if (sWorkerThread.getThreadId() != Process.myTid()) {
// Flush the LauncherModel worker thread, so that if we just did another
// processInstallShortcut, we give it time for its shortcut to get added to the
// database (getItemsInLocalCoordinates reads the database)
model.flushWorkerThread();
}
final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context);
// Try adding to the workspace screens incrementally, starting at the default or center
// screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1))
firstScreenIndex = Math.min(firstScreenIndex, sBgWorkspaceScreens.size());
int count = sBgWorkspaceScreens.size();
for (int screen = firstScreenIndex; screen < count && !found; screen++) {
int[] tmpCoordinates = new int[2];
if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates,
sBgWorkspaceScreens.get(screen))) {
// Update the Launcher db
return new Pair<Long, int[]>(sBgWorkspaceScreens.get(screen), tmpCoordinates);
}
}
}
// XXX: Create a new page and add it to the first spot
return null;
}
public void addAndBindAddedApps(final Context context, final ArrayList<ApplicationInfo> added,
final Callbacks callbacks) {
// Process the newly added applications and add them to the database first
Runnable r = new Runnable() {
public void run() {
final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>();
final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>();
synchronized(sBgLock) {
Iterator<ApplicationInfo> iter = added.iterator();
while (iter.hasNext()) {
ApplicationInfo a = iter.next();
final String name = a.title.toString();
final Intent launchIntent = a.intent;
// Short-circuit this logic if the icon exists somewhere on the workspace
if (LauncherModel.shortcutExists(context, name, launchIntent)) {
continue;
}
// Add this icon to the db, creating a new page if necessary
int startSearchPageIndex = 1;
Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context,
name, launchIntent, startSearchPageIndex);
if (coords == null) {
// If we can't find a valid position, then just add a new screen.
// This takes time so we need to re-queue the add until the new
// page is added.
LauncherAppState appState = LauncherAppState.getInstance();
LauncherProvider lp = appState.getLauncherProvider();
long screenId = lp.generateNewScreenId();
// Update the model
sBgWorkspaceScreens.add(screenId);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
// Save the screen id for binding in the workspace
addedWorkspaceScreensFinal.add(screenId);
// Find the coordinate again
coords = LauncherModel.findNextAvailableIconSpace(context,
a.title.toString(), a.intent, startSearchPageIndex);
}
if (coords == null) {
throw new RuntimeException("Coordinates should not be null");
}
final ShortcutInfo shortcutInfo = a.makeShortcut();
// Add the shortcut to the db
addItemToDatabase(context, shortcutInfo,
LauncherSettings.Favorites.CONTAINER_DESKTOP,
coords.first, coords.second[0], coords.second[1], false);
// Save the ShortcutInfo for binding in the workspace
addedShortcutsFinal.add(shortcutInfo);
}
}
runOnMainThread(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAddScreens(addedWorkspaceScreensFinal);
callbacks.bindItems(addedShortcutsFinal, 0,
addedShortcutsFinal.size(), true);
}
}
});
}
};
runOnWorkerThread(r);
}
public Bitmap getFallbackIcon() {
return Bitmap.createBitmap(mDefaultIcon);
}
public void unbindItemInfosAndClearQueuedBindRunnables() {
if (sWorkerThread.getThreadId() == Process.myTid()) {
throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " +
"main thread");
}
// Clear any deferred bind runnables
mDeferredBindRunnables.clear();
// Remove any queued bind runnables
mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE);
// Unbind all the workspace items
unbindWorkspaceItemsOnMainThread();
}
/** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */
void unbindWorkspaceItemsOnMainThread() {
// Ensure that we don't use the same workspace items data structure on the main thread
// by making a copy of workspace items first.
final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>();
final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>();
synchronized (sBgLock) {
tmpWorkspaceItems.addAll(sBgWorkspaceItems);
tmpAppWidgets.addAll(sBgAppWidgets);
}
Runnable r = new Runnable() {
@Override
public void run() {
for (ItemInfo item : tmpWorkspaceItems) {
item.unbind();
}
for (ItemInfo item : tmpAppWidgets) {
item.unbind();
}
}
};
runOnMainThread(r);
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
long screenId, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screenId, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screenId, cellX, cellY);
}
}
static void checkItemInfoLocked(
final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
ItemInfo modelItem = sBgItemsIdMap.get(itemId);
if (modelItem != null && item != modelItem) {
// check all the data is consistent
if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) {
ShortcutInfo modelShortcut = (ShortcutInfo) modelItem;
ShortcutInfo shortcut = (ShortcutInfo) item;
if (modelShortcut.title.toString().equals(shortcut.title.toString()) &&
modelShortcut.intent.filterEquals(shortcut.intent) &&
modelShortcut.id == shortcut.id &&
modelShortcut.itemType == shortcut.itemType &&
modelShortcut.container == shortcut.container &&
modelShortcut.screenId == shortcut.screenId &&
modelShortcut.cellX == shortcut.cellX &&
modelShortcut.cellY == shortcut.cellY &&
modelShortcut.spanX == shortcut.spanX &&
modelShortcut.spanY == shortcut.spanY &&
((modelShortcut.dropPos == null && shortcut.dropPos == null) ||
(modelShortcut.dropPos != null &&
shortcut.dropPos != null &&
modelShortcut.dropPos[0] == shortcut.dropPos[0] &&
modelShortcut.dropPos[1] == shortcut.dropPos[1]))) {
// For all intents and purposes, this is the same object
return;
}
}
// the modelItem needs to match up perfectly with item if our model is
// to be consistent with the database-- for now, just require
// modelItem == item or the equality check above
String msg = "item: " + ((item != null) ? item.toString() : "null") +
"modelItem: " +
((modelItem != null) ? modelItem.toString() : "null") +
"Error: ItemInfo passed to checkItemInfo doesn't match original";
RuntimeException e = new RuntimeException(msg);
if (stackTrace != null) {
e.setStackTrace(stackTrace);
}
// TODO: something breaks this in the upgrade path
//throw e;
}
}
static void checkItemInfo(final ItemInfo item) {
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
final long itemId = item.id;
Runnable r = new Runnable() {
public void run() {
synchronized (sBgLock) {
checkItemInfoLocked(itemId, item, stackTrace);
}
}
};
runOnWorkerThread(r);
}
static void updateItemInDatabaseHelper(Context context, final ContentValues values,
final ItemInfo item, final String callingFunction) {
final long itemId = item.id;
final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
final ContentResolver cr = context.getContentResolver();
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Runnable r = new Runnable() {
public void run() {
cr.update(uri, values, null, null);
updateItemArrays(item, itemId, stackTrace);
}
};
runOnWorkerThread(r);
}
static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList,
final ArrayList<ItemInfo> items, final String callingFunction) {
final ContentResolver cr = context.getContentResolver();
final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
Runnable r = new Runnable() {
public void run() {
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
int count = items.size();
for (int i = 0; i < count; i++) {
ItemInfo item = items.get(i);
final long itemId = item.id;
final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false);
ContentValues values = valuesList.get(i);
ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build());
updateItemArrays(item, itemId, stackTrace);
}
try {
cr.applyBatch(LauncherProvider.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
};
runOnWorkerThread(r);
}
static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) {
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
checkItemInfoLocked(itemId, item, stackTrace);
if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
// Item is in a folder, make sure this folder exists
if (!sBgFolders.containsKey(item.container)) {
// An items container is being set to a that of an item which is not in
// the list of Folders.
String msg = "item: " + item + " container being set to: " +
item.container + ", not in the list of folders";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
// Items are added/removed from the corresponding FolderInfo elsewhere, such
// as in Workspace.onDrop. Here, we just add/remove them from the list of items
// that are on the desktop, as appropriate
ItemInfo modelItem = sBgItemsIdMap.get(itemId);
if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
switch (modelItem.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
if (!sBgWorkspaceItems.contains(modelItem)) {
sBgWorkspaceItems.add(modelItem);
}
break;
default:
break;
}
} else {
sBgWorkspaceItems.remove(modelItem);
}
}
}
public void flushWorkerThread() {
mFlushingWorkerThread = true;
Runnable waiter = new Runnable() {
public void run() {
synchronized (this) {
notifyAll();
mFlushingWorkerThread = false;
}
}
};
synchronized(waiter) {
runOnWorkerThread(waiter);
if (mLoaderTask != null) {
synchronized(mLoaderTask) {
mLoaderTask.notify();
}
}
boolean success = false;
while (!success) {
try {
waiter.wait();
success = true;
} catch (InterruptedException e) {
}
}
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY) {
String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
" (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Launcher.sDumpLogs.add(transaction);
Log.d(TAG, transaction);
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase");
}
/**
* Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
* cellX, cellY have already been updated on the ItemInfos.
*/
static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items,
final long container, final int screen) {
ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>();
int count = items.size();
for (int i = 0; i < count; i++) {
ItemInfo item = items.get(i);
String transaction = "DbDebug Modify item (" + item.title + ") in db, id: "
+ item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX
+ ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", "
+ item.cellX + ", " + item.cellY + ")";
Launcher.sDumpLogs.add(transaction);
item.container = container;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX,
item.cellY);
} else {
item.screenId = screen;
}
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
contentValues.add(values);
}
updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase");
}
/**
* Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
*/
static void modifyItemInDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) {
String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id +
" (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY +
") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")";
Launcher.sDumpLogs.add(transaction);
Log.d(TAG, transaction);
item.cellX = cellX;
item.cellY = cellY;
item.spanX = spanX;
item.spanY = spanY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SPANX, item.spanX);
values.put(LauncherSettings.Favorites.SPANY, item.spanY);
values.put(LauncherSettings.Favorites.SCREEN, item.screenId);
updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase");
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, final ItemInfo item) {
final ContentValues values = new ContentValues();
item.onAddToDatabase(values);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase");
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screenId = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
LauncherAppState app = LauncherAppState.getInstance();
item.id = app.getLauncherProvider().generateNewItemId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
+ item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
+ cellY + ")";
Launcher.sDumpLogs.add(transaction);
Log.d(TAG, transaction);
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
checkItemInfoLocked(item.id, item, null);
sBgItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sBgWorkspaceItems.add(item);
} else {
if (!sBgFolders.containsKey(item.container)) {
// Adding an item to a folder that doesn't exist.
String msg = "adding item: " + item + " to a folder that " +
" doesn't exist";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
}
};
runOnWorkerThread(r);
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
+ item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
", " + item.cellY + ")";
Launcher.sDumpLogs.add(transaction);
Log.d(TAG, transaction);
cr.delete(uriToDelete, null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.remove(item.id);
for (ItemInfo info: sBgItemsIdMap.values()) {
if (info.container == item.id) {
// We are deleting a folder which still contains items that
// think they are contained by that folder.
String msg = "deleting a folder (" + item + ") which still " +
"contains items (" + info + ")";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sBgItemsIdMap.remove(item.id);
sBgDbIconCache.remove(item);
}
}
};
runOnWorkerThread(r);
}
/**
* Update the order of the workspace screens in the database. The array list contains
* a list of screen ids in the order that they should appear.
*/
void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
final ContentResolver cr = context.getContentResolver();
final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
// Remove any negative screen ids -- these aren't persisted
Iterator<Long> iter = screensCopy.iterator();
while (iter.hasNext()) {
long id = iter.next();
if (id < 0) {
iter.remove();
}
}
Runnable r = new Runnable() {
@Override
public void run() {
// Clear the table
cr.delete(uri, null, null);
int count = screens.size();
ContentValues[] values = new ContentValues[count];
for (int i = 0; i < count; i++) {
ContentValues v = new ContentValues();
long screenId = screens.get(i);
v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
values[i] = v;
}
cr.bulkInsert(uri, values);
sBgWorkspaceScreens.clear();
sBgWorkspaceScreens.addAll(screensCopy);
}
};
runOnWorkerThread(r);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
sBgItemsIdMap.remove(info.id);
sBgFolders.remove(info.id);
sBgDbIconCache.remove(info);
sBgWorkspaceItems.remove(info);
}
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
for (ItemInfo childInfo : info.contents) {
sBgItemsIdMap.remove(childInfo.id);
sBgDbIconCache.remove(childInfo);
}
}
}
};
runOnWorkerThread(r);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps/workspace.
forceReload();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// Check if configuration change was an mcc/mnc change which would affect app resources
// and we would need to clear out the labels in all apps/workspace. Same handling as
// above for ACTION_LOCALE_CHANGED
Configuration currentConfig = context.getResources().getConfiguration();
if (mPreviousConfigMcc != currentConfig.mcc) {
Log.d(TAG, "Reload apps on config change. curr_mcc:"
+ currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
forceReload();
}
// Update previousConfig
mPreviousConfigMcc = currentConfig.mcc;
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
private void forceReload() {
resetLoadedState(true, true);
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload.
startLoaderFromBackground();
}
public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mAllAppsLoaded or
// mWorkspaceLoaded to true later
stopLoaderLocked();
if (resetAllAppsLoaded) mAllAppsLoaded = false;
if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(false, -1);
}
}
// If there is already a loader task running, tell it to stop.
// returns true if isLaunching() was true on the old task
private boolean stopLoaderLocked() {
boolean isLaunching = false;
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
isLaunching = true;
}
oldTask.stopLocked();
}
return isLaunching;
}
public void startLoader(boolean isLaunching, int synchronousBindPage) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Clear any deferred bind-runnables from the synchronized load process
// We must do this before any loading/binding is scheduled below.
mDeferredBindRunnables.clear();
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
// also, don't downgrade isLaunching if we're already running
isLaunching = isLaunching || stopLoaderLocked();
mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
mLoaderTask.runBindSynchronousPage(synchronousBindPage);
} else {
sWorkerThread.setPriority(Thread.NORM_PRIORITY);
sWorker.post(mLoaderTask);
}
}
}
}
void bindRemainingSynchronousPages() {
// Post the remaining side pages to be loaded
if (!mDeferredBindRunnables.isEmpty()) {
for (final Runnable r : mDeferredBindRunnables) {
mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
}
mDeferredBindRunnables.clear();
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
boolean isLoadingWorkspace() {
synchronized (mLock) {
if (mLoaderTask != null) {
return mLoaderTask.isLoadingWorkspace();
}
}
return false;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private boolean mIsLaunching;
private boolean mIsLoadingAndBindingWorkspace;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private boolean mIsUpgradePath;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
boolean isLoadingWorkspace() {
return mIsLoadingAndBindingWorkspace;
}
private void loadAndBindWorkspace() {
mIsLoadingAndBindingWorkspace = true;
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
}
// Bind the workspace
bindWorkspace(-1);
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
try {
// Just in case mFlushingWorkerThread changes but we aren't woken up,
// wait no longer than 1sec at a time
this.wait(1000);
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
void runBindSynchronousPage(int synchronousBindPage) {
if (synchronousBindPage < 0) {
// Ensure that we have a valid page index to load synchronously
throw new RuntimeException("Should not call runBindSynchronousPage() without " +
"valid page index");
}
if (!mAllAppsLoaded || !mWorkspaceLoaded) {
// Ensure that we don't try and bind a specified page when the pages have not been
// loaded already (we should load everything asynchronously in that case)
throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
}
synchronized (mLock) {
if (mIsLoaderTaskRunning) {
// Ensure that we are never running the background loading at this point since
// we also touch the background collections
throw new RuntimeException("Error! Background loading is already running");
}
}
// XXX: Throw an exception if we are already loading (since we touch the worker thread
// data structures, we can't allow any other thread to touch that data, but because
// this call is synchronous, we can get away with not locking).
// The LauncherModel is static in the LauncherAppState and mHandler may have queued
// operations from the previous activity. We need to ensure that all queued operations
// are executed before any synchronous binding work is done.
mHandler.flush();
// Divide the set of loaded items into those that we are binding synchronously, and
// everything else that is to be bound normally (asynchronously).
bindWorkspace(synchronousBindPage);
// XXX: For now, continue posting the binding of AllApps as there are other issues that
// arise from that.
onlyBindAllApps();
}
public void run() {
synchronized (mLock) {
mIsLoaderTaskRunning = true;
}
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
// Restore the default thread priority after we are done loading items
synchronized (mLock) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
synchronized (sBgLock) {
for (Object key : sBgDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
}
sBgDbIconCache.clear();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
mIsLoaderTaskRunning = false;
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
long containerIndex = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0] != null) {
Log.e(TAG, "Error loading shortcut into hotseat " + item
+ " into position (" + item.screenId + ":" + item.cellX + ","
+ item.cellY + ") occupied by "
+ occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0]);
return false;
}
} else {
ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
items[(int) item.screenId][0] = item;
occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
return true;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
if (!occupied.containsKey(item.screenId)) {
ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
occupied.put(item.screenId, items);
}
ItemInfo[][] screens = occupied.get(item.screenId);
// Check if any workspace icons overlap with each other
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (screens[x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screenId + ":"
+ x + "," + y
+ ") occupied by "
+ screens[x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
screens[x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
// Make sure the default workspace is loaded, if needed
boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb();
Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI;
mIsUpgradePath = loadOldDb;
synchronized (sBgLock) {
sBgWorkspaceItems.clear();
sBgAppWidgets.clear();
sBgFolders.clear();
sBgItemsIdMap.clear();
sBgDbIconCache.clear();
sBgWorkspaceScreens.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(contentUri, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that
// here
if (intent.getAction() != null &&
intent.getCategories() != null &&
intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screenId = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sBgFolders, container);
folderInfo.add(info);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
info.screenId = permuteScreens(info.screenId);
}
sBgItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(folderInfo);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
folderInfo.screenId = permuteScreens(folderInfo.screenId);
}
sBgItemsIdMap.put(folderInfo.id, folderInfo);
sBgFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.sDumpLogs.add(log);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screenId = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container != " +
"CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
appWidgetInfo.screenId =
permuteScreens(appWidgetInfo.screenId);
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sBgAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
- c.close();
+ if (c != null) {
+ c.close();
+ }
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (loadOldDb) {
long maxScreenId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
!sBgWorkspaceScreens.contains(screenId)) {
sBgWorkspaceScreens.add(screenId);
if (screenId > maxScreenId) {
maxScreenId = screenId;
}
}
}
Collections.sort(sBgWorkspaceScreens);
mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
} else {
Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
try {
final int idIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens._ID);
final int rankIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens.SCREEN_RANK);
while (sc.moveToNext()) {
try {
long screenId = sc.getLong(idIndex);
int rank = sc.getInt(rankIndex);
orderedScreens.put(rank, screenId);
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
sc.close();
}
Iterator<Integer> iter = orderedScreens.keySet().iterator();
while (iter.hasNext()) {
sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
}
// Remove any empty screens
ArrayList<Long> unusedScreens = new ArrayList<Long>();
unusedScreens.addAll(sBgWorkspaceScreens);
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
unusedScreens.contains(screenId)) {
unusedScreens.remove(screenId);
}
}
// If there are any empty screens remove them, and update.
if (unusedScreens.size() != 0) {
sBgWorkspaceScreens.removeAll(unusedScreens);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
int nScreens = occupied.size();
for (int y = 0; y < mCellCountY; y++) {
String line = "";
Iterator<Long> iter = occupied.keySet().iterator();
while (iter.hasNext()) {
long screenId = iter.next();
if (screenId > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
}
// We rearrange the screens from the old launcher
// 12345 -> 34512
private long permuteScreens(long screen) {
if (screen >= 2) {
return screen - 2;
} else {
return screen + 3;
}
}
/** Filters the set of items who are directly or indirectly (via another container) on the
* specified screen. */
private void filterCurrentWorkspaceItems(int currentScreen,
ArrayList<ItemInfo> allWorkspaceItems,
ArrayList<ItemInfo> currentScreenItems,
ArrayList<ItemInfo> otherScreenItems) {
// Purge any null ItemInfos
Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
while (iter.hasNext()) {
ItemInfo i = iter.next();
if (i == null) {
iter.remove();
}
}
// If we aren't filtering on a screen, then the set of items to load is the full set of
// items given.
if (currentScreen < 0) {
currentScreenItems.addAll(allWorkspaceItems);
}
// Order the set of items by their containers first, this allows use to walk through the
// list sequentially, build up a list of containers that are in the specified screen,
// as well as all items in those containers.
Set<Long> itemsOnScreen = new HashSet<Long>();
Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return (int) (lhs.container - rhs.container);
}
});
for (ItemInfo info : allWorkspaceItems) {
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (info.screenId == currentScreen) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
} else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
if (itemsOnScreen.contains(info.container)) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
}
}
}
/** Filters the set of widgets which are on the specified screen. */
private void filterCurrentAppWidgets(int currentScreen,
ArrayList<LauncherAppWidgetInfo> appWidgets,
ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenWidgets.addAll(appWidgets);
}
for (LauncherAppWidgetInfo widget : appWidgets) {
if (widget == null) continue;
if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
widget.screenId == currentScreen) {
currentScreenWidgets.add(widget);
} else {
otherScreenWidgets.add(widget);
}
}
}
/** Filters the set of folders which are on the specified screen. */
private void filterCurrentFolders(int currentScreen,
HashMap<Long, ItemInfo> itemsIdMap,
HashMap<Long, FolderInfo> folders,
HashMap<Long, FolderInfo> currentScreenFolders,
HashMap<Long, FolderInfo> otherScreenFolders) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenFolders.putAll(folders);
}
for (long id : folders.keySet()) {
ItemInfo info = itemsIdMap.get(id);
FolderInfo folder = folders.get(id);
if (info == null || folder == null) continue;
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
info.screenId == currentScreen) {
currentScreenFolders.put(id, folder);
} else {
otherScreenFolders.put(id, folder);
}
}
}
/** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
* right) */
private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
// XXX: review this
Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
int cellCountX = LauncherModel.getCellCountX();
int cellCountY = LauncherModel.getCellCountY();
int screenOffset = cellCountX * cellCountY;
int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
lhs.cellY * cellCountX + lhs.cellX);
long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
rhs.cellY * cellCountX + rhs.cellX);
return (int) (lr - rr);
}
});
}
private void bindWorkspaceScreens(final Callbacks oldCallbacks,
final ArrayList<Long> orderedScreens) {
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindScreens(orderedScreens);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
private void bindWorkspaceItems(final Callbacks oldCallbacks,
final ArrayList<ItemInfo> workspaceItems,
final ArrayList<LauncherAppWidgetInfo> appWidgets,
final HashMap<Long, FolderInfo> folders,
ArrayList<Runnable> deferredBindRunnables) {
final boolean postOnMainThread = (deferredBindRunnables != null);
// Bind the workspace items
int N = workspaceItems.size();
for (int i = 0; i < N; i += ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(workspaceItems, start, start+chunkSize,
false);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the folders
if (!folders.isEmpty()) {
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(folders);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the widgets, one at a time
N = appWidgets.size();
for (int i = 0; i < N; i++) {
final LauncherAppWidgetInfo widget = appWidgets.get(i);
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
}
/**
* Binds all loaded data to actual views on the main thread.
*/
private void bindWorkspace(int synchronizeBindPage) {
final long t = SystemClock.uptimeMillis();
Runnable r;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
oldCallbacks.getCurrentWorkspaceScreen();
// Load all the items that are on the current page first (and in the process, unbind
// all the existing workspace items before we call startBinding() below.
unbindWorkspaceItemsOnMainThread();
ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> appWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
synchronized (sBgLock) {
workspaceItems.addAll(sBgWorkspaceItems);
appWidgets.addAll(sBgAppWidgets);
folders.putAll(sBgFolders);
itemsIdMap.putAll(sBgItemsIdMap);
orderedScreenIds.addAll(sBgWorkspaceScreens);
}
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
// Separate the items that are on the current screen, and all the other remaining items
filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
otherWorkspaceItems);
filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
otherAppWidgets);
filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
otherFolders);
sortWorkspaceItemsSpatially(currentWorkspaceItems);
sortWorkspaceItemsSpatially(otherWorkspaceItems);
// Tell the workspace that we're about to start binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
// Load items on the current page
bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
currentFolders, null);
if (isLoadingSynchronously) {
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.onPageBoundSynchronously(currentScreen);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
// Load all the remaining pages (if we are loading synchronously, we want to defer this
// work until after the first render)
mDeferredBindRunnables.clear();
bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
(isLoadingSynchronously ? mDeferredBindRunnables : null));
// Tell the workspace that we're done binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems(mIsUpgradePath);
}
// If we're profiling, ensure this is the last thing in the queue.
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
mIsLoadingAndBindingWorkspace = false;
}
};
if (isLoadingSynchronously) {
mDeferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllApps();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mAllAppsLoaded = true;
}
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
@SuppressWarnings("unchecked")
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Runnable r = new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
};
boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
if (isRunningOnMainThread) {
r.run();
} else {
mHandler.post(r);
}
}
private void loadAllApps() {
final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
return;
}
final PackageManager packageManager = mContext.getPackageManager();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// Clear the list of apps
mBgAllAppsList.clear();
// Query for the set of apps
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
}
// Fail if we don't have any apps
if (apps == null || apps.isEmpty()) {
return;
}
// Sort the applications by name
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
// Create the ApplicationInfos
final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
for (int i = 0; i < apps.size(); i++) {
// This builds the icon bitmaps.
mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
}
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
// Post callback on main thread
mHandler.post(new Runnable() {
public void run() {
final long bindTime = SystemClock.uptimeMillis();
if (callbacks != null) {
callbacks.bindAllApplications(added);
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - bindTime) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "Icons processed in "
+ (SystemClock.uptimeMillis() - loadTime) + "ms");
}
}
public void dumpState() {
synchronized (sBgLock) {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
}
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp.getContext();
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mBgAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mBgAllAppsList.updatePackage(context, packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mBgAllAppsList.removePackage(packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> modified = null;
final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
if (mBgAllAppsList.added.size() > 0) {
added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
mBgAllAppsList.added.clear();
}
if (mBgAllAppsList.modified.size() > 0) {
modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
mBgAllAppsList.modified.clear();
}
if (mBgAllAppsList.removed.size() > 0) {
removedApps.addAll(mBgAllAppsList.removed);
mBgAllAppsList.removed.clear();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
// Ensure that we add all the workspace applications to the db
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, added, cb);
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
// Update the launcher db to reflect the changes
for (ApplicationInfo a : modifiedFinal) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
if (isShortcutInfoUpdateable(i)) {
ShortcutInfo info = (ShortcutInfo) i;
info.title = a.title.toString();
updateItemInDatabase(context, info);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
// If a package has been removed, or an app has been removed as a result of
// an update (for example), make the removed callback.
if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
final boolean packageRemoved = (mOp == OP_REMOVE);
final ArrayList<String> removedPackageNames =
new ArrayList<String>(Arrays.asList(packages));
// Update the launcher db to reflect the removal of apps
if (packageRemoved) {
for (String pn : removedPackageNames) {
ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
} else {
for (ApplicationInfo a : removedApps) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindComponentsRemoved(removedPackageNames,
removedApps, packageRemoved);
}
}
});
}
final ArrayList<Object> widgetsAndShortcuts =
getSortedWidgetsAndShortcuts(context);
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated(widgetsAndShortcuts);
}
}
});
}
}
// Returns a list of ResolveInfos/AppWindowInfos in sorted order
public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
PackageManager packageManager = context.getPackageManager();
final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Collections.sort(widgetsAndShortcuts,
new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
return widgetsAndShortcuts;
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
try {
PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
if (!pi.applicationInfo.enabled) {
// If we return null here, the corresponding item will be removed from the launcher
// db and will not appear in the workspace.
return null;
}
info.initFlagsAndFirstInstallTime(pi);
} catch (NameNotFoundException e) {
Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
// Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
// if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
// via resolveActivity().
ResolveInfo resolveInfo = null;
ComponentName oldComponent = intent.getComponent();
Intent newIntent = new Intent(intent.getAction(), null);
newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
newIntent.setPackage(oldComponent.getPackageName());
List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
for (ResolveInfo i : infos) {
ComponentName cn = new ComponentName(i.activityInfo.packageName,
i.activityInfo.name);
if (cn.equals(oldComponent)) {
resolveInfo = i;
}
}
if (resolveInfo == null) {
resolveInfo = manager.resolveActivity(intent, 0);
}
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
ItemInfoFilter f) {
HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
for (ItemInfo i : infos) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
ComponentName cn = info.intent.getComponent();
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
} else if (i instanceof FolderInfo) {
FolderInfo info = (FolderInfo) i;
for (ShortcutInfo s : info.contents) {
ComponentName cn = s.intent.getComponent();
if (cn != null && f.filterItem(info, s, cn)) {
filtered.add(s);
}
}
} else if (i instanceof LauncherAppWidgetInfo) {
LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
ComponentName cn = info.providerName;
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
}
}
return new ArrayList<ItemInfo>(filtered);
}
private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.getPackageName().equals(pn);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.equals(cname);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
public static boolean isShortcutInfoUpdateable(ItemInfo i) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
Intent intent = info.intent;
ComponentName name = intent.getComponent();
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
return true;
}
}
return false;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
if (info == null) {
return null;
}
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (intent == null) {
// If the intent is null, we can't construct a valid ShortcutInfo, so we return null
Log.e(TAG, "Can't construct ShorcutInfo with null intent");
return null;
}
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
public static final Comparator<ApplicationInfo> getAppNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = collator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
}
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return collator.compare(a.label.toString(), b.label.toString());
}
};
}
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
mCollator = Collator.getInstance();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
mCollator = Collator.getInstance();
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
mCollator = Collator.getInstance();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| true | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screenId = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
LauncherAppState app = LauncherAppState.getInstance();
item.id = app.getLauncherProvider().generateNewItemId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
+ item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
+ cellY + ")";
Launcher.sDumpLogs.add(transaction);
Log.d(TAG, transaction);
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
checkItemInfoLocked(item.id, item, null);
sBgItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sBgWorkspaceItems.add(item);
} else {
if (!sBgFolders.containsKey(item.container)) {
// Adding an item to a folder that doesn't exist.
String msg = "adding item: " + item + " to a folder that " +
" doesn't exist";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
}
};
runOnWorkerThread(r);
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
+ item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
", " + item.cellY + ")";
Launcher.sDumpLogs.add(transaction);
Log.d(TAG, transaction);
cr.delete(uriToDelete, null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.remove(item.id);
for (ItemInfo info: sBgItemsIdMap.values()) {
if (info.container == item.id) {
// We are deleting a folder which still contains items that
// think they are contained by that folder.
String msg = "deleting a folder (" + item + ") which still " +
"contains items (" + info + ")";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sBgItemsIdMap.remove(item.id);
sBgDbIconCache.remove(item);
}
}
};
runOnWorkerThread(r);
}
/**
* Update the order of the workspace screens in the database. The array list contains
* a list of screen ids in the order that they should appear.
*/
void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
final ContentResolver cr = context.getContentResolver();
final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
// Remove any negative screen ids -- these aren't persisted
Iterator<Long> iter = screensCopy.iterator();
while (iter.hasNext()) {
long id = iter.next();
if (id < 0) {
iter.remove();
}
}
Runnable r = new Runnable() {
@Override
public void run() {
// Clear the table
cr.delete(uri, null, null);
int count = screens.size();
ContentValues[] values = new ContentValues[count];
for (int i = 0; i < count; i++) {
ContentValues v = new ContentValues();
long screenId = screens.get(i);
v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
values[i] = v;
}
cr.bulkInsert(uri, values);
sBgWorkspaceScreens.clear();
sBgWorkspaceScreens.addAll(screensCopy);
}
};
runOnWorkerThread(r);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
sBgItemsIdMap.remove(info.id);
sBgFolders.remove(info.id);
sBgDbIconCache.remove(info);
sBgWorkspaceItems.remove(info);
}
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
for (ItemInfo childInfo : info.contents) {
sBgItemsIdMap.remove(childInfo.id);
sBgDbIconCache.remove(childInfo);
}
}
}
};
runOnWorkerThread(r);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps/workspace.
forceReload();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// Check if configuration change was an mcc/mnc change which would affect app resources
// and we would need to clear out the labels in all apps/workspace. Same handling as
// above for ACTION_LOCALE_CHANGED
Configuration currentConfig = context.getResources().getConfiguration();
if (mPreviousConfigMcc != currentConfig.mcc) {
Log.d(TAG, "Reload apps on config change. curr_mcc:"
+ currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
forceReload();
}
// Update previousConfig
mPreviousConfigMcc = currentConfig.mcc;
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
private void forceReload() {
resetLoadedState(true, true);
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload.
startLoaderFromBackground();
}
public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mAllAppsLoaded or
// mWorkspaceLoaded to true later
stopLoaderLocked();
if (resetAllAppsLoaded) mAllAppsLoaded = false;
if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(false, -1);
}
}
// If there is already a loader task running, tell it to stop.
// returns true if isLaunching() was true on the old task
private boolean stopLoaderLocked() {
boolean isLaunching = false;
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
isLaunching = true;
}
oldTask.stopLocked();
}
return isLaunching;
}
public void startLoader(boolean isLaunching, int synchronousBindPage) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Clear any deferred bind-runnables from the synchronized load process
// We must do this before any loading/binding is scheduled below.
mDeferredBindRunnables.clear();
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
// also, don't downgrade isLaunching if we're already running
isLaunching = isLaunching || stopLoaderLocked();
mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
mLoaderTask.runBindSynchronousPage(synchronousBindPage);
} else {
sWorkerThread.setPriority(Thread.NORM_PRIORITY);
sWorker.post(mLoaderTask);
}
}
}
}
void bindRemainingSynchronousPages() {
// Post the remaining side pages to be loaded
if (!mDeferredBindRunnables.isEmpty()) {
for (final Runnable r : mDeferredBindRunnables) {
mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
}
mDeferredBindRunnables.clear();
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
boolean isLoadingWorkspace() {
synchronized (mLock) {
if (mLoaderTask != null) {
return mLoaderTask.isLoadingWorkspace();
}
}
return false;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private boolean mIsLaunching;
private boolean mIsLoadingAndBindingWorkspace;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private boolean mIsUpgradePath;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
boolean isLoadingWorkspace() {
return mIsLoadingAndBindingWorkspace;
}
private void loadAndBindWorkspace() {
mIsLoadingAndBindingWorkspace = true;
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
}
// Bind the workspace
bindWorkspace(-1);
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
try {
// Just in case mFlushingWorkerThread changes but we aren't woken up,
// wait no longer than 1sec at a time
this.wait(1000);
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
void runBindSynchronousPage(int synchronousBindPage) {
if (synchronousBindPage < 0) {
// Ensure that we have a valid page index to load synchronously
throw new RuntimeException("Should not call runBindSynchronousPage() without " +
"valid page index");
}
if (!mAllAppsLoaded || !mWorkspaceLoaded) {
// Ensure that we don't try and bind a specified page when the pages have not been
// loaded already (we should load everything asynchronously in that case)
throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
}
synchronized (mLock) {
if (mIsLoaderTaskRunning) {
// Ensure that we are never running the background loading at this point since
// we also touch the background collections
throw new RuntimeException("Error! Background loading is already running");
}
}
// XXX: Throw an exception if we are already loading (since we touch the worker thread
// data structures, we can't allow any other thread to touch that data, but because
// this call is synchronous, we can get away with not locking).
// The LauncherModel is static in the LauncherAppState and mHandler may have queued
// operations from the previous activity. We need to ensure that all queued operations
// are executed before any synchronous binding work is done.
mHandler.flush();
// Divide the set of loaded items into those that we are binding synchronously, and
// everything else that is to be bound normally (asynchronously).
bindWorkspace(synchronousBindPage);
// XXX: For now, continue posting the binding of AllApps as there are other issues that
// arise from that.
onlyBindAllApps();
}
public void run() {
synchronized (mLock) {
mIsLoaderTaskRunning = true;
}
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
// Restore the default thread priority after we are done loading items
synchronized (mLock) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
synchronized (sBgLock) {
for (Object key : sBgDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
}
sBgDbIconCache.clear();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
mIsLoaderTaskRunning = false;
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
long containerIndex = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0] != null) {
Log.e(TAG, "Error loading shortcut into hotseat " + item
+ " into position (" + item.screenId + ":" + item.cellX + ","
+ item.cellY + ") occupied by "
+ occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0]);
return false;
}
} else {
ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
items[(int) item.screenId][0] = item;
occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
return true;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
if (!occupied.containsKey(item.screenId)) {
ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
occupied.put(item.screenId, items);
}
ItemInfo[][] screens = occupied.get(item.screenId);
// Check if any workspace icons overlap with each other
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (screens[x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screenId + ":"
+ x + "," + y
+ ") occupied by "
+ screens[x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
screens[x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
// Make sure the default workspace is loaded, if needed
boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb();
Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI;
mIsUpgradePath = loadOldDb;
synchronized (sBgLock) {
sBgWorkspaceItems.clear();
sBgAppWidgets.clear();
sBgFolders.clear();
sBgItemsIdMap.clear();
sBgDbIconCache.clear();
sBgWorkspaceScreens.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(contentUri, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that
// here
if (intent.getAction() != null &&
intent.getCategories() != null &&
intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screenId = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sBgFolders, container);
folderInfo.add(info);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
info.screenId = permuteScreens(info.screenId);
}
sBgItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(folderInfo);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
folderInfo.screenId = permuteScreens(folderInfo.screenId);
}
sBgItemsIdMap.put(folderInfo.id, folderInfo);
sBgFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.sDumpLogs.add(log);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screenId = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container != " +
"CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
appWidgetInfo.screenId =
permuteScreens(appWidgetInfo.screenId);
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sBgAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (loadOldDb) {
long maxScreenId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
!sBgWorkspaceScreens.contains(screenId)) {
sBgWorkspaceScreens.add(screenId);
if (screenId > maxScreenId) {
maxScreenId = screenId;
}
}
}
Collections.sort(sBgWorkspaceScreens);
mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
} else {
Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
try {
final int idIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens._ID);
final int rankIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens.SCREEN_RANK);
while (sc.moveToNext()) {
try {
long screenId = sc.getLong(idIndex);
int rank = sc.getInt(rankIndex);
orderedScreens.put(rank, screenId);
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
sc.close();
}
Iterator<Integer> iter = orderedScreens.keySet().iterator();
while (iter.hasNext()) {
sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
}
// Remove any empty screens
ArrayList<Long> unusedScreens = new ArrayList<Long>();
unusedScreens.addAll(sBgWorkspaceScreens);
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
unusedScreens.contains(screenId)) {
unusedScreens.remove(screenId);
}
}
// If there are any empty screens remove them, and update.
if (unusedScreens.size() != 0) {
sBgWorkspaceScreens.removeAll(unusedScreens);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
int nScreens = occupied.size();
for (int y = 0; y < mCellCountY; y++) {
String line = "";
Iterator<Long> iter = occupied.keySet().iterator();
while (iter.hasNext()) {
long screenId = iter.next();
if (screenId > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
}
// We rearrange the screens from the old launcher
// 12345 -> 34512
private long permuteScreens(long screen) {
if (screen >= 2) {
return screen - 2;
} else {
return screen + 3;
}
}
/** Filters the set of items who are directly or indirectly (via another container) on the
* specified screen. */
private void filterCurrentWorkspaceItems(int currentScreen,
ArrayList<ItemInfo> allWorkspaceItems,
ArrayList<ItemInfo> currentScreenItems,
ArrayList<ItemInfo> otherScreenItems) {
// Purge any null ItemInfos
Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
while (iter.hasNext()) {
ItemInfo i = iter.next();
if (i == null) {
iter.remove();
}
}
// If we aren't filtering on a screen, then the set of items to load is the full set of
// items given.
if (currentScreen < 0) {
currentScreenItems.addAll(allWorkspaceItems);
}
// Order the set of items by their containers first, this allows use to walk through the
// list sequentially, build up a list of containers that are in the specified screen,
// as well as all items in those containers.
Set<Long> itemsOnScreen = new HashSet<Long>();
Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return (int) (lhs.container - rhs.container);
}
});
for (ItemInfo info : allWorkspaceItems) {
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (info.screenId == currentScreen) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
} else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
if (itemsOnScreen.contains(info.container)) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
}
}
}
/** Filters the set of widgets which are on the specified screen. */
private void filterCurrentAppWidgets(int currentScreen,
ArrayList<LauncherAppWidgetInfo> appWidgets,
ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenWidgets.addAll(appWidgets);
}
for (LauncherAppWidgetInfo widget : appWidgets) {
if (widget == null) continue;
if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
widget.screenId == currentScreen) {
currentScreenWidgets.add(widget);
} else {
otherScreenWidgets.add(widget);
}
}
}
/** Filters the set of folders which are on the specified screen. */
private void filterCurrentFolders(int currentScreen,
HashMap<Long, ItemInfo> itemsIdMap,
HashMap<Long, FolderInfo> folders,
HashMap<Long, FolderInfo> currentScreenFolders,
HashMap<Long, FolderInfo> otherScreenFolders) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenFolders.putAll(folders);
}
for (long id : folders.keySet()) {
ItemInfo info = itemsIdMap.get(id);
FolderInfo folder = folders.get(id);
if (info == null || folder == null) continue;
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
info.screenId == currentScreen) {
currentScreenFolders.put(id, folder);
} else {
otherScreenFolders.put(id, folder);
}
}
}
/** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
* right) */
private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
// XXX: review this
Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
int cellCountX = LauncherModel.getCellCountX();
int cellCountY = LauncherModel.getCellCountY();
int screenOffset = cellCountX * cellCountY;
int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
lhs.cellY * cellCountX + lhs.cellX);
long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
rhs.cellY * cellCountX + rhs.cellX);
return (int) (lr - rr);
}
});
}
private void bindWorkspaceScreens(final Callbacks oldCallbacks,
final ArrayList<Long> orderedScreens) {
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindScreens(orderedScreens);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
private void bindWorkspaceItems(final Callbacks oldCallbacks,
final ArrayList<ItemInfo> workspaceItems,
final ArrayList<LauncherAppWidgetInfo> appWidgets,
final HashMap<Long, FolderInfo> folders,
ArrayList<Runnable> deferredBindRunnables) {
final boolean postOnMainThread = (deferredBindRunnables != null);
// Bind the workspace items
int N = workspaceItems.size();
for (int i = 0; i < N; i += ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(workspaceItems, start, start+chunkSize,
false);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the folders
if (!folders.isEmpty()) {
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(folders);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the widgets, one at a time
N = appWidgets.size();
for (int i = 0; i < N; i++) {
final LauncherAppWidgetInfo widget = appWidgets.get(i);
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
}
/**
* Binds all loaded data to actual views on the main thread.
*/
private void bindWorkspace(int synchronizeBindPage) {
final long t = SystemClock.uptimeMillis();
Runnable r;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
oldCallbacks.getCurrentWorkspaceScreen();
// Load all the items that are on the current page first (and in the process, unbind
// all the existing workspace items before we call startBinding() below.
unbindWorkspaceItemsOnMainThread();
ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> appWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
synchronized (sBgLock) {
workspaceItems.addAll(sBgWorkspaceItems);
appWidgets.addAll(sBgAppWidgets);
folders.putAll(sBgFolders);
itemsIdMap.putAll(sBgItemsIdMap);
orderedScreenIds.addAll(sBgWorkspaceScreens);
}
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
// Separate the items that are on the current screen, and all the other remaining items
filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
otherWorkspaceItems);
filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
otherAppWidgets);
filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
otherFolders);
sortWorkspaceItemsSpatially(currentWorkspaceItems);
sortWorkspaceItemsSpatially(otherWorkspaceItems);
// Tell the workspace that we're about to start binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
// Load items on the current page
bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
currentFolders, null);
if (isLoadingSynchronously) {
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.onPageBoundSynchronously(currentScreen);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
// Load all the remaining pages (if we are loading synchronously, we want to defer this
// work until after the first render)
mDeferredBindRunnables.clear();
bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
(isLoadingSynchronously ? mDeferredBindRunnables : null));
// Tell the workspace that we're done binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems(mIsUpgradePath);
}
// If we're profiling, ensure this is the last thing in the queue.
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
mIsLoadingAndBindingWorkspace = false;
}
};
if (isLoadingSynchronously) {
mDeferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllApps();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mAllAppsLoaded = true;
}
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
@SuppressWarnings("unchecked")
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Runnable r = new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
};
boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
if (isRunningOnMainThread) {
r.run();
} else {
mHandler.post(r);
}
}
private void loadAllApps() {
final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
return;
}
final PackageManager packageManager = mContext.getPackageManager();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// Clear the list of apps
mBgAllAppsList.clear();
// Query for the set of apps
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
}
// Fail if we don't have any apps
if (apps == null || apps.isEmpty()) {
return;
}
// Sort the applications by name
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
// Create the ApplicationInfos
final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
for (int i = 0; i < apps.size(); i++) {
// This builds the icon bitmaps.
mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
}
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
// Post callback on main thread
mHandler.post(new Runnable() {
public void run() {
final long bindTime = SystemClock.uptimeMillis();
if (callbacks != null) {
callbacks.bindAllApplications(added);
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - bindTime) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "Icons processed in "
+ (SystemClock.uptimeMillis() - loadTime) + "ms");
}
}
public void dumpState() {
synchronized (sBgLock) {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
}
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp.getContext();
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mBgAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mBgAllAppsList.updatePackage(context, packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mBgAllAppsList.removePackage(packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> modified = null;
final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
if (mBgAllAppsList.added.size() > 0) {
added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
mBgAllAppsList.added.clear();
}
if (mBgAllAppsList.modified.size() > 0) {
modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
mBgAllAppsList.modified.clear();
}
if (mBgAllAppsList.removed.size() > 0) {
removedApps.addAll(mBgAllAppsList.removed);
mBgAllAppsList.removed.clear();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
// Ensure that we add all the workspace applications to the db
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, added, cb);
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
// Update the launcher db to reflect the changes
for (ApplicationInfo a : modifiedFinal) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
if (isShortcutInfoUpdateable(i)) {
ShortcutInfo info = (ShortcutInfo) i;
info.title = a.title.toString();
updateItemInDatabase(context, info);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
// If a package has been removed, or an app has been removed as a result of
// an update (for example), make the removed callback.
if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
final boolean packageRemoved = (mOp == OP_REMOVE);
final ArrayList<String> removedPackageNames =
new ArrayList<String>(Arrays.asList(packages));
// Update the launcher db to reflect the removal of apps
if (packageRemoved) {
for (String pn : removedPackageNames) {
ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
} else {
for (ApplicationInfo a : removedApps) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindComponentsRemoved(removedPackageNames,
removedApps, packageRemoved);
}
}
});
}
final ArrayList<Object> widgetsAndShortcuts =
getSortedWidgetsAndShortcuts(context);
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated(widgetsAndShortcuts);
}
}
});
}
}
// Returns a list of ResolveInfos/AppWindowInfos in sorted order
public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
PackageManager packageManager = context.getPackageManager();
final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Collections.sort(widgetsAndShortcuts,
new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
return widgetsAndShortcuts;
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
try {
PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
if (!pi.applicationInfo.enabled) {
// If we return null here, the corresponding item will be removed from the launcher
// db and will not appear in the workspace.
return null;
}
info.initFlagsAndFirstInstallTime(pi);
} catch (NameNotFoundException e) {
Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
// Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
// if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
// via resolveActivity().
ResolveInfo resolveInfo = null;
ComponentName oldComponent = intent.getComponent();
Intent newIntent = new Intent(intent.getAction(), null);
newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
newIntent.setPackage(oldComponent.getPackageName());
List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
for (ResolveInfo i : infos) {
ComponentName cn = new ComponentName(i.activityInfo.packageName,
i.activityInfo.name);
if (cn.equals(oldComponent)) {
resolveInfo = i;
}
}
if (resolveInfo == null) {
resolveInfo = manager.resolveActivity(intent, 0);
}
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
ItemInfoFilter f) {
HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
for (ItemInfo i : infos) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
ComponentName cn = info.intent.getComponent();
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
} else if (i instanceof FolderInfo) {
FolderInfo info = (FolderInfo) i;
for (ShortcutInfo s : info.contents) {
ComponentName cn = s.intent.getComponent();
if (cn != null && f.filterItem(info, s, cn)) {
filtered.add(s);
}
}
} else if (i instanceof LauncherAppWidgetInfo) {
LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
ComponentName cn = info.providerName;
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
}
}
return new ArrayList<ItemInfo>(filtered);
}
private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.getPackageName().equals(pn);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.equals(cname);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
public static boolean isShortcutInfoUpdateable(ItemInfo i) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
Intent intent = info.intent;
ComponentName name = intent.getComponent();
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
return true;
}
}
return false;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
if (info == null) {
return null;
}
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (intent == null) {
// If the intent is null, we can't construct a valid ShortcutInfo, so we return null
Log.e(TAG, "Can't construct ShorcutInfo with null intent");
return null;
}
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
public static final Comparator<ApplicationInfo> getAppNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = collator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
}
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return collator.compare(a.label.toString(), b.label.toString());
}
};
}
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
mCollator = Collator.getInstance();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
mCollator = Collator.getInstance();
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
mCollator = Collator.getInstance();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screenId = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final long screenId, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screenId < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screenId = screenId;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
LauncherAppState app = LauncherAppState.getInstance();
item.id = app.getLauncherProvider().generateNewItemId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Add item (" + item.title + ") to db, id: "
+ item.id + " (" + container + ", " + screenId + ", " + cellX + ", "
+ cellY + ")";
Launcher.sDumpLogs.add(transaction);
Log.d(TAG, transaction);
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
checkItemInfoLocked(item.id, item, null);
sBgItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sBgWorkspaceItems.add(item);
} else {
if (!sBgFolders.containsKey(item.container)) {
// Adding an item to a folder that doesn't exist.
String msg = "adding item: " + item + " to a folder that " +
" doesn't exist";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
}
};
runOnWorkerThread(r);
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, long screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
Runnable r = new Runnable() {
public void run() {
String transaction = "DbDebug Delete item (" + item.title + ") from db, id: "
+ item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX +
", " + item.cellY + ")";
Launcher.sDumpLogs.add(transaction);
Log.d(TAG, transaction);
cr.delete(uriToDelete, null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sBgFolders.remove(item.id);
for (ItemInfo info: sBgItemsIdMap.values()) {
if (info.container == item.id) {
// We are deleting a folder which still contains items that
// think they are contained by that folder.
String msg = "deleting a folder (" + item + ") which still " +
"contains items (" + info + ")";
Log.e(TAG, msg);
Launcher.dumpDebugLogsToConsole();
}
}
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sBgWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sBgAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sBgItemsIdMap.remove(item.id);
sBgDbIconCache.remove(item);
}
}
};
runOnWorkerThread(r);
}
/**
* Update the order of the workspace screens in the database. The array list contains
* a list of screen ids in the order that they should appear.
*/
void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
final ContentResolver cr = context.getContentResolver();
final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
// Remove any negative screen ids -- these aren't persisted
Iterator<Long> iter = screensCopy.iterator();
while (iter.hasNext()) {
long id = iter.next();
if (id < 0) {
iter.remove();
}
}
Runnable r = new Runnable() {
@Override
public void run() {
// Clear the table
cr.delete(uri, null, null);
int count = screens.size();
ContentValues[] values = new ContentValues[count];
for (int i = 0; i < count; i++) {
ContentValues v = new ContentValues();
long screenId = screens.get(i);
v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
values[i] = v;
}
cr.bulkInsert(uri, values);
sBgWorkspaceScreens.clear();
sBgWorkspaceScreens.addAll(screensCopy);
}
};
runOnWorkerThread(r);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
Runnable r = new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
sBgItemsIdMap.remove(info.id);
sBgFolders.remove(info.id);
sBgDbIconCache.remove(info);
sBgWorkspaceItems.remove(info);
}
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
// Lock on mBgLock *after* the db operation
synchronized (sBgLock) {
for (ItemInfo childInfo : info.contents) {
sBgItemsIdMap.remove(childInfo.id);
sBgDbIconCache.remove(childInfo);
}
}
}
};
runOnWorkerThread(r);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps/workspace.
forceReload();
} else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
// Check if configuration change was an mcc/mnc change which would affect app resources
// and we would need to clear out the labels in all apps/workspace. Same handling as
// above for ACTION_LOCALE_CHANGED
Configuration currentConfig = context.getResources().getConfiguration();
if (mPreviousConfigMcc != currentConfig.mcc) {
Log.d(TAG, "Reload apps on config change. curr_mcc:"
+ currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc);
forceReload();
}
// Update previousConfig
mPreviousConfigMcc = currentConfig.mcc;
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
private void forceReload() {
resetLoadedState(true, true);
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload.
startLoaderFromBackground();
}
public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) {
synchronized (mLock) {
// Stop any existing loaders first, so they don't set mAllAppsLoaded or
// mWorkspaceLoaded to true later
stopLoaderLocked();
if (resetAllAppsLoaded) mAllAppsLoaded = false;
if (resetWorkspaceLoaded) mWorkspaceLoaded = false;
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(false, -1);
}
}
// If there is already a loader task running, tell it to stop.
// returns true if isLaunching() was true on the old task
private boolean stopLoaderLocked() {
boolean isLaunching = false;
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
isLaunching = true;
}
oldTask.stopLocked();
}
return isLaunching;
}
public void startLoader(boolean isLaunching, int synchronousBindPage) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Clear any deferred bind-runnables from the synchronized load process
// We must do this before any loading/binding is scheduled below.
mDeferredBindRunnables.clear();
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
// also, don't downgrade isLaunching if we're already running
isLaunching = isLaunching || stopLoaderLocked();
mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching);
if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) {
mLoaderTask.runBindSynchronousPage(synchronousBindPage);
} else {
sWorkerThread.setPriority(Thread.NORM_PRIORITY);
sWorker.post(mLoaderTask);
}
}
}
}
void bindRemainingSynchronousPages() {
// Post the remaining side pages to be loaded
if (!mDeferredBindRunnables.isEmpty()) {
for (final Runnable r : mDeferredBindRunnables) {
mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE);
}
mDeferredBindRunnables.clear();
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
boolean isLoadingWorkspace() {
synchronized (mLock) {
if (mLoaderTask != null) {
return mLoaderTask.isLoadingWorkspace();
}
}
return false;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private boolean mIsLaunching;
private boolean mIsLoadingAndBindingWorkspace;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private boolean mIsUpgradePath;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
boolean isLoadingWorkspace() {
return mIsLoadingAndBindingWorkspace;
}
private void loadAndBindWorkspace() {
mIsLoadingAndBindingWorkspace = true;
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
}
// Bind the workspace
bindWorkspace(-1);
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) {
try {
// Just in case mFlushingWorkerThread changes but we aren't woken up,
// wait no longer than 1sec at a time
this.wait(1000);
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
void runBindSynchronousPage(int synchronousBindPage) {
if (synchronousBindPage < 0) {
// Ensure that we have a valid page index to load synchronously
throw new RuntimeException("Should not call runBindSynchronousPage() without " +
"valid page index");
}
if (!mAllAppsLoaded || !mWorkspaceLoaded) {
// Ensure that we don't try and bind a specified page when the pages have not been
// loaded already (we should load everything asynchronously in that case)
throw new RuntimeException("Expecting AllApps and Workspace to be loaded");
}
synchronized (mLock) {
if (mIsLoaderTaskRunning) {
// Ensure that we are never running the background loading at this point since
// we also touch the background collections
throw new RuntimeException("Error! Background loading is already running");
}
}
// XXX: Throw an exception if we are already loading (since we touch the worker thread
// data structures, we can't allow any other thread to touch that data, but because
// this call is synchronous, we can get away with not locking).
// The LauncherModel is static in the LauncherAppState and mHandler may have queued
// operations from the previous activity. We need to ensure that all queued operations
// are executed before any synchronous binding work is done.
mHandler.flush();
// Divide the set of loaded items into those that we are binding synchronously, and
// everything else that is to be bound normally (asynchronously).
bindWorkspace(synchronousBindPage);
// XXX: For now, continue posting the binding of AllApps as there are other issues that
// arise from that.
onlyBindAllApps();
}
public void run() {
synchronized (mLock) {
mIsLoaderTaskRunning = true;
}
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
// Restore the default thread priority after we are done loading items
synchronized (mLock) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
synchronized (sBgLock) {
for (Object key : sBgDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key));
}
sBgDbIconCache.clear();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
mIsLoaderTaskRunning = false;
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) {
long containerIndex = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) {
if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0] != null) {
Log.e(TAG, "Error loading shortcut into hotseat " + item
+ " into position (" + item.screenId + ":" + item.cellX + ","
+ item.cellY + ") occupied by "
+ occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT)
[(int) item.screenId][0]);
return false;
}
} else {
ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
items[(int) item.screenId][0] = item;
occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items);
return true;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
if (!occupied.containsKey(item.screenId)) {
ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1];
occupied.put(item.screenId, items);
}
ItemInfo[][] screens = occupied.get(item.screenId);
// Check if any workspace icons overlap with each other
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (screens[x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screenId + ":"
+ x + "," + y
+ ") occupied by "
+ screens[x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
screens[x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
// Make sure the default workspace is loaded, if needed
boolean loadOldDb = mApp.getLauncherProvider().shouldLoadOldDb();
Uri contentUri = loadOldDb ? LauncherSettings.Favorites.OLD_CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI;
mIsUpgradePath = loadOldDb;
synchronized (sBgLock) {
sBgWorkspaceItems.clear();
sBgAppWidgets.clear();
sBgFolders.clear();
sBgItemsIdMap.clear();
sBgDbIconCache.clear();
sBgWorkspaceScreens.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(contentUri, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
// Load workspace in reverse order to ensure that latest items are loaded first (and
// before any earlier duplicates)
final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>();
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
//final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
//final int displayModeIndex = c.getColumnIndexOrThrow(
// LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
// App shortcuts that used to be automatically added to Launcher
// didn't always have the correct intent flags set, so do that
// here
if (intent.getAction() != null &&
intent.getCategories() != null &&
intent.getAction().equals(Intent.ACTION_MAIN) &&
intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
intent.addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
}
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screenId = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sBgFolders, container);
folderInfo.add(info);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
info.screenId = permuteScreens(info.screenId);
}
sBgItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screenId = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sBgWorkspaceItems.add(folderInfo);
break;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
folderInfo.screenId = permuteScreens(folderInfo.screenId);
}
sBgItemsIdMap.put(folderInfo.id, folderInfo);
sBgFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
String log = "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId;
Log.e(TAG, log);
Launcher.sDumpLogs.add(log);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId,
provider.provider);
appWidgetInfo.id = id;
appWidgetInfo.screenId = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
int[] minSpan = Launcher.getMinSpanForWidget(context, provider);
appWidgetInfo.minSpanX = minSpan[0];
appWidgetInfo.minSpanY = minSpan[1];
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container != " +
"CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
loadOldDb) {
appWidgetInfo.screenId =
permuteScreens(appWidgetInfo.screenId);
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sBgAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
if (c != null) {
c.close();
}
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (loadOldDb) {
long maxScreenId = 0;
// If we're importing we use the old screen order.
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
!sBgWorkspaceScreens.contains(screenId)) {
sBgWorkspaceScreens.add(screenId);
if (screenId > maxScreenId) {
maxScreenId = screenId;
}
}
}
Collections.sort(sBgWorkspaceScreens);
mApp.getLauncherProvider().updateMaxScreenId(maxScreenId);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
} else {
Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();
try {
final int idIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens._ID);
final int rankIndex = sc.getColumnIndexOrThrow(
LauncherSettings.WorkspaceScreens.SCREEN_RANK);
while (sc.moveToNext()) {
try {
long screenId = sc.getLong(idIndex);
int rank = sc.getInt(rankIndex);
orderedScreens.put(rank, screenId);
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
sc.close();
}
Iterator<Integer> iter = orderedScreens.keySet().iterator();
while (iter.hasNext()) {
sBgWorkspaceScreens.add(orderedScreens.get(iter.next()));
}
// Remove any empty screens
ArrayList<Long> unusedScreens = new ArrayList<Long>();
unusedScreens.addAll(sBgWorkspaceScreens);
for (ItemInfo item: sBgItemsIdMap.values()) {
long screenId = item.screenId;
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
unusedScreens.contains(screenId)) {
unusedScreens.remove(screenId);
}
}
// If there are any empty screens remove them, and update.
if (unusedScreens.size() != 0) {
sBgWorkspaceScreens.removeAll(unusedScreens);
updateWorkspaceScreenOrder(context, sBgWorkspaceScreens);
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
int nScreens = occupied.size();
for (int y = 0; y < mCellCountY; y++) {
String line = "";
Iterator<Long> iter = occupied.keySet().iterator();
while (iter.hasNext()) {
long screenId = iter.next();
if (screenId > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied.get(screenId)[x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
}
// We rearrange the screens from the old launcher
// 12345 -> 34512
private long permuteScreens(long screen) {
if (screen >= 2) {
return screen - 2;
} else {
return screen + 3;
}
}
/** Filters the set of items who are directly or indirectly (via another container) on the
* specified screen. */
private void filterCurrentWorkspaceItems(int currentScreen,
ArrayList<ItemInfo> allWorkspaceItems,
ArrayList<ItemInfo> currentScreenItems,
ArrayList<ItemInfo> otherScreenItems) {
// Purge any null ItemInfos
Iterator<ItemInfo> iter = allWorkspaceItems.iterator();
while (iter.hasNext()) {
ItemInfo i = iter.next();
if (i == null) {
iter.remove();
}
}
// If we aren't filtering on a screen, then the set of items to load is the full set of
// items given.
if (currentScreen < 0) {
currentScreenItems.addAll(allWorkspaceItems);
}
// Order the set of items by their containers first, this allows use to walk through the
// list sequentially, build up a list of containers that are in the specified screen,
// as well as all items in those containers.
Set<Long> itemsOnScreen = new HashSet<Long>();
Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return (int) (lhs.container - rhs.container);
}
});
for (ItemInfo info : allWorkspaceItems) {
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (info.screenId == currentScreen) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
} else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
if (itemsOnScreen.contains(info.container)) {
currentScreenItems.add(info);
itemsOnScreen.add(info.id);
} else {
otherScreenItems.add(info);
}
}
}
}
/** Filters the set of widgets which are on the specified screen. */
private void filterCurrentAppWidgets(int currentScreen,
ArrayList<LauncherAppWidgetInfo> appWidgets,
ArrayList<LauncherAppWidgetInfo> currentScreenWidgets,
ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenWidgets.addAll(appWidgets);
}
for (LauncherAppWidgetInfo widget : appWidgets) {
if (widget == null) continue;
if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
widget.screenId == currentScreen) {
currentScreenWidgets.add(widget);
} else {
otherScreenWidgets.add(widget);
}
}
}
/** Filters the set of folders which are on the specified screen. */
private void filterCurrentFolders(int currentScreen,
HashMap<Long, ItemInfo> itemsIdMap,
HashMap<Long, FolderInfo> folders,
HashMap<Long, FolderInfo> currentScreenFolders,
HashMap<Long, FolderInfo> otherScreenFolders) {
// If we aren't filtering on a screen, then the set of items to load is the full set of
// widgets given.
if (currentScreen < 0) {
currentScreenFolders.putAll(folders);
}
for (long id : folders.keySet()) {
ItemInfo info = itemsIdMap.get(id);
FolderInfo folder = folders.get(id);
if (info == null || folder == null) continue;
if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
info.screenId == currentScreen) {
currentScreenFolders.put(id, folder);
} else {
otherScreenFolders.put(id, folder);
}
}
}
/** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to
* right) */
private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) {
// XXX: review this
Collections.sort(workspaceItems, new Comparator<ItemInfo>() {
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
int cellCountX = LauncherModel.getCellCountX();
int cellCountY = LauncherModel.getCellCountY();
int screenOffset = cellCountX * cellCountY;
int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat
long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset +
lhs.cellY * cellCountX + lhs.cellX);
long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset +
rhs.cellY * cellCountX + rhs.cellX);
return (int) (lr - rr);
}
});
}
private void bindWorkspaceScreens(final Callbacks oldCallbacks,
final ArrayList<Long> orderedScreens) {
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindScreens(orderedScreens);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
private void bindWorkspaceItems(final Callbacks oldCallbacks,
final ArrayList<ItemInfo> workspaceItems,
final ArrayList<LauncherAppWidgetInfo> appWidgets,
final HashMap<Long, FolderInfo> folders,
ArrayList<Runnable> deferredBindRunnables) {
final boolean postOnMainThread = (deferredBindRunnables != null);
// Bind the workspace items
int N = workspaceItems.size();
for (int i = 0; i < N; i += ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
final Runnable r = new Runnable() {
@Override
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(workspaceItems, start, start+chunkSize,
false);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the folders
if (!folders.isEmpty()) {
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(folders);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
// Bind the widgets, one at a time
N = appWidgets.size();
for (int i = 0; i < N; i++) {
final LauncherAppWidgetInfo widget = appWidgets.get(i);
final Runnable r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
};
if (postOnMainThread) {
deferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
}
/**
* Binds all loaded data to actual views on the main thread.
*/
private void bindWorkspace(int synchronizeBindPage) {
final long t = SystemClock.uptimeMillis();
Runnable r;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
final boolean isLoadingSynchronously = (synchronizeBindPage > -1);
final int currentScreen = isLoadingSynchronously ? synchronizeBindPage :
oldCallbacks.getCurrentWorkspaceScreen();
// Load all the items that are on the current page first (and in the process, unbind
// all the existing workspace items before we call startBinding() below.
unbindWorkspaceItemsOnMainThread();
ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> appWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>();
HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>();
ArrayList<Long> orderedScreenIds = new ArrayList<Long>();
synchronized (sBgLock) {
workspaceItems.addAll(sBgWorkspaceItems);
appWidgets.addAll(sBgAppWidgets);
folders.putAll(sBgFolders);
itemsIdMap.putAll(sBgItemsIdMap);
orderedScreenIds.addAll(sBgWorkspaceScreens);
}
ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>();
ArrayList<LauncherAppWidgetInfo> currentAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
ArrayList<LauncherAppWidgetInfo> otherAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>();
HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>();
// Separate the items that are on the current screen, and all the other remaining items
filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems,
otherWorkspaceItems);
filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets,
otherAppWidgets);
filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders,
otherFolders);
sortWorkspaceItemsSpatially(currentWorkspaceItems);
sortWorkspaceItemsSpatially(otherWorkspaceItems);
// Tell the workspace that we're about to start binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
bindWorkspaceScreens(oldCallbacks, orderedScreenIds);
// Load items on the current page
bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets,
currentFolders, null);
if (isLoadingSynchronously) {
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.onPageBoundSynchronously(currentScreen);
}
}
};
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
// Load all the remaining pages (if we are loading synchronously, we want to defer this
// work until after the first render)
mDeferredBindRunnables.clear();
bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders,
(isLoadingSynchronously ? mDeferredBindRunnables : null));
// Tell the workspace that we're done binding items
r = new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems(mIsUpgradePath);
}
// If we're profiling, ensure this is the last thing in the queue.
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
mIsLoadingAndBindingWorkspace = false;
}
};
if (isLoadingSynchronously) {
mDeferredBindRunnables.add(r);
} else {
runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE);
}
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllApps();
synchronized (LoaderTask.this) {
if (mStopped) {
return;
}
mAllAppsLoaded = true;
}
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
@SuppressWarnings("unchecked")
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone();
Runnable r = new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
};
boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid());
if (isRunningOnMainThread) {
r.run();
} else {
mHandler.post(r);
}
}
private void loadAllApps() {
final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)");
return;
}
final PackageManager packageManager = mContext.getPackageManager();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// Clear the list of apps
mBgAllAppsList.clear();
// Query for the set of apps
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps");
}
// Fail if we don't have any apps
if (apps == null || apps.isEmpty()) {
return;
}
// Sort the applications by name
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
// Create the ApplicationInfos
final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
for (int i = 0; i < apps.size(); i++) {
// This builds the icon bitmaps.
mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
}
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mBgAllAppsList.added;
mBgAllAppsList.added = new ArrayList<ApplicationInfo>();
// Post callback on main thread
mHandler.post(new Runnable() {
public void run() {
final long bindTime = SystemClock.uptimeMillis();
if (callbacks != null) {
callbacks.bindAllApplications(added);
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - bindTime) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "Icons processed in "
+ (SystemClock.uptimeMillis() - loadTime) + "ms");
}
}
public void dumpState() {
synchronized (sBgLock) {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size());
}
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp.getContext();
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mBgAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mBgAllAppsList.updatePackage(context, packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mBgAllAppsList.removePackage(packages[i]);
WidgetPreviewLoader.removeFromDb(
mApp.getWidgetPreviewCacheDb(), packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> modified = null;
final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>();
if (mBgAllAppsList.added.size() > 0) {
added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added);
mBgAllAppsList.added.clear();
}
if (mBgAllAppsList.modified.size() > 0) {
modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified);
mBgAllAppsList.modified.clear();
}
if (mBgAllAppsList.removed.size() > 0) {
removedApps.addAll(mBgAllAppsList.removed);
mBgAllAppsList.removed.clear();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
// Ensure that we add all the workspace applications to the db
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
addAndBindAddedApps(context, added, cb);
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
// Update the launcher db to reflect the changes
for (ApplicationInfo a : modifiedFinal) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
if (isShortcutInfoUpdateable(i)) {
ShortcutInfo info = (ShortcutInfo) i;
info.title = a.title.toString();
updateItemInDatabase(context, info);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
// If a package has been removed, or an app has been removed as a result of
// an update (for example), make the removed callback.
if (mOp == OP_REMOVE || !removedApps.isEmpty()) {
final boolean packageRemoved = (mOp == OP_REMOVE);
final ArrayList<String> removedPackageNames =
new ArrayList<String>(Arrays.asList(packages));
// Update the launcher db to reflect the removal of apps
if (packageRemoved) {
for (String pn : removedPackageNames) {
ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
} else {
for (ApplicationInfo a : removedApps) {
ArrayList<ItemInfo> infos =
getItemInfoForComponentName(a.componentName);
for (ItemInfo i : infos) {
deleteItemFromDatabase(context, i);
}
}
}
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindComponentsRemoved(removedPackageNames,
removedApps, packageRemoved);
}
}
});
}
final ArrayList<Object> widgetsAndShortcuts =
getSortedWidgetsAndShortcuts(context);
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated(widgetsAndShortcuts);
}
}
});
}
}
// Returns a list of ResolveInfos/AppWindowInfos in sorted order
public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) {
PackageManager packageManager = context.getPackageManager();
final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders());
Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
Collections.sort(widgetsAndShortcuts,
new LauncherModel.WidgetAndShortcutNameComparator(packageManager));
return widgetsAndShortcuts;
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
try {
PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0);
if (!pi.applicationInfo.enabled) {
// If we return null here, the corresponding item will be removed from the launcher
// db and will not appear in the workspace.
return null;
}
info.initFlagsAndFirstInstallTime(pi);
} catch (NameNotFoundException e) {
Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName());
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
// Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and
// if that fails, or is ambiguious, fallback to the standard way of getting the resolve info
// via resolveActivity().
ResolveInfo resolveInfo = null;
ComponentName oldComponent = intent.getComponent();
Intent newIntent = new Intent(intent.getAction(), null);
newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
newIntent.setPackage(oldComponent.getPackageName());
List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0);
for (ResolveInfo i : infos) {
ComponentName cn = new ComponentName(i.activityInfo.packageName,
i.activityInfo.name);
if (cn.equals(oldComponent)) {
resolveInfo = i;
}
}
if (resolveInfo == null) {
resolveInfo = manager.resolveActivity(intent, 0);
}
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos,
ItemInfoFilter f) {
HashSet<ItemInfo> filtered = new HashSet<ItemInfo>();
for (ItemInfo i : infos) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
ComponentName cn = info.intent.getComponent();
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
} else if (i instanceof FolderInfo) {
FolderInfo info = (FolderInfo) i;
for (ShortcutInfo s : info.contents) {
ComponentName cn = s.intent.getComponent();
if (cn != null && f.filterItem(info, s, cn)) {
filtered.add(s);
}
}
} else if (i instanceof LauncherAppWidgetInfo) {
LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i;
ComponentName cn = info.providerName;
if (cn != null && f.filterItem(null, info, cn)) {
filtered.add(info);
}
}
}
return new ArrayList<ItemInfo>(filtered);
}
private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.getPackageName().equals(pn);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) {
HashSet<ItemInfo> infos = new HashSet<ItemInfo>();
ItemInfoFilter filter = new ItemInfoFilter() {
@Override
public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) {
return cn.equals(cname);
}
};
return filterItemInfos(sBgItemsIdMap.values(), filter);
}
public static boolean isShortcutInfoUpdateable(ItemInfo i) {
if (i instanceof ShortcutInfo) {
ShortcutInfo info = (ShortcutInfo) i;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
Intent intent = info.intent;
ComponentName name = intent.getComponent();
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
return true;
}
}
return false;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
@SuppressWarnings("all") // suppress dead code warning
final boolean debug = false;
if (debug) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
if (info == null) {
return null;
}
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (intent == null) {
// If the intent is null, we can't construct a valid ShortcutInfo, so we return null
Log.e(TAG, "Can't construct ShorcutInfo with null intent");
return null;
}
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
public static final Comparator<ApplicationInfo> getAppNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = collator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
}
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() {
final Collator collator = Collator.getInstance();
return new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return collator.compare(a.label.toString(), b.label.toString());
}
};
}
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
mCollator = Collator.getInstance();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
mCollator = Collator.getInstance();
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private Collator mCollator;
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
mCollator = Collator.getInstance();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return mCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
|
diff --git a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java
index 6f082b1b..322e263c 100644
--- a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java
+++ b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java
@@ -1,767 +1,767 @@
package com.jayway.maven.plugins.android.phase04processclasses;
import com.jayway.maven.plugins.android.AbstractAndroidMojo;
import com.jayway.maven.plugins.android.CommandExecutor;
import com.jayway.maven.plugins.android.ExecutionException;
import com.jayway.maven.plugins.android.config.ConfigHandler;
import com.jayway.maven.plugins.android.config.ConfigPojo;
import com.jayway.maven.plugins.android.config.PullParameter;
import com.jayway.maven.plugins.android.configuration.Proguard;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.RepositoryUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.util.artifact.JavaScopes;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Processes both application and dependency classes using the ProGuard byte code obfuscator,
* minimzer, and optimizer. For more information, see https://proguard.sourceforge.net.
*
* @author Jonson
* @author Matthias Kaeppler
* @author Manfred Moser
* @author Michal Harakal
* @goal proguard
* @phase process-classes
* @requiresDependencyResolution compile
*/
public class ProguardMojo extends AbstractAndroidMojo
{
/**
* <p>
* ProGuard configuration. ProGuard is disabled by default. Set the skip parameter to false to activate proguard.
* A complete configuartion can include any of the following:
* </p>
* <p/>
* <pre>
* <proguard>
* <skip>true|false</skip>
* <config>proguard.cfg</config>
* <configs>
* <config>${env.ANDROID_HOME}/tools/proguard/proguard-android.txt</config>
* </configs>
* <proguardJarPath>someAbsolutePathToProguardJar</proguardJarPath>
* <filterMavenDescriptor>true|false</filterMavenDescriptor>
* <filterManifest>true|false</filterManifest>
* <jvmArguments>
* <jvmArgument>-Xms256m</jvmArgument>
* <jvmArgument>-Xmx512m</jvmArgument>
* </jvmArguments>
* </proguard>
* </pre>
* <p>
* A good practice is to create a release profile in your POM, in which you enable ProGuard.
* ProGuard should be disabled for development builds, since it obfuscates class and field
* names, and it may interfere with test projects that rely on your application classes.
* All parameters can be overridden in profiles or the the proguard* properties. Default values apply and are
* documented with these properties.
* </p>
*
* @parameter
*/
@ConfigPojo
protected Proguard proguard;
/**
* Whether ProGuard is enabled or not. Defaults to true.
*
* @parameter expression="${android.proguard.skip}"
* @optional
*/
private Boolean proguardSkip;
@PullParameter( defaultValue = "true" )
private Boolean parsedSkip;
/**
* Path to the ProGuard configuration file (relative to project root). Defaults to "proguard.cfg"
*
* @parameter expression="${android.proguard.config}"
* @optional
*/
private File proguardConfig;
@PullParameter( defaultValue = "${project.basedir}/proguard.cfg" )
private File parsedConfig;
/**
* Additional ProGuard configuration files (relative to project root).
*
* @parameter expression="${android.proguard.configs}"
* @optional
*/
private String[] proguardConfigs;
@PullParameter( defaultValueGetterMethod = "getDefaultProguardConfigs" )
private String[] parsedConfigs;
/**
* Additional ProGuard options
*
* @parameter expression="${android.proguard.options}"
* @optional
*/
private String[] proguardOptions;
@PullParameter( defaultValueGetterMethod = "getDefaultProguardOptions" )
private String[] parsedOptions;
/**
* Path to the proguard jar and therefore version of proguard to be used. By default this will load the jar from
* the Android SDK install. Overriding it with an absolute path allows you to use a newer or custom proguard
* version..
* <p/>
* You can also reference an external Proguard version as a plugin dependency like this:
* <pre>
* <plugin>
* <groupId>com.jayway.maven.plugins.android.generation2</groupId>
* <artifactId>android-maven-plugin</artifactId>
* <dependencies>
* <dependency>
* <groupId>net.sf.proguard</groupId>
* <artifactId>proguard-base</artifactId>
* <version>4.7</version>
* </dependency>
* </dependencies>
* </pre>
* <p/>
* which will download and use Proguard 4.7 as deployed to the Central Repository.
*
* @parameter expression="${android.proguard.proguardJarPath}
* @optional
*/
private String proguardProguardJarPath;
@PullParameter( defaultValueGetterMethod = "getProguardJarPath" )
private String parsedProguardJarPath;
/**
* Path relative to the project's build directory (target) where proguard puts folowing files:
* <p/>
* <ul>
* <li>dump.txt</li>
* <li>seeds.txt</li>
* <li>usage.txt</li>
* <li>mapping.txt</li>
* </ul>
* <p/>
* You can define the directory like this:
* <pre>
* <proguard>
* <skip>false</skip>
* <config>proguard.cfg</config>
* <outputDirectory>my_proguard</outputDirectory>
* </proguard>
* </pre>
* <p/>
* Output directory is defined relatively so it could be also outside of the target directory.
* <p/>
*
* @parameter expression="${android.proguard.outputDirectory}"
* @optional
*/
private File outputDirectory;
@PullParameter( defaultValue = "${project.build.directory}/proguard" )
private File parsedOutputDirectory;
/**
* @parameter expression="${android.proguard.obfuscatedJar}"
* default-value="${project.build.directory}/${project.build.finalName}_obfuscated.jar"
*/
private String obfuscatedJar;
/**
* Extra JVM Arguments. Using these you can e.g. increase memory for the jvm running the build.
* Defaults to "-Xmx512M".
*
* @parameter expression="${android.proguard.jvmArguments}"
* @optional
*/
private String[] proguardJvmArguments;
@PullParameter( defaultValueGetterMethod = "getDefaultJvmArguments" )
private String[] parsedJvmArguments;
/**
* If set to true will add a filter to remove META-INF/maven/* files. Defaults to false.
*
* @parameter expression="${android.proguard.filterMavenDescriptor}"
* @optional
*/
private Boolean proguardFilterMavenDescriptor;
@PullParameter( defaultValue = "true" )
private Boolean parsedFilterMavenDescriptor;
/**
* If set to true will add a filter to remove META-INF/MANIFEST.MF files. Defaults to false.
*
* @parameter expression="${android.proguard.filterManifest}"
* @optional
*/
private Boolean proguardFilterManifest;
@PullParameter( defaultValue = "true" )
private Boolean parsedFilterManifest;
/**
* If set to true JDK jars will be included as library jars and corresponding filters
* will be applied to android.jar. Defaults to true.
* @parameter expression="${android.proguard.includeJdkLibs}"
*/
private Boolean includeJdkLibs;
@PullParameter( defaultValue = "true" )
private Boolean parsedIncludeJdkLibs;
/**
* If set to true the mapping.txt file will be attached as artifact of type <code>map</code>
* @parameter expression="${android.proguard.attachMap}"
*/
private Boolean attachMap;
@PullParameter( defaultValue = "false" )
private Boolean parsedAttachMap;
/**
* The plugin dependencies.
*
* @parameter expression="${plugin.artifacts}"
* @required
* @readonly
*/
protected List< Artifact > pluginDependencies;
private static final Collection< String > ANDROID_LIBRARY_EXCLUDED_FILTER = Arrays
.asList( "org/xml/**", "org/w3c/**", "java/**", "javax/**" );
private static final Collection< String > MAVEN_DESCRIPTOR = Arrays.asList( "META-INF/maven/**" );
private static final Collection< String > META_INF_MANIFEST = Arrays.asList( "META-INF/MANIFEST.MF" );
/**
* For Proguard is required only jar type dependencies, all other like .so or .apklib can be skipped.
*/
private static final String USED_DEPENDENCY_TYPE = "jar";
private Collection< String > globalInJarExcludes = new HashSet< String >();
private List< Artifact > artifactBlacklist = new LinkedList< Artifact >();
private List< Artifact > artifactsToShift = new LinkedList< Artifact >();
private List< ProGuardInput > inJars = new LinkedList< ProguardMojo.ProGuardInput >();
private List< ProGuardInput > libraryJars = new LinkedList< ProguardMojo.ProGuardInput >();
private File javaHomeDir;
private File javaLibDir;
private File altJavaLibDir;
private static class ProGuardInput
{
private String path;
private Collection< String > excludedFilter;
public ProGuardInput( String path, Collection< String > excludedFilter )
{
this.path = path;
this.excludedFilter = excludedFilter;
}
public String toCommandLine()
{
if ( excludedFilter != null && !excludedFilter.isEmpty() )
{
StringBuilder sb = new StringBuilder( "'\"" );
sb.append( path );
sb.append( "\"(" );
for ( Iterator< String > it = excludedFilter.iterator(); it.hasNext(); )
{
sb.append( '!' ).append( it.next() );
if ( it.hasNext() )
{
sb.append( ',' );
}
}
sb.append( ")'" );
return sb.toString();
}
else
{
return "\'\"" + path + "\"\'";
}
}
@Override
public String toString()
{
return "ProGuardInput{"
+ "path='" + path + '\''
+ ", excludedFilter=" + excludedFilter
+ '}';
}
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
ConfigHandler configHandler = new ConfigHandler( this, this.session, this.execution );
configHandler.parseConfiguration();
if ( !parsedSkip )
{
if ( parsedConfig.exists() )
{
// TODO: make the property name a constant sometime after switching to @Mojo
project.getProperties().setProperty( "android.proguard.obfuscatedJar", obfuscatedJar );
executeProguard();
}
else
{
getLog().info( String
.format( "Proguard skipped because the configuration file doesn't exist: %s", parsedConfig ) );
}
}
}
private void executeProguard() throws MojoExecutionException
{
final File proguardDir = this.parsedOutputDirectory;
if ( !proguardDir.exists() && !proguardDir.mkdir() )
{
throw new MojoExecutionException( "Cannot create proguard output directory" );
}
else
{
if ( proguardDir.exists() && !proguardDir.isDirectory() )
{
throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List< String > commands = new ArrayList< String >();
collectJvmArguments( commands );
commands.add( "-jar" );
commands.add( parsedProguardJarPath );
- commands.add( "@" + parsedConfig );
+ commands.add( "@\"" + parsedConfig + "\"" );
for ( String config : parsedConfigs )
{
- commands.add( "@" + config );
+ commands.add( "@\"" + config + "\"" );
}
if ( proguardFile != null )
{
- commands.add( "@" + proguardFile.getAbsolutePath() );
+ commands.add( "@\"" + proguardFile.getAbsolutePath() + "\"" );
}
collectInputFiles( commands );
commands.add( "-outjars" );
commands.add( "'\"" + obfuscatedJar + "\"'" );
commands.add( "-dump" );
commands.add( "'\"" + proguardDir + File.separator + "dump.txt\"'" );
commands.add( "-printseeds" );
commands.add( "'\"" + proguardDir + File.separator + "seeds.txt\"'" );
commands.add( "-printusage" );
commands.add( "'\"" + proguardDir + File.separator + "usage.txt\"'" );
File mapFile = new File( proguardDir, "mapping.txt" );
commands.add( "-printmapping" );
commands.add( "'\"" + mapFile + "\"'" );
commands.addAll( Arrays.asList( parsedOptions ) );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().info( javaExecutable + " " + commands.toString() );
try
{
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
if ( parsedAttachMap )
{
projectHelper.attachArtifact( project, "map", mapFile );
}
}
/**
* Convert the jvm arguments in parsedJvmArguments as populated by the config in format as needed by the java
* command. Also preserve backwards compatibility in terms of dashes required or not..
*
* @param commands
*/
private void collectJvmArguments( List< String > commands )
{
if ( parsedJvmArguments != null )
{
for ( String jvmArgument : parsedJvmArguments )
{
// preserve backward compatibility allowing argument with or without dash (e.g.
// Xmx512m as well as -Xmx512m should work) (see
// http://code.google.com/p/maven-android-plugin/issues/detail?id=153)
if ( !jvmArgument.startsWith( "-" ) )
{
jvmArgument = "-" + jvmArgument;
}
commands.add( jvmArgument );
}
}
}
private void collectInputFiles( List< String > commands )
{
// commons-logging breaks everything horribly, so we skip it from the program
// dependencies and declare it to be a library dependency instead
skipArtifact( "commons-logging", "commons-logging", true );
collectProgramInputFiles();
for ( ProGuardInput injar : inJars )
{
getLog().debug( "Added injar : " + injar );
commands.add( "-injars" );
commands.add( injar.toCommandLine() );
}
collectLibraryInputFiles();
for ( ProGuardInput libraryjar : libraryJars )
{
getLog().debug( "Added libraryJar : " + libraryjar );
commands.add( "-libraryjars" );
commands.add( libraryjar.toCommandLine() );
}
}
/**
* Figure out the full path to the current java executable.
*
* @return the full path to the current java executable.
*/
private static File getJavaExecutable()
{
final String javaHome = System.getProperty( "java.home" );
final String slash = File.separator;
return new File( javaHome + slash + "bin" + slash + "java" );
}
private void skipArtifact( String groupId, String artifactId, boolean shiftToLibraries )
{
artifactBlacklist.add( RepositoryUtils.toArtifact( new DefaultArtifact( groupId, artifactId, null, null ) ) );
if ( shiftToLibraries )
{
artifactsToShift
.add( RepositoryUtils.toArtifact( new DefaultArtifact( groupId, artifactId, null, null ) ) );
}
}
private boolean isBlacklistedArtifact( Artifact artifact )
{
for ( Artifact artifactToSkip : artifactBlacklist )
{
if ( artifactToSkip.getGroupId().equals( artifact.getGroupId() ) && artifactToSkip.getArtifactId()
.equals( artifact.getArtifactId() ) )
{
return true;
}
}
return false;
}
private boolean isShiftedArtifact( Artifact artifact )
{
for ( Artifact artifactToShift : artifactsToShift )
{
if ( artifactToShift.getGroupId().equals( artifact.getGroupId() ) && artifactToShift.getArtifactId()
.equals( artifact.getArtifactId() ) )
{
return true;
}
}
return false;
}
private void collectProgramInputFiles()
{
if ( parsedFilterManifest )
{
globalInJarExcludes.addAll( META_INF_MANIFEST );
}
if ( parsedFilterMavenDescriptor )
{
globalInJarExcludes.addAll( MAVEN_DESCRIPTOR );
}
// we first add the application's own class files
addInJar( project.getBuild().getOutputDirectory() );
// we then add all its dependencies (incl. transitive ones), unless they're blacklisted
for ( Artifact artifact : getTransitiveDependencyArtifacts() )
{
if ( isBlacklistedArtifact( artifact ) || !USED_DEPENDENCY_TYPE.equals( artifact.getType() ) )
{
continue;
}
addInJar( artifact.getFile().getAbsolutePath(), globalInJarExcludes );
}
}
private void addInJar( String path, Collection< String > filterExpression )
{
inJars.add( new ProGuardInput( path, filterExpression ) );
}
private void addInJar( String path )
{
addInJar( path, null );
}
private void addLibraryJar( String path, Collection< String > filterExpression )
{
libraryJars.add( new ProGuardInput( path, filterExpression ) );
}
private void addLibraryJar( String path )
{
addLibraryJar( path, null );
}
private void collectLibraryInputFiles()
{
if ( parsedIncludeJdkLibs )
{
// we have to add the Java framework classes to the library JARs, since they are not
// distributed with the JAR on Central, and since we'll strip them out of the android.jar
// that is shipped with the SDK (since that is not a complete Java distribution)
File rtJar = getJVMLibrary( "rt.jar" );
if ( rtJar == null )
{
rtJar = getJVMLibrary( "classes.jar" );
}
if ( rtJar != null )
{
addLibraryJar( rtJar.getPath() );
}
// we also need to add the JAR containing e.g. javax.servlet
File jsseJar = getJVMLibrary( "jsse.jar" );
if ( jsseJar != null )
{
addLibraryJar( jsseJar.getPath() );
}
// and the javax.crypto stuff
File jceJar = getJVMLibrary( "jce.jar" );
if ( jceJar != null )
{
addLibraryJar( jceJar.getPath() );
}
}
// we treat any dependencies with provided scope as library JARs
for ( Artifact artifact : project.getArtifacts() )
{
if ( artifact.getScope().equals( JavaScopes.PROVIDED ) )
{
if ( artifact.getArtifactId().equals( "android" ) && parsedIncludeJdkLibs )
{
addLibraryJar( artifact.getFile().getAbsolutePath(), ANDROID_LIBRARY_EXCLUDED_FILTER );
}
else
{
addLibraryJar( artifact.getFile().getAbsolutePath() );
}
}
else
{
if ( isShiftedArtifact( artifact ) )
{
// this is a blacklisted artifact that should be processed as a library instead
addLibraryJar( artifact.getFile().getAbsolutePath() );
}
}
}
}
/**
* Get the path to the proguard jar.
*
* @return
* @throws MojoExecutionException
*/
private String getProguardJarPath() throws MojoExecutionException
{
String proguardJarPath = getProguardJarPathFromDependencies();
if ( StringUtils.isEmpty( proguardJarPath ) )
{
File proguardJarPathFile = new File( getAndroidSdk().getToolsPath(), "proguard/lib/proguard.jar" );
return proguardJarPathFile.getAbsolutePath();
}
return proguardJarPath;
}
private String getProguardJarPathFromDependencies() throws MojoExecutionException
{
Artifact proguardArtifact = null;
int proguardArtifactDistance = -1;
for ( Artifact artifact : pluginDependencies )
{
getLog().debug( "pluginArtifact: " + artifact.getFile() );
if ( ( "proguard".equals( artifact.getArtifactId() ) ) || ( "proguard-base"
.equals( artifact.getArtifactId() ) ) )
{
int distance = artifact.getDependencyTrail().size();
getLog().debug( "proguard DependencyTrail: " + distance );
if ( proguardArtifactDistance == -1 )
{
proguardArtifact = artifact;
proguardArtifactDistance = distance;
}
else
{
if ( distance < proguardArtifactDistance )
{
proguardArtifact = artifact;
proguardArtifactDistance = distance;
}
}
}
}
if ( proguardArtifact != null )
{
getLog().debug( "proguardArtifact: " + proguardArtifact.getFile() );
return proguardArtifact.getFile().getAbsoluteFile().toString();
}
else
{
return null;
}
}
/**
* Get the default JVM arguments for the proguard invocation.
*
* @return
* @see #parsedJvmArguments
*/
private String[] getDefaultJvmArguments()
{
return new String[] { "-Xmx512M" };
}
/**
* Get the default ProGuard config files.
*
* @return
* @see #parsedConfigs
*/
private String[] getDefaultProguardConfigs()
{
return new String[0];
}
/**
* Get the default ProGuard options.
*
* @return
* @see #parsedOptions
*/
private String[] getDefaultProguardOptions()
{
return new String[0];
}
/**
* Finds a library file in either the primary or alternate lib directory.
* @param fileName The base name of the file.
* @return Either a canonical filename, or {@code null} if not found.
*/
private File getJVMLibrary( String fileName )
{
File libFile = new File( getJavaLibDir(), fileName );
if ( !libFile.exists() )
{
libFile = new File( getAltJavaLibDir(), fileName );
if ( !libFile.exists() )
{
libFile = null;
}
}
return libFile;
}
/**
* Determines the java.home directory.
* @return The java.home directory, as a File.
*/
private File getJavaHomeDir()
{
if ( javaHomeDir == null )
{
javaHomeDir = new File( System.getProperty( "java.home" ) );
}
return javaHomeDir;
}
/**
* Determines the primary JVM library location.
* @return The primary library directory, as a File.
*/
private File getJavaLibDir()
{
if ( javaLibDir == null )
{
javaLibDir = new File( getJavaHomeDir(), "lib" );
}
return javaLibDir;
}
/**
* Determines the alternate JVM library location (applies with older
* MacOSX JVMs).
* @return The alternate JVM library location, as a File.
*/
private File getAltJavaLibDir()
{
if ( altJavaLibDir == null )
{
altJavaLibDir = new File( getJavaHomeDir().getParent(), "Classes" );
}
return altJavaLibDir;
}
}
| false | true | private void executeProguard() throws MojoExecutionException
{
final File proguardDir = this.parsedOutputDirectory;
if ( !proguardDir.exists() && !proguardDir.mkdir() )
{
throw new MojoExecutionException( "Cannot create proguard output directory" );
}
else
{
if ( proguardDir.exists() && !proguardDir.isDirectory() )
{
throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List< String > commands = new ArrayList< String >();
collectJvmArguments( commands );
commands.add( "-jar" );
commands.add( parsedProguardJarPath );
commands.add( "@" + parsedConfig );
for ( String config : parsedConfigs )
{
commands.add( "@" + config );
}
if ( proguardFile != null )
{
commands.add( "@" + proguardFile.getAbsolutePath() );
}
collectInputFiles( commands );
commands.add( "-outjars" );
commands.add( "'\"" + obfuscatedJar + "\"'" );
commands.add( "-dump" );
commands.add( "'\"" + proguardDir + File.separator + "dump.txt\"'" );
commands.add( "-printseeds" );
commands.add( "'\"" + proguardDir + File.separator + "seeds.txt\"'" );
commands.add( "-printusage" );
commands.add( "'\"" + proguardDir + File.separator + "usage.txt\"'" );
File mapFile = new File( proguardDir, "mapping.txt" );
commands.add( "-printmapping" );
commands.add( "'\"" + mapFile + "\"'" );
commands.addAll( Arrays.asList( parsedOptions ) );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().info( javaExecutable + " " + commands.toString() );
try
{
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
if ( parsedAttachMap )
{
projectHelper.attachArtifact( project, "map", mapFile );
}
}
| private void executeProguard() throws MojoExecutionException
{
final File proguardDir = this.parsedOutputDirectory;
if ( !proguardDir.exists() && !proguardDir.mkdir() )
{
throw new MojoExecutionException( "Cannot create proguard output directory" );
}
else
{
if ( proguardDir.exists() && !proguardDir.isDirectory() )
{
throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List< String > commands = new ArrayList< String >();
collectJvmArguments( commands );
commands.add( "-jar" );
commands.add( parsedProguardJarPath );
commands.add( "@\"" + parsedConfig + "\"" );
for ( String config : parsedConfigs )
{
commands.add( "@\"" + config + "\"" );
}
if ( proguardFile != null )
{
commands.add( "@\"" + proguardFile.getAbsolutePath() + "\"" );
}
collectInputFiles( commands );
commands.add( "-outjars" );
commands.add( "'\"" + obfuscatedJar + "\"'" );
commands.add( "-dump" );
commands.add( "'\"" + proguardDir + File.separator + "dump.txt\"'" );
commands.add( "-printseeds" );
commands.add( "'\"" + proguardDir + File.separator + "seeds.txt\"'" );
commands.add( "-printusage" );
commands.add( "'\"" + proguardDir + File.separator + "usage.txt\"'" );
File mapFile = new File( proguardDir, "mapping.txt" );
commands.add( "-printmapping" );
commands.add( "'\"" + mapFile + "\"'" );
commands.addAll( Arrays.asList( parsedOptions ) );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().info( javaExecutable + " " + commands.toString() );
try
{
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
if ( parsedAttachMap )
{
projectHelper.attachArtifact( project, "map", mapFile );
}
}
|
diff --git a/src/netproj/skeleton/Link.java b/src/netproj/skeleton/Link.java
index 98ab3f2..345e284 100644
--- a/src/netproj/skeleton/Link.java
+++ b/src/netproj/skeleton/Link.java
@@ -1,219 +1,222 @@
package netproj.skeleton;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.*;
/**
* A Link that transmits packets to multiple devices in a network.
*
* The link has an output buffer that stores packets waiting to be transmitted. The link keeps track
* of the output buffer sizes of the senders to simulate output buffers at the senders. This should
* be transparent to anyone who is using this class at a higher level.
*
* Traffic is logged at {@code FINEST} level.
*
* @author emil
*/
public class Link {
private int bitsPerSec;
private int delayMs;
private long bitsSent; // for logging
private long lastReset; // for logging
private Queue<PacketDevicePair> buffer;
private List<Device> devices;
private PacketProcessor packetProcessor;
private static final Logger logger = Logger.getLogger(Link.class.getCanonicalName());
private String id;
/**
* Creates a link that transmits messages to multiple devices.
*
* @param bitsPerSec Bandwidth of the link in bits per second.
* @param delayMs Propagation delay in ms.
* @param devices List of devices that this link transmits to.
*/
public Link(int bitsPerSec, int delayMs, List<Device> devices) {
this.bitsPerSec = bitsPerSec;
this.delayMs = delayMs;
bitsSent = 0;
buffer = new ConcurrentLinkedQueue<PacketDevicePair>();
this.devices = new ArrayList<Device>(devices);
packetProcessor = new PacketProcessor();
}
public int getBitsPerSec() {
return bitsPerSec;
}
public void setBitsPerSec(int bitsPerSec) {
this.bitsPerSec = bitsPerSec;
}
public int getDelayMs() {
return delayMs;
}
public void setDelayMs(int delayMs) {
this.delayMs = delayMs;
}
/**
* Starts transmitting packets.
*
* Note that messages are still accepted in the buffer even before starting to transmit.
*/
public void start() {
packetProcessor.start();
}
/**
* Stops transmitting packets.
*
* Note that messages are left in the buffer.
*/
public void stop() {
packetProcessor.interrupt();
}
/**
* Lists all devices that this link transmits to.
*/
public List<Device> getDevices() {
synchronized (devices) {
return new ArrayList<Device>(devices);
}
}
/**
* Transmits {@code packet} to all devices on this link except {@code sender}.
*
* Puts the packet in the output buffer if there is enough space there and transmits it when
* its turn comes.
*/
public void sendMessage(Device sender, Packet packet) {
synchronized (sender) {
if (packet.getSizeInBits() + sender.getOutputBuffUsed() <= sender.getOutputBuffSize()) {
buffer.add(new PacketDevicePair(packet, sender));
sender.useOutputBuff(packet.getSizeInBits());
synchronized (buffer) {
buffer.notifyAll();
}
} else {
logger.finest("Packet " + packet.getPacketId() + " addressed to "
+ Integer.toHexString(packet.getDestAddress())
+ " dropped after " + Integer.toHexString(sender.getAddress()));
sender.recordDroppedPacket(packet);
}
}
}
public String toString() {
String ret = "-";
for(Device d : devices) {
ret += Integer.toHexString(d.getAddress()) + "-";
}
return ret;
}
public long getLastReset() {
return lastReset;
}
public long resetBitsSent() {
long temp = bitsSent;
bitsSent = 0;
lastReset = System.currentTimeMillis();
return temp;
}
/**
* Thread that transmits packets from the output buffer.
*
* This thread will wait on the buffer if there are no more packets to transmit, so it should be
* notified whenever a new packet arrives.
*
* @author emil
*/
private class PacketProcessor extends Thread {
/**
* Transmits any packets in the buffer and then waits for new ones.
*/
@Override
public void run() {
while (!this.isInterrupted()) {
try {
PacketDevicePair pdp = buffer.poll();
if (pdp != null) {
Packet packet = pdp.getMessage();
Device dev = pdp.getDevice();
// Free space in the sender's output buffer
synchronized (dev) {
dev.useOutputBuff(-packet.getSizeInBits());
}
// Wait for the packet to be transmitted over this link
synchronized (this) {
- wait(Math.max(1, 1000 * packet.getSizeInBits() / bitsPerSec));
+ long time = 1000 * packet.getSizeInBits() / bitsPerSec;
+ if (time > 0) {
+ wait(time);
+ }
}
packet.setPropDelayTime(delayMs);
bitsSent += packet.getSizeInBits();
// Put the packet in the input buffers of all devices on this link except
// the sender
synchronized (devices) {
for (Device device : devices) {
if (device != dev) {
device.receivePacket(packet);
}
}
}
} else {
// No packets are awaiting to be sent, so wait while the buffer is notified.
synchronized (buffer) {
buffer.wait();
}
}
} catch (InterruptedException e) {
logger.log(Level.WARNING, "Message processor for " + id + " was interrupted.",
e);
break;
}
}
}
}
/**
* A pair of a packet and a device.
*
* @author nathan
*/
private class PacketDevicePair {
private Packet packet;
private Device dev;
public PacketDevicePair(Packet packet, Device dev) {
this.packet = packet;
this.dev = dev;
}
public Packet getMessage() {
return packet;
}
public Device getDevice() {
return dev;
}
}
}
| true | true | public void run() {
while (!this.isInterrupted()) {
try {
PacketDevicePair pdp = buffer.poll();
if (pdp != null) {
Packet packet = pdp.getMessage();
Device dev = pdp.getDevice();
// Free space in the sender's output buffer
synchronized (dev) {
dev.useOutputBuff(-packet.getSizeInBits());
}
// Wait for the packet to be transmitted over this link
synchronized (this) {
wait(Math.max(1, 1000 * packet.getSizeInBits() / bitsPerSec));
}
packet.setPropDelayTime(delayMs);
bitsSent += packet.getSizeInBits();
// Put the packet in the input buffers of all devices on this link except
// the sender
synchronized (devices) {
for (Device device : devices) {
if (device != dev) {
device.receivePacket(packet);
}
}
}
} else {
// No packets are awaiting to be sent, so wait while the buffer is notified.
synchronized (buffer) {
buffer.wait();
}
}
} catch (InterruptedException e) {
logger.log(Level.WARNING, "Message processor for " + id + " was interrupted.",
e);
break;
}
}
}
| public void run() {
while (!this.isInterrupted()) {
try {
PacketDevicePair pdp = buffer.poll();
if (pdp != null) {
Packet packet = pdp.getMessage();
Device dev = pdp.getDevice();
// Free space in the sender's output buffer
synchronized (dev) {
dev.useOutputBuff(-packet.getSizeInBits());
}
// Wait for the packet to be transmitted over this link
synchronized (this) {
long time = 1000 * packet.getSizeInBits() / bitsPerSec;
if (time > 0) {
wait(time);
}
}
packet.setPropDelayTime(delayMs);
bitsSent += packet.getSizeInBits();
// Put the packet in the input buffers of all devices on this link except
// the sender
synchronized (devices) {
for (Device device : devices) {
if (device != dev) {
device.receivePacket(packet);
}
}
}
} else {
// No packets are awaiting to be sent, so wait while the buffer is notified.
synchronized (buffer) {
buffer.wait();
}
}
} catch (InterruptedException e) {
logger.log(Level.WARNING, "Message processor for " + id + " was interrupted.",
e);
break;
}
}
}
|
diff --git a/src/com/menny/android/anysoftkeyboard/keyboards/HebrewKeyboard.java b/src/com/menny/android/anysoftkeyboard/keyboards/HebrewKeyboard.java
index a8bc3801..33f89e9b 100755
--- a/src/com/menny/android/anysoftkeyboard/keyboards/HebrewKeyboard.java
+++ b/src/com/menny/android/anysoftkeyboard/keyboards/HebrewKeyboard.java
@@ -1,66 +1,68 @@
package com.menny.android.anysoftkeyboard.keyboards;
import android.view.KeyEvent;
import com.menny.android.anysoftkeyboard.AnyKeyboardContextProvider;
import com.menny.android.anysoftkeyboard.R;
import com.menny.android.anysoftkeyboard.Dictionary.Dictionary;
import com.menny.android.anysoftkeyboard.keyboards.AnyKeyboard.HardKeyboardTranslator;
public class HebrewKeyboard extends AnyKeyboard implements HardKeyboardTranslator
{
private static final HardKeyboardSequenceHandler msKeySequenceHandler;
static
{
msKeySequenceHandler = new HardKeyboardSequenceHandler();
msKeySequenceHandler.addQwertyTranslation("\u05e5\u05e3\u05e7\u05e8\u05d0\u05d8\u05d5\u05df\u05dd\u05e4\u05e9\u05d3\u05d2\u05db\u05e2\u05d9\u05d7\u05dc\u05da\u05d6\u05e1\u05d1\u05d4\u05e0\u05de\u05e6");
msKeySequenceHandler.addSequence(new int[]{KeyEvent.KEYCODE_COMMA}, '\u05ea');
}
public HebrewKeyboard(AnyKeyboardContextProvider context)
{
super(context, KeyboardFactory.HEBREW_KEYBOARD, R.xml.heb_qwerty, true, R.string.heb_keyboard, false, Dictionary.Language.Hebrew, R.drawable.he);
}
@Override
public boolean isLetter(char keyValue) {
//Hebrew also support "
return super.isLetter(keyValue) || (keyValue == '\"');
}
@Override
protected void setPopupKeyChars(Key aKey) {
if (aKey.codes[0] == 1513)
{
aKey.popupResId = R.xml.popup;
aKey.popupCharacters = "\u20aa";
}
else
super.setPopupKeyChars(aKey);
}
public void translatePhysicalCharacter(HardKeyboardAction action)
{
- if (action.isAltActive() && (action.getKeyCode() == KeyEvent.KEYCODE_COMMA))
+ if (action.isShiftActive() && (action.getKeyCode() == KeyEvent.KEYCODE_COMMA))
{
+ //see issue 129
//this is a special case - we support comma by giving
- //ALT+comma, since question itself is TET Hebrew letter.
+ //shift+comma, since question itself is TET Hebrew letter.
action.setNewKeyCode((char)',');
}
- else if (action.isShiftActive() && (action.getKeyCode() == KeyEvent.KEYCODE_COMMA))
+ else if (action.isAltActive() && (action.getKeyCode() == KeyEvent.KEYCODE_COMMA))
{
+ //see issue 129
//this is a special case - we support comma by giving
- //shift+comma, since question itself is TET Hebrew letter.
+ //alt+comma, since question itself is TET Hebrew letter.
action.setNewKeyCode((char)'?');
}
else if (action.isAltActive() && (action.getKeyCode() == KeyEvent.KEYCODE_A))
{//New Israeli Shekel (ALT+HEBREW SHIN) - issue 90
action.setNewKeyCode((char)'\u20aa');
}
else if ((!action.isAltActive()) && (!action.isShiftActive()))
{
final char translated = msKeySequenceHandler.getSequenceCharacter(action.getKeyCode(), getKeyboardContext());
if (translated != 0)
action.setNewKeyCode(translated);
}
}
}
| false | true | public void translatePhysicalCharacter(HardKeyboardAction action)
{
if (action.isAltActive() && (action.getKeyCode() == KeyEvent.KEYCODE_COMMA))
{
//this is a special case - we support comma by giving
//ALT+comma, since question itself is TET Hebrew letter.
action.setNewKeyCode((char)',');
}
else if (action.isShiftActive() && (action.getKeyCode() == KeyEvent.KEYCODE_COMMA))
{
//this is a special case - we support comma by giving
//shift+comma, since question itself is TET Hebrew letter.
action.setNewKeyCode((char)'?');
}
else if (action.isAltActive() && (action.getKeyCode() == KeyEvent.KEYCODE_A))
{//New Israeli Shekel (ALT+HEBREW SHIN) - issue 90
action.setNewKeyCode((char)'\u20aa');
}
else if ((!action.isAltActive()) && (!action.isShiftActive()))
{
final char translated = msKeySequenceHandler.getSequenceCharacter(action.getKeyCode(), getKeyboardContext());
if (translated != 0)
action.setNewKeyCode(translated);
}
}
| public void translatePhysicalCharacter(HardKeyboardAction action)
{
if (action.isShiftActive() && (action.getKeyCode() == KeyEvent.KEYCODE_COMMA))
{
//see issue 129
//this is a special case - we support comma by giving
//shift+comma, since question itself is TET Hebrew letter.
action.setNewKeyCode((char)',');
}
else if (action.isAltActive() && (action.getKeyCode() == KeyEvent.KEYCODE_COMMA))
{
//see issue 129
//this is a special case - we support comma by giving
//alt+comma, since question itself is TET Hebrew letter.
action.setNewKeyCode((char)'?');
}
else if (action.isAltActive() && (action.getKeyCode() == KeyEvent.KEYCODE_A))
{//New Israeli Shekel (ALT+HEBREW SHIN) - issue 90
action.setNewKeyCode((char)'\u20aa');
}
else if ((!action.isAltActive()) && (!action.isShiftActive()))
{
final char translated = msKeySequenceHandler.getSequenceCharacter(action.getKeyCode(), getKeyboardContext());
if (translated != 0)
action.setNewKeyCode(translated);
}
}
|
diff --git a/framework/src/org/apache/cordova/FileTransfer.java b/framework/src/org/apache/cordova/FileTransfer.java
index 0f285ae1..4accd55c 100644
--- a/framework/src/org/apache/cordova/FileTransfer.java
+++ b/framework/src/org/apache/cordova/FileTransfer.java
@@ -1,562 +1,564 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.util.Log;
import android.webkit.CookieManager;
public class FileTransfer extends Plugin {
private static final String LOG_TAG = "FileTransfer";
private static final String LINE_START = "--";
private static final String LINE_END = "\r\n";
private static final String BOUNDARY = "*****";
public static int FILE_NOT_FOUND_ERR = 1;
public static int INVALID_URL_ERR = 2;
public static int CONNECTION_ERR = 3;
private SSLSocketFactory defaultSSLSocketFactory = null;
private HostnameVerifier defaultHostnameVerifier = null;
/* (non-Javadoc)
* @see org.apache.cordova.api.Plugin#execute(java.lang.String, org.json.JSONArray, java.lang.String)
*/
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
String source = null;
String target = null;
try {
source = args.getString(0);
target = args.getString(1);
} catch (JSONException e) {
Log.d(LOG_TAG, "Missing source or target");
return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Missing source or target");
}
if (action.equals("upload")) {
return upload(source, target, args);
} else if (action.equals("download")) {
return download(source, target);
} else {
return new PluginResult(PluginResult.Status.INVALID_ACTION);
}
}
/**
* Uploads the specified file to the server URL provided using an HTTP multipart request.
* @param source Full path of the file on the file system
* @param target URL of the server to receive the file
* @param args JSON Array of args
*
* args[2] fileKey Name of file request parameter
* args[3] fileName File name to be used on server
* args[4] mimeType Describes file content type
* args[5] params key:value pairs of user-defined parameters
* @return FileUploadResult containing result of upload request
*/
private PluginResult upload(String source, String target, JSONArray args) {
Log.d(LOG_TAG, "upload " + source + " to " + target);
HttpURLConnection conn = null;
try {
// Setup the options
String fileKey = getArgument(args, 2, "file");
String fileName = getArgument(args, 3, "image.jpg");
String mimeType = getArgument(args, 4, "image/jpeg");
JSONObject params = args.optJSONObject(5);
if (params == null) params = new JSONObject();
boolean trustEveryone = args.optBoolean(6);
boolean chunkedMode = args.optBoolean(7) || args.isNull(7); //Always use chunked mode unless set to false as per API
Log.d(LOG_TAG, "fileKey: " + fileKey);
Log.d(LOG_TAG, "fileName: " + fileName);
Log.d(LOG_TAG, "mimeType: " + mimeType);
Log.d(LOG_TAG, "params: " + params);
Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
// Create return object
FileUploadResult result = new FileUploadResult();
// Get a input stream of the file on the phone
FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source);
DataOutputStream dos = null;
int bytesRead, bytesAvailable, bufferSize;
long totalBytes;
byte[] buffer;
int maxBufferSize = 8096;
//------------------ CLIENT REQUEST
// open a URL connection to the server
URL url = new URL(target);
// Open a HTTP connection to the URL based on protocol
if (url.getProtocol().toLowerCase().equals("https")) {
// Using standard HTTPS connection. Will not allow self signed certificate
if (!trustEveryone) {
conn = (HttpsURLConnection) url.openConnection();
}
// Use our HTTPS connection that blindly trusts everyone.
// This should only be used in debug environments
else {
// Setup the HTTPS connection class to trust everyone
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
// Save the current hostnameVerifier
defaultHostnameVerifier = https.getHostnameVerifier();
// Setup the connection not to verify hostnames
https.setHostnameVerifier(DO_NOT_VERIFY);
conn = https;
}
}
// Return a standard HTTP connection
else {
conn = (HttpURLConnection) url.openConnection();
}
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
// Handle the other headers
try {
JSONObject headers = params.getJSONObject("headers");
for (Iterator iter = headers.keys(); iter.hasNext();)
{
String headerKey = iter.next().toString();
conn.setRequestProperty(headerKey, headers.getString(headerKey));
}
} catch (JSONException e1) {
// No headers to be manipulated!
}
// Set the cookies on the response
String cookie = CookieManager.getInstance().getCookie(target);
if (cookie != null) {
conn.setRequestProperty("Cookie", cookie);
}
/*
* Store the non-file portions of the multipart data as a string, so that we can add it
* to the contentSize, since it is part of the body of the HTTP request.
*/
String extraParams = "";
try {
for (Iterator iter = params.keys(); iter.hasNext();) {
Object key = iter.next();
if(!String.valueOf(key).equals("headers"))
{
extraParams += LINE_START + BOUNDARY + LINE_END;
extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
extraParams += LINE_END + LINE_END;
extraParams += params.getString(key.toString());
extraParams += LINE_END;
}
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
extraParams += LINE_START + BOUNDARY + LINE_END;
extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";
+ byte[] extraBytes = extraParams.getBytes("UTF-8");
String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;
+ byte[] fileNameBytes = fileName.getBytes("UTF-8");
// Should set this up as an option
if (chunkedMode) {
conn.setChunkedStreamingMode(maxBufferSize);
}
else
{
- int stringLength = extraParams.length() + midParams.length() + tailParams.length() + fileName.getBytes("UTF-8").length;
+ int stringLength = extraBytes.length + midParams.length() + tailParams.length() + fileNameBytes.length;
Log.d(LOG_TAG, "String Length: " + stringLength);
int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
Log.d(LOG_TAG, "Content Length: " + fixedLength);
conn.setFixedLengthStreamingMode(fixedLength);
}
dos = new DataOutputStream( conn.getOutputStream() );
- dos.writeBytes(extraParams);
- //We don't want to chagne encoding, we just want this to write for all Unicode.
- dos.write(fileName.getBytes("UTF-8"));
+ //We don't want to change encoding, we just want this to write for all Unicode.
+ dos.write(extraBytes);
+ dos.write(fileNameBytes);
dos.writeBytes(midParams);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytes = 0;
while (bytesRead > 0) {
totalBytes += bytesRead;
result.setBytesSent(totalBytes);
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(tailParams);
// close streams
fileInputStream.close();
dos.flush();
dos.close();
//------------------ read the SERVER RESPONSE
StringBuffer responseString = new StringBuffer("");
DataInputStream inStream;
try {
inStream = new DataInputStream ( conn.getInputStream() );
} catch(FileNotFoundException e) {
Log.e(LOG_TAG, e.toString(), e);
throw new IOException("Received error from server");
}
String line;
while (( line = inStream.readLine()) != null) {
responseString.append(line);
}
Log.d(LOG_TAG, "got response from server");
Log.d(LOG_TAG, responseString.toString());
// send request and retrieve response
result.setResponseCode(conn.getResponseCode());
result.setResponse(responseString.toString());
inStream.close();
// Revert back to the proper verifier and socket factories
if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
}
Log.d(LOG_TAG, "****** About to return a result from upload");
return new PluginResult(PluginResult.Status.OK, result.toJSONObject());
} catch (FileNotFoundException e) {
JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (MalformedURLException e) {
JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (IOException e) {
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
} catch (Throwable t) {
// Shouldn't happen, but will
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
Log.wtf(LOG_TAG, error.toString(), t);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
// always verify the host - don't check for certificate
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
/**
* This function will install a trust manager that will blindly trust all SSL
* certificates. The reason this code is being added is to enable developers
* to do development using self signed SSL certificates on their web server.
*
* The standard HttpsURLConnection class will throw an exception on self
* signed certificates if this code is not run.
*/
private void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
// Install the all-trusting trust manager
try {
// Backup the current SSL socket factory
defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
// Install our all trusting manager
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
}
private JSONObject createFileTransferError(int errorCode, String source, String target, HttpURLConnection connection) {
Integer httpStatus = null;
if (connection != null) {
try {
httpStatus = connection.getResponseCode();
} catch (IOException e) {
Log.w(LOG_TAG, "Error getting HTTP status code from connection.", e);
}
}
return createFileTransferError(errorCode, source, target, httpStatus);
}
/**
* Create an error object based on the passed in errorCode
* @param errorCode the error
* @return JSONObject containing the error
*/
private JSONObject createFileTransferError(int errorCode, String source, String target, Integer httpStatus) {
JSONObject error = null;
try {
error = new JSONObject();
error.put("code", errorCode);
error.put("source", source);
error.put("target", target);
if (httpStatus != null) {
error.put("http_status", httpStatus);
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return error;
}
/**
* Convenience method to read a parameter from the list of JSON args.
* @param args the args passed to the Plugin
* @param position the position to retrieve the arg from
* @param defaultString the default to be used if the arg does not exist
* @return String with the retrieved value
*/
private String getArgument(JSONArray args, int position, String defaultString) {
String arg = defaultString;
if (args.length() >= position) {
arg = args.optString(position);
if (arg == null || "null".equals(arg)) {
arg = defaultString;
}
}
return arg;
}
/**
* Downloads a file form a given URL and saves it to the specified directory.
*
* @param source URL of the server to receive the file
* @param target Full path of the file on the file system
* @return JSONObject the downloaded file
*/
private PluginResult download(String source, String target) {
Log.d(LOG_TAG, "download " + source + " to " + target);
HttpURLConnection connection = null;
try {
File file = getFileFromPath(target);
// create needed directories
file.getParentFile().mkdirs();
// connect to server
if (webView.isUrlWhiteListed(source))
{
URL url = new URL(source);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//Add cookie support
String cookie = CookieManager.getInstance().getCookie(source);
if(cookie != null)
{
connection.setRequestProperty("cookie", cookie);
}
connection.connect();
Log.d(LOG_TAG, "Download file: " + url);
connection.connect();
Log.d(LOG_TAG, "Download file:" + url);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
FileOutputStream outputStream = new FileOutputStream(file);
// write bytes to file
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
Log.d(LOG_TAG, "Saved file: " + target);
// create FileEntry object
FileUtils fileUtil = new FileUtils();
JSONObject fileEntry = fileUtil.getEntry(file);
return new PluginResult(PluginResult.Status.OK, fileEntry);
}
else
{
Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, 401);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
}
} catch (FileNotFoundException e) {
JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (MalformedURLException e) {
JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, connection);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (Exception e) { // IOException, JSONException, NullPointer
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Get an input stream based on file path or content:// uri
*
* @param path foo
* @return an input stream
* @throws FileNotFoundException
*/
private InputStream getPathFromUri(String path) throws FileNotFoundException {
if (path.startsWith("content:")) {
Uri uri = Uri.parse(path);
return ctx.getActivity().getContentResolver().openInputStream(uri);
}
else if (path.startsWith("file://")) {
int question = path.indexOf("?");
if (question == -1) {
return new FileInputStream(path.substring(7));
} else {
return new FileInputStream(path.substring(7, question));
}
}
else {
return new FileInputStream(path);
}
}
/**
* Get a File object from the passed in path
*
* @param path file path
* @return file object
*/
private File getFileFromPath(String path) throws FileNotFoundException {
File file;
String prefix = "file://";
if (path.startsWith(prefix)) {
file = new File(path.substring(prefix.length()));
} else {
file = new File(path);
}
if (file.getParent() == null) {
throw new FileNotFoundException();
}
return file;
}
}
| false | true | private PluginResult upload(String source, String target, JSONArray args) {
Log.d(LOG_TAG, "upload " + source + " to " + target);
HttpURLConnection conn = null;
try {
// Setup the options
String fileKey = getArgument(args, 2, "file");
String fileName = getArgument(args, 3, "image.jpg");
String mimeType = getArgument(args, 4, "image/jpeg");
JSONObject params = args.optJSONObject(5);
if (params == null) params = new JSONObject();
boolean trustEveryone = args.optBoolean(6);
boolean chunkedMode = args.optBoolean(7) || args.isNull(7); //Always use chunked mode unless set to false as per API
Log.d(LOG_TAG, "fileKey: " + fileKey);
Log.d(LOG_TAG, "fileName: " + fileName);
Log.d(LOG_TAG, "mimeType: " + mimeType);
Log.d(LOG_TAG, "params: " + params);
Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
// Create return object
FileUploadResult result = new FileUploadResult();
// Get a input stream of the file on the phone
FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source);
DataOutputStream dos = null;
int bytesRead, bytesAvailable, bufferSize;
long totalBytes;
byte[] buffer;
int maxBufferSize = 8096;
//------------------ CLIENT REQUEST
// open a URL connection to the server
URL url = new URL(target);
// Open a HTTP connection to the URL based on protocol
if (url.getProtocol().toLowerCase().equals("https")) {
// Using standard HTTPS connection. Will not allow self signed certificate
if (!trustEveryone) {
conn = (HttpsURLConnection) url.openConnection();
}
// Use our HTTPS connection that blindly trusts everyone.
// This should only be used in debug environments
else {
// Setup the HTTPS connection class to trust everyone
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
// Save the current hostnameVerifier
defaultHostnameVerifier = https.getHostnameVerifier();
// Setup the connection not to verify hostnames
https.setHostnameVerifier(DO_NOT_VERIFY);
conn = https;
}
}
// Return a standard HTTP connection
else {
conn = (HttpURLConnection) url.openConnection();
}
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
// Handle the other headers
try {
JSONObject headers = params.getJSONObject("headers");
for (Iterator iter = headers.keys(); iter.hasNext();)
{
String headerKey = iter.next().toString();
conn.setRequestProperty(headerKey, headers.getString(headerKey));
}
} catch (JSONException e1) {
// No headers to be manipulated!
}
// Set the cookies on the response
String cookie = CookieManager.getInstance().getCookie(target);
if (cookie != null) {
conn.setRequestProperty("Cookie", cookie);
}
/*
* Store the non-file portions of the multipart data as a string, so that we can add it
* to the contentSize, since it is part of the body of the HTTP request.
*/
String extraParams = "";
try {
for (Iterator iter = params.keys(); iter.hasNext();) {
Object key = iter.next();
if(!String.valueOf(key).equals("headers"))
{
extraParams += LINE_START + BOUNDARY + LINE_END;
extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
extraParams += LINE_END + LINE_END;
extraParams += params.getString(key.toString());
extraParams += LINE_END;
}
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
extraParams += LINE_START + BOUNDARY + LINE_END;
extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";
String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;
// Should set this up as an option
if (chunkedMode) {
conn.setChunkedStreamingMode(maxBufferSize);
}
else
{
int stringLength = extraParams.length() + midParams.length() + tailParams.length() + fileName.getBytes("UTF-8").length;
Log.d(LOG_TAG, "String Length: " + stringLength);
int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
Log.d(LOG_TAG, "Content Length: " + fixedLength);
conn.setFixedLengthStreamingMode(fixedLength);
}
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(extraParams);
//We don't want to chagne encoding, we just want this to write for all Unicode.
dos.write(fileName.getBytes("UTF-8"));
dos.writeBytes(midParams);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytes = 0;
while (bytesRead > 0) {
totalBytes += bytesRead;
result.setBytesSent(totalBytes);
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(tailParams);
// close streams
fileInputStream.close();
dos.flush();
dos.close();
//------------------ read the SERVER RESPONSE
StringBuffer responseString = new StringBuffer("");
DataInputStream inStream;
try {
inStream = new DataInputStream ( conn.getInputStream() );
} catch(FileNotFoundException e) {
Log.e(LOG_TAG, e.toString(), e);
throw new IOException("Received error from server");
}
String line;
while (( line = inStream.readLine()) != null) {
responseString.append(line);
}
Log.d(LOG_TAG, "got response from server");
Log.d(LOG_TAG, responseString.toString());
// send request and retrieve response
result.setResponseCode(conn.getResponseCode());
result.setResponse(responseString.toString());
inStream.close();
// Revert back to the proper verifier and socket factories
if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
}
Log.d(LOG_TAG, "****** About to return a result from upload");
return new PluginResult(PluginResult.Status.OK, result.toJSONObject());
} catch (FileNotFoundException e) {
JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (MalformedURLException e) {
JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (IOException e) {
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
} catch (Throwable t) {
// Shouldn't happen, but will
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
Log.wtf(LOG_TAG, error.toString(), t);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
| private PluginResult upload(String source, String target, JSONArray args) {
Log.d(LOG_TAG, "upload " + source + " to " + target);
HttpURLConnection conn = null;
try {
// Setup the options
String fileKey = getArgument(args, 2, "file");
String fileName = getArgument(args, 3, "image.jpg");
String mimeType = getArgument(args, 4, "image/jpeg");
JSONObject params = args.optJSONObject(5);
if (params == null) params = new JSONObject();
boolean trustEveryone = args.optBoolean(6);
boolean chunkedMode = args.optBoolean(7) || args.isNull(7); //Always use chunked mode unless set to false as per API
Log.d(LOG_TAG, "fileKey: " + fileKey);
Log.d(LOG_TAG, "fileName: " + fileName);
Log.d(LOG_TAG, "mimeType: " + mimeType);
Log.d(LOG_TAG, "params: " + params);
Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
// Create return object
FileUploadResult result = new FileUploadResult();
// Get a input stream of the file on the phone
FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source);
DataOutputStream dos = null;
int bytesRead, bytesAvailable, bufferSize;
long totalBytes;
byte[] buffer;
int maxBufferSize = 8096;
//------------------ CLIENT REQUEST
// open a URL connection to the server
URL url = new URL(target);
// Open a HTTP connection to the URL based on protocol
if (url.getProtocol().toLowerCase().equals("https")) {
// Using standard HTTPS connection. Will not allow self signed certificate
if (!trustEveryone) {
conn = (HttpsURLConnection) url.openConnection();
}
// Use our HTTPS connection that blindly trusts everyone.
// This should only be used in debug environments
else {
// Setup the HTTPS connection class to trust everyone
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
// Save the current hostnameVerifier
defaultHostnameVerifier = https.getHostnameVerifier();
// Setup the connection not to verify hostnames
https.setHostnameVerifier(DO_NOT_VERIFY);
conn = https;
}
}
// Return a standard HTTP connection
else {
conn = (HttpURLConnection) url.openConnection();
}
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
// Handle the other headers
try {
JSONObject headers = params.getJSONObject("headers");
for (Iterator iter = headers.keys(); iter.hasNext();)
{
String headerKey = iter.next().toString();
conn.setRequestProperty(headerKey, headers.getString(headerKey));
}
} catch (JSONException e1) {
// No headers to be manipulated!
}
// Set the cookies on the response
String cookie = CookieManager.getInstance().getCookie(target);
if (cookie != null) {
conn.setRequestProperty("Cookie", cookie);
}
/*
* Store the non-file portions of the multipart data as a string, so that we can add it
* to the contentSize, since it is part of the body of the HTTP request.
*/
String extraParams = "";
try {
for (Iterator iter = params.keys(); iter.hasNext();) {
Object key = iter.next();
if(!String.valueOf(key).equals("headers"))
{
extraParams += LINE_START + BOUNDARY + LINE_END;
extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
extraParams += LINE_END + LINE_END;
extraParams += params.getString(key.toString());
extraParams += LINE_END;
}
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
extraParams += LINE_START + BOUNDARY + LINE_END;
extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";
byte[] extraBytes = extraParams.getBytes("UTF-8");
String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;
byte[] fileNameBytes = fileName.getBytes("UTF-8");
// Should set this up as an option
if (chunkedMode) {
conn.setChunkedStreamingMode(maxBufferSize);
}
else
{
int stringLength = extraBytes.length + midParams.length() + tailParams.length() + fileNameBytes.length;
Log.d(LOG_TAG, "String Length: " + stringLength);
int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
Log.d(LOG_TAG, "Content Length: " + fixedLength);
conn.setFixedLengthStreamingMode(fixedLength);
}
dos = new DataOutputStream( conn.getOutputStream() );
//We don't want to change encoding, we just want this to write for all Unicode.
dos.write(extraBytes);
dos.write(fileNameBytes);
dos.writeBytes(midParams);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytes = 0;
while (bytesRead > 0) {
totalBytes += bytesRead;
result.setBytesSent(totalBytes);
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(tailParams);
// close streams
fileInputStream.close();
dos.flush();
dos.close();
//------------------ read the SERVER RESPONSE
StringBuffer responseString = new StringBuffer("");
DataInputStream inStream;
try {
inStream = new DataInputStream ( conn.getInputStream() );
} catch(FileNotFoundException e) {
Log.e(LOG_TAG, e.toString(), e);
throw new IOException("Received error from server");
}
String line;
while (( line = inStream.readLine()) != null) {
responseString.append(line);
}
Log.d(LOG_TAG, "got response from server");
Log.d(LOG_TAG, responseString.toString());
// send request and retrieve response
result.setResponseCode(conn.getResponseCode());
result.setResponse(responseString.toString());
inStream.close();
// Revert back to the proper verifier and socket factories
if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
}
Log.d(LOG_TAG, "****** About to return a result from upload");
return new PluginResult(PluginResult.Status.OK, result.toJSONObject());
} catch (FileNotFoundException e) {
JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (MalformedURLException e) {
JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (IOException e) {
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
} catch (Throwable t) {
// Shouldn't happen, but will
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
Log.wtf(LOG_TAG, error.toString(), t);
return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
|
diff --git a/src/org/opensaml/xml/security/credential/criteria/EvaluableX509SubjectKeyIdentifierCredentialCriteria.java b/src/org/opensaml/xml/security/credential/criteria/EvaluableX509SubjectKeyIdentifierCredentialCriteria.java
index 5a9c883..e2dc8ea 100644
--- a/src/org/opensaml/xml/security/credential/criteria/EvaluableX509SubjectKeyIdentifierCredentialCriteria.java
+++ b/src/org/opensaml/xml/security/credential/criteria/EvaluableX509SubjectKeyIdentifierCredentialCriteria.java
@@ -1,97 +1,97 @@
/*
* Copyright [2007] [University Corporation for Advanced Internet Development, Inc.]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensaml.xml.security.credential.criteria;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import org.apache.log4j.Logger;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.security.x509.X509Credential;
import org.opensaml.xml.security.x509.X509SubjectKeyIdentifierCriteria;
import org.opensaml.xml.security.x509.X509Util;
/**
* Instance of evaluable credential criteria for evaluating whether a credential's certificate contains a particular
* subject key identifier.
*/
public class EvaluableX509SubjectKeyIdentifierCredentialCriteria implements EvaluableCredentialCriteria {
/** Logger. */
private static Logger log = Logger.getLogger(EvaluableX509SubjectKeyIdentifierCredentialCriteria.class);
/** Base criteria. */
private byte[] ski;
/**
* Constructor.
*
* @param criteria the criteria which is the basis for evaluation
*/
public EvaluableX509SubjectKeyIdentifierCredentialCriteria(X509SubjectKeyIdentifierCriteria criteria) {
if (criteria == null) {
throw new NullPointerException("Criteria instance may not be null");
}
ski = criteria.getSubjectKeyIdentifier();
}
/**
* Constructor.
*
* @param newSKI the criteria value which is the basis for evaluation
*/
public EvaluableX509SubjectKeyIdentifierCredentialCriteria(byte[] newSKI) {
if (newSKI == null || newSKI.length == 0) {
throw new IllegalArgumentException("Subject key identifier may not be null or empty");
}
ski = newSKI;
}
/** {@inheritDoc} */
public Boolean evaluate(Credential target) {
if (target == null) {
log.error("Credential target was null");
return null;
}
if (! (target instanceof X509Credential)) {
- log.info("Credential is not an X509Credential, does not satisfy issuer name and serial number criteria");
+ log.info("Credential is not an X509Credential, does not satisfy subject key identifier criteria");
return Boolean.FALSE;
}
X509Credential x509Cred = (X509Credential) target;
X509Certificate entityCert = x509Cred.getEntityCertificate();
if (entityCert == null) {
log.info("X509Credential did not contain an entity certificate, does not satisfy criteria");
return Boolean.FALSE;
}
byte[] credSKI = X509Util.getSubjectKeyIdentifier(entityCert);
if (credSKI == null || credSKI.length == 0) {
log.info("Could not evaluate criteria, certificate contained no subject key identifier extension");
return null;
}
Boolean result = Arrays.equals(ski, credSKI);
if (log.isDebugEnabled()) {
//TODO find hex-encoder to make SKI byte[] values more readable
log.debug(String.format("Evaluation of credential data '%s' against criteria data '%s' was: '%s'",
credSKI.toString(), ski.toString(), result));
}
return result;
}
}
| true | true | public Boolean evaluate(Credential target) {
if (target == null) {
log.error("Credential target was null");
return null;
}
if (! (target instanceof X509Credential)) {
log.info("Credential is not an X509Credential, does not satisfy issuer name and serial number criteria");
return Boolean.FALSE;
}
X509Credential x509Cred = (X509Credential) target;
X509Certificate entityCert = x509Cred.getEntityCertificate();
if (entityCert == null) {
log.info("X509Credential did not contain an entity certificate, does not satisfy criteria");
return Boolean.FALSE;
}
byte[] credSKI = X509Util.getSubjectKeyIdentifier(entityCert);
if (credSKI == null || credSKI.length == 0) {
log.info("Could not evaluate criteria, certificate contained no subject key identifier extension");
return null;
}
Boolean result = Arrays.equals(ski, credSKI);
if (log.isDebugEnabled()) {
//TODO find hex-encoder to make SKI byte[] values more readable
log.debug(String.format("Evaluation of credential data '%s' against criteria data '%s' was: '%s'",
credSKI.toString(), ski.toString(), result));
}
return result;
}
| public Boolean evaluate(Credential target) {
if (target == null) {
log.error("Credential target was null");
return null;
}
if (! (target instanceof X509Credential)) {
log.info("Credential is not an X509Credential, does not satisfy subject key identifier criteria");
return Boolean.FALSE;
}
X509Credential x509Cred = (X509Credential) target;
X509Certificate entityCert = x509Cred.getEntityCertificate();
if (entityCert == null) {
log.info("X509Credential did not contain an entity certificate, does not satisfy criteria");
return Boolean.FALSE;
}
byte[] credSKI = X509Util.getSubjectKeyIdentifier(entityCert);
if (credSKI == null || credSKI.length == 0) {
log.info("Could not evaluate criteria, certificate contained no subject key identifier extension");
return null;
}
Boolean result = Arrays.equals(ski, credSKI);
if (log.isDebugEnabled()) {
//TODO find hex-encoder to make SKI byte[] values more readable
log.debug(String.format("Evaluation of credential data '%s' against criteria data '%s' was: '%s'",
credSKI.toString(), ski.toString(), result));
}
return result;
}
|
diff --git a/src/com/jpii/navalbattle/game/turn/Player.java b/src/com/jpii/navalbattle/game/turn/Player.java
index 3c4cc1fb..a77c0e6e 100644
--- a/src/com/jpii/navalbattle/game/turn/Player.java
+++ b/src/com/jpii/navalbattle/game/turn/Player.java
@@ -1,130 +1,131 @@
package com.jpii.navalbattle.game.turn;
import java.util.ArrayList;
import com.jpii.navalbattle.game.NavalGame;
import com.jpii.navalbattle.game.entity.MoveableEntity;
import com.jpii.navalbattle.pavo.grid.Entity;
public class Player {
ArrayList<Entity> entities;
public String name;
protected boolean turnOver;
int score;
byte color;
int playernumber;
public Player(String name){
entities = new ArrayList<Entity>();
this.name = name;
turnOver = false;
score = 0;
}
public void setPlayerNumber(int pnum){
playernumber = pnum;
}
public void setTeamColor(byte b){
color = b;
}
public void startTurn(){
}
public void takeTurn(){
reset();
}
public void endTurn(){
}
public void reset(){
resetMovement();
resetAttack();
NavalGame.getHud().update();
}
public void resetMovement(){
for (int index =0; index<entities.size(); index++){
Entity e1 = entities.get(index);
if(e1.getHandle()%10 == 1){
MoveableEntity e = (MoveableEntity) e1;
e.resetMovement();
}
}
}
public void resetAttack(){
for (int index =0; index<entities.size(); index++){
Entity e1 = entities.get(index);
if(e1.getHandle()%10 == 1){
MoveableEntity e = (MoveableEntity) e1;
e.resetAttack();
}
}
}
public boolean myEntity(Entity e){
return entities.contains(e);
}
public void addEntity(Entity e){
entities.add(e);
e.setTeamColor(color);
}
public Entity getEntity(int index) {
return entities.get(index);
}
public boolean isTurnOver(){
return turnOver;
}
public int getTotalEntities() {
return entities.size();
}
public void addscore(int add){
score +=add;
}
public void setscore(int set){
score = set;
}
public void subtractscore(int sub){
score -=sub;
}
public int getScore(){
return score;
}
public void removeEntity(Entity e){
while(entities.remove(e))
;
}
public void nextEntity(Entity e){
Entity temp = null;
if(e==null){
temp = entities.get(0);
}
else{
if(entities.contains(e)){
- temp = entities.get(entities.indexOf(e));
+ temp = entities.get(entities.indexOf(e)+1);
}
else{
entities.get(0);
}
}
if(temp == null)
return;
temp.getManager().getWorld().animatedSetLoc(temp.getLocation(),0.054392019f);
+ NavalGame.getHud().setEntity(temp);
}
}
| false | true | public void nextEntity(Entity e){
Entity temp = null;
if(e==null){
temp = entities.get(0);
}
else{
if(entities.contains(e)){
temp = entities.get(entities.indexOf(e));
}
else{
entities.get(0);
}
}
if(temp == null)
return;
temp.getManager().getWorld().animatedSetLoc(temp.getLocation(),0.054392019f);
}
| public void nextEntity(Entity e){
Entity temp = null;
if(e==null){
temp = entities.get(0);
}
else{
if(entities.contains(e)){
temp = entities.get(entities.indexOf(e)+1);
}
else{
entities.get(0);
}
}
if(temp == null)
return;
temp.getManager().getWorld().animatedSetLoc(temp.getLocation(),0.054392019f);
NavalGame.getHud().setEntity(temp);
}
|
diff --git a/framework/src/play/mvc/ActionInvoker.java b/framework/src/play/mvc/ActionInvoker.java
index 816f38f4..e9ff9fc7 100644
--- a/framework/src/play/mvc/ActionInvoker.java
+++ b/framework/src/play/mvc/ActionInvoker.java
@@ -1,478 +1,478 @@
package play.mvc;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import play.Logger;
import play.Play;
import play.PlayPlugin;
import play.cache.CacheFor;
import play.classloading.enhancers.ControllersEnhancer.ControllerInstrumentation;
import play.classloading.enhancers.ControllersEnhancer.ControllerSupport;
import play.data.binding.Binder;
import play.data.parsing.UrlEncodedParser;
import play.data.validation.Validation;
import play.exceptions.ActionNotFoundException;
import play.exceptions.JavaExecutionException;
import play.exceptions.PlayException;
import play.exceptions.UnexpectedException;
import play.i18n.Lang;
import play.mvc.Router.Route;
import play.mvc.results.NoResult;
import play.mvc.results.NotFound;
import play.mvc.results.Result;
import play.utils.Java;
import play.utils.Utils;
import com.jamonapi.Monitor;
import com.jamonapi.MonitorFactory;
/**
* Invoke an action after an HTTP request.
*/
public class ActionInvoker {
@SuppressWarnings("unchecked")
public static void invoke(Http.Request request, Http.Response response) {
Monitor monitor = null;
try {
if (!Play.started) {
return;
}
Http.Request.current.set(request);
Http.Response.current.set(response);
Scope.Params.current.set(request.params);
Scope.RenderArgs.current.set(new Scope.RenderArgs());
Scope.RouteArgs.current.set(new Scope.RouteArgs());
Scope.Session.current.set(Scope.Session.restore());
Scope.Flash.current.set(Scope.Flash.restore());
// 1. Route and resolve format if not already done
if (request.action == null) {
for (PlayPlugin plugin : Play.plugins) {
plugin.routeRequest(request);
}
Route route = Router.route(request);
for (PlayPlugin plugin : Play.plugins) {
plugin.onRequestRouting(route);
}
}
request.resolveFormat();
// 2. Find the action method
Method actionMethod = null;
try {
Object[] ca = getActionMethod(request.action);
actionMethod = (Method) ca[1];
request.controller = ((Class) ca[0]).getName().substring(12).replace("$", "");
request.controllerClass = ((Class) ca[0]);
request.actionMethod = actionMethod.getName();
request.action = request.controller + "." + request.actionMethod;
request.invokedMethod = actionMethod;
} catch (ActionNotFoundException e) {
Logger.error(e, "%s action not found", e.getAction());
throw new NotFound(String.format("%s action not found", e.getAction()));
}
Logger.trace("------- %s", actionMethod);
// 3. Prepare request params
Scope.Params.current().__mergeWith(request.routeArgs);
// add parameters from the URI query string
Scope.Params.current()._mergeWith(UrlEncodedParser.parseQueryString(new ByteArrayInputStream(request.querystring.getBytes("utf-8"))));
Lang.resolvefrom(request);
// 4. Easy debugging ...
if (Play.mode == Play.Mode.DEV) {
Controller.class.getDeclaredField("params").set(null, Scope.Params.current());
Controller.class.getDeclaredField("request").set(null, Http.Request.current());
Controller.class.getDeclaredField("response").set(null, Http.Response.current());
Controller.class.getDeclaredField("session").set(null, Scope.Session.current());
Controller.class.getDeclaredField("flash").set(null, Scope.Flash.current());
Controller.class.getDeclaredField("renderArgs").set(null, Scope.RenderArgs.current());
Controller.class.getDeclaredField("routeArgs").set(null, Scope.RouteArgs.current());
Controller.class.getDeclaredField("validation").set(null, Validation.current());
}
ControllerInstrumentation.stopActionCall();
for (PlayPlugin plugin : Play.plugins) {
plugin.beforeActionInvocation(actionMethod);
}
// Monitoring
monitor = MonitorFactory.start(request.action + "()");
// 5. Invoke the action
// There is a difference between a get and a post when binding data. The get does not care about validation while
// the post does.
try {
// @Before
List<Method> befores = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Before.class);
Collections.sort(befores, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Before before1 = m1.getAnnotation(Before.class);
Before before2 = m2.getAnnotation(Before.class);
return before1.priority() - before2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method before : befores) {
String[] unless = before.getAnnotation(Before.class).unless();
String[] only = before.getAnnotation(Before.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
before.setAccessible(true);
inferResult(invokeControllerMethod(before));
}
}
// Action
Result actionResult = null;
String cacheKey = "actioncache:" + request.action + ":" + request.querystring;
// Check the cache (only for GET or HEAD)
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
actionResult = (Result) play.cache.Cache.get(cacheKey);
}
if (actionResult == null) {
ControllerInstrumentation.initActionCall();
try {
inferResult(invokeControllerMethod(actionMethod));
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
actionResult = (Result) ex.getTargetException();
// Cache it if needed
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
play.cache.Cache.set(cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
}
} else {
// @Catch
Object[] args = new Object[]{ex.getTargetException()};
List<Method> catches = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Catch.class);
Collections.sort(catches, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Catch catch1 = m1.getAnnotation(Catch.class);
Catch catch2 = m2.getAnnotation(Catch.class);
return catch1.priority() - catch2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method mCatch : catches) {
Class[] exceptions = mCatch.getAnnotation(Catch.class).value();
if (exceptions.length == 0) {
exceptions = new Class[]{Exception.class};
}
for (Class exception : exceptions) {
if (exception.isInstance(args[0])) {
mCatch.setAccessible(true);
inferResult(invokeControllerMethod(mCatch, args));
break;
}
}
}
throw ex;
}
}
}
// @After
List<Method> afters = Java.findAllAnnotatedMethods(Controller.getControllerClass(), After.class);
Collections.sort(afters, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
After after1 = m1.getAnnotation(After.class);
After after2 = m2.getAnnotation(After.class);
return after1.priority() - after2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method after : afters) {
String[] unless = after.getAnnotation(After.class).unless();
String[] only = after.getAnnotation(After.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
after.setAccessible(true);
inferResult(invokeControllerMethod(after));
}
}
monitor.stop();
monitor = null;
// OK, re-throw the original action result
if (actionResult != null) {
throw actionResult;
}
throw new NoResult();
} catch (IllegalAccessException ex) {
throw ex;
} catch (IllegalArgumentException ex) {
throw ex;
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
throw (Result) ex.getTargetException();
}
// Re-throw the enclosed exception
if (ex.getTargetException() instanceof PlayException) {
throw (PlayException) ex.getTargetException();
}
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
}
} catch (Result result) {
for (PlayPlugin plugin : Play.plugins) {
plugin.onActionInvocationResult(result);
}
// OK there is a result to apply
// Save session & flash scope now
Scope.Session.current().save();
Scope.Flash.current().save();
result.apply(request, response);
for (PlayPlugin plugin : Play.plugins) {
plugin.afterActionInvocation();
}
// @Finally
if (Controller.getControllerClass() != null) {
try {
List<Method> allFinally = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Finally.class);
Collections.sort(allFinally, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Finally finally1 = m1.getAnnotation(Finally.class);
Finally finally2 = m2.getAnnotation(Finally.class);
return finally1.priority() - finally2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method aFinally : allFinally) {
String[] unless = aFinally.getAnnotation(Finally.class).unless();
String[] only = aFinally.getAnnotation(Finally.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
aFinally.setAccessible(true);
- invokeControllerMethod(aFinally, new Object[0]);
+ invokeControllerMethod(aFinally, null);
}
}
} catch (InvocationTargetException ex) {
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
} catch (Exception e) {
throw new UnexpectedException("Exception while doing @Finally", e);
}
}
} catch (PlayException e) {
throw e;
} catch (Exception e) {
throw new UnexpectedException(e);
} finally {
if (monitor != null) {
monitor.stop();
}
}
}
@SuppressWarnings("unchecked")
public static void inferResult(Object o) {
// Return type inference
if (o != null) {
if (o instanceof NoResult) {
return;
}
if (o instanceof Result) {
// Of course
throw (Result)o;
}
if (o instanceof InputStream) {
Controller.renderBinary((InputStream) o);
}
if (o instanceof File) {
Controller.renderBinary((File) o);
}
if (o instanceof Map) {
Controller.renderTemplate((Map<String, Object>) o);
}
if (o instanceof Object[]) {
Controller.render(o);
}
Controller.renderHtml(o);
}
}
public static Object invokeControllerMethod(Method method) throws Exception {
return invokeControllerMethod(method, null);
}
public static Object invokeControllerMethod(Method method, Object[] forceArgs) throws Exception {
if (Modifier.isStatic(method.getModifiers()) && !method.getDeclaringClass().getName().matches("^controllers\\..*\\$class$")) {
return method.invoke(null, forceArgs == null ? getActionMethodArgs(method, null) : forceArgs);
} else if (Modifier.isStatic(method.getModifiers())) {
Object[] args = getActionMethodArgs(method, null);
args[0] = Http.Request.current().controllerClass.getDeclaredField("MODULE$").get(null);
return method.invoke(null, args);
} else {
Object instance = null;
try {
instance = method.getDeclaringClass().getDeclaredField("MODULE$").get(null);
} catch (Exception e) {
throw new ActionNotFoundException(Http.Request.current().action, e);
}
return method.invoke(instance, forceArgs == null ? getActionMethodArgs(method, instance) : forceArgs);
}
}
public static Object[] getActionMethod(String fullAction) {
Method actionMethod = null;
Class controllerClass = null;
try {
if (!fullAction.startsWith("controllers.")) {
fullAction = "controllers." + fullAction;
}
String controller = fullAction.substring(0, fullAction.lastIndexOf("."));
String action = fullAction.substring(fullAction.lastIndexOf(".") + 1);
controllerClass = Play.classloader.getClassIgnoreCase(controller);
if (controllerClass == null) {
throw new ActionNotFoundException(fullAction, new Exception("Controller " + controller + " not found"));
}
if (!ControllerSupport.class.isAssignableFrom(controllerClass)) {
// Try the scala way
controllerClass = Play.classloader.getClassIgnoreCase(controller + "$");
if (!ControllerSupport.class.isAssignableFrom(controllerClass)) {
throw new ActionNotFoundException(fullAction, new Exception("class " + controller + " does not extend play.mvc.Controller"));
}
}
actionMethod = Java.findActionMethod(action, controllerClass);
if (actionMethod == null) {
throw new ActionNotFoundException(fullAction, new Exception("No method public static void " + action + "() was found in class " + controller));
}
} catch (PlayException e) {
throw e;
} catch (Exception e) {
throw new ActionNotFoundException(fullAction, e);
}
return new Object[]{controllerClass, actionMethod};
}
public static Object[] getActionMethodArgs(Method method, Object o) throws Exception {
String[] paramsNames = Java.parameterNames(method);
if (paramsNames == null && method.getParameterTypes().length > 0) {
throw new UnexpectedException("Parameter names not found for method " + method);
}
Object[] rArgs = new Object[method.getParameterTypes().length];
for (int i = 0; i < method.getParameterTypes().length; i++) {
Class<?> type = method.getParameterTypes()[i];
Map<String, String[]> params = new HashMap<String, String[]>();
if (type.equals(String.class) || Number.class.isAssignableFrom(type) || type.isPrimitive()) {
params.put(paramsNames[i], Scope.Params.current().getAll(paramsNames[i]));
} else {
params.putAll(Scope.Params.current().all());
}
Logger.trace("getActionMethodArgs name [" + paramsNames[i] + "] annotation [" + Utils.join(method.getParameterAnnotations()[i], " ") + "]");
rArgs[i] = Binder.bind(paramsNames[i], method.getParameterTypes()[i], method.getGenericParameterTypes()[i], method.getParameterAnnotations()[i], params, o, method, i + 1);
}
return rArgs;
}
}
| true | true | public static void invoke(Http.Request request, Http.Response response) {
Monitor monitor = null;
try {
if (!Play.started) {
return;
}
Http.Request.current.set(request);
Http.Response.current.set(response);
Scope.Params.current.set(request.params);
Scope.RenderArgs.current.set(new Scope.RenderArgs());
Scope.RouteArgs.current.set(new Scope.RouteArgs());
Scope.Session.current.set(Scope.Session.restore());
Scope.Flash.current.set(Scope.Flash.restore());
// 1. Route and resolve format if not already done
if (request.action == null) {
for (PlayPlugin plugin : Play.plugins) {
plugin.routeRequest(request);
}
Route route = Router.route(request);
for (PlayPlugin plugin : Play.plugins) {
plugin.onRequestRouting(route);
}
}
request.resolveFormat();
// 2. Find the action method
Method actionMethod = null;
try {
Object[] ca = getActionMethod(request.action);
actionMethod = (Method) ca[1];
request.controller = ((Class) ca[0]).getName().substring(12).replace("$", "");
request.controllerClass = ((Class) ca[0]);
request.actionMethod = actionMethod.getName();
request.action = request.controller + "." + request.actionMethod;
request.invokedMethod = actionMethod;
} catch (ActionNotFoundException e) {
Logger.error(e, "%s action not found", e.getAction());
throw new NotFound(String.format("%s action not found", e.getAction()));
}
Logger.trace("------- %s", actionMethod);
// 3. Prepare request params
Scope.Params.current().__mergeWith(request.routeArgs);
// add parameters from the URI query string
Scope.Params.current()._mergeWith(UrlEncodedParser.parseQueryString(new ByteArrayInputStream(request.querystring.getBytes("utf-8"))));
Lang.resolvefrom(request);
// 4. Easy debugging ...
if (Play.mode == Play.Mode.DEV) {
Controller.class.getDeclaredField("params").set(null, Scope.Params.current());
Controller.class.getDeclaredField("request").set(null, Http.Request.current());
Controller.class.getDeclaredField("response").set(null, Http.Response.current());
Controller.class.getDeclaredField("session").set(null, Scope.Session.current());
Controller.class.getDeclaredField("flash").set(null, Scope.Flash.current());
Controller.class.getDeclaredField("renderArgs").set(null, Scope.RenderArgs.current());
Controller.class.getDeclaredField("routeArgs").set(null, Scope.RouteArgs.current());
Controller.class.getDeclaredField("validation").set(null, Validation.current());
}
ControllerInstrumentation.stopActionCall();
for (PlayPlugin plugin : Play.plugins) {
plugin.beforeActionInvocation(actionMethod);
}
// Monitoring
monitor = MonitorFactory.start(request.action + "()");
// 5. Invoke the action
// There is a difference between a get and a post when binding data. The get does not care about validation while
// the post does.
try {
// @Before
List<Method> befores = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Before.class);
Collections.sort(befores, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Before before1 = m1.getAnnotation(Before.class);
Before before2 = m2.getAnnotation(Before.class);
return before1.priority() - before2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method before : befores) {
String[] unless = before.getAnnotation(Before.class).unless();
String[] only = before.getAnnotation(Before.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
before.setAccessible(true);
inferResult(invokeControllerMethod(before));
}
}
// Action
Result actionResult = null;
String cacheKey = "actioncache:" + request.action + ":" + request.querystring;
// Check the cache (only for GET or HEAD)
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
actionResult = (Result) play.cache.Cache.get(cacheKey);
}
if (actionResult == null) {
ControllerInstrumentation.initActionCall();
try {
inferResult(invokeControllerMethod(actionMethod));
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
actionResult = (Result) ex.getTargetException();
// Cache it if needed
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
play.cache.Cache.set(cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
}
} else {
// @Catch
Object[] args = new Object[]{ex.getTargetException()};
List<Method> catches = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Catch.class);
Collections.sort(catches, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Catch catch1 = m1.getAnnotation(Catch.class);
Catch catch2 = m2.getAnnotation(Catch.class);
return catch1.priority() - catch2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method mCatch : catches) {
Class[] exceptions = mCatch.getAnnotation(Catch.class).value();
if (exceptions.length == 0) {
exceptions = new Class[]{Exception.class};
}
for (Class exception : exceptions) {
if (exception.isInstance(args[0])) {
mCatch.setAccessible(true);
inferResult(invokeControllerMethod(mCatch, args));
break;
}
}
}
throw ex;
}
}
}
// @After
List<Method> afters = Java.findAllAnnotatedMethods(Controller.getControllerClass(), After.class);
Collections.sort(afters, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
After after1 = m1.getAnnotation(After.class);
After after2 = m2.getAnnotation(After.class);
return after1.priority() - after2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method after : afters) {
String[] unless = after.getAnnotation(After.class).unless();
String[] only = after.getAnnotation(After.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
after.setAccessible(true);
inferResult(invokeControllerMethod(after));
}
}
monitor.stop();
monitor = null;
// OK, re-throw the original action result
if (actionResult != null) {
throw actionResult;
}
throw new NoResult();
} catch (IllegalAccessException ex) {
throw ex;
} catch (IllegalArgumentException ex) {
throw ex;
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
throw (Result) ex.getTargetException();
}
// Re-throw the enclosed exception
if (ex.getTargetException() instanceof PlayException) {
throw (PlayException) ex.getTargetException();
}
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
}
} catch (Result result) {
for (PlayPlugin plugin : Play.plugins) {
plugin.onActionInvocationResult(result);
}
// OK there is a result to apply
// Save session & flash scope now
Scope.Session.current().save();
Scope.Flash.current().save();
result.apply(request, response);
for (PlayPlugin plugin : Play.plugins) {
plugin.afterActionInvocation();
}
// @Finally
if (Controller.getControllerClass() != null) {
try {
List<Method> allFinally = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Finally.class);
Collections.sort(allFinally, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Finally finally1 = m1.getAnnotation(Finally.class);
Finally finally2 = m2.getAnnotation(Finally.class);
return finally1.priority() - finally2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method aFinally : allFinally) {
String[] unless = aFinally.getAnnotation(Finally.class).unless();
String[] only = aFinally.getAnnotation(Finally.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
aFinally.setAccessible(true);
invokeControllerMethod(aFinally, new Object[0]);
}
}
} catch (InvocationTargetException ex) {
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
} catch (Exception e) {
throw new UnexpectedException("Exception while doing @Finally", e);
}
}
} catch (PlayException e) {
throw e;
} catch (Exception e) {
throw new UnexpectedException(e);
} finally {
if (monitor != null) {
monitor.stop();
}
}
}
| public static void invoke(Http.Request request, Http.Response response) {
Monitor monitor = null;
try {
if (!Play.started) {
return;
}
Http.Request.current.set(request);
Http.Response.current.set(response);
Scope.Params.current.set(request.params);
Scope.RenderArgs.current.set(new Scope.RenderArgs());
Scope.RouteArgs.current.set(new Scope.RouteArgs());
Scope.Session.current.set(Scope.Session.restore());
Scope.Flash.current.set(Scope.Flash.restore());
// 1. Route and resolve format if not already done
if (request.action == null) {
for (PlayPlugin plugin : Play.plugins) {
plugin.routeRequest(request);
}
Route route = Router.route(request);
for (PlayPlugin plugin : Play.plugins) {
plugin.onRequestRouting(route);
}
}
request.resolveFormat();
// 2. Find the action method
Method actionMethod = null;
try {
Object[] ca = getActionMethod(request.action);
actionMethod = (Method) ca[1];
request.controller = ((Class) ca[0]).getName().substring(12).replace("$", "");
request.controllerClass = ((Class) ca[0]);
request.actionMethod = actionMethod.getName();
request.action = request.controller + "." + request.actionMethod;
request.invokedMethod = actionMethod;
} catch (ActionNotFoundException e) {
Logger.error(e, "%s action not found", e.getAction());
throw new NotFound(String.format("%s action not found", e.getAction()));
}
Logger.trace("------- %s", actionMethod);
// 3. Prepare request params
Scope.Params.current().__mergeWith(request.routeArgs);
// add parameters from the URI query string
Scope.Params.current()._mergeWith(UrlEncodedParser.parseQueryString(new ByteArrayInputStream(request.querystring.getBytes("utf-8"))));
Lang.resolvefrom(request);
// 4. Easy debugging ...
if (Play.mode == Play.Mode.DEV) {
Controller.class.getDeclaredField("params").set(null, Scope.Params.current());
Controller.class.getDeclaredField("request").set(null, Http.Request.current());
Controller.class.getDeclaredField("response").set(null, Http.Response.current());
Controller.class.getDeclaredField("session").set(null, Scope.Session.current());
Controller.class.getDeclaredField("flash").set(null, Scope.Flash.current());
Controller.class.getDeclaredField("renderArgs").set(null, Scope.RenderArgs.current());
Controller.class.getDeclaredField("routeArgs").set(null, Scope.RouteArgs.current());
Controller.class.getDeclaredField("validation").set(null, Validation.current());
}
ControllerInstrumentation.stopActionCall();
for (PlayPlugin plugin : Play.plugins) {
plugin.beforeActionInvocation(actionMethod);
}
// Monitoring
monitor = MonitorFactory.start(request.action + "()");
// 5. Invoke the action
// There is a difference between a get and a post when binding data. The get does not care about validation while
// the post does.
try {
// @Before
List<Method> befores = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Before.class);
Collections.sort(befores, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Before before1 = m1.getAnnotation(Before.class);
Before before2 = m2.getAnnotation(Before.class);
return before1.priority() - before2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method before : befores) {
String[] unless = before.getAnnotation(Before.class).unless();
String[] only = before.getAnnotation(Before.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = before.getDeclaringClass().getName().substring(12).replace("$", "") + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
before.setAccessible(true);
inferResult(invokeControllerMethod(before));
}
}
// Action
Result actionResult = null;
String cacheKey = "actioncache:" + request.action + ":" + request.querystring;
// Check the cache (only for GET or HEAD)
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
actionResult = (Result) play.cache.Cache.get(cacheKey);
}
if (actionResult == null) {
ControllerInstrumentation.initActionCall();
try {
inferResult(invokeControllerMethod(actionMethod));
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
actionResult = (Result) ex.getTargetException();
// Cache it if needed
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
play.cache.Cache.set(cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
}
} else {
// @Catch
Object[] args = new Object[]{ex.getTargetException()};
List<Method> catches = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Catch.class);
Collections.sort(catches, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Catch catch1 = m1.getAnnotation(Catch.class);
Catch catch2 = m2.getAnnotation(Catch.class);
return catch1.priority() - catch2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method mCatch : catches) {
Class[] exceptions = mCatch.getAnnotation(Catch.class).value();
if (exceptions.length == 0) {
exceptions = new Class[]{Exception.class};
}
for (Class exception : exceptions) {
if (exception.isInstance(args[0])) {
mCatch.setAccessible(true);
inferResult(invokeControllerMethod(mCatch, args));
break;
}
}
}
throw ex;
}
}
}
// @After
List<Method> afters = Java.findAllAnnotatedMethods(Controller.getControllerClass(), After.class);
Collections.sort(afters, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
After after1 = m1.getAnnotation(After.class);
After after2 = m2.getAnnotation(After.class);
return after1.priority() - after2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method after : afters) {
String[] unless = after.getAnnotation(After.class).unless();
String[] only = after.getAnnotation(After.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = after.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
after.setAccessible(true);
inferResult(invokeControllerMethod(after));
}
}
monitor.stop();
monitor = null;
// OK, re-throw the original action result
if (actionResult != null) {
throw actionResult;
}
throw new NoResult();
} catch (IllegalAccessException ex) {
throw ex;
} catch (IllegalArgumentException ex) {
throw ex;
} catch (InvocationTargetException ex) {
// It's a Result ? (expected)
if (ex.getTargetException() instanceof Result) {
throw (Result) ex.getTargetException();
}
// Re-throw the enclosed exception
if (ex.getTargetException() instanceof PlayException) {
throw (PlayException) ex.getTargetException();
}
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
}
} catch (Result result) {
for (PlayPlugin plugin : Play.plugins) {
plugin.onActionInvocationResult(result);
}
// OK there is a result to apply
// Save session & flash scope now
Scope.Session.current().save();
Scope.Flash.current().save();
result.apply(request, response);
for (PlayPlugin plugin : Play.plugins) {
plugin.afterActionInvocation();
}
// @Finally
if (Controller.getControllerClass() != null) {
try {
List<Method> allFinally = Java.findAllAnnotatedMethods(Controller.getControllerClass(), Finally.class);
Collections.sort(allFinally, new Comparator<Method>() {
public int compare(Method m1, Method m2) {
Finally finally1 = m1.getAnnotation(Finally.class);
Finally finally2 = m2.getAnnotation(Finally.class);
return finally1.priority() - finally2.priority();
}
});
ControllerInstrumentation.stopActionCall();
for (Method aFinally : allFinally) {
String[] unless = aFinally.getAnnotation(Finally.class).unless();
String[] only = aFinally.getAnnotation(Finally.class).only();
boolean skip = false;
for (String un : only) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = false;
break;
} else {
skip = true;
}
}
for (String un : unless) {
if (!un.contains(".")) {
un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
}
if (un.equals(request.action)) {
skip = true;
break;
}
}
if (!skip) {
aFinally.setAccessible(true);
invokeControllerMethod(aFinally, null);
}
}
} catch (InvocationTargetException ex) {
StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex.getTargetException());
if (element != null) {
throw new JavaExecutionException(Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber(), ex.getTargetException());
}
throw new JavaExecutionException(Http.Request.current().action, ex);
} catch (Exception e) {
throw new UnexpectedException("Exception while doing @Finally", e);
}
}
} catch (PlayException e) {
throw e;
} catch (Exception e) {
throw new UnexpectedException(e);
} finally {
if (monitor != null) {
monitor.stop();
}
}
}
|
diff --git a/simulator/src/main/java/net/sourceforge/cilib/simulator/Main.java b/simulator/src/main/java/net/sourceforge/cilib/simulator/Main.java
index d3adebda..c71fa408 100644
--- a/simulator/src/main/java/net/sourceforge/cilib/simulator/Main.java
+++ b/simulator/src/main/java/net/sourceforge/cilib/simulator/Main.java
@@ -1,53 +1,54 @@
/**
* Computational Intelligence Library (CIlib)
* Copyright (C) 2003 - 2010
* Computational Intelligence Research Group (CIRG@UP)
* Department of Computer Science
* University of Pretoria
* South Africa
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
package net.sourceforge.cilib.simulator;
import java.io.File;
import java.util.List;
import net.sourceforge.cilib.algorithm.ProgressListener;
/**
* This is the entry point for the CIlib simulator. This class accepts one
* command line parameter, which is the name of the XML config file to parse.
*
*/
public final class Main {
private Main() {
throw new UnsupportedOperationException("Cannot instantiate.");
}
/**
* Main entry point for the simulator.
* @param args provided arguments.
*/
public static void main(String[] args) {
- if (args.length < 1) {
- throw new IllegalArgumentException("Please provide the correct arguments.\nUsage: Simulator <simulation-config.xml> [-textprogress|-guiprogress]");
+ if (args.length != 1) {
+ System.out.println("Please provide the correct arguments.\nUsage: Simulator <simulation-config.xml>");
+ System.exit(1);
}
final List<Simulator> simulators = SimulatorShell.prepare(new File(args[0]));
ProgressListener progress = new ProgressText(simulators.size());
SimulatorShell.execute(simulators, progress);
}
}
| true | true | public static void main(String[] args) {
if (args.length < 1) {
throw new IllegalArgumentException("Please provide the correct arguments.\nUsage: Simulator <simulation-config.xml> [-textprogress|-guiprogress]");
}
final List<Simulator> simulators = SimulatorShell.prepare(new File(args[0]));
ProgressListener progress = new ProgressText(simulators.size());
SimulatorShell.execute(simulators, progress);
}
| public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Please provide the correct arguments.\nUsage: Simulator <simulation-config.xml>");
System.exit(1);
}
final List<Simulator> simulators = SimulatorShell.prepare(new File(args[0]));
ProgressListener progress = new ProgressText(simulators.size());
SimulatorShell.execute(simulators, progress);
}
|
diff --git a/yamcs-core/src/main/java/org/yamcs/xtce/SpreadsheetLoader.java b/yamcs-core/src/main/java/org/yamcs/xtce/SpreadsheetLoader.java
index 227e09d1d..2e5f196a7 100644
--- a/yamcs-core/src/main/java/org/yamcs/xtce/SpreadsheetLoader.java
+++ b/yamcs-core/src/main/java/org/yamcs/xtce/SpreadsheetLoader.java
@@ -1,1020 +1,1020 @@
package org.yamcs.xtce;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteOrder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.ConfigurationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jxl.Cell;
import jxl.CellType;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.yamcs.xtce.AlarmRanges;
import org.yamcs.xtce.BaseDataType;
import org.yamcs.xtce.BinaryDataEncoding;
import org.yamcs.xtce.BinaryParameterType;
import org.yamcs.xtce.Calibrator;
import org.yamcs.xtce.Comparison;
import org.yamcs.xtce.ComparisonList;
import org.yamcs.xtce.ContainerEntry;
import org.yamcs.xtce.DataEncoding;
import org.yamcs.xtce.DynamicIntegerValue;
import org.yamcs.xtce.EnumeratedParameterType;
import org.yamcs.xtce.FixedIntegerValue;
import org.yamcs.xtce.FloatDataEncoding;
import org.yamcs.xtce.FloatParameterType;
import org.yamcs.xtce.FloatRange;
import org.yamcs.xtce.IntegerDataEncoding;
import org.yamcs.xtce.IntegerParameterType;
import org.yamcs.xtce.NameReference.ResolvedAction;
import org.yamcs.xtce.NumericContextAlarm;
import org.yamcs.xtce.Parameter;
import org.yamcs.xtce.ParameterEntry;
import org.yamcs.xtce.ParameterInstanceRef;
import org.yamcs.xtce.ParameterType;
import org.yamcs.xtce.PolynomialCalibrator;
import org.yamcs.xtce.Repeat;
import org.yamcs.xtce.SequenceContainer;
import org.yamcs.xtce.SequenceEntry;
import org.yamcs.xtce.SplineCalibrator;
import org.yamcs.xtce.SplinePoint;
import org.yamcs.xtce.StringDataEncoding;
import org.yamcs.xtce.StringParameterType;
import org.yamcs.xtce.NameReference.Type;
import org.yamcs.xtce.SequenceEntry.ReferenceLocationType;
import org.yamcs.xtce.xml.XtceAliasSet;
/**
* This class loads database from excel spreadsheets. Used for the Solar instruments for which the TM
* database is too complicated to store in the MDB.
*
* @author nm, ddw
*
*/
public class SpreadsheetLoader implements SpaceSystemLoader {
HashMap<String,Calibrator> calibrators = new HashMap<String, Calibrator>();
HashMap<String,ArrayList<LimitDef>> limits = new HashMap<String,ArrayList<LimitDef>>();
HashMap<String,EnumeratedParameterType> enumerations = new HashMap<String, EnumeratedParameterType>();
HashMap<String,Parameter> parameters = new HashMap<String, Parameter>();
//columns in the parameters sheet
final static int IDX_PARAM_OPSNAME=0;
final static int IDX_PARAM_BITLENGTH=1;
final static int IDX_PARAM_RAWTYPE=2;
final static int IDX_PARAM_ENGTYPE=3;
final static int IDX_PARAM_ENGUNIT=4;
final static int IDX_PARAM_CALIBRATION=5;
final static int IDX_PARAM_LOWWARNILIMIT=6;
final static int IDX_PARAM_HIGHWARNILIMIT=7;
final static int IDX_PARAM_LOWCRITICALLIMIT=8;
final static int IDX_PARAM_HIGHCRITICALLIMIT=9;
final static int IDX_PARAM_PATH=10;
//columns in the containers sheet
final static int IDX_CONT_NAME=0;
final static int IDX_CONT_PARENT=1;
final static int IDX_CONT_CONDITION=2;
final static int IDX_CONT_FLAGS=3;
final static int IDX_CONT_PARA_NAME=4;
final static int IDX_CONT_RELPOS=5;
final static int IDX_CONT_SIZEINBITS=6;
final static int IDX_CONT_EXPECTED_INTERVAL=7;
//columns in calibrations sheet
final static int IDX_CALIB_NAME=0;
final static int IDX_CALIB_TYPE=1;
final static int IDX_CALIB_CALIB1=2;
final static int IDX_CALIB_CALIB2=3;
// Increment major when breaking backward compatibility, increment minor when making backward compatible changes
final static String FORMAT_VERSION="2.1";
// Explicitly support these versions (i.e. load without warning)
final static String[] FORMAT_VERSIONS_SUPPORTED = new String[]{ "1.6", "1.7", "2.0", FORMAT_VERSION };
Workbook workbook;
String opsnamePrefix;
String configName, path;
SpaceSystem spaceSystem;
static Logger log=LoggerFactory.getLogger(SpreadsheetLoader.class.getName());
/*
* configSection is the name under which this config appears in the database
*/
public SpreadsheetLoader(String filename ) throws ConfigurationException {
this.configName = new File(filename).getName();
path = filename;
}
@Override
public String getConfigName(){
return configName;
}
@Override
public SpaceSystem load() throws ConfigurationException, DatabaseLoadException {
log.info("Loading spreadsheet " + path);
try {
// Given path may be relative, so use absolute path to report issues
File ssFile = new File( path );
if( !ssFile.exists() ) throw new FileNotFoundException( ssFile.getAbsolutePath() );
workbook = Workbook.getWorkbook( ssFile );
loadGeneral();
loadCalibrators();
loadLimitsSheet();
loadParameters();
loadContainers();
} catch (BiffException e) {
throw new DatabaseLoadException(e);
} catch (IOException e) {
throw new DatabaseLoadException(e);
}
return spaceSystem;
}
@Override
public boolean needsUpdate(RandomAccessFile consistencyDateFile) throws IOException, ConfigurationException {
String line;
while((line=consistencyDateFile.readLine())!=null) {
if(line.startsWith(configName)) {
File f=new File(path);
if(!f.exists()) throw new ConfigurationException("The file "+f.getAbsolutePath()+" doesn't exist");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/DDD HH:mm:ss");
try {
Date serializedDate=sdf.parse(line.substring(configName.length()+1));
if(serializedDate.getTime()>=f.lastModified()) {
log.info("Serialized excel database "+configName+" is up to date.");
return false;
} else {
log.info("Serialized excel database "+configName+" is NOT up to date: serializedDate="+serializedDate+" mdbConsistencyDate="+new Date(f.lastModified()));
return true;
}
} catch (ParseException e) {
log.warn("can not parse the date from "+line+": ", e);
return true;
}
}
}
log.info("Could not find a line starting with 'MDB' in the consistency date file");
return true;
}
@Override
public void writeConsistencyDate(FileWriter consistencyDateFile) throws IOException {
File f=new File(path);
consistencyDateFile.write(configName+" "+(new SimpleDateFormat("yyyy/DDD HH:mm:ss")).format(f.lastModified())+"\n");
}
private void loadGeneral() throws ConfigurationException{
Sheet gen_sheet = workbook.getSheet("General");
Cell[] cells = gen_sheet.getRow(1);
// Version check
String version=cells[0].getContents();
// Specific versions supported
boolean supported = false;
for( String supportedVersion:FORMAT_VERSIONS_SUPPORTED ) {
if( version.equals( supportedVersion ) ) {
supported = true;
}
}
// If not explicitly supported, check major version number...
if( !supported ) {
String sheetCompatVersion = version.substring( 0, version.indexOf('.') );
String loaderCompatVersion = FORMAT_VERSION.substring( 0, FORMAT_VERSION.indexOf('.'));
supported = loaderCompatVersion.equals( sheetCompatVersion );
// If major version number matches, but minor number differs
if( supported && !FORMAT_VERSION.equals( version ) ) {
log.info( String.format( "Some spreadsheet features for '%s' may not be supported by this loader: Spreadsheet version (%s) differs from loader supported version (%s)", configName, version, FORMAT_VERSION ) );
}
}
if( !supported ) {
throw new ConfigurationException( String.format( "Spreadsheet '%s' format version (%s) not supported by loader version (%s)", configName, version, FORMAT_VERSION ) );
}
// Check we have a name
String name = cells[1].getContents();
if( "".equals( name ) ) {
throw new ConfigurationException( String.format( "Must provide a name in cell B:2 in spreadsheet '%s'", configName ) );
}
spaceSystem=new SpaceSystem(name);
// Add a header
Header header = new Header();
spaceSystem.setHeader( header );
if( cells.length >= 3 ) {
header.setVersion( cells[2].getContents() );
}
try {
File wbf = new File( path );
Date d = new Date( wbf.lastModified() );
String date = (new SimpleDateFormat("yyyy/DDD HH:mm:ss")).format( d );
header.setDate( date );
} catch ( Exception e ) {
// Ignore
}
// Opsname prefix is optional
if( cells.length >= 4 ) {
opsnamePrefix=cells[3].getContents();
} else {
opsnamePrefix="";
log.info( "No opsnamePrefix specified for {}", configName );
}
}
private void loadCalibrators() {
//read the calibrations
Sheet cal_sheet = workbook.getSheet("Calibration");
double[] pol_coef = null;
// SplinePoint = pointpair
ArrayList<SplinePoint>spline = null;
EnumeratedParameterType enumeration = null;
// start at 1 to not use the first line (= title line)
int start = 1;
while(true) {
// we first search for a row containing (= starting) a new calibration
while (start < cal_sheet.getRows()) {
Cell[] cells = cal_sheet.getRow(start);
if ((cells.length > 0) && (cells[0].getContents().length() > 0) && !cells[0].getContents().startsWith("#")) {
break;
}
start++;
}
if (start >= cal_sheet.getRows()) {
break;
}
Cell[] cells = cal_sheet.getRow(start);
String name = cells[IDX_CALIB_NAME].getContents();
String type = cells[IDX_CALIB_TYPE].getContents();
// now we search for the matching last row of that calibration
int end = start + 1;
while (end < cal_sheet.getRows()) {
cells = cal_sheet.getRow(end);
if (!hasColumn(cells, IDX_CALIB_CALIB1)) {
break;
}
end++;
}
if ("enumeration".equalsIgnoreCase(type)) {
enumeration = new EnumeratedParameterType(name);
} else if ("polynomial".equalsIgnoreCase(type)) {
pol_coef = new double[end - start];
} else if ("pointpair".equalsIgnoreCase(type)) {
spline = new ArrayList<SplinePoint>();
} else {
error("Calibration:"+(start+1)+" calibration type '"+type+"' not supported. Supported types: enumeration, polynomial and pointpair");
}
for (int j = start; j < end; j++) {
try {
cells = cal_sheet.getRow(j);
if ("enumeration".equalsIgnoreCase(type)) {
try {
long raw=Integer.decode(cells[IDX_CALIB_CALIB1].getContents());
enumeration.addEnumerationValue(raw, cells[IDX_CALIB_CALIB2].getContents());
} catch(NumberFormatException e) {
error("Can't get integer from raw value out of '"+cells[IDX_CALIB_CALIB1].getContents()+"' for Calibration sheet, line "+(j+1));
}
} else if ("polynomial".equalsIgnoreCase(type)) {
pol_coef[j - start] = getNumber(cells[IDX_CALIB_CALIB1]);
} else if ("pointpair".equalsIgnoreCase(type)) {
spline.add(new SplinePoint(getNumber(cells[IDX_CALIB_CALIB1]), getNumber(cells[IDX_CALIB_CALIB2])));
}
} catch(RuntimeException e) {
log.error("Exception caught when reading line "+(j+1)+" from "+path);
throw e;
}
}
if ("enumeration".equalsIgnoreCase(type)) {
enumerations.put(name, enumeration);
} else if ("polynomial".equalsIgnoreCase(type)) {
calibrators.put(name, new PolynomialCalibrator(pol_coef));
} else if ("pointpair".equalsIgnoreCase(type)) {
calibrators.put(name, new SplineCalibrator(spline));
}
start = end;
}
//System.out.println("enumerations: " + enumerations + "\n");
//System.out.println("calibrators: " + calibrators + "\n");
}
private double getNumber(Cell cell) {
if((cell.getType()==CellType.NUMBER) || (cell.getType()==CellType.NUMBER_FORMULA)) {
return ((NumberCell) cell).getValue();
} else {
return Double.parseDouble(cell.getContents());
}
}
/**
* If there is a sheet with the Limits, load it now!
*/
private void loadLimitsSheet() {
//read the calibrations
Sheet cal_sheet = workbook.getSheet("Limits");
if(cal_sheet==null)return;
// start at 1 to not use the first line (= title line)
int start = 1;
while(true) {
// we first search for a row containing (= starting) a new calibration
while (start < cal_sheet.getRows()) {
Cell[] cells = cal_sheet.getRow(start);
if ((cells.length > 0) && (cells[0].getContents().length() > 0)) {
break;
}
start++;
}
if (start >= cal_sheet.getRows()) {
break;
}
Cell[] cells = cal_sheet.getRow(start);
String name = cells[0].getContents();
// now we search for the matching last row of the limit
int end = start + 1;
while (end < cal_sheet.getRows()) {
cells = cal_sheet.getRow(end);
if (isRowEmpty(cells) || (cells[0].getContents().length() != 0)) {
break;
}
end++;
}
for (int j = start; j < end; j++) {
try {
cells = cal_sheet.getRow(j);
String condition=cells[1].getContents();
if(condition.length()==0) condition=null;
String mins=(cells.length>2)?cells[2].getContents():"";
String maxs=(cells.length>3)?cells[3].getContents():"";
double min=(mins.length()>0)?Double.parseDouble(mins): Double.NEGATIVE_INFINITY;
double max=(maxs.length()>0)?Double.parseDouble(maxs): Double.POSITIVE_INFINITY;
FloatRange range=new FloatRange(min,max);
AlarmRanges ranges=new AlarmRanges();
ranges.warningRange=range;
ArrayList<LimitDef> al=limits.get(name);
if(al==null) {
al=new ArrayList<LimitDef>();
limits.put(name, al);
}
al.add(new LimitDef(condition,ranges));
} catch(RuntimeException e) {
log.error("Exception caught when reading line "+(j+1)+" from "+path);
throw e;
}
}
ArrayList<LimitDef> al=limits.get(name);
if((al==null)||(al.size()==0)) {
log.warn("Limit definition '"+name+"' on line "+start+" contains no range; Limit ignored");
limits.remove(name);
} else if(!limits.containsKey(name) && al.size()>1) {
log.warn("Limit definition '"+name+"' on line "+start+" contains more than one range but has no condition; Limit ignored");
}
start = end;
}
//System.out.println("enumerations: " + enumerations + "\n");
//System.out.println("calibrators: " + calibrators + "\n");
}
private boolean isRowEmpty(Cell[] cells) {
for(int i=0;i<cells.length;i++)
if(cells[i].getContents().length()>0) return false;
return true;
}
private void loadParameters() {
Sheet para_sheet = workbook.getSheet("Parameters");
for (int i = 1; i < para_sheet.getRows(); i++) {
Cell[] cells = para_sheet.getRow(i);
if ((cells == null) || (cells.length < 4) || cells[0].getContents().startsWith("#")) {
continue;
}
String name = cells[IDX_PARAM_OPSNAME].getContents();
if (name.length() == 0) {
continue;
}
//String path = cells[IDX_MEAS_PATH].getContents();
String rawtype = cells[IDX_PARAM_RAWTYPE].getContents();
if("DerivedValue".equalsIgnoreCase(rawtype)) continue;
int bitlength=-1;
try {
String bitls=cells[IDX_PARAM_BITLENGTH].getContents();
if(!bitls.isEmpty()) bitlength = Integer.decode(bitls);
} catch(NumberFormatException e) {
error("Parameters:"+(i+1)+": can't get bitlength out of '"+cells[IDX_PARAM_BITLENGTH].getContents()+"'");
}
String engtype = cells[IDX_PARAM_ENGTYPE].getContents();
String calib=null;
if(cells.length>IDX_PARAM_CALIBRATION) calib = cells[IDX_PARAM_CALIBRATION].getContents();
if("n".equals(calib) || "".equals(calib))calib=null;
if("y".equalsIgnoreCase(calib)) calib=name;
ParameterType ptype=null;
if ("uint".equalsIgnoreCase(engtype)) {
ptype = new IntegerParameterType(name);
((IntegerParameterType)ptype).signed = false;
} else if ("int".equalsIgnoreCase(engtype)) {
ptype = new IntegerParameterType(name);
} else if ("float".equalsIgnoreCase(engtype)) {
ptype = new FloatParameterType(name);
} else if ("enumerated".equalsIgnoreCase(engtype)) {
if(calib==null) {
error("parameter " + name + " has to have an enumeration");
}
ptype = enumerations.get(calib);
if (ptype == null) {
error("parameter " + name + " is supposed to have an enumeration '" + calib + "' but the enumeration does not exist");
}
} else if ("string".equalsIgnoreCase(engtype)) {
ptype = new StringParameterType(name);
} else if ("binary".equalsIgnoreCase(engtype)) {
ptype = new BinaryParameterType(name);
} else {
error("Parameters:"+(i+1)+": unknown parameter type " + engtype);
}
loadParameterLimits(ptype,cells);
//calibrations
DataEncoding encoding = null;
if (("uint".equalsIgnoreCase(rawtype)) || ("int".equalsIgnoreCase(rawtype))) {
if(bitlength==-1) error("Parameters:"+(i+1)+" for integer parameters bitlength is mandatory");
encoding = new IntegerDataEncoding(name, bitlength);
if ("int".equalsIgnoreCase(rawtype)) {
encoding = new IntegerDataEncoding(name, bitlength);
((IntegerDataEncoding)encoding).encoding = IntegerDataEncoding.Encoding.twosCompliment;
}
if ((!"enumerated".equalsIgnoreCase(engtype)) && (calib!=null)) {
Calibrator c = calibrators.get(calib);
if (c == null) {
error("parameter " + name + " is supposed to have a calibrator '" + calib + "' but the calibrator does not exist");
}
((IntegerDataEncoding)encoding).defaultCalibrator = c;
}
} else if ("bytestream".equalsIgnoreCase(rawtype)) {
if(bitlength==-1) error("Parameters:"+(i+1)+" for bytestream parameters bitlength is mandatory");
encoding=new BinaryDataEncoding(name, bitlength);
} else if ("string".equalsIgnoreCase(rawtype)) {
// Version <= 1.6 String type
// STRING
if(bitlength==-1) {
// Assume null-terminated if no length specified
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.TerminationChar);
} else {
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.Fixed);
encoding.setSizeInBits(bitlength);
}
} else if ( "fixedstring".equalsIgnoreCase( rawtype ) ) {
// v1.7 String type
// FIXEDSTRING
if(bitlength==-1) error("Parameters:"+(i+1)+" bitlength is mandatory for fixedstring raw type");
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.Fixed);
encoding.setSizeInBits(bitlength);
} else if ( rawtype.toLowerCase().startsWith( "terminatedstring" ) ) {
// v1.7 String type
// TERMINATEDSTRING
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.TerminationChar);
// Use specified byte if found, otherwise accept class default.
int startBracket = rawtype.indexOf( '(' );
if( startBracket != -1 ) {
int endBracket = rawtype.indexOf( ')', startBracket );
if( endBracket != -1 ) {
try {
byte terminationChar = Byte.parseByte( rawtype.substring( rawtype.indexOf('x', startBracket)+1, endBracket ).trim(), 16 );
((StringDataEncoding)encoding).setTerminationChar(terminationChar);
} catch (NumberFormatException e) {
error( "Parameters:"+(i+1)+" could not parse specified base 16 terminator from "+rawtype );
}
}
}
} else if ( rawtype.toLowerCase().startsWith( "prependedsizestring" ) ) {
// v1.7 String type
// PREPENDEDSIZESTRING
encoding=new StringDataEncoding( name, StringDataEncoding.SizeType.LeadingSize );
// Use specified size if found, otherwise accept class default.
int startBracket = rawtype.indexOf( '(' );
if( startBracket != -1 ) {
int endBracket = rawtype.indexOf( ')', startBracket );
if( endBracket != -1 ) {
try {
int sizeInBitsOfSizeTag = Integer.parseInt( rawtype.substring(startBracket+1, endBracket).trim() );
((StringDataEncoding)encoding).setSizeInBitsOfSizeTag( sizeInBitsOfSizeTag );
} catch (NumberFormatException e) {
error( "Parameters:"+(i+1)+" could not parse integer size from "+rawtype );
}
}
}
} else if ("float".equalsIgnoreCase(rawtype)) {
if(bitlength==-1) error("Parameters:"+(i+1)+" for float parameters bitlength is mandatory");
encoding=new FloatDataEncoding(name, bitlength);
if(calib!=null) {
Calibrator c = calibrators.get(calib);
if (c == null) {
error("parameter " + name + " is supposed to have a calibrator '" + calib + "' but the calibrator does not exist.");
} else {
((FloatDataEncoding)encoding).defaultCalibrator = c;
}
}
} else {
error("unknown raw type " + rawtype);
}
if (ptype instanceof IntegerParameterType) {
// Integers can be encoded as strings
if( encoding instanceof StringDataEncoding ) {
// Create a new int encoding which uses the configured string encoding
IntegerDataEncoding intStringEncoding = new IntegerDataEncoding(name, ((StringDataEncoding)encoding));
if( calib != null ) {
Calibrator c = calibrators.get(calib);
if( c == null ) {
error("Parameter " + name + " specified calibrator '" + calib + "' but the calibrator does not exist");
}
intStringEncoding.defaultCalibrator = c;
}
((IntegerParameterType)ptype).encoding = intStringEncoding;
} else {
((IntegerParameterType)ptype).encoding = encoding;
}
} else if (ptype instanceof BinaryParameterType) {
((BinaryParameterType)ptype).encoding = encoding;
} else if (ptype instanceof FloatParameterType) {
// Floats can be encoded as strings
if ( encoding instanceof StringDataEncoding ) {
// Create a new float encoding which uses the configured string encoding
FloatDataEncoding floatStringEncoding = new FloatDataEncoding( name, ((StringDataEncoding)encoding) );
if(calib!=null) {
Calibrator c = calibrators.get(calib);
if( c == null ) {
error("Parameter " + name + " specified calibrator '" + calib + "' but the calibrator does not exist.");
} else {
floatStringEncoding.defaultCalibrator = c;
}
}
((FloatParameterType)ptype).encoding = floatStringEncoding;
} else {
((FloatParameterType)ptype).encoding = encoding;
}
} else if (ptype instanceof EnumeratedParameterType) {
// Enumerations encoded as string integers
if( encoding instanceof StringDataEncoding ) {
IntegerDataEncoding intStringEncoding = new IntegerDataEncoding(name, ((StringDataEncoding)encoding));
// Don't set calibrator, already done when making ptype
((EnumeratedParameterType)ptype).encoding = intStringEncoding;
} else {
((EnumeratedParameterType)ptype).encoding = encoding;
}
} else if (ptype instanceof StringParameterType) {
((StringParameterType)ptype).encoding = encoding;
}
Parameter param = new Parameter(name);
param.setParameterType(ptype);
parameters.put(param.getName(), param);
XtceAliasSet xas=new XtceAliasSet();
xas.addAlias(MdbMappings.MDB_OPSNAME, opsnamePrefix+param.getName());
param.setAliasSet(xas);
spaceSystem.addParameter(param);
}
/* System.out.println("got parameters:");
for (Parameter p: parameters.values()) {
System.out.println(p);
}
*/ }
private void loadParameterLimits(ParameterType ptype, Cell[] cells) {
if (cells.length<=IDX_PARAM_LOWWARNILIMIT) return;
String mins=cells[IDX_PARAM_LOWWARNILIMIT].getContents();
//System.out.println("limits.length="+limits.size()+"limits: "+limits.keySet() +"mins="+mins);
if(limits.containsKey(mins)) { //limit is specified on the separate sheet
for(LimitDef ld:limits.get(mins)) {
Pattern p=Pattern.compile("(\\w+)(==|!=|>|<|>=|<=)(\\w+)");
if(ld.condition.length()>0) {
Matcher m=p.matcher(ld.condition);
if((!m.matches()) ||(m.groupCount()!=3)) {
log.warn("Cannot parse alarm condition '"+ld.condition+"'");
continue;
}
String pname=m.group(1);
String values=m.group(3);
String op=m.group(2);
Parameter para=parameters.get(pname);
if(para!=null) {
ParameterInstanceRef paraRef=new ParameterInstanceRef(para);
Comparison c;
if(para.parameterType instanceof IntegerParameterType) {
try {
long value=Long.parseLong(values);
c=new Comparison(paraRef,value,Comparison.stringToOperator(op));
} catch (NumberFormatException e) {
log.warn("Cannot parse alarm condition '"+ld.condition+"': "+e.getMessage());
continue;
}
} else if(para.parameterType instanceof EnumeratedParameterType) {
c=new Comparison(paraRef, values, Comparison.stringToOperator(op));
} else {
log.warn("Conditions not supported for parameter of type "+para.parameterType);
continue;
}
NumericContextAlarm nca=new NumericContextAlarm();
nca.setContextMatch(c);
nca.setStaticAlarmRanges(ld.ranges);
if(ptype instanceof IntegerParameterType){
((IntegerParameterType)ptype).addContextAlarm(nca);
} else {
((FloatParameterType)ptype).addContextAlarm(nca);
}
} else { //TODO
// ParameterInstanceRef paraRef=new ParameterInstanceRef(new NameReference(pname));
// Comparison c=new Comparison(paraRef, Comparison.stringToOperator(op));
}
} else {
setDefaultWarningAlarmRange(ptype, ld.ranges.warningRange);
setDefaultCriticalAlarmRange(ptype, ld.ranges.criticalRange);
}
}
} else if((cells.length>IDX_PARAM_HIGHWARNILIMIT) && ((ptype instanceof IntegerParameterType) || (ptype instanceof FloatParameterType))) {
String maxs=cells[IDX_PARAM_HIGHWARNILIMIT].getContents();
if((mins.length()>0) && (maxs.length()>0)) {
double min=(mins.length()>0)?Double.parseDouble(mins):Double.NEGATIVE_INFINITY;
double max=(maxs.length()>0)?Double.parseDouble(maxs):Double.POSITIVE_INFINITY;
setDefaultWarningAlarmRange(ptype,new FloatRange(min,max));
}
}
// danger limits
if((cells.length>IDX_PARAM_HIGHCRITICALLIMIT) && ((ptype instanceof IntegerParameterType) || (ptype instanceof FloatParameterType))) {
mins=cells[IDX_PARAM_LOWCRITICALLIMIT].getContents();
String maxs=cells[IDX_PARAM_HIGHCRITICALLIMIT].getContents();
if((mins.length()>0) && (maxs.length()>0)) {
double min=Double.parseDouble(mins);
double max=Double.parseDouble(maxs);
setDefaultCriticalAlarmRange(ptype, new FloatRange(min,max));
}
}
}
private void setDefaultCriticalAlarmRange(ParameterType ptype, FloatRange range) {
if(range==null)return;
if(ptype instanceof IntegerParameterType){
((IntegerParameterType)ptype).setDefaultCriticalAlarmRange(range);
} else {
((FloatParameterType)ptype).setDefaultCriticalAlarmRange(range);
}
}
private void setDefaultWarningAlarmRange(ParameterType ptype, FloatRange range) {
if(range==null)return;
if(ptype instanceof IntegerParameterType){
((IntegerParameterType)ptype).setDefaultWarningAlarmRange(range);
} else {
((FloatParameterType)ptype).setDefaultWarningAlarmRange(range);
}
}
private void loadContainers() throws DatabaseLoadException {
Sheet tm_sheet = workbook.getSheet("Containers");
HashMap<String, SequenceContainer> containers = new HashMap<String, SequenceContainer>();
for (int i = 1; i < tm_sheet.getRows(); i++) {
// search for a new packet definition, starting from row i
// (explanatory note, i is incremented inside this loop too, and that's why the following 4 lines work)
Cell[] cells = tm_sheet.getRow(i);
if (cells == null || cells.length<1) {
log.debug("Ignoring line {} because it's empty",(i+1));
continue;
}
if(cells[0].getContents().equals("")|| cells[0].getContents().startsWith("#")) {
log.debug("Ignoring line {} because first cell is empty or starts with '#'", (i+1));
continue;
}
// at this point, cells contains the data (name, path, ...) of either
// a) a sub-container (inherits from another packet)
// b) an aggregate container (which will be used as if it were a measurement, by other (sub)containers)
String name = cells[IDX_CONT_NAME].getContents();
String parent=null;
String condition=null;
if(cells.length>IDX_CONT_PARENT) {
parent=cells[IDX_CONT_PARENT].getContents();
if(cells.length<=IDX_CONT_CONDITION) {
error("parent specified but without inheritance condition on container on line "+(i+1));
}
condition = cells[IDX_CONT_CONDITION].getContents();
//if( "".equals( condition ) ) {
// error( String.format( "Container %s (from spreadsheet '%s' line %d) has a parent container specified but no inheritance condition", name, configName, i));
//}
}
if("".equals(parent)) parent=null;
// absoluteoffset is the absolute offset of the first parameter of the container
int absoluteoffset=-1;
if(parent==null) {
absoluteoffset=0;
} else {
int x=parent.indexOf(":");
if(x!=-1) {
absoluteoffset=Integer.decode(parent.substring(x+1));
parent=parent.substring(0, x);
}
}
int containerSizeInBits=-1;
if(hasColumn(cells, IDX_CONT_SIZEINBITS)) {
containerSizeInBits=Integer.decode(cells[IDX_CONT_SIZEINBITS].getContents());
}
RateInStream rate=null;
if(hasColumn(cells, IDX_CONT_EXPECTED_INTERVAL)) {
int expint=Integer.decode(cells[IDX_CONT_EXPECTED_INTERVAL].getContents());
rate=new RateInStream(expint);
}
// create a new SequenceContainer that will hold the parameters (i.e. SequenceEntries) for the ORDINARY/SUB/AGGREGATE packets, and register that new SequenceContainer in the containers hashmap
SequenceContainer container = new SequenceContainer(name);
container.sizeInBits=containerSizeInBits;
containers.put(name, container);
container.setRateInStream(rate);
//System.out.println("for "+name+" got absoluteoffset="+)
// we mark the start of the TM packet and advance to the next line, to get to the first parameter (if there is one)
int start = i++;
// now, we start processing the parameters (or references to aggregate containers)
boolean end = false;
int counter = 0; // sequence number of the SequenceEntrys in the SequenceContainer
while (!end && (i < tm_sheet.getRows())) {
// get the next row, containing a measurement/aggregate reference
cells = tm_sheet.getRow(i);
// determine whether we have not reached the end of the packet definition.
if ((cells == null) || (cells.length <= IDX_CONT_RELPOS) || cells[IDX_CONT_RELPOS].getContents().equals("")) {
end = true; continue;
}
// extract a few variables, for further use
String flags = cells[IDX_CONT_FLAGS].getContents();
String paraname = cells[IDX_CONT_PARA_NAME].getContents();
if((cells.length<=IDX_CONT_RELPOS)||cells[IDX_CONT_RELPOS].getContents().equals("")) error("relpos is not specified for "+paraname+" on line "+(i+1));
int relpos = Integer.decode(cells[IDX_CONT_RELPOS].getContents());
// we add the relative position to the absoluteoffset, to specify the location of the new parameter. We only do this if the absoluteoffset is not equal to -1, because that would mean that we cannot and should not use absolute positions anymore
if (absoluteoffset != -1) {
absoluteoffset += relpos;
}
// the repeat string will contain the number of times a measurement (or aggregate container) should be repeated. It is a String because at this point it can be either a number or a reference to another measurement
String repeat = "";
// we check whether the measurement (or aggregate container) has a '*' inside it, meaning that it is a repeat measurement/aggregate
Matcher m = Pattern.compile("(.*)[*](.*)").matcher(paraname);
if (m.matches()) {
repeat = m.group(1);
paraname = m.group(2);
}
// check whether this measurement/aggregate actually has an entry in the parameters table
// first we check if it is a measurement by trying to retrieve it from the parameters map. If this succeeds we add it as a new parameterentry,
// otherwise, we search for it in the containersmap, as it is probably an aggregate. If it is not, we encountered an error
// note that one of the next 2 lines will return null, but this does not pose a problem, it makes programming easier along the way
Parameter param = parameters.get(paraname);
SequenceContainer sc = containers.get(paraname);
// if the sequenceentry is repeated a fixed number of times, this number is recorded in the 'repeated' variable and used to calculate the next absoluteoffset (done below)
int repeated = -1;
if (param != null) {
SequenceEntry se;
if(flags.contains("L")) {
if(param.parameterType instanceof IntegerParameterType) {
((IntegerParameterType)param.parameterType).encoding.byteOrder=ByteOrder.LITTLE_ENDIAN;
} else if(param.parameterType instanceof FloatParameterType) {
((FloatParameterType)param.parameterType).encoding.byteOrder=ByteOrder.LITTLE_ENDIAN;
} else if(param.parameterType instanceof EnumeratedParameterType) {
((EnumeratedParameterType)param.parameterType).encoding.byteOrder=ByteOrder.LITTLE_ENDIAN;
} else {
error("little endian not supported for this parameter: "+param);
}
}
// if absoluteoffset is -1, somewhere along the line we came across a measurement or aggregate that had as a result that the absoluteoffset could not be determined anymore; hence, a relative position is added
if (absoluteoffset == -1) {
se = new ParameterEntry(counter, container, relpos, ReferenceLocationType.previousEntry, param);
} else {
se = new ParameterEntry(counter, container, absoluteoffset, ReferenceLocationType.containerStart, param);
}
// also check if the parameter should be added multiple times, and if so, do so
repeated = addRepeat(se, repeat);
container.entryList.add(se);
} else {
if (sc != null) {
// ok, we found it as an aggregate, so we add it to the entryList of container, as a new ContainerEntry
// if absoluteoffset is -1, somewhere along the line we came across a measurement or aggregate that had as a result that the absoluteoffset could not be determined anymore; hence, a relative position is added
SequenceEntry se;
if (absoluteoffset == -1) {
se = new ContainerEntry(counter, container, relpos, ReferenceLocationType.previousEntry, sc);
} else {
se = new ContainerEntry(counter, container, absoluteoffset, ReferenceLocationType.containerStart, sc);
}
// also check if the parameter should be added multiple times, and if so, do so
repeated = addRepeat(se, repeat);
container.entryList.add(se);
} else {
throw new DatabaseLoadException("error on line "+(i+1)+" of the Containers sheet: the measurement/container '" + paraname + "' was not found in the parameters or containers map");
}
}
// after adding this measurement, we need to update the absoluteoffset for the next one. For this, we add the size of the current SequenceEntry to the absoluteoffset
int size=getSize(param,sc);
- if ((repeated != -1) && (size != -1)) {
+ if ((repeated != -1) && (size != -1) && (absoluteoffset != -1)) {
absoluteoffset += repeated * size;
} else {
// from this moment on, absoluteoffset is set to -1, meaning that all subsequent SequenceEntries must be relative
absoluteoffset = -1;
}
// increment the counters;
i++; counter++;
}
// at this point, we have added all the parameters and aggregate containers to the current packets. What remains to be done is link it with its base
if(parent!=null) {
// the condition is parsed and used to create the container.restrictionCriteria
//1) get the parent, from the same sheet
SequenceContainer sc = containers.get(parent);
//the parent is not in the same sheet, try to get from the Xtcedb
if(sc==null) {
sc = spaceSystem.getSequenceContainer(parent);
}
if (sc != null) {
container.setBaseContainer(sc);
} else {
final SequenceContainer c=container;
NameReference nr=new NameReference(parent, Type.SEQUENCE_CONTAINTER,
new ResolvedAction() {
@Override
public boolean resolved(NameDescription nd) {
c.setBaseContainer((SequenceContainer) nd);
return true;
}
});
spaceSystem.addUnresolvedReference(nr);
}
// 2) extract the condition and create the restrictioncriteria
ComparisonList cl = new ComparisonList();
// If conditions have been specified...
if( !"".equals( condition ) ) {
// 2.2) if there are multiple conditions, we get them all by splitting according to the ';' between the condition
String splitted[] = condition.split(";");
for (String sp: splitted) {
// 2.3) in each splitted part, we search for either =, !=, <=, >=, < or > and add this as a Comparison
Matcher m = Pattern.compile("(.*?)(=|!=|<=|>=|<|>)(.*)").matcher(sp);
if(!m.matches()) throw new DatabaseLoadException("error on line "+(start+1)+" of the Containers sheet: cannot parse inheritance condition '"+sp+"'");
Parameter param=null;
String paramName=m.group(1);
param = spaceSystem.getParameter(paramName);
// we now get the actual comparison operator (and we change '=' to '==')
String operation = m.group(2);
if (operation.equals("="))
operation="==";
Comparison.OperatorType coperator=Comparison.stringToOperator(operation);
// create the Comparison and add it
try {
if (param != null) {
ParameterInstanceRef pref=new ParameterInstanceRef(param, false);
cl.comparisons.add(new Comparison(pref, Integer.decode(m.group(3)), coperator));
} else {
final ParameterInstanceRef pref=new ParameterInstanceRef(false);
final Comparison ucomp=new Comparison(pref, Integer.decode(m.group(3)), coperator);
cl.comparisons.add(ucomp);
NameReference nr=new NameReference(paramName, Type.PARAMETER,
new ResolvedAction() {
@Override
public boolean resolved(NameDescription nd) {
pref.setParameter((Parameter)nd);
return true;
}
});
spaceSystem.addUnresolvedReference(nr);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
error("non-existing comparison found: " + m.group(2));
}
}
}
// 3) add the restrictioncriteria
container.restrictionCriteria = cl;
} else {
if(spaceSystem.getRootSequenceContainer()==null) {
spaceSystem.setRootSequenceContainer(container);
}
}
XtceAliasSet xas=new XtceAliasSet();
xas.addAlias(MdbMappings.MDB_OPSNAME, opsnamePrefix+container.getName());
container.setAliasSet(xas);
spaceSystem.addSequenceContainer(container);
}
}
private boolean hasColumn(Cell[] cells, int idx) {
return (cells.length>idx) && (cells[idx].getContents()!=null) && (!cells[idx].getContents().equals(""));
}
private void error(String s) {
System.err.println(s);
System.exit(-1);
}
/**
*/
private int getSize(Parameter param, SequenceContainer sc) {
// either we have a Parameter or we have a SequenceContainer, we cannot have both or neither
if (param != null) {
DataEncoding de = ((BaseDataType)param.getParameterType()).getEncoding();
if(de==null) error("Cannot determine the data encoding for "+param.getName());
if (de instanceof FloatDataEncoding) {
return de.sizeInBits;
} else if (de instanceof IntegerDataEncoding) {
return de.sizeInBits;
} else if (de instanceof BinaryDataEncoding) {
return de.sizeInBits;
} else if (de instanceof StringDataEncoding) {
return -1;
} else {
error("no known size for data encoding : " + de);
}
} else {
return sc.sizeInBits;
}
// this point should never be reached
return 0;
}
/** If repeat != "", decodes it to either an integer or a parameter and adds it to the SequenceEntry
* If repeat is an integer, this integer is returned
*/
private int addRepeat(SequenceEntry se, String repeat) {
if (!repeat.equals("")) {
se.repeatEntry = new Repeat();
try {
int rep = Integer.decode(repeat);
se.repeatEntry.count = new FixedIntegerValue();
((FixedIntegerValue)se.repeatEntry.count).value = rep;
return rep;
} catch (NumberFormatException e) {
se.repeatEntry.count = new DynamicIntegerValue();
Parameter repeatparam=parameters.get(repeat);
if(repeatparam==null) {
error("Can not find the parameter for repeat "+repeat);
}
((DynamicIntegerValue)se.repeatEntry.count).parameter = repeatparam;
return -1;
}
} else {
return 1;
}
}
class LimitDef {
public LimitDef(String condition, AlarmRanges ranges) {
this.condition=condition;
this.ranges=ranges;
}
String condition;
AlarmRanges ranges;
}
}
| true | true | private void loadParameters() {
Sheet para_sheet = workbook.getSheet("Parameters");
for (int i = 1; i < para_sheet.getRows(); i++) {
Cell[] cells = para_sheet.getRow(i);
if ((cells == null) || (cells.length < 4) || cells[0].getContents().startsWith("#")) {
continue;
}
String name = cells[IDX_PARAM_OPSNAME].getContents();
if (name.length() == 0) {
continue;
}
//String path = cells[IDX_MEAS_PATH].getContents();
String rawtype = cells[IDX_PARAM_RAWTYPE].getContents();
if("DerivedValue".equalsIgnoreCase(rawtype)) continue;
int bitlength=-1;
try {
String bitls=cells[IDX_PARAM_BITLENGTH].getContents();
if(!bitls.isEmpty()) bitlength = Integer.decode(bitls);
} catch(NumberFormatException e) {
error("Parameters:"+(i+1)+": can't get bitlength out of '"+cells[IDX_PARAM_BITLENGTH].getContents()+"'");
}
String engtype = cells[IDX_PARAM_ENGTYPE].getContents();
String calib=null;
if(cells.length>IDX_PARAM_CALIBRATION) calib = cells[IDX_PARAM_CALIBRATION].getContents();
if("n".equals(calib) || "".equals(calib))calib=null;
if("y".equalsIgnoreCase(calib)) calib=name;
ParameterType ptype=null;
if ("uint".equalsIgnoreCase(engtype)) {
ptype = new IntegerParameterType(name);
((IntegerParameterType)ptype).signed = false;
} else if ("int".equalsIgnoreCase(engtype)) {
ptype = new IntegerParameterType(name);
} else if ("float".equalsIgnoreCase(engtype)) {
ptype = new FloatParameterType(name);
} else if ("enumerated".equalsIgnoreCase(engtype)) {
if(calib==null) {
error("parameter " + name + " has to have an enumeration");
}
ptype = enumerations.get(calib);
if (ptype == null) {
error("parameter " + name + " is supposed to have an enumeration '" + calib + "' but the enumeration does not exist");
}
} else if ("string".equalsIgnoreCase(engtype)) {
ptype = new StringParameterType(name);
} else if ("binary".equalsIgnoreCase(engtype)) {
ptype = new BinaryParameterType(name);
} else {
error("Parameters:"+(i+1)+": unknown parameter type " + engtype);
}
loadParameterLimits(ptype,cells);
//calibrations
DataEncoding encoding = null;
if (("uint".equalsIgnoreCase(rawtype)) || ("int".equalsIgnoreCase(rawtype))) {
if(bitlength==-1) error("Parameters:"+(i+1)+" for integer parameters bitlength is mandatory");
encoding = new IntegerDataEncoding(name, bitlength);
if ("int".equalsIgnoreCase(rawtype)) {
encoding = new IntegerDataEncoding(name, bitlength);
((IntegerDataEncoding)encoding).encoding = IntegerDataEncoding.Encoding.twosCompliment;
}
if ((!"enumerated".equalsIgnoreCase(engtype)) && (calib!=null)) {
Calibrator c = calibrators.get(calib);
if (c == null) {
error("parameter " + name + " is supposed to have a calibrator '" + calib + "' but the calibrator does not exist");
}
((IntegerDataEncoding)encoding).defaultCalibrator = c;
}
} else if ("bytestream".equalsIgnoreCase(rawtype)) {
if(bitlength==-1) error("Parameters:"+(i+1)+" for bytestream parameters bitlength is mandatory");
encoding=new BinaryDataEncoding(name, bitlength);
} else if ("string".equalsIgnoreCase(rawtype)) {
// Version <= 1.6 String type
// STRING
if(bitlength==-1) {
// Assume null-terminated if no length specified
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.TerminationChar);
} else {
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.Fixed);
encoding.setSizeInBits(bitlength);
}
} else if ( "fixedstring".equalsIgnoreCase( rawtype ) ) {
// v1.7 String type
// FIXEDSTRING
if(bitlength==-1) error("Parameters:"+(i+1)+" bitlength is mandatory for fixedstring raw type");
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.Fixed);
encoding.setSizeInBits(bitlength);
} else if ( rawtype.toLowerCase().startsWith( "terminatedstring" ) ) {
// v1.7 String type
// TERMINATEDSTRING
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.TerminationChar);
// Use specified byte if found, otherwise accept class default.
int startBracket = rawtype.indexOf( '(' );
if( startBracket != -1 ) {
int endBracket = rawtype.indexOf( ')', startBracket );
if( endBracket != -1 ) {
try {
byte terminationChar = Byte.parseByte( rawtype.substring( rawtype.indexOf('x', startBracket)+1, endBracket ).trim(), 16 );
((StringDataEncoding)encoding).setTerminationChar(terminationChar);
} catch (NumberFormatException e) {
error( "Parameters:"+(i+1)+" could not parse specified base 16 terminator from "+rawtype );
}
}
}
} else if ( rawtype.toLowerCase().startsWith( "prependedsizestring" ) ) {
// v1.7 String type
// PREPENDEDSIZESTRING
encoding=new StringDataEncoding( name, StringDataEncoding.SizeType.LeadingSize );
// Use specified size if found, otherwise accept class default.
int startBracket = rawtype.indexOf( '(' );
if( startBracket != -1 ) {
int endBracket = rawtype.indexOf( ')', startBracket );
if( endBracket != -1 ) {
try {
int sizeInBitsOfSizeTag = Integer.parseInt( rawtype.substring(startBracket+1, endBracket).trim() );
((StringDataEncoding)encoding).setSizeInBitsOfSizeTag( sizeInBitsOfSizeTag );
} catch (NumberFormatException e) {
error( "Parameters:"+(i+1)+" could not parse integer size from "+rawtype );
}
}
}
} else if ("float".equalsIgnoreCase(rawtype)) {
if(bitlength==-1) error("Parameters:"+(i+1)+" for float parameters bitlength is mandatory");
encoding=new FloatDataEncoding(name, bitlength);
if(calib!=null) {
Calibrator c = calibrators.get(calib);
if (c == null) {
error("parameter " + name + " is supposed to have a calibrator '" + calib + "' but the calibrator does not exist.");
} else {
((FloatDataEncoding)encoding).defaultCalibrator = c;
}
}
} else {
error("unknown raw type " + rawtype);
}
if (ptype instanceof IntegerParameterType) {
// Integers can be encoded as strings
if( encoding instanceof StringDataEncoding ) {
// Create a new int encoding which uses the configured string encoding
IntegerDataEncoding intStringEncoding = new IntegerDataEncoding(name, ((StringDataEncoding)encoding));
if( calib != null ) {
Calibrator c = calibrators.get(calib);
if( c == null ) {
error("Parameter " + name + " specified calibrator '" + calib + "' but the calibrator does not exist");
}
intStringEncoding.defaultCalibrator = c;
}
((IntegerParameterType)ptype).encoding = intStringEncoding;
} else {
((IntegerParameterType)ptype).encoding = encoding;
}
} else if (ptype instanceof BinaryParameterType) {
((BinaryParameterType)ptype).encoding = encoding;
} else if (ptype instanceof FloatParameterType) {
// Floats can be encoded as strings
if ( encoding instanceof StringDataEncoding ) {
// Create a new float encoding which uses the configured string encoding
FloatDataEncoding floatStringEncoding = new FloatDataEncoding( name, ((StringDataEncoding)encoding) );
if(calib!=null) {
Calibrator c = calibrators.get(calib);
if( c == null ) {
error("Parameter " + name + " specified calibrator '" + calib + "' but the calibrator does not exist.");
} else {
floatStringEncoding.defaultCalibrator = c;
}
}
((FloatParameterType)ptype).encoding = floatStringEncoding;
} else {
((FloatParameterType)ptype).encoding = encoding;
}
} else if (ptype instanceof EnumeratedParameterType) {
// Enumerations encoded as string integers
if( encoding instanceof StringDataEncoding ) {
IntegerDataEncoding intStringEncoding = new IntegerDataEncoding(name, ((StringDataEncoding)encoding));
// Don't set calibrator, already done when making ptype
((EnumeratedParameterType)ptype).encoding = intStringEncoding;
} else {
((EnumeratedParameterType)ptype).encoding = encoding;
}
} else if (ptype instanceof StringParameterType) {
((StringParameterType)ptype).encoding = encoding;
}
Parameter param = new Parameter(name);
param.setParameterType(ptype);
parameters.put(param.getName(), param);
XtceAliasSet xas=new XtceAliasSet();
xas.addAlias(MdbMappings.MDB_OPSNAME, opsnamePrefix+param.getName());
param.setAliasSet(xas);
spaceSystem.addParameter(param);
}
/* System.out.println("got parameters:");
for (Parameter p: parameters.values()) {
System.out.println(p);
}
*/ }
private void loadParameterLimits(ParameterType ptype, Cell[] cells) {
if (cells.length<=IDX_PARAM_LOWWARNILIMIT) return;
String mins=cells[IDX_PARAM_LOWWARNILIMIT].getContents();
//System.out.println("limits.length="+limits.size()+"limits: "+limits.keySet() +"mins="+mins);
if(limits.containsKey(mins)) { //limit is specified on the separate sheet
for(LimitDef ld:limits.get(mins)) {
Pattern p=Pattern.compile("(\\w+)(==|!=|>|<|>=|<=)(\\w+)");
if(ld.condition.length()>0) {
Matcher m=p.matcher(ld.condition);
if((!m.matches()) ||(m.groupCount()!=3)) {
log.warn("Cannot parse alarm condition '"+ld.condition+"'");
continue;
}
String pname=m.group(1);
String values=m.group(3);
String op=m.group(2);
Parameter para=parameters.get(pname);
if(para!=null) {
ParameterInstanceRef paraRef=new ParameterInstanceRef(para);
Comparison c;
if(para.parameterType instanceof IntegerParameterType) {
try {
long value=Long.parseLong(values);
c=new Comparison(paraRef,value,Comparison.stringToOperator(op));
} catch (NumberFormatException e) {
log.warn("Cannot parse alarm condition '"+ld.condition+"': "+e.getMessage());
continue;
}
} else if(para.parameterType instanceof EnumeratedParameterType) {
c=new Comparison(paraRef, values, Comparison.stringToOperator(op));
} else {
log.warn("Conditions not supported for parameter of type "+para.parameterType);
continue;
}
NumericContextAlarm nca=new NumericContextAlarm();
nca.setContextMatch(c);
nca.setStaticAlarmRanges(ld.ranges);
if(ptype instanceof IntegerParameterType){
((IntegerParameterType)ptype).addContextAlarm(nca);
} else {
((FloatParameterType)ptype).addContextAlarm(nca);
}
} else { //TODO
// ParameterInstanceRef paraRef=new ParameterInstanceRef(new NameReference(pname));
// Comparison c=new Comparison(paraRef, Comparison.stringToOperator(op));
}
} else {
setDefaultWarningAlarmRange(ptype, ld.ranges.warningRange);
setDefaultCriticalAlarmRange(ptype, ld.ranges.criticalRange);
}
}
} else if((cells.length>IDX_PARAM_HIGHWARNILIMIT) && ((ptype instanceof IntegerParameterType) || (ptype instanceof FloatParameterType))) {
String maxs=cells[IDX_PARAM_HIGHWARNILIMIT].getContents();
if((mins.length()>0) && (maxs.length()>0)) {
double min=(mins.length()>0)?Double.parseDouble(mins):Double.NEGATIVE_INFINITY;
double max=(maxs.length()>0)?Double.parseDouble(maxs):Double.POSITIVE_INFINITY;
setDefaultWarningAlarmRange(ptype,new FloatRange(min,max));
}
}
// danger limits
if((cells.length>IDX_PARAM_HIGHCRITICALLIMIT) && ((ptype instanceof IntegerParameterType) || (ptype instanceof FloatParameterType))) {
mins=cells[IDX_PARAM_LOWCRITICALLIMIT].getContents();
String maxs=cells[IDX_PARAM_HIGHCRITICALLIMIT].getContents();
if((mins.length()>0) && (maxs.length()>0)) {
double min=Double.parseDouble(mins);
double max=Double.parseDouble(maxs);
setDefaultCriticalAlarmRange(ptype, new FloatRange(min,max));
}
}
}
private void setDefaultCriticalAlarmRange(ParameterType ptype, FloatRange range) {
if(range==null)return;
if(ptype instanceof IntegerParameterType){
((IntegerParameterType)ptype).setDefaultCriticalAlarmRange(range);
} else {
((FloatParameterType)ptype).setDefaultCriticalAlarmRange(range);
}
}
private void setDefaultWarningAlarmRange(ParameterType ptype, FloatRange range) {
if(range==null)return;
if(ptype instanceof IntegerParameterType){
((IntegerParameterType)ptype).setDefaultWarningAlarmRange(range);
} else {
((FloatParameterType)ptype).setDefaultWarningAlarmRange(range);
}
}
private void loadContainers() throws DatabaseLoadException {
Sheet tm_sheet = workbook.getSheet("Containers");
HashMap<String, SequenceContainer> containers = new HashMap<String, SequenceContainer>();
for (int i = 1; i < tm_sheet.getRows(); i++) {
// search for a new packet definition, starting from row i
// (explanatory note, i is incremented inside this loop too, and that's why the following 4 lines work)
Cell[] cells = tm_sheet.getRow(i);
if (cells == null || cells.length<1) {
log.debug("Ignoring line {} because it's empty",(i+1));
continue;
}
if(cells[0].getContents().equals("")|| cells[0].getContents().startsWith("#")) {
log.debug("Ignoring line {} because first cell is empty or starts with '#'", (i+1));
continue;
}
// at this point, cells contains the data (name, path, ...) of either
// a) a sub-container (inherits from another packet)
// b) an aggregate container (which will be used as if it were a measurement, by other (sub)containers)
String name = cells[IDX_CONT_NAME].getContents();
String parent=null;
String condition=null;
if(cells.length>IDX_CONT_PARENT) {
parent=cells[IDX_CONT_PARENT].getContents();
if(cells.length<=IDX_CONT_CONDITION) {
error("parent specified but without inheritance condition on container on line "+(i+1));
}
condition = cells[IDX_CONT_CONDITION].getContents();
//if( "".equals( condition ) ) {
// error( String.format( "Container %s (from spreadsheet '%s' line %d) has a parent container specified but no inheritance condition", name, configName, i));
//}
}
if("".equals(parent)) parent=null;
// absoluteoffset is the absolute offset of the first parameter of the container
int absoluteoffset=-1;
if(parent==null) {
absoluteoffset=0;
} else {
int x=parent.indexOf(":");
if(x!=-1) {
absoluteoffset=Integer.decode(parent.substring(x+1));
parent=parent.substring(0, x);
}
}
int containerSizeInBits=-1;
if(hasColumn(cells, IDX_CONT_SIZEINBITS)) {
containerSizeInBits=Integer.decode(cells[IDX_CONT_SIZEINBITS].getContents());
}
RateInStream rate=null;
if(hasColumn(cells, IDX_CONT_EXPECTED_INTERVAL)) {
int expint=Integer.decode(cells[IDX_CONT_EXPECTED_INTERVAL].getContents());
rate=new RateInStream(expint);
}
// create a new SequenceContainer that will hold the parameters (i.e. SequenceEntries) for the ORDINARY/SUB/AGGREGATE packets, and register that new SequenceContainer in the containers hashmap
SequenceContainer container = new SequenceContainer(name);
container.sizeInBits=containerSizeInBits;
containers.put(name, container);
container.setRateInStream(rate);
//System.out.println("for "+name+" got absoluteoffset="+)
// we mark the start of the TM packet and advance to the next line, to get to the first parameter (if there is one)
int start = i++;
// now, we start processing the parameters (or references to aggregate containers)
boolean end = false;
int counter = 0; // sequence number of the SequenceEntrys in the SequenceContainer
while (!end && (i < tm_sheet.getRows())) {
// get the next row, containing a measurement/aggregate reference
cells = tm_sheet.getRow(i);
// determine whether we have not reached the end of the packet definition.
if ((cells == null) || (cells.length <= IDX_CONT_RELPOS) || cells[IDX_CONT_RELPOS].getContents().equals("")) {
end = true; continue;
}
// extract a few variables, for further use
String flags = cells[IDX_CONT_FLAGS].getContents();
String paraname = cells[IDX_CONT_PARA_NAME].getContents();
if((cells.length<=IDX_CONT_RELPOS)||cells[IDX_CONT_RELPOS].getContents().equals("")) error("relpos is not specified for "+paraname+" on line "+(i+1));
int relpos = Integer.decode(cells[IDX_CONT_RELPOS].getContents());
// we add the relative position to the absoluteoffset, to specify the location of the new parameter. We only do this if the absoluteoffset is not equal to -1, because that would mean that we cannot and should not use absolute positions anymore
if (absoluteoffset != -1) {
absoluteoffset += relpos;
}
// the repeat string will contain the number of times a measurement (or aggregate container) should be repeated. It is a String because at this point it can be either a number or a reference to another measurement
String repeat = "";
// we check whether the measurement (or aggregate container) has a '*' inside it, meaning that it is a repeat measurement/aggregate
Matcher m = Pattern.compile("(.*)[*](.*)").matcher(paraname);
if (m.matches()) {
repeat = m.group(1);
paraname = m.group(2);
}
// check whether this measurement/aggregate actually has an entry in the parameters table
// first we check if it is a measurement by trying to retrieve it from the parameters map. If this succeeds we add it as a new parameterentry,
// otherwise, we search for it in the containersmap, as it is probably an aggregate. If it is not, we encountered an error
// note that one of the next 2 lines will return null, but this does not pose a problem, it makes programming easier along the way
Parameter param = parameters.get(paraname);
SequenceContainer sc = containers.get(paraname);
// if the sequenceentry is repeated a fixed number of times, this number is recorded in the 'repeated' variable and used to calculate the next absoluteoffset (done below)
int repeated = -1;
if (param != null) {
SequenceEntry se;
if(flags.contains("L")) {
if(param.parameterType instanceof IntegerParameterType) {
((IntegerParameterType)param.parameterType).encoding.byteOrder=ByteOrder.LITTLE_ENDIAN;
} else if(param.parameterType instanceof FloatParameterType) {
((FloatParameterType)param.parameterType).encoding.byteOrder=ByteOrder.LITTLE_ENDIAN;
} else if(param.parameterType instanceof EnumeratedParameterType) {
((EnumeratedParameterType)param.parameterType).encoding.byteOrder=ByteOrder.LITTLE_ENDIAN;
} else {
error("little endian not supported for this parameter: "+param);
}
}
// if absoluteoffset is -1, somewhere along the line we came across a measurement or aggregate that had as a result that the absoluteoffset could not be determined anymore; hence, a relative position is added
if (absoluteoffset == -1) {
se = new ParameterEntry(counter, container, relpos, ReferenceLocationType.previousEntry, param);
} else {
se = new ParameterEntry(counter, container, absoluteoffset, ReferenceLocationType.containerStart, param);
}
// also check if the parameter should be added multiple times, and if so, do so
repeated = addRepeat(se, repeat);
container.entryList.add(se);
} else {
if (sc != null) {
// ok, we found it as an aggregate, so we add it to the entryList of container, as a new ContainerEntry
// if absoluteoffset is -1, somewhere along the line we came across a measurement or aggregate that had as a result that the absoluteoffset could not be determined anymore; hence, a relative position is added
SequenceEntry se;
if (absoluteoffset == -1) {
se = new ContainerEntry(counter, container, relpos, ReferenceLocationType.previousEntry, sc);
} else {
se = new ContainerEntry(counter, container, absoluteoffset, ReferenceLocationType.containerStart, sc);
}
// also check if the parameter should be added multiple times, and if so, do so
repeated = addRepeat(se, repeat);
container.entryList.add(se);
} else {
throw new DatabaseLoadException("error on line "+(i+1)+" of the Containers sheet: the measurement/container '" + paraname + "' was not found in the parameters or containers map");
}
}
// after adding this measurement, we need to update the absoluteoffset for the next one. For this, we add the size of the current SequenceEntry to the absoluteoffset
int size=getSize(param,sc);
if ((repeated != -1) && (size != -1)) {
absoluteoffset += repeated * size;
} else {
// from this moment on, absoluteoffset is set to -1, meaning that all subsequent SequenceEntries must be relative
absoluteoffset = -1;
}
// increment the counters;
i++; counter++;
}
// at this point, we have added all the parameters and aggregate containers to the current packets. What remains to be done is link it with its base
if(parent!=null) {
// the condition is parsed and used to create the container.restrictionCriteria
//1) get the parent, from the same sheet
SequenceContainer sc = containers.get(parent);
//the parent is not in the same sheet, try to get from the Xtcedb
if(sc==null) {
sc = spaceSystem.getSequenceContainer(parent);
}
if (sc != null) {
container.setBaseContainer(sc);
} else {
final SequenceContainer c=container;
NameReference nr=new NameReference(parent, Type.SEQUENCE_CONTAINTER,
new ResolvedAction() {
@Override
public boolean resolved(NameDescription nd) {
c.setBaseContainer((SequenceContainer) nd);
return true;
}
});
spaceSystem.addUnresolvedReference(nr);
}
// 2) extract the condition and create the restrictioncriteria
ComparisonList cl = new ComparisonList();
// If conditions have been specified...
if( !"".equals( condition ) ) {
// 2.2) if there are multiple conditions, we get them all by splitting according to the ';' between the condition
String splitted[] = condition.split(";");
for (String sp: splitted) {
// 2.3) in each splitted part, we search for either =, !=, <=, >=, < or > and add this as a Comparison
Matcher m = Pattern.compile("(.*?)(=|!=|<=|>=|<|>)(.*)").matcher(sp);
if(!m.matches()) throw new DatabaseLoadException("error on line "+(start+1)+" of the Containers sheet: cannot parse inheritance condition '"+sp+"'");
Parameter param=null;
String paramName=m.group(1);
param = spaceSystem.getParameter(paramName);
// we now get the actual comparison operator (and we change '=' to '==')
String operation = m.group(2);
if (operation.equals("="))
operation="==";
Comparison.OperatorType coperator=Comparison.stringToOperator(operation);
// create the Comparison and add it
try {
if (param != null) {
ParameterInstanceRef pref=new ParameterInstanceRef(param, false);
cl.comparisons.add(new Comparison(pref, Integer.decode(m.group(3)), coperator));
} else {
final ParameterInstanceRef pref=new ParameterInstanceRef(false);
final Comparison ucomp=new Comparison(pref, Integer.decode(m.group(3)), coperator);
cl.comparisons.add(ucomp);
NameReference nr=new NameReference(paramName, Type.PARAMETER,
new ResolvedAction() {
@Override
public boolean resolved(NameDescription nd) {
pref.setParameter((Parameter)nd);
return true;
}
});
spaceSystem.addUnresolvedReference(nr);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
error("non-existing comparison found: " + m.group(2));
}
}
}
// 3) add the restrictioncriteria
container.restrictionCriteria = cl;
} else {
if(spaceSystem.getRootSequenceContainer()==null) {
spaceSystem.setRootSequenceContainer(container);
}
}
XtceAliasSet xas=new XtceAliasSet();
xas.addAlias(MdbMappings.MDB_OPSNAME, opsnamePrefix+container.getName());
container.setAliasSet(xas);
spaceSystem.addSequenceContainer(container);
}
}
private boolean hasColumn(Cell[] cells, int idx) {
return (cells.length>idx) && (cells[idx].getContents()!=null) && (!cells[idx].getContents().equals(""));
}
private void error(String s) {
System.err.println(s);
System.exit(-1);
}
/**
*/
private int getSize(Parameter param, SequenceContainer sc) {
// either we have a Parameter or we have a SequenceContainer, we cannot have both or neither
if (param != null) {
DataEncoding de = ((BaseDataType)param.getParameterType()).getEncoding();
if(de==null) error("Cannot determine the data encoding for "+param.getName());
if (de instanceof FloatDataEncoding) {
return de.sizeInBits;
} else if (de instanceof IntegerDataEncoding) {
return de.sizeInBits;
} else if (de instanceof BinaryDataEncoding) {
return de.sizeInBits;
} else if (de instanceof StringDataEncoding) {
return -1;
} else {
error("no known size for data encoding : " + de);
}
} else {
return sc.sizeInBits;
}
// this point should never be reached
return 0;
}
/** If repeat != "", decodes it to either an integer or a parameter and adds it to the SequenceEntry
* If repeat is an integer, this integer is returned
*/
private int addRepeat(SequenceEntry se, String repeat) {
if (!repeat.equals("")) {
se.repeatEntry = new Repeat();
try {
int rep = Integer.decode(repeat);
se.repeatEntry.count = new FixedIntegerValue();
((FixedIntegerValue)se.repeatEntry.count).value = rep;
return rep;
} catch (NumberFormatException e) {
se.repeatEntry.count = new DynamicIntegerValue();
Parameter repeatparam=parameters.get(repeat);
if(repeatparam==null) {
error("Can not find the parameter for repeat "+repeat);
}
((DynamicIntegerValue)se.repeatEntry.count).parameter = repeatparam;
return -1;
}
} else {
return 1;
}
}
class LimitDef {
public LimitDef(String condition, AlarmRanges ranges) {
this.condition=condition;
this.ranges=ranges;
}
String condition;
AlarmRanges ranges;
}
}
| private void loadParameters() {
Sheet para_sheet = workbook.getSheet("Parameters");
for (int i = 1; i < para_sheet.getRows(); i++) {
Cell[] cells = para_sheet.getRow(i);
if ((cells == null) || (cells.length < 4) || cells[0].getContents().startsWith("#")) {
continue;
}
String name = cells[IDX_PARAM_OPSNAME].getContents();
if (name.length() == 0) {
continue;
}
//String path = cells[IDX_MEAS_PATH].getContents();
String rawtype = cells[IDX_PARAM_RAWTYPE].getContents();
if("DerivedValue".equalsIgnoreCase(rawtype)) continue;
int bitlength=-1;
try {
String bitls=cells[IDX_PARAM_BITLENGTH].getContents();
if(!bitls.isEmpty()) bitlength = Integer.decode(bitls);
} catch(NumberFormatException e) {
error("Parameters:"+(i+1)+": can't get bitlength out of '"+cells[IDX_PARAM_BITLENGTH].getContents()+"'");
}
String engtype = cells[IDX_PARAM_ENGTYPE].getContents();
String calib=null;
if(cells.length>IDX_PARAM_CALIBRATION) calib = cells[IDX_PARAM_CALIBRATION].getContents();
if("n".equals(calib) || "".equals(calib))calib=null;
if("y".equalsIgnoreCase(calib)) calib=name;
ParameterType ptype=null;
if ("uint".equalsIgnoreCase(engtype)) {
ptype = new IntegerParameterType(name);
((IntegerParameterType)ptype).signed = false;
} else if ("int".equalsIgnoreCase(engtype)) {
ptype = new IntegerParameterType(name);
} else if ("float".equalsIgnoreCase(engtype)) {
ptype = new FloatParameterType(name);
} else if ("enumerated".equalsIgnoreCase(engtype)) {
if(calib==null) {
error("parameter " + name + " has to have an enumeration");
}
ptype = enumerations.get(calib);
if (ptype == null) {
error("parameter " + name + " is supposed to have an enumeration '" + calib + "' but the enumeration does not exist");
}
} else if ("string".equalsIgnoreCase(engtype)) {
ptype = new StringParameterType(name);
} else if ("binary".equalsIgnoreCase(engtype)) {
ptype = new BinaryParameterType(name);
} else {
error("Parameters:"+(i+1)+": unknown parameter type " + engtype);
}
loadParameterLimits(ptype,cells);
//calibrations
DataEncoding encoding = null;
if (("uint".equalsIgnoreCase(rawtype)) || ("int".equalsIgnoreCase(rawtype))) {
if(bitlength==-1) error("Parameters:"+(i+1)+" for integer parameters bitlength is mandatory");
encoding = new IntegerDataEncoding(name, bitlength);
if ("int".equalsIgnoreCase(rawtype)) {
encoding = new IntegerDataEncoding(name, bitlength);
((IntegerDataEncoding)encoding).encoding = IntegerDataEncoding.Encoding.twosCompliment;
}
if ((!"enumerated".equalsIgnoreCase(engtype)) && (calib!=null)) {
Calibrator c = calibrators.get(calib);
if (c == null) {
error("parameter " + name + " is supposed to have a calibrator '" + calib + "' but the calibrator does not exist");
}
((IntegerDataEncoding)encoding).defaultCalibrator = c;
}
} else if ("bytestream".equalsIgnoreCase(rawtype)) {
if(bitlength==-1) error("Parameters:"+(i+1)+" for bytestream parameters bitlength is mandatory");
encoding=new BinaryDataEncoding(name, bitlength);
} else if ("string".equalsIgnoreCase(rawtype)) {
// Version <= 1.6 String type
// STRING
if(bitlength==-1) {
// Assume null-terminated if no length specified
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.TerminationChar);
} else {
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.Fixed);
encoding.setSizeInBits(bitlength);
}
} else if ( "fixedstring".equalsIgnoreCase( rawtype ) ) {
// v1.7 String type
// FIXEDSTRING
if(bitlength==-1) error("Parameters:"+(i+1)+" bitlength is mandatory for fixedstring raw type");
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.Fixed);
encoding.setSizeInBits(bitlength);
} else if ( rawtype.toLowerCase().startsWith( "terminatedstring" ) ) {
// v1.7 String type
// TERMINATEDSTRING
encoding=new StringDataEncoding(name, StringDataEncoding.SizeType.TerminationChar);
// Use specified byte if found, otherwise accept class default.
int startBracket = rawtype.indexOf( '(' );
if( startBracket != -1 ) {
int endBracket = rawtype.indexOf( ')', startBracket );
if( endBracket != -1 ) {
try {
byte terminationChar = Byte.parseByte( rawtype.substring( rawtype.indexOf('x', startBracket)+1, endBracket ).trim(), 16 );
((StringDataEncoding)encoding).setTerminationChar(terminationChar);
} catch (NumberFormatException e) {
error( "Parameters:"+(i+1)+" could not parse specified base 16 terminator from "+rawtype );
}
}
}
} else if ( rawtype.toLowerCase().startsWith( "prependedsizestring" ) ) {
// v1.7 String type
// PREPENDEDSIZESTRING
encoding=new StringDataEncoding( name, StringDataEncoding.SizeType.LeadingSize );
// Use specified size if found, otherwise accept class default.
int startBracket = rawtype.indexOf( '(' );
if( startBracket != -1 ) {
int endBracket = rawtype.indexOf( ')', startBracket );
if( endBracket != -1 ) {
try {
int sizeInBitsOfSizeTag = Integer.parseInt( rawtype.substring(startBracket+1, endBracket).trim() );
((StringDataEncoding)encoding).setSizeInBitsOfSizeTag( sizeInBitsOfSizeTag );
} catch (NumberFormatException e) {
error( "Parameters:"+(i+1)+" could not parse integer size from "+rawtype );
}
}
}
} else if ("float".equalsIgnoreCase(rawtype)) {
if(bitlength==-1) error("Parameters:"+(i+1)+" for float parameters bitlength is mandatory");
encoding=new FloatDataEncoding(name, bitlength);
if(calib!=null) {
Calibrator c = calibrators.get(calib);
if (c == null) {
error("parameter " + name + " is supposed to have a calibrator '" + calib + "' but the calibrator does not exist.");
} else {
((FloatDataEncoding)encoding).defaultCalibrator = c;
}
}
} else {
error("unknown raw type " + rawtype);
}
if (ptype instanceof IntegerParameterType) {
// Integers can be encoded as strings
if( encoding instanceof StringDataEncoding ) {
// Create a new int encoding which uses the configured string encoding
IntegerDataEncoding intStringEncoding = new IntegerDataEncoding(name, ((StringDataEncoding)encoding));
if( calib != null ) {
Calibrator c = calibrators.get(calib);
if( c == null ) {
error("Parameter " + name + " specified calibrator '" + calib + "' but the calibrator does not exist");
}
intStringEncoding.defaultCalibrator = c;
}
((IntegerParameterType)ptype).encoding = intStringEncoding;
} else {
((IntegerParameterType)ptype).encoding = encoding;
}
} else if (ptype instanceof BinaryParameterType) {
((BinaryParameterType)ptype).encoding = encoding;
} else if (ptype instanceof FloatParameterType) {
// Floats can be encoded as strings
if ( encoding instanceof StringDataEncoding ) {
// Create a new float encoding which uses the configured string encoding
FloatDataEncoding floatStringEncoding = new FloatDataEncoding( name, ((StringDataEncoding)encoding) );
if(calib!=null) {
Calibrator c = calibrators.get(calib);
if( c == null ) {
error("Parameter " + name + " specified calibrator '" + calib + "' but the calibrator does not exist.");
} else {
floatStringEncoding.defaultCalibrator = c;
}
}
((FloatParameterType)ptype).encoding = floatStringEncoding;
} else {
((FloatParameterType)ptype).encoding = encoding;
}
} else if (ptype instanceof EnumeratedParameterType) {
// Enumerations encoded as string integers
if( encoding instanceof StringDataEncoding ) {
IntegerDataEncoding intStringEncoding = new IntegerDataEncoding(name, ((StringDataEncoding)encoding));
// Don't set calibrator, already done when making ptype
((EnumeratedParameterType)ptype).encoding = intStringEncoding;
} else {
((EnumeratedParameterType)ptype).encoding = encoding;
}
} else if (ptype instanceof StringParameterType) {
((StringParameterType)ptype).encoding = encoding;
}
Parameter param = new Parameter(name);
param.setParameterType(ptype);
parameters.put(param.getName(), param);
XtceAliasSet xas=new XtceAliasSet();
xas.addAlias(MdbMappings.MDB_OPSNAME, opsnamePrefix+param.getName());
param.setAliasSet(xas);
spaceSystem.addParameter(param);
}
/* System.out.println("got parameters:");
for (Parameter p: parameters.values()) {
System.out.println(p);
}
*/ }
private void loadParameterLimits(ParameterType ptype, Cell[] cells) {
if (cells.length<=IDX_PARAM_LOWWARNILIMIT) return;
String mins=cells[IDX_PARAM_LOWWARNILIMIT].getContents();
//System.out.println("limits.length="+limits.size()+"limits: "+limits.keySet() +"mins="+mins);
if(limits.containsKey(mins)) { //limit is specified on the separate sheet
for(LimitDef ld:limits.get(mins)) {
Pattern p=Pattern.compile("(\\w+)(==|!=|>|<|>=|<=)(\\w+)");
if(ld.condition.length()>0) {
Matcher m=p.matcher(ld.condition);
if((!m.matches()) ||(m.groupCount()!=3)) {
log.warn("Cannot parse alarm condition '"+ld.condition+"'");
continue;
}
String pname=m.group(1);
String values=m.group(3);
String op=m.group(2);
Parameter para=parameters.get(pname);
if(para!=null) {
ParameterInstanceRef paraRef=new ParameterInstanceRef(para);
Comparison c;
if(para.parameterType instanceof IntegerParameterType) {
try {
long value=Long.parseLong(values);
c=new Comparison(paraRef,value,Comparison.stringToOperator(op));
} catch (NumberFormatException e) {
log.warn("Cannot parse alarm condition '"+ld.condition+"': "+e.getMessage());
continue;
}
} else if(para.parameterType instanceof EnumeratedParameterType) {
c=new Comparison(paraRef, values, Comparison.stringToOperator(op));
} else {
log.warn("Conditions not supported for parameter of type "+para.parameterType);
continue;
}
NumericContextAlarm nca=new NumericContextAlarm();
nca.setContextMatch(c);
nca.setStaticAlarmRanges(ld.ranges);
if(ptype instanceof IntegerParameterType){
((IntegerParameterType)ptype).addContextAlarm(nca);
} else {
((FloatParameterType)ptype).addContextAlarm(nca);
}
} else { //TODO
// ParameterInstanceRef paraRef=new ParameterInstanceRef(new NameReference(pname));
// Comparison c=new Comparison(paraRef, Comparison.stringToOperator(op));
}
} else {
setDefaultWarningAlarmRange(ptype, ld.ranges.warningRange);
setDefaultCriticalAlarmRange(ptype, ld.ranges.criticalRange);
}
}
} else if((cells.length>IDX_PARAM_HIGHWARNILIMIT) && ((ptype instanceof IntegerParameterType) || (ptype instanceof FloatParameterType))) {
String maxs=cells[IDX_PARAM_HIGHWARNILIMIT].getContents();
if((mins.length()>0) && (maxs.length()>0)) {
double min=(mins.length()>0)?Double.parseDouble(mins):Double.NEGATIVE_INFINITY;
double max=(maxs.length()>0)?Double.parseDouble(maxs):Double.POSITIVE_INFINITY;
setDefaultWarningAlarmRange(ptype,new FloatRange(min,max));
}
}
// danger limits
if((cells.length>IDX_PARAM_HIGHCRITICALLIMIT) && ((ptype instanceof IntegerParameterType) || (ptype instanceof FloatParameterType))) {
mins=cells[IDX_PARAM_LOWCRITICALLIMIT].getContents();
String maxs=cells[IDX_PARAM_HIGHCRITICALLIMIT].getContents();
if((mins.length()>0) && (maxs.length()>0)) {
double min=Double.parseDouble(mins);
double max=Double.parseDouble(maxs);
setDefaultCriticalAlarmRange(ptype, new FloatRange(min,max));
}
}
}
private void setDefaultCriticalAlarmRange(ParameterType ptype, FloatRange range) {
if(range==null)return;
if(ptype instanceof IntegerParameterType){
((IntegerParameterType)ptype).setDefaultCriticalAlarmRange(range);
} else {
((FloatParameterType)ptype).setDefaultCriticalAlarmRange(range);
}
}
private void setDefaultWarningAlarmRange(ParameterType ptype, FloatRange range) {
if(range==null)return;
if(ptype instanceof IntegerParameterType){
((IntegerParameterType)ptype).setDefaultWarningAlarmRange(range);
} else {
((FloatParameterType)ptype).setDefaultWarningAlarmRange(range);
}
}
private void loadContainers() throws DatabaseLoadException {
Sheet tm_sheet = workbook.getSheet("Containers");
HashMap<String, SequenceContainer> containers = new HashMap<String, SequenceContainer>();
for (int i = 1; i < tm_sheet.getRows(); i++) {
// search for a new packet definition, starting from row i
// (explanatory note, i is incremented inside this loop too, and that's why the following 4 lines work)
Cell[] cells = tm_sheet.getRow(i);
if (cells == null || cells.length<1) {
log.debug("Ignoring line {} because it's empty",(i+1));
continue;
}
if(cells[0].getContents().equals("")|| cells[0].getContents().startsWith("#")) {
log.debug("Ignoring line {} because first cell is empty or starts with '#'", (i+1));
continue;
}
// at this point, cells contains the data (name, path, ...) of either
// a) a sub-container (inherits from another packet)
// b) an aggregate container (which will be used as if it were a measurement, by other (sub)containers)
String name = cells[IDX_CONT_NAME].getContents();
String parent=null;
String condition=null;
if(cells.length>IDX_CONT_PARENT) {
parent=cells[IDX_CONT_PARENT].getContents();
if(cells.length<=IDX_CONT_CONDITION) {
error("parent specified but without inheritance condition on container on line "+(i+1));
}
condition = cells[IDX_CONT_CONDITION].getContents();
//if( "".equals( condition ) ) {
// error( String.format( "Container %s (from spreadsheet '%s' line %d) has a parent container specified but no inheritance condition", name, configName, i));
//}
}
if("".equals(parent)) parent=null;
// absoluteoffset is the absolute offset of the first parameter of the container
int absoluteoffset=-1;
if(parent==null) {
absoluteoffset=0;
} else {
int x=parent.indexOf(":");
if(x!=-1) {
absoluteoffset=Integer.decode(parent.substring(x+1));
parent=parent.substring(0, x);
}
}
int containerSizeInBits=-1;
if(hasColumn(cells, IDX_CONT_SIZEINBITS)) {
containerSizeInBits=Integer.decode(cells[IDX_CONT_SIZEINBITS].getContents());
}
RateInStream rate=null;
if(hasColumn(cells, IDX_CONT_EXPECTED_INTERVAL)) {
int expint=Integer.decode(cells[IDX_CONT_EXPECTED_INTERVAL].getContents());
rate=new RateInStream(expint);
}
// create a new SequenceContainer that will hold the parameters (i.e. SequenceEntries) for the ORDINARY/SUB/AGGREGATE packets, and register that new SequenceContainer in the containers hashmap
SequenceContainer container = new SequenceContainer(name);
container.sizeInBits=containerSizeInBits;
containers.put(name, container);
container.setRateInStream(rate);
//System.out.println("for "+name+" got absoluteoffset="+)
// we mark the start of the TM packet and advance to the next line, to get to the first parameter (if there is one)
int start = i++;
// now, we start processing the parameters (or references to aggregate containers)
boolean end = false;
int counter = 0; // sequence number of the SequenceEntrys in the SequenceContainer
while (!end && (i < tm_sheet.getRows())) {
// get the next row, containing a measurement/aggregate reference
cells = tm_sheet.getRow(i);
// determine whether we have not reached the end of the packet definition.
if ((cells == null) || (cells.length <= IDX_CONT_RELPOS) || cells[IDX_CONT_RELPOS].getContents().equals("")) {
end = true; continue;
}
// extract a few variables, for further use
String flags = cells[IDX_CONT_FLAGS].getContents();
String paraname = cells[IDX_CONT_PARA_NAME].getContents();
if((cells.length<=IDX_CONT_RELPOS)||cells[IDX_CONT_RELPOS].getContents().equals("")) error("relpos is not specified for "+paraname+" on line "+(i+1));
int relpos = Integer.decode(cells[IDX_CONT_RELPOS].getContents());
// we add the relative position to the absoluteoffset, to specify the location of the new parameter. We only do this if the absoluteoffset is not equal to -1, because that would mean that we cannot and should not use absolute positions anymore
if (absoluteoffset != -1) {
absoluteoffset += relpos;
}
// the repeat string will contain the number of times a measurement (or aggregate container) should be repeated. It is a String because at this point it can be either a number or a reference to another measurement
String repeat = "";
// we check whether the measurement (or aggregate container) has a '*' inside it, meaning that it is a repeat measurement/aggregate
Matcher m = Pattern.compile("(.*)[*](.*)").matcher(paraname);
if (m.matches()) {
repeat = m.group(1);
paraname = m.group(2);
}
// check whether this measurement/aggregate actually has an entry in the parameters table
// first we check if it is a measurement by trying to retrieve it from the parameters map. If this succeeds we add it as a new parameterentry,
// otherwise, we search for it in the containersmap, as it is probably an aggregate. If it is not, we encountered an error
// note that one of the next 2 lines will return null, but this does not pose a problem, it makes programming easier along the way
Parameter param = parameters.get(paraname);
SequenceContainer sc = containers.get(paraname);
// if the sequenceentry is repeated a fixed number of times, this number is recorded in the 'repeated' variable and used to calculate the next absoluteoffset (done below)
int repeated = -1;
if (param != null) {
SequenceEntry se;
if(flags.contains("L")) {
if(param.parameterType instanceof IntegerParameterType) {
((IntegerParameterType)param.parameterType).encoding.byteOrder=ByteOrder.LITTLE_ENDIAN;
} else if(param.parameterType instanceof FloatParameterType) {
((FloatParameterType)param.parameterType).encoding.byteOrder=ByteOrder.LITTLE_ENDIAN;
} else if(param.parameterType instanceof EnumeratedParameterType) {
((EnumeratedParameterType)param.parameterType).encoding.byteOrder=ByteOrder.LITTLE_ENDIAN;
} else {
error("little endian not supported for this parameter: "+param);
}
}
// if absoluteoffset is -1, somewhere along the line we came across a measurement or aggregate that had as a result that the absoluteoffset could not be determined anymore; hence, a relative position is added
if (absoluteoffset == -1) {
se = new ParameterEntry(counter, container, relpos, ReferenceLocationType.previousEntry, param);
} else {
se = new ParameterEntry(counter, container, absoluteoffset, ReferenceLocationType.containerStart, param);
}
// also check if the parameter should be added multiple times, and if so, do so
repeated = addRepeat(se, repeat);
container.entryList.add(se);
} else {
if (sc != null) {
// ok, we found it as an aggregate, so we add it to the entryList of container, as a new ContainerEntry
// if absoluteoffset is -1, somewhere along the line we came across a measurement or aggregate that had as a result that the absoluteoffset could not be determined anymore; hence, a relative position is added
SequenceEntry se;
if (absoluteoffset == -1) {
se = new ContainerEntry(counter, container, relpos, ReferenceLocationType.previousEntry, sc);
} else {
se = new ContainerEntry(counter, container, absoluteoffset, ReferenceLocationType.containerStart, sc);
}
// also check if the parameter should be added multiple times, and if so, do so
repeated = addRepeat(se, repeat);
container.entryList.add(se);
} else {
throw new DatabaseLoadException("error on line "+(i+1)+" of the Containers sheet: the measurement/container '" + paraname + "' was not found in the parameters or containers map");
}
}
// after adding this measurement, we need to update the absoluteoffset for the next one. For this, we add the size of the current SequenceEntry to the absoluteoffset
int size=getSize(param,sc);
if ((repeated != -1) && (size != -1) && (absoluteoffset != -1)) {
absoluteoffset += repeated * size;
} else {
// from this moment on, absoluteoffset is set to -1, meaning that all subsequent SequenceEntries must be relative
absoluteoffset = -1;
}
// increment the counters;
i++; counter++;
}
// at this point, we have added all the parameters and aggregate containers to the current packets. What remains to be done is link it with its base
if(parent!=null) {
// the condition is parsed and used to create the container.restrictionCriteria
//1) get the parent, from the same sheet
SequenceContainer sc = containers.get(parent);
//the parent is not in the same sheet, try to get from the Xtcedb
if(sc==null) {
sc = spaceSystem.getSequenceContainer(parent);
}
if (sc != null) {
container.setBaseContainer(sc);
} else {
final SequenceContainer c=container;
NameReference nr=new NameReference(parent, Type.SEQUENCE_CONTAINTER,
new ResolvedAction() {
@Override
public boolean resolved(NameDescription nd) {
c.setBaseContainer((SequenceContainer) nd);
return true;
}
});
spaceSystem.addUnresolvedReference(nr);
}
// 2) extract the condition and create the restrictioncriteria
ComparisonList cl = new ComparisonList();
// If conditions have been specified...
if( !"".equals( condition ) ) {
// 2.2) if there are multiple conditions, we get them all by splitting according to the ';' between the condition
String splitted[] = condition.split(";");
for (String sp: splitted) {
// 2.3) in each splitted part, we search for either =, !=, <=, >=, < or > and add this as a Comparison
Matcher m = Pattern.compile("(.*?)(=|!=|<=|>=|<|>)(.*)").matcher(sp);
if(!m.matches()) throw new DatabaseLoadException("error on line "+(start+1)+" of the Containers sheet: cannot parse inheritance condition '"+sp+"'");
Parameter param=null;
String paramName=m.group(1);
param = spaceSystem.getParameter(paramName);
// we now get the actual comparison operator (and we change '=' to '==')
String operation = m.group(2);
if (operation.equals("="))
operation="==";
Comparison.OperatorType coperator=Comparison.stringToOperator(operation);
// create the Comparison and add it
try {
if (param != null) {
ParameterInstanceRef pref=new ParameterInstanceRef(param, false);
cl.comparisons.add(new Comparison(pref, Integer.decode(m.group(3)), coperator));
} else {
final ParameterInstanceRef pref=new ParameterInstanceRef(false);
final Comparison ucomp=new Comparison(pref, Integer.decode(m.group(3)), coperator);
cl.comparisons.add(ucomp);
NameReference nr=new NameReference(paramName, Type.PARAMETER,
new ResolvedAction() {
@Override
public boolean resolved(NameDescription nd) {
pref.setParameter((Parameter)nd);
return true;
}
});
spaceSystem.addUnresolvedReference(nr);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
error("non-existing comparison found: " + m.group(2));
}
}
}
// 3) add the restrictioncriteria
container.restrictionCriteria = cl;
} else {
if(spaceSystem.getRootSequenceContainer()==null) {
spaceSystem.setRootSequenceContainer(container);
}
}
XtceAliasSet xas=new XtceAliasSet();
xas.addAlias(MdbMappings.MDB_OPSNAME, opsnamePrefix+container.getName());
container.setAliasSet(xas);
spaceSystem.addSequenceContainer(container);
}
}
private boolean hasColumn(Cell[] cells, int idx) {
return (cells.length>idx) && (cells[idx].getContents()!=null) && (!cells[idx].getContents().equals(""));
}
private void error(String s) {
System.err.println(s);
System.exit(-1);
}
/**
*/
private int getSize(Parameter param, SequenceContainer sc) {
// either we have a Parameter or we have a SequenceContainer, we cannot have both or neither
if (param != null) {
DataEncoding de = ((BaseDataType)param.getParameterType()).getEncoding();
if(de==null) error("Cannot determine the data encoding for "+param.getName());
if (de instanceof FloatDataEncoding) {
return de.sizeInBits;
} else if (de instanceof IntegerDataEncoding) {
return de.sizeInBits;
} else if (de instanceof BinaryDataEncoding) {
return de.sizeInBits;
} else if (de instanceof StringDataEncoding) {
return -1;
} else {
error("no known size for data encoding : " + de);
}
} else {
return sc.sizeInBits;
}
// this point should never be reached
return 0;
}
/** If repeat != "", decodes it to either an integer or a parameter and adds it to the SequenceEntry
* If repeat is an integer, this integer is returned
*/
private int addRepeat(SequenceEntry se, String repeat) {
if (!repeat.equals("")) {
se.repeatEntry = new Repeat();
try {
int rep = Integer.decode(repeat);
se.repeatEntry.count = new FixedIntegerValue();
((FixedIntegerValue)se.repeatEntry.count).value = rep;
return rep;
} catch (NumberFormatException e) {
se.repeatEntry.count = new DynamicIntegerValue();
Parameter repeatparam=parameters.get(repeat);
if(repeatparam==null) {
error("Can not find the parameter for repeat "+repeat);
}
((DynamicIntegerValue)se.repeatEntry.count).parameter = repeatparam;
return -1;
}
} else {
return 1;
}
}
class LimitDef {
public LimitDef(String condition, AlarmRanges ranges) {
this.condition=condition;
this.ranges=ranges;
}
String condition;
AlarmRanges ranges;
}
}
|
diff --git a/extension/eevolution/warehousemanagement/src/main/java/org/eevolution/process/GenerateShipmentOutBound.java b/extension/eevolution/warehousemanagement/src/main/java/org/eevolution/process/GenerateShipmentOutBound.java
index 5708700..e0b614c 100644
--- a/extension/eevolution/warehousemanagement/src/main/java/org/eevolution/process/GenerateShipmentOutBound.java
+++ b/extension/eevolution/warehousemanagement/src/main/java/org/eevolution/process/GenerateShipmentOutBound.java
@@ -1,234 +1,234 @@
/**********************************************************************
* This file is part of Adempiere ERP Bazaar *
* http://www.adempiere.org *
* *
* Copyright (C) Victor Perez *
* Copyright (C) Contributors *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, *
* MA 02110-1301, USA. *
* *
* Contributors: *
* - Victor Perez ([email protected] ) *
* *
* Sponsors: *
* - e-Evolution (http://www.e-evolution.com/) *
**********************************************************************/
package org.eevolution.process;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.logging.Level;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.model.X_T_Selection;
import org.compiere.model.MBPartner;
import org.compiere.model.MDocType;
import org.compiere.model.MInOut;
import org.compiere.model.MInOutLine;
import org.compiere.model.MLocator;
import org.compiere.model.MOrder;
import org.compiere.model.MOrderLine;
import org.compiere.model.MOrg;
import org.compiere.model.MPInstance;
import org.compiere.model.MStorage;
import org.compiere.model.MWarehouse;
import org.compiere.model.Query;
import org.compiere.process.ProcessInfoParameter;
import org.compiere.process.SvrProcess;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.engines.Warehouse.WMRuleEngine;
import org.eevolution.model.I_WM_InOutBound;
import org.eevolution.model.I_WM_InOutBoundLine;
import org.eevolution.model.MDDOrder;
import org.eevolution.model.MDDOrderLine;
import org.eevolution.model.MWMInOutBound;
import org.eevolution.model.MWMInOutBoundLine;
import org.eevolution.model.X_WM_InOutBound;
/**
*
* @author [email protected], www.e-evolution.com
* @version $Id: $
*/
public class GenerateShipmentOutBound extends SvrProcess
{
/** Record ID */
protected int p_Record_ID = 0;
protected String p_DocAction = null;
protected boolean p_IsIncludeNotAvailable = false;
protected Timestamp p_MovementDate = null;
private Hashtable m_shipments = new Hashtable();
/**
* Get Parameters
*/
protected void prepare ()
{
p_Record_ID = getRecord_ID();
for (ProcessInfoParameter para:getParameter())
{
String name = para.getParameterName();
if (para.getParameter() == null)
;
else if (name.equals("DocAction"))
{
p_DocAction = (String)para.getParameter();
}
else if (name.equals("IsIncludeNotAvailable"))
{
p_IsIncludeNotAvailable = "Y".equals(para.getParameter());
}
else if (name.equals("MovementDate"))
{
p_MovementDate = (Timestamp)para.getParameter();
}
else
log.log(Level.SEVERE, "Unknown Parameter: " + name);
}
}
/**
* Process - Generate Export Format
* @return info
*/
@SuppressWarnings("unchecked")
protected String doIt () throws Exception
{
String whereClause = "EXISTS (SELECT T_Selection_ID FROM T_Selection WHERE T_Selection.AD_PInstance_ID=? AND T_Selection.T_Selection_ID=WM_InOutBoundLine.WM_InOutboundLine_ID)";
Collection <MWMInOutBoundLine> boundlines = new Query(getCtx(), I_WM_InOutBoundLine.Table_Name, whereClause, get_TrxName())
.setClient_ID()
.setParameters(new Object[]{getAD_PInstance_ID()})
.list();
int seq = 10;
for (MWMInOutBoundLine boundline: boundlines)
{
if(boundline.getQtyToShip().signum() > 0 || p_IsIncludeNotAvailable)
{
createMInOut(boundline);
}
seq ++;
}
Enumeration shipments = m_shipments.elements();
while (shipments.hasMoreElements())
{
MInOut inout = (MInOut) shipments.nextElement();
inout.completeIt();
inout.saveEx();
}
return ""; //;"@DocumentNo@ " + bound.getDocumentNo();
}
/**
* Create Shipment to Out Bound Order
* @param Out Bound Order Line
*/
public void createMInOut(MWMInOutBoundLine line)
{
MOrderLine oline = line.getMOrderLine();
if(line.getPickedQty().subtract(oline.getQtyDelivered()).signum() <= 0 && !p_IsIncludeNotAvailable)
{
return;
}
MLocator standing = null;
BigDecimal QtyDelivered = Env.ZERO;
if(p_IsIncludeNotAvailable)
{
standing = MLocator.getDefault((MWarehouse)line.getParent().getM_Warehouse());
QtyDelivered = line.getQtyToPick().subtract(oline.getQtyDelivered());
}
else
{
standing = line.getMLocator();
QtyDelivered = line.getPickedQty().subtract(oline.getQtyDelivered());
}
MInOut inout = getMInOut(oline);
inout.setIsSOTrx(true);
inout.saveEx();
MInOutLine shipmentLine = new MInOutLine(line.getCtx(), 0 , line.get_TrxName());
shipmentLine.setM_InOut_ID(inout.getM_InOut_ID());
shipmentLine.setM_Locator_ID(standing.getM_Locator_ID());
shipmentLine.setM_Product_ID(line.getM_Product_ID());
- shipmentLine.setQtyEntered(line.getPickedQty());
+ shipmentLine.setQtyEntered(QtyDelivered);
shipmentLine.setMovementQty(QtyDelivered);
shipmentLine.setC_OrderLine_ID(oline.getC_OrderLine_ID());
shipmentLine.saveEx();
}
/**
* get Document Type
* @param docBaseType
* @return int Document Type
*/
protected int getDocType(String docBaseType)
{
MDocType[] docs = MDocType.getOfDocBaseType(getCtx(), docBaseType);
if (docs == null || docs.length == 0)
{
String reference = Msg.getMsg(getCtx(), "SequenceDocNotFound");
String textMsg = "Not found default document type for docbasetype "+ docBaseType;
throw new AdempiereException(textMsg);
}
else
{
for (MDocType doc : docs)
{
if(doc.isSOTrx())
{
log.info("Doc Type for "+docBaseType+": "+ doc.getC_DocType_ID());
return doc.getC_DocType_ID();
}
}
String textMsg = "Not found default document type for docbasetype "+ docBaseType;
throw new AdempiereException(textMsg);
}
}
/**
* Create Shipment heder
* @param oline Sales Order Line
* @return MInOut return the Shipment header
*/
private MInOut getMInOut(MOrderLine oline)
{
MInOut inout = (MInOut) m_shipments.get(oline.getC_Order_ID());
if(inout != null)
{
return inout;
}
MOrder order = oline.getParent();
inout = new MInOut(order,getDocType(MDocType.DOCBASETYPE_MaterialDelivery), p_MovementDate);
m_shipments.put(order.getC_Order_ID(), inout);
return inout;
}
}
| true | true | public void createMInOut(MWMInOutBoundLine line)
{
MOrderLine oline = line.getMOrderLine();
if(line.getPickedQty().subtract(oline.getQtyDelivered()).signum() <= 0 && !p_IsIncludeNotAvailable)
{
return;
}
MLocator standing = null;
BigDecimal QtyDelivered = Env.ZERO;
if(p_IsIncludeNotAvailable)
{
standing = MLocator.getDefault((MWarehouse)line.getParent().getM_Warehouse());
QtyDelivered = line.getQtyToPick().subtract(oline.getQtyDelivered());
}
else
{
standing = line.getMLocator();
QtyDelivered = line.getPickedQty().subtract(oline.getQtyDelivered());
}
MInOut inout = getMInOut(oline);
inout.setIsSOTrx(true);
inout.saveEx();
MInOutLine shipmentLine = new MInOutLine(line.getCtx(), 0 , line.get_TrxName());
shipmentLine.setM_InOut_ID(inout.getM_InOut_ID());
shipmentLine.setM_Locator_ID(standing.getM_Locator_ID());
shipmentLine.setM_Product_ID(line.getM_Product_ID());
shipmentLine.setQtyEntered(line.getPickedQty());
shipmentLine.setMovementQty(QtyDelivered);
shipmentLine.setC_OrderLine_ID(oline.getC_OrderLine_ID());
shipmentLine.saveEx();
}
| public void createMInOut(MWMInOutBoundLine line)
{
MOrderLine oline = line.getMOrderLine();
if(line.getPickedQty().subtract(oline.getQtyDelivered()).signum() <= 0 && !p_IsIncludeNotAvailable)
{
return;
}
MLocator standing = null;
BigDecimal QtyDelivered = Env.ZERO;
if(p_IsIncludeNotAvailable)
{
standing = MLocator.getDefault((MWarehouse)line.getParent().getM_Warehouse());
QtyDelivered = line.getQtyToPick().subtract(oline.getQtyDelivered());
}
else
{
standing = line.getMLocator();
QtyDelivered = line.getPickedQty().subtract(oline.getQtyDelivered());
}
MInOut inout = getMInOut(oline);
inout.setIsSOTrx(true);
inout.saveEx();
MInOutLine shipmentLine = new MInOutLine(line.getCtx(), 0 , line.get_TrxName());
shipmentLine.setM_InOut_ID(inout.getM_InOut_ID());
shipmentLine.setM_Locator_ID(standing.getM_Locator_ID());
shipmentLine.setM_Product_ID(line.getM_Product_ID());
shipmentLine.setQtyEntered(QtyDelivered);
shipmentLine.setMovementQty(QtyDelivered);
shipmentLine.setC_OrderLine_ID(oline.getC_OrderLine_ID());
shipmentLine.saveEx();
}
|
diff --git a/src/com/android/contacts/detail/ContactDetailFragment.java b/src/com/android/contacts/detail/ContactDetailFragment.java
index 87c321ef6..cde1215d6 100644
--- a/src/com/android/contacts/detail/ContactDetailFragment.java
+++ b/src/com/android/contacts/detail/ContactDetailFragment.java
@@ -1,2233 +1,2242 @@
/*
* 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.contacts.detail;
import android.app.Activity;
import android.app.Fragment;
import android.app.SearchManager;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.ParseException;
import android.net.Uri;
import android.net.WebAddress;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Directory;
import android.provider.ContactsContract.DisplayNameSources;
import android.provider.ContactsContract.StatusUpdates;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.DragEvent;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.TextView;
import com.android.contacts.Collapser;
import com.android.contacts.Collapser.Collapsible;
import com.android.contacts.ContactPresenceIconUtil;
import com.android.contacts.ContactSaveService;
import com.android.contacts.ContactsUtils;
import com.android.contacts.GroupMetaData;
import com.android.contacts.R;
import com.android.contacts.TypePrecedence;
import com.android.contacts.activities.ContactDetailActivity.FragmentKeyListener;
import com.android.contacts.editor.SelectAccountDialogFragment;
import com.android.contacts.model.AccountTypeManager;
import com.android.contacts.model.Contact;
import com.android.contacts.model.RawContact;
import com.android.contacts.model.RawContactDelta;
import com.android.contacts.model.RawContactDelta.ValuesDelta;
import com.android.contacts.model.RawContactDeltaList;
import com.android.contacts.model.RawContactModifier;
import com.android.contacts.model.account.AccountType;
import com.android.contacts.model.account.AccountType.EditType;
import com.android.contacts.model.account.AccountWithDataSet;
import com.android.contacts.model.dataitem.DataItem;
import com.android.contacts.model.dataitem.DataKind;
import com.android.contacts.model.dataitem.EmailDataItem;
import com.android.contacts.model.dataitem.EventDataItem;
import com.android.contacts.model.dataitem.GroupMembershipDataItem;
import com.android.contacts.model.dataitem.ImDataItem;
import com.android.contacts.model.dataitem.NicknameDataItem;
import com.android.contacts.model.dataitem.NoteDataItem;
import com.android.contacts.model.dataitem.OrganizationDataItem;
import com.android.contacts.model.dataitem.PhoneDataItem;
import com.android.contacts.model.dataitem.RelationDataItem;
import com.android.contacts.model.dataitem.SipAddressDataItem;
import com.android.contacts.model.dataitem.StructuredNameDataItem;
import com.android.contacts.model.dataitem.StructuredPostalDataItem;
import com.android.contacts.model.dataitem.WebsiteDataItem;
import com.android.contacts.util.AccountsListAdapter.AccountListFilter;
import com.android.contacts.util.ClipboardUtils;
import com.android.contacts.util.Constants;
import com.android.contacts.util.DataStatus;
import com.android.contacts.util.DateUtils;
import com.android.contacts.util.PhoneCapabilityTester;
import com.android.contacts.util.StructuredPostalUtils;
import com.android.internal.telephony.ITelephony;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ContactDetailFragment extends Fragment implements FragmentKeyListener,
SelectAccountDialogFragment.Listener, OnItemClickListener {
private static final String TAG = "ContactDetailFragment";
private interface ContextMenuIds {
static final int COPY_TEXT = 0;
static final int CLEAR_DEFAULT = 1;
static final int SET_DEFAULT = 2;
}
private static final String KEY_CONTACT_URI = "contactUri";
private static final String KEY_LIST_STATE = "liststate";
private Context mContext;
private View mView;
private OnScrollListener mVerticalScrollListener;
private Uri mLookupUri;
private Listener mListener;
private Contact mContactData;
private ViewGroup mStaticPhotoContainer;
private View mPhotoTouchOverlay;
private ListView mListView;
private ViewAdapter mAdapter;
private Uri mPrimaryPhoneUri = null;
private ViewEntryDimensions mViewEntryDimensions;
private final ContactDetailPhotoSetter mPhotoSetter = new ContactDetailPhotoSetter();
private Button mQuickFixButton;
private QuickFix mQuickFix;
private String mDefaultCountryIso;
private boolean mContactHasSocialUpdates;
private boolean mShowStaticPhoto = true;
private final QuickFix[] mPotentialQuickFixes = new QuickFix[] {
new MakeLocalCopyQuickFix(),
new AddToMyContactsQuickFix()
};
/**
* Device capability: Set during buildEntries and used in the long-press context menu
*/
private boolean mHasPhone;
/**
* Device capability: Set during buildEntries and used in the long-press context menu
*/
private boolean mHasSms;
/**
* Device capability: Set during buildEntries and used in the long-press context menu
*/
private boolean mHasSip;
/**
* The view shown if the detail list is empty.
* We set this to the list view when first bind the adapter, so that it won't be shown while
* we're loading data.
*/
private View mEmptyView;
/**
* Saved state of the {@link ListView}. This must be saved and applied to the {@ListView} only
* when the adapter has been populated again.
*/
private Parcelable mListState;
/**
* Lists of specific types of entries to be shown in contact details.
*/
private ArrayList<DetailViewEntry> mPhoneEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mSmsEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mEmailEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mPostalEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mImEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mNicknameEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mGroupEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mRelationEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mNoteEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mWebsiteEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mSipEntries = new ArrayList<DetailViewEntry>();
private ArrayList<DetailViewEntry> mEventEntries = new ArrayList<DetailViewEntry>();
private final Map<AccountType, List<DetailViewEntry>> mOtherEntriesMap =
new HashMap<AccountType, List<DetailViewEntry>>();
private ArrayList<ViewEntry> mAllEntries = new ArrayList<ViewEntry>();
private LayoutInflater mInflater;
private boolean mIsUniqueNumber;
private boolean mIsUniqueEmail;
private ListPopupWindow mPopup;
/**
* This is to forward touch events to the list view to enable users to scroll the list view
* from the blank area underneath the static photo when the layout with static photo is used.
*/
private OnTouchListener mForwardTouchToListView = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mListView != null) {
mListView.dispatchTouchEvent(event);
return true;
}
return false;
}
};
/**
* This is to forward drag events to the list view to enable users to scroll the list view
* from the blank area underneath the static photo when the layout with static photo is used.
*/
private OnDragListener mForwardDragToListView = new OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
if (mListView != null) {
mListView.dispatchDragEvent(event);
return true;
}
return false;
}
};
public ContactDetailFragment() {
// Explicit constructor for inflation
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mLookupUri = savedInstanceState.getParcelable(KEY_CONTACT_URI);
mListState = savedInstanceState.getParcelable(KEY_LIST_STATE);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_CONTACT_URI, mLookupUri);
if (mListView != null) {
outState.putParcelable(KEY_LIST_STATE, mListView.onSaveInstanceState());
}
}
@Override
public void onPause() {
dismissPopupIfShown();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
mDefaultCountryIso = ContactsUtils.getCurrentCountryIso(mContext);
mViewEntryDimensions = new ViewEntryDimensions(mContext.getResources());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) {
mView = inflater.inflate(R.layout.contact_detail_fragment, container, false);
// Set the touch and drag listener to forward the event to the mListView so that
// vertical scrolling can happen from outside of the list view.
mView.setOnTouchListener(mForwardTouchToListView);
mView.setOnDragListener(mForwardDragToListView);
mInflater = inflater;
mStaticPhotoContainer = (ViewGroup) mView.findViewById(R.id.static_photo_container);
mPhotoTouchOverlay = mView.findViewById(R.id.photo_touch_intercept_overlay);
mListView = (ListView) mView.findViewById(android.R.id.list);
mListView.setOnItemClickListener(this);
mListView.setItemsCanFocus(true);
mListView.setOnScrollListener(mVerticalScrollListener);
// Don't set it to mListView yet. We do so later when we bind the adapter.
mEmptyView = mView.findViewById(android.R.id.empty);
mQuickFixButton = (Button) mView.findViewById(R.id.contact_quick_fix);
mQuickFixButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mQuickFix != null) {
mQuickFix.execute();
}
}
});
mView.setVisibility(View.INVISIBLE);
if (mContactData != null) {
bindData();
}
return mView;
}
public void setListener(Listener value) {
mListener = value;
}
protected Context getContext() {
return mContext;
}
protected Listener getListener() {
return mListener;
}
protected Contact getContactData() {
return mContactData;
}
public void setVerticalScrollListener(OnScrollListener listener) {
mVerticalScrollListener = listener;
}
public Uri getUri() {
return mLookupUri;
}
/**
* Sets whether the static contact photo (that is not in a scrolling region), should be shown
* or not.
*/
public void setShowStaticPhoto(boolean showPhoto) {
mShowStaticPhoto = showPhoto;
}
/**
* Shows the contact detail with a message indicating there are no contact details.
*/
public void showEmptyState() {
setData(null, null);
}
public void setData(Uri lookupUri, Contact result) {
mLookupUri = lookupUri;
mContactData = result;
bindData();
}
/**
* Reset the list adapter in this {@link Fragment} to get rid of any saved scroll position
* from a previous contact.
*/
public void resetAdapter() {
if (mListView != null) {
mListView.setAdapter(mAdapter);
}
}
/**
* Returns the top coordinate of the first item in the {@link ListView}. If the first item
* in the {@link ListView} is not visible or there are no children in the list, then return
* Integer.MIN_VALUE. Note that the returned value will be <= 0 because the first item in the
* list cannot have a positive offset.
*/
public int getFirstListItemOffset() {
return ContactDetailDisplayUtils.getFirstListItemOffset(mListView);
}
/**
* Tries to scroll the first item to the given offset (this can be a no-op if the list is
* already in the correct position).
* @param offset which should be <= 0
*/
public void requestToMoveToOffset(int offset) {
ContactDetailDisplayUtils.requestToMoveToOffset(mListView, offset);
}
protected void bindData() {
if (mView == null) {
return;
}
if (isAdded()) {
getActivity().invalidateOptionsMenu();
}
if (mContactData == null) {
mView.setVisibility(View.INVISIBLE);
if (mStaticPhotoContainer != null) {
mStaticPhotoContainer.setVisibility(View.GONE);
}
mAllEntries.clear();
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
return;
}
// Figure out if the contact has social updates or not
mContactHasSocialUpdates = !mContactData.getStreamItems().isEmpty();
// Setup the photo if applicable
if (mStaticPhotoContainer != null) {
// The presence of a static photo container is not sufficient to determine whether or
// not we should show the photo. Check the mShowStaticPhoto flag which can be set by an
// outside class depending on screen size, layout, and whether the contact has social
// updates or not.
if (mShowStaticPhoto) {
mStaticPhotoContainer.setVisibility(View.VISIBLE);
final ImageView photoView = (ImageView) mStaticPhotoContainer.findViewById(
R.id.photo);
final boolean expandPhotoOnClick = mContactData.getPhotoUri() != null;
final OnClickListener listener = mPhotoSetter.setupContactPhotoForClick(
mContext, mContactData, photoView, expandPhotoOnClick);
if (mPhotoTouchOverlay != null) {
mPhotoTouchOverlay.setVisibility(View.VISIBLE);
if (expandPhotoOnClick || mContactData.isWritableContact(mContext)) {
mPhotoTouchOverlay.setOnClickListener(listener);
} else {
mPhotoTouchOverlay.setClickable(false);
}
}
} else {
mStaticPhotoContainer.setVisibility(View.GONE);
}
}
// Build up the contact entries
buildEntries();
// Collapse similar data items for select {@link DataKind}s.
Collapser.collapseList(mPhoneEntries);
Collapser.collapseList(mSmsEntries);
Collapser.collapseList(mEmailEntries);
Collapser.collapseList(mPostalEntries);
Collapser.collapseList(mImEntries);
mIsUniqueNumber = mPhoneEntries.size() == 1;
mIsUniqueEmail = mEmailEntries.size() == 1;
// Make one aggregated list of all entries for display to the user.
setupFlattenedList();
if (mAdapter == null) {
mAdapter = new ViewAdapter();
mListView.setAdapter(mAdapter);
}
// Restore {@link ListView} state if applicable because the adapter is now populated.
if (mListState != null) {
mListView.onRestoreInstanceState(mListState);
mListState = null;
}
mAdapter.notifyDataSetChanged();
mListView.setEmptyView(mEmptyView);
configureQuickFix();
mView.setVisibility(View.VISIBLE);
}
/*
* Sets {@link #mQuickFix} to a useful action and configures the visibility of
* {@link #mQuickFixButton}
*/
private void configureQuickFix() {
mQuickFix = null;
for (QuickFix fix : mPotentialQuickFixes) {
if (fix.isApplicable()) {
mQuickFix = fix;
break;
}
}
// Configure the button
if (mQuickFix == null) {
mQuickFixButton.setVisibility(View.GONE);
} else {
mQuickFixButton.setVisibility(View.VISIBLE);
mQuickFixButton.setText(mQuickFix.getTitle());
}
}
/** @return default group id or -1 if no group or several groups are marked as default */
private long getDefaultGroupId(List<GroupMetaData> groups) {
long defaultGroupId = -1;
for (GroupMetaData group : groups) {
if (group.isDefaultGroup()) {
// two default groups? return neither
if (defaultGroupId != -1) return -1;
defaultGroupId = group.getGroupId();
}
}
return defaultGroupId;
}
/**
* Build up the entries to display on the screen.
*/
private final void buildEntries() {
mHasPhone = PhoneCapabilityTester.isPhone(mContext);
mHasSms = PhoneCapabilityTester.isSmsIntentRegistered(mContext);
mHasSip = PhoneCapabilityTester.isSipPhone(mContext);
// Clear out the old entries
mAllEntries.clear();
mPrimaryPhoneUri = null;
// Build up method entries
if (mContactData == null) {
return;
}
ArrayList<String> groups = new ArrayList<String>();
for (RawContact rawContact: mContactData.getRawContacts()) {
final long rawContactId = rawContact.getId();
for (DataItem dataItem : rawContact.getDataItems()) {
dataItem.setRawContactId(rawContactId);
if (dataItem.getMimeType() == null) continue;
if (dataItem instanceof GroupMembershipDataItem) {
GroupMembershipDataItem groupMembership =
(GroupMembershipDataItem) dataItem;
Long groupId = groupMembership.getGroupRowId();
if (groupId != null) {
handleGroupMembership(groups, mContactData.getGroupMetaData(), groupId);
}
continue;
}
final DataKind kind = dataItem.getDataKind();
if (kind == null) continue;
final DetailViewEntry entry = DetailViewEntry.fromValues(mContext, dataItem,
mContactData.isDirectoryEntry(), mContactData.getDirectoryId());
entry.maxLines = kind.maxLinesForDisplay;
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = dataItem.isSuperPrimary();
if (dataItem instanceof StructuredNameDataItem) {
// Always ignore the name. It is shown in the header if set
} else if (dataItem instanceof PhoneDataItem && hasData) {
PhoneDataItem phone = (PhoneDataItem) dataItem;
// Build phone entries
entry.data = phone.getFormattedPhoneNumber();
+ if (entry.data == null) {
+ // This case happens when the quick contact was opened from the contact
+ // list, and then, the user touches the quick contact image and brings the
+ // user to the detail card. In this case, the Contact object that was
+ // loaded from quick contacts does not contain the formatted phone number,
+ // so it must be loaded here.
+ phone.computeFormattedPhoneNumber(mDefaultCountryIso);
+ entry.data = phone.getFormattedPhoneNumber();
+ }
final Intent phoneIntent = mHasPhone ?
ContactsUtils.getCallIntent(entry.data) : null;
final Intent smsIntent = mHasSms ? new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null)) : null;
// Configure Icons and Intents.
if (mHasPhone && mHasSms) {
entry.intent = phoneIntent;
entry.secondaryIntent = smsIntent;
entry.secondaryActionIcon = kind.iconAltRes;
entry.secondaryActionDescription = kind.iconAltDescriptionRes;
} else if (mHasPhone) {
entry.intent = phoneIntent;
} else if (mHasSms) {
entry.intent = smsIntent;
} else {
entry.intent = null;
}
// Remember super-primary phone
if (isSuperPrimary) mPrimaryPhoneUri = entry.uri;
entry.isPrimary = isSuperPrimary;
// If the entry is a primary entry, then render it first in the view.
if (entry.isPrimary) {
// add to beginning of list so that this phone number shows up first
mPhoneEntries.add(0, entry);
} else {
// add to end of list
mPhoneEntries.add(entry);
}
} else if (dataItem instanceof EmailDataItem && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
// If entry is a primary entry, then render it first in the view.
if (entry.isPrimary) {
mEmailEntries.add(0, entry);
} else {
mEmailEntries.add(entry);
}
// When Email rows have status, create additional Im row
final DataStatus status = mContactData.getStatuses().get(entry.id);
if (status != null) {
EmailDataItem email = (EmailDataItem) dataItem;
ImDataItem im = ImDataItem.createFromEmail(email);
final DetailViewEntry imEntry = DetailViewEntry.fromValues(mContext, im,
mContactData.isDirectoryEntry(), mContactData.getDirectoryId());
buildImActions(mContext, imEntry, im);
imEntry.setPresence(status.getPresence());
imEntry.maxLines = kind.maxLinesForDisplay;
mImEntries.add(imEntry);
}
} else if (dataItem instanceof StructuredPostalDataItem && hasData) {
// Build postal entries
entry.intent = StructuredPostalUtils.getViewPostalAddressIntent(entry.data);
mPostalEntries.add(entry);
} else if (dataItem instanceof ImDataItem && hasData) {
// Build IM entries
buildImActions(mContext, entry, (ImDataItem) dataItem);
// Apply presence when available
final DataStatus status = mContactData.getStatuses().get(entry.id);
if (status != null) {
entry.setPresence(status.getPresence());
}
mImEntries.add(entry);
} else if (dataItem instanceof OrganizationDataItem) {
// Organizations are not shown. The first one is shown in the header
// and subsequent ones are not supported anymore
} else if (dataItem instanceof NicknameDataItem && hasData) {
// Build nickname entries
final boolean isNameRawContact =
(mContactData.getNameRawContactId() == rawContactId);
final boolean duplicatesTitle =
isNameRawContact
&& mContactData.getDisplayNameSource() == DisplayNameSources.NICKNAME;
if (!duplicatesTitle) {
entry.uri = null;
mNicknameEntries.add(entry);
}
} else if (dataItem instanceof NoteDataItem && hasData) {
// Build note entries
entry.uri = null;
mNoteEntries.add(entry);
} else if (dataItem instanceof WebsiteDataItem && hasData) {
// Build Website entries
entry.uri = null;
try {
WebAddress webAddress = new WebAddress(entry.data);
entry.intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(webAddress.toString()));
} catch (ParseException e) {
Log.e(TAG, "Couldn't parse website: " + entry.data);
}
mWebsiteEntries.add(entry);
} else if (dataItem instanceof SipAddressDataItem && hasData) {
// Build SipAddress entries
entry.uri = null;
if (mHasSip) {
entry.intent = ContactsUtils.getCallIntent(
Uri.fromParts(Constants.SCHEME_SIP, entry.data, null));
} else {
entry.intent = null;
}
mSipEntries.add(entry);
// TODO: Now that SipAddress is in its own list of entries
// (instead of grouped in mOtherEntries), consider
// repositioning it right under the phone number.
// (Then, we'd also update FallbackAccountType.java to set
// secondary=false for this field, and tweak the weight
// of its DataKind.)
} else if (dataItem instanceof EventDataItem && hasData) {
entry.data = DateUtils.formatDate(mContext, entry.data);
entry.uri = null;
mEventEntries.add(entry);
} else if (dataItem instanceof RelationDataItem && hasData) {
entry.intent = new Intent(Intent.ACTION_SEARCH);
entry.intent.putExtra(SearchManager.QUERY, entry.data);
entry.intent.setType(Contacts.CONTENT_TYPE);
mRelationEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW);
entry.intent.setDataAndType(entry.uri, entry.mimetype);
entry.data = dataItem.buildDataString();
if (!TextUtils.isEmpty(entry.data)) {
// If the account type exists in the hash map, add it as another entry for
// that account type
AccountType type = dataItem.getAccountType();
if (mOtherEntriesMap.containsKey(type)) {
List<DetailViewEntry> listEntries = mOtherEntriesMap.get(type);
listEntries.add(entry);
} else {
// Otherwise create a new list with the entry and add it to the hash map
List<DetailViewEntry> listEntries = new ArrayList<DetailViewEntry>();
listEntries.add(entry);
mOtherEntriesMap.put(type, listEntries);
}
}
}
}
}
if (!groups.isEmpty()) {
DetailViewEntry entry = new DetailViewEntry();
Collections.sort(groups);
StringBuilder sb = new StringBuilder();
int size = groups.size();
for (int i = 0; i < size; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(groups.get(i));
}
entry.mimetype = GroupMembership.MIMETYPE;
entry.kind = mContext.getString(R.string.groupsLabel);
entry.data = sb.toString();
mGroupEntries.add(entry);
}
}
/**
* Collapse all contact detail entries into one aggregated list with a {@link HeaderViewEntry}
* at the top.
*/
private void setupFlattenedList() {
// All contacts should have a header view (even if there is no data for the contact).
mAllEntries.add(new HeaderViewEntry());
addPhoneticName();
flattenList(mPhoneEntries);
flattenList(mSmsEntries);
flattenList(mEmailEntries);
flattenList(mImEntries);
flattenList(mNicknameEntries);
flattenList(mWebsiteEntries);
addNetworks();
flattenList(mSipEntries);
flattenList(mPostalEntries);
flattenList(mEventEntries);
flattenList(mGroupEntries);
flattenList(mRelationEntries);
flattenList(mNoteEntries);
}
/**
* Add phonetic name (if applicable) to the aggregated list of contact details. This has to be
* done manually because phonetic name doesn't have a mimetype or action intent.
*/
private void addPhoneticName() {
String phoneticName = ContactDetailDisplayUtils.getPhoneticName(mContext, mContactData);
if (TextUtils.isEmpty(phoneticName)) {
return;
}
// Add a title
String phoneticNameKindTitle = mContext.getString(R.string.name_phonetic);
mAllEntries.add(new KindTitleViewEntry(phoneticNameKindTitle.toUpperCase()));
// Add the phonetic name
final DetailViewEntry entry = new DetailViewEntry();
entry.kind = phoneticNameKindTitle;
entry.data = phoneticName;
mAllEntries.add(entry);
}
/**
* Add attribution and other third-party entries (if applicable) under the "networks" section
* of the aggregated list of contact details. This has to be done manually because the
* attribution does not have a mimetype and the third-party entries don't have actually belong
* to the same {@link DataKind}.
*/
private void addNetworks() {
String attribution = ContactDetailDisplayUtils.getAttribution(mContext, mContactData);
boolean hasAttribution = !TextUtils.isEmpty(attribution);
int networksCount = mOtherEntriesMap.keySet().size();
// Note: invitableCount will always be 0 for me profile. (ContactLoader won't set
// invitable types for me profile.)
int invitableCount = mContactData.getInvitableAccountTypes().size();
if (!hasAttribution && networksCount == 0 && invitableCount == 0) {
return;
}
// Add a title
String networkKindTitle = mContext.getString(R.string.connections);
mAllEntries.add(new KindTitleViewEntry(networkKindTitle.toUpperCase()));
// Add the attribution if applicable
if (hasAttribution) {
final DetailViewEntry entry = new DetailViewEntry();
entry.kind = networkKindTitle;
entry.data = attribution;
mAllEntries.add(entry);
// Add a divider below the attribution if there are network details that will follow
if (networksCount > 0) {
mAllEntries.add(new SeparatorViewEntry());
}
}
// Add the other entries from third parties
for (AccountType accountType : mOtherEntriesMap.keySet()) {
// Add a title for each third party app
mAllEntries.add(new NetworkTitleViewEntry(mContext, accountType));
for (DetailViewEntry detailEntry : mOtherEntriesMap.get(accountType)) {
// Add indented separator
SeparatorViewEntry separatorEntry = new SeparatorViewEntry();
separatorEntry.setIsInSubSection(true);
mAllEntries.add(separatorEntry);
// Add indented detail
detailEntry.setIsInSubSection(true);
mAllEntries.add(detailEntry);
}
}
mOtherEntriesMap.clear();
// Add the "More networks" button, which opens the invitable account type list popup.
if (invitableCount > 0) {
addMoreNetworks();
}
}
/**
* Add the "More networks" entry. When clicked, show a popup containing a list of invitable
* account types.
*/
private void addMoreNetworks() {
// First, prepare for the popup.
// Adapter for the list popup.
final InvitableAccountTypesAdapter popupAdapter = new InvitableAccountTypesAdapter(mContext,
mContactData);
// Listener called when a popup item is clicked.
final AdapterView.OnItemClickListener popupItemListener
= new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (mListener != null && mContactData != null) {
mListener.onItemClicked(ContactsUtils.getInvitableIntent(
popupAdapter.getItem(position) /* account type */,
mContactData.getLookupUri()));
}
}
};
// Then create the click listener for the "More network" entry. Open the popup.
View.OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
showListPopup(v, popupAdapter, popupItemListener);
}
};
// Finally create the entry.
mAllEntries.add(new AddConnectionViewEntry(mContext, onClickListener));
}
/**
* Iterate through {@link DetailViewEntry} in the given list and add it to a list of all
* entries. Add a {@link KindTitleViewEntry} at the start if the length of the list is not 0.
* Add {@link SeparatorViewEntry}s as dividers as appropriate. Clear the original list.
*/
private void flattenList(ArrayList<DetailViewEntry> entries) {
int count = entries.size();
// Add a title for this kind by extracting the kind from the first entry
if (count > 0) {
String kind = entries.get(0).kind;
mAllEntries.add(new KindTitleViewEntry(kind.toUpperCase()));
}
// Add all the data entries for this kind
for (int i = 0; i < count; i++) {
// For all entries except the first one, add a divider above the entry
if (i != 0) {
mAllEntries.add(new SeparatorViewEntry());
}
mAllEntries.add(entries.get(i));
}
// Clear old list because it's not needed anymore.
entries.clear();
}
/**
* Maps group ID to the corresponding group name, collapses all synonymous groups.
* Ignores default groups (e.g. My Contacts) and favorites groups.
*/
private void handleGroupMembership(
ArrayList<String> groups, List<GroupMetaData> groupMetaData, long groupId) {
if (groupMetaData == null) {
return;
}
for (GroupMetaData group : groupMetaData) {
if (group.getGroupId() == groupId) {
if (!group.isDefaultGroup() && !group.isFavorites()) {
String title = group.getTitle();
if (!TextUtils.isEmpty(title) && !groups.contains(title)) {
groups.add(title);
}
}
break;
}
}
}
/**
* Writes the Instant Messaging action into the given entry value.
*/
@VisibleForTesting
public static void buildImActions(Context context, DetailViewEntry entry,
ImDataItem im) {
final boolean isEmail = im.isCreatedFromEmail();
if (!isEmail && !im.isProtocolValid()) {
return;
}
final String data = im.getData();
if (TextUtils.isEmpty(data)) {
return;
}
final int protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK : im.getProtocol();
if (protocol == Im.PROTOCOL_GOOGLE_TALK) {
final int chatCapability = im.getChatCapability();
entry.chatCapability = chatCapability;
entry.typeString = Im.getProtocolLabel(context.getResources(), Im.PROTOCOL_GOOGLE_TALK,
null).toString();
if ((chatCapability & Im.CAPABILITY_HAS_CAMERA) != 0) {
entry.intent =
new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?message"));
entry.secondaryIntent =
new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?call"));
} else if ((chatCapability & Im.CAPABILITY_HAS_VOICE) != 0) {
// Allow Talking and Texting
entry.intent =
new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?message"));
entry.secondaryIntent =
new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?call"));
} else {
entry.intent =
new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?message"));
}
} else {
// Build an IM Intent
String host = im.getCustomProtocol();
if (protocol != Im.PROTOCOL_CUSTOM) {
// Try bringing in a well-known host for specific protocols
host = ContactsUtils.lookupProviderNameFromId(protocol);
}
if (!TextUtils.isEmpty(host)) {
final String authority = host.toLowerCase();
final Uri imUri = new Uri.Builder().scheme(Constants.SCHEME_IMTO).authority(
authority).appendPath(data).build();
entry.intent = new Intent(Intent.ACTION_SENDTO, imUri);
}
}
}
/**
* Show a list popup. Used for "popup-able" entry, such as "More networks".
*/
private void showListPopup(View anchorView, ListAdapter adapter,
final AdapterView.OnItemClickListener onItemClickListener) {
dismissPopupIfShown();
mPopup = new ListPopupWindow(mContext, null);
mPopup.setAnchorView(anchorView);
mPopup.setWidth(anchorView.getWidth());
mPopup.setAdapter(adapter);
mPopup.setModal(true);
// We need to wrap the passed onItemClickListener here, so that we can dismiss() the
// popup afterwards. Otherwise we could directly use the passed listener.
mPopup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
onItemClickListener.onItemClick(parent, view, position, id);
dismissPopupIfShown();
}
});
mPopup.show();
}
private void dismissPopupIfShown() {
if (mPopup != null && mPopup.isShowing()) {
mPopup.dismiss();
}
mPopup = null;
}
/**
* Base class for an item in the {@link ViewAdapter} list of data, which is
* supplied to the {@link ListView}.
*/
static class ViewEntry {
private final int viewTypeForAdapter;
protected long id = -1;
/** Whether or not the entry can be focused on or not. */
protected boolean isEnabled = false;
ViewEntry(int viewType) {
viewTypeForAdapter = viewType;
}
int getViewType() {
return viewTypeForAdapter;
}
long getId() {
return id;
}
boolean isEnabled(){
return isEnabled;
}
/**
* Called when the entry is clicked. Only {@link #isEnabled} entries can get clicked.
*
* @param clickedView {@link View} that was clicked (Used, for example, as the anchor view
* for a popup.)
* @param fragmentListener {@link Listener} set to {@link ContactDetailFragment}
*/
public void click(View clickedView, Listener fragmentListener) {
}
}
/**
* Header item in the {@link ViewAdapter} list of data.
*/
private static class HeaderViewEntry extends ViewEntry {
HeaderViewEntry() {
super(ViewAdapter.VIEW_TYPE_HEADER_ENTRY);
}
}
/**
* Separator between items of the same {@link DataKind} in the
* {@link ViewAdapter} list of data.
*/
private static class SeparatorViewEntry extends ViewEntry {
/**
* Whether or not the entry is in a subsection (if true then the contents will be indented
* to the right)
*/
private boolean mIsInSubSection = false;
SeparatorViewEntry() {
super(ViewAdapter.VIEW_TYPE_SEPARATOR_ENTRY);
}
public void setIsInSubSection(boolean isInSubSection) {
mIsInSubSection = isInSubSection;
}
public boolean isInSubSection() {
return mIsInSubSection;
}
}
/**
* Title entry for items of the same {@link DataKind} in the
* {@link ViewAdapter} list of data.
*/
private static class KindTitleViewEntry extends ViewEntry {
private final String mTitle;
KindTitleViewEntry(String titleText) {
super(ViewAdapter.VIEW_TYPE_KIND_TITLE_ENTRY);
mTitle = titleText;
}
public String getTitle() {
return mTitle;
}
}
/**
* A title for a section of contact details from a single 3rd party network.
*/
private static class NetworkTitleViewEntry extends ViewEntry {
private final Drawable mIcon;
private final CharSequence mLabel;
public NetworkTitleViewEntry(Context context, AccountType type) {
super(ViewAdapter.VIEW_TYPE_NETWORK_TITLE_ENTRY);
this.mIcon = type.getDisplayIcon(context);
this.mLabel = type.getDisplayLabel(context);
this.isEnabled = false;
}
public Drawable getIcon() {
return mIcon;
}
public CharSequence getLabel() {
return mLabel;
}
}
/**
* This is used for the "Add Connections" entry.
*/
private static class AddConnectionViewEntry extends ViewEntry {
private final Drawable mIcon;
private final CharSequence mLabel;
private final View.OnClickListener mOnClickListener;
private AddConnectionViewEntry(Context context, View.OnClickListener onClickListener) {
super(ViewAdapter.VIEW_TYPE_ADD_CONNECTION_ENTRY);
this.mIcon = context.getResources().getDrawable(
R.drawable.ic_menu_add_field_holo_light);
this.mLabel = context.getString(R.string.add_connection_button);
this.mOnClickListener = onClickListener;
this.isEnabled = true;
}
@Override
public void click(View clickedView, Listener fragmentListener) {
if (mOnClickListener == null) return;
mOnClickListener.onClick(clickedView);
}
public Drawable getIcon() {
return mIcon;
}
public CharSequence getLabel() {
return mLabel;
}
}
/**
* An item with a single detail for a contact in the {@link ViewAdapter}
* list of data.
*/
static class DetailViewEntry extends ViewEntry implements Collapsible<DetailViewEntry> {
// TODO: Make getters/setters for these fields
public int type = -1;
public String kind;
public String typeString;
public String data;
public Uri uri;
public int maxLines = 1;
public String mimetype;
public Context context = null;
public boolean isPrimary = false;
public int secondaryActionIcon = -1;
public int secondaryActionDescription = -1;
public Intent intent;
public Intent secondaryIntent = null;
public ArrayList<Long> ids = new ArrayList<Long>();
public int collapseCount = 0;
public int presence = -1;
public int chatCapability = 0;
private boolean mIsInSubSection = false;
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("== DetailViewEntry ==\n");
sb.append(" type: " + type + "\n");
sb.append(" kind: " + kind + "\n");
sb.append(" typeString: " + typeString + "\n");
sb.append(" data: " + data + "\n");
sb.append(" uri: " + uri.toString() + "\n");
sb.append(" maxLines: " + maxLines + "\n");
sb.append(" mimetype: " + mimetype + "\n");
sb.append(" isPrimary: " + (isPrimary ? "true" : "false") + "\n");
sb.append(" secondaryActionIcon: " + secondaryActionIcon + "\n");
sb.append(" secondaryActionDescription: " + secondaryActionDescription + "\n");
if (intent == null) {
sb.append(" intent: " + intent.toString() + "\n");
} else {
sb.append(" intent: " + intent.toString() + "\n");
}
if (secondaryIntent == null) {
sb.append(" secondaryIntent: (null)\n");
} else {
sb.append(" secondaryIntent: " + secondaryIntent.toString() + "\n");
}
sb.append(" ids: " + Iterables.toString(ids) + "\n");
sb.append(" collapseCount: " + collapseCount + "\n");
sb.append(" presence: " + presence + "\n");
sb.append(" chatCapability: " + chatCapability + "\n");
sb.append(" mIsInSubsection: " + (mIsInSubSection ? "true" : "false") + "\n");
return sb.toString();
}
DetailViewEntry() {
super(ViewAdapter.VIEW_TYPE_DETAIL_ENTRY);
isEnabled = true;
}
/**
* Build new {@link DetailViewEntry} and populate from the given values.
*/
public static DetailViewEntry fromValues(Context context, DataItem item,
boolean isDirectoryEntry, long directoryId) {
final DetailViewEntry entry = new DetailViewEntry();
entry.id = item.getId();
entry.context = context;
entry.uri = ContentUris.withAppendedId(Data.CONTENT_URI, entry.id);
if (isDirectoryEntry) {
entry.uri = entry.uri.buildUpon().appendQueryParameter(
ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(directoryId)).build();
}
entry.mimetype = item.getMimeType();
entry.kind = item.getKindString();
entry.data = item.buildDataString();
if (item.hasKindTypeColumn()) {
entry.type = item.getKindTypeColumn();
// get type string
entry.typeString = "";
for (EditType type : item.getDataKind().typeList) {
if (type.rawValue == entry.type) {
if (type.customColumn == null) {
// Non-custom type. Get its description from the resource
entry.typeString = context.getString(type.labelRes);
} else {
// Custom type. Read it from the database
entry.typeString =
item.getContentValues().getAsString(type.customColumn);
}
break;
}
}
} else {
entry.typeString = "";
}
return entry;
}
public void setPresence(int presence) {
this.presence = presence;
}
public void setIsInSubSection(boolean isInSubSection) {
mIsInSubSection = isInSubSection;
}
public boolean isInSubSection() {
return mIsInSubSection;
}
@Override
public boolean collapseWith(DetailViewEntry entry) {
// assert equal collapse keys
if (!shouldCollapseWith(entry)) {
return false;
}
// Choose the label associated with the highest type precedence.
if (TypePrecedence.getTypePrecedence(mimetype, type)
> TypePrecedence.getTypePrecedence(entry.mimetype, entry.type)) {
type = entry.type;
kind = entry.kind;
typeString = entry.typeString;
}
// Choose the max of the maxLines and maxLabelLines values.
maxLines = Math.max(maxLines, entry.maxLines);
// Choose the presence with the highest precedence.
if (StatusUpdates.getPresencePrecedence(presence)
< StatusUpdates.getPresencePrecedence(entry.presence)) {
presence = entry.presence;
}
// If any of the collapsed entries are primary make the whole thing primary.
isPrimary = entry.isPrimary ? true : isPrimary;
// uri, and contactdId, shouldn't make a difference. Just keep the original.
// Keep track of all the ids that have been collapsed with this one.
ids.add(entry.getId());
collapseCount++;
return true;
}
@Override
public boolean shouldCollapseWith(DetailViewEntry entry) {
if (entry == null) {
return false;
}
if (!ContactsUtils.shouldCollapse(mimetype, data, entry.mimetype, entry.data)) {
return false;
}
if (!TextUtils.equals(mimetype, entry.mimetype)
|| !ContactsUtils.areIntentActionEqual(intent, entry.intent)
|| !ContactsUtils.areIntentActionEqual(
secondaryIntent, entry.secondaryIntent)) {
return false;
}
return true;
}
@Override
public void click(View clickedView, Listener fragmentListener) {
if (fragmentListener == null || intent == null) return;
fragmentListener.onItemClicked(intent);
}
}
/**
* Cache of the children views for a view that displays a header view entry.
*/
private static class HeaderViewCache {
public final TextView displayNameView;
public final TextView companyView;
public final ImageView photoView;
public final View photoOverlayView;
public final ImageView starredView;
public final int layoutResourceId;
public HeaderViewCache(View view, int layoutResourceInflated) {
displayNameView = (TextView) view.findViewById(R.id.name);
companyView = (TextView) view.findViewById(R.id.company);
photoView = (ImageView) view.findViewById(R.id.photo);
photoOverlayView = view.findViewById(R.id.photo_touch_intercept_overlay);
starredView = (ImageView) view.findViewById(R.id.star);
layoutResourceId = layoutResourceInflated;
}
public void enablePhotoOverlay(OnClickListener listener) {
if (photoOverlayView != null) {
photoOverlayView.setOnClickListener(listener);
photoOverlayView.setVisibility(View.VISIBLE);
}
}
}
private static class KindTitleViewCache {
public final TextView titleView;
public KindTitleViewCache(View view) {
titleView = (TextView)view.findViewById(R.id.title);
}
}
/**
* Cache of the children views for a view that displays a {@link NetworkTitleViewEntry}
*/
private static class NetworkTitleViewCache {
public final TextView name;
public final ImageView icon;
public NetworkTitleViewCache(View view) {
name = (TextView) view.findViewById(R.id.network_title);
icon = (ImageView) view.findViewById(R.id.network_icon);
}
}
/**
* Cache of the children views for a view that displays a {@link AddConnectionViewEntry}
*/
private static class AddConnectionViewCache {
public final TextView name;
public final ImageView icon;
public final View primaryActionView;
public AddConnectionViewCache(View view) {
name = (TextView) view.findViewById(R.id.add_connection_label);
icon = (ImageView) view.findViewById(R.id.add_connection_icon);
primaryActionView = view.findViewById(R.id.primary_action_view);
}
}
/**
* Cache of the children views of a contact detail entry represented by a
* {@link DetailViewEntry}
*/
private static class DetailViewCache {
public final TextView type;
public final TextView data;
public final ImageView presenceIcon;
public final ImageView secondaryActionButton;
public final View actionsViewContainer;
public final View primaryActionView;
public final View secondaryActionViewContainer;
public final View secondaryActionDivider;
public final View primaryIndicator;
public DetailViewCache(View view,
OnClickListener primaryActionClickListener,
OnClickListener secondaryActionClickListener) {
type = (TextView) view.findViewById(R.id.type);
data = (TextView) view.findViewById(R.id.data);
primaryIndicator = view.findViewById(R.id.primary_indicator);
presenceIcon = (ImageView) view.findViewById(R.id.presence_icon);
actionsViewContainer = view.findViewById(R.id.actions_view_container);
actionsViewContainer.setOnClickListener(primaryActionClickListener);
primaryActionView = view.findViewById(R.id.primary_action_view);
secondaryActionViewContainer = view.findViewById(
R.id.secondary_action_view_container);
secondaryActionViewContainer.setOnClickListener(
secondaryActionClickListener);
secondaryActionButton = (ImageView) view.findViewById(
R.id.secondary_action_button);
secondaryActionDivider = view.findViewById(R.id.vertical_divider);
}
}
private final class ViewAdapter extends BaseAdapter {
public static final int VIEW_TYPE_DETAIL_ENTRY = 0;
public static final int VIEW_TYPE_HEADER_ENTRY = 1;
public static final int VIEW_TYPE_KIND_TITLE_ENTRY = 2;
public static final int VIEW_TYPE_NETWORK_TITLE_ENTRY = 3;
public static final int VIEW_TYPE_ADD_CONNECTION_ENTRY = 4;
public static final int VIEW_TYPE_SEPARATOR_ENTRY = 5;
private static final int VIEW_TYPE_COUNT = 6;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
switch (getItemViewType(position)) {
case VIEW_TYPE_HEADER_ENTRY:
return getHeaderEntryView(convertView, parent);
case VIEW_TYPE_SEPARATOR_ENTRY:
return getSeparatorEntryView(position, convertView, parent);
case VIEW_TYPE_KIND_TITLE_ENTRY:
return getKindTitleEntryView(position, convertView, parent);
case VIEW_TYPE_DETAIL_ENTRY:
return getDetailEntryView(position, convertView, parent);
case VIEW_TYPE_NETWORK_TITLE_ENTRY:
return getNetworkTitleEntryView(position, convertView, parent);
case VIEW_TYPE_ADD_CONNECTION_ENTRY:
return getAddConnectionEntryView(position, convertView, parent);
default:
throw new IllegalStateException("Invalid view type ID " +
getItemViewType(position));
}
}
private View getHeaderEntryView(View convertView, ViewGroup parent) {
final int desiredLayoutResourceId = mContactHasSocialUpdates ?
R.layout.detail_header_contact_with_updates :
R.layout.detail_header_contact_without_updates;
View result = null;
HeaderViewCache viewCache = null;
// Only use convertView if it has the same layout resource ID as the one desired
// (the two can be different on wide 2-pane screens where the detail fragment is reused
// for many different contacts that do and do not have social updates).
if (convertView != null) {
viewCache = (HeaderViewCache) convertView.getTag();
if (viewCache.layoutResourceId == desiredLayoutResourceId) {
result = convertView;
}
}
// Otherwise inflate a new header view and create a new view cache.
if (result == null) {
result = mInflater.inflate(desiredLayoutResourceId, parent, false);
viewCache = new HeaderViewCache(result, desiredLayoutResourceId);
result.setTag(viewCache);
}
ContactDetailDisplayUtils.setDisplayName(mContext, mContactData,
viewCache.displayNameView);
ContactDetailDisplayUtils.setCompanyName(mContext, mContactData, viewCache.companyView);
// Set the photo if it should be displayed
if (viewCache.photoView != null) {
final boolean expandOnClick = mContactData.getPhotoUri() != null;
final OnClickListener listener = mPhotoSetter.setupContactPhotoForClick(
mContext, mContactData, viewCache.photoView, expandOnClick);
if (expandOnClick || mContactData.isWritableContact(mContext)) {
viewCache.enablePhotoOverlay(listener);
}
}
// Set the starred state if it should be displayed
final ImageView favoritesStar = viewCache.starredView;
if (favoritesStar != null) {
ContactDetailDisplayUtils.configureStarredImageView(favoritesStar,
mContactData.isDirectoryEntry(), mContactData.isUserProfile(),
mContactData.getStarred());
final Uri lookupUri = mContactData.getLookupUri();
favoritesStar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Toggle "starred" state
// Make sure there is a contact
if (lookupUri != null) {
// Read the current starred value from the UI instead of using the last
// loaded state. This allows rapid tapping without writing the same
// value several times
final Object tag = favoritesStar.getTag();
final boolean isStarred = tag == null
? false : (Boolean) favoritesStar.getTag();
// To improve responsiveness, swap out the picture (and tag) in the UI
// already
ContactDetailDisplayUtils.configureStarredImageView(favoritesStar,
mContactData.isDirectoryEntry(), mContactData.isUserProfile(),
!isStarred);
// Now perform the real save
Intent intent = ContactSaveService.createSetStarredIntent(
getContext(), lookupUri, !isStarred);
getContext().startService(intent);
}
}
});
}
return result;
}
private View getSeparatorEntryView(int position, View convertView, ViewGroup parent) {
final SeparatorViewEntry entry = (SeparatorViewEntry) getItem(position);
final View result = (convertView != null) ? convertView :
mInflater.inflate(R.layout.contact_detail_separator_entry_view, parent, false);
result.setPadding(entry.isInSubSection() ? mViewEntryDimensions.getWidePaddingLeft() :
mViewEntryDimensions.getPaddingLeft(), 0,
mViewEntryDimensions.getPaddingRight(), 0);
return result;
}
private View getKindTitleEntryView(int position, View convertView, ViewGroup parent) {
final KindTitleViewEntry entry = (KindTitleViewEntry) getItem(position);
final View result;
final KindTitleViewCache viewCache;
if (convertView != null) {
result = convertView;
viewCache = (KindTitleViewCache)result.getTag();
} else {
result = mInflater.inflate(R.layout.list_separator, parent, false);
viewCache = new KindTitleViewCache(result);
result.setTag(viewCache);
}
viewCache.titleView.setText(entry.getTitle());
return result;
}
private View getNetworkTitleEntryView(int position, View convertView, ViewGroup parent) {
final NetworkTitleViewEntry entry = (NetworkTitleViewEntry) getItem(position);
final View result;
final NetworkTitleViewCache viewCache;
if (convertView != null) {
result = convertView;
viewCache = (NetworkTitleViewCache) result.getTag();
} else {
result = mInflater.inflate(R.layout.contact_detail_network_title_entry_view,
parent, false);
viewCache = new NetworkTitleViewCache(result);
result.setTag(viewCache);
}
viewCache.name.setText(entry.getLabel());
viewCache.icon.setImageDrawable(entry.getIcon());
return result;
}
private View getAddConnectionEntryView(int position, View convertView, ViewGroup parent) {
final AddConnectionViewEntry entry = (AddConnectionViewEntry) getItem(position);
final View result;
final AddConnectionViewCache viewCache;
if (convertView != null) {
result = convertView;
viewCache = (AddConnectionViewCache) result.getTag();
} else {
result = mInflater.inflate(R.layout.contact_detail_add_connection_entry_view,
parent, false);
viewCache = new AddConnectionViewCache(result);
result.setTag(viewCache);
}
viewCache.name.setText(entry.getLabel());
viewCache.icon.setImageDrawable(entry.getIcon());
viewCache.primaryActionView.setOnClickListener(entry.mOnClickListener);
return result;
}
private View getDetailEntryView(int position, View convertView, ViewGroup parent) {
final DetailViewEntry entry = (DetailViewEntry) getItem(position);
final View v;
final DetailViewCache viewCache;
// Check to see if we can reuse convertView
if (convertView != null) {
v = convertView;
viewCache = (DetailViewCache) v.getTag();
} else {
// Create a new view if needed
v = mInflater.inflate(R.layout.contact_detail_list_item, parent, false);
// Cache the children
viewCache = new DetailViewCache(v,
mPrimaryActionClickListener, mSecondaryActionClickListener);
v.setTag(viewCache);
}
bindDetailView(position, v, entry);
return v;
}
private void bindDetailView(int position, View view, DetailViewEntry entry) {
final Resources resources = mContext.getResources();
DetailViewCache views = (DetailViewCache) view.getTag();
if (!TextUtils.isEmpty(entry.typeString)) {
views.type.setText(entry.typeString.toUpperCase());
views.type.setVisibility(View.VISIBLE);
} else {
views.type.setVisibility(View.GONE);
}
views.data.setText(entry.data);
setMaxLines(views.data, entry.maxLines);
// Set the default contact method
views.primaryIndicator.setVisibility(entry.isPrimary ? View.VISIBLE : View.GONE);
// Set the presence icon
final Drawable presenceIcon = ContactPresenceIconUtil.getPresenceIcon(
mContext, entry.presence);
final ImageView presenceIconView = views.presenceIcon;
if (presenceIcon != null) {
presenceIconView.setImageDrawable(presenceIcon);
presenceIconView.setVisibility(View.VISIBLE);
} else {
presenceIconView.setVisibility(View.GONE);
}
final ActionsViewContainer actionsButtonContainer =
(ActionsViewContainer) views.actionsViewContainer;
actionsButtonContainer.setTag(entry);
actionsButtonContainer.setPosition(position);
registerForContextMenu(actionsButtonContainer);
// Set the secondary action button
final ImageView secondaryActionView = views.secondaryActionButton;
Drawable secondaryActionIcon = null;
String secondaryActionDescription = null;
if (entry.secondaryActionIcon != -1) {
secondaryActionIcon = resources.getDrawable(entry.secondaryActionIcon);
secondaryActionDescription = resources.getString(entry.secondaryActionDescription);
} else if ((entry.chatCapability & Im.CAPABILITY_HAS_CAMERA) != 0) {
secondaryActionIcon =
resources.getDrawable(R.drawable.sym_action_videochat_holo_light);
secondaryActionDescription = resources.getString(R.string.video_chat);
} else if ((entry.chatCapability & Im.CAPABILITY_HAS_VOICE) != 0) {
secondaryActionIcon =
resources.getDrawable(R.drawable.sym_action_audiochat_holo_light);
secondaryActionDescription = resources.getString(R.string.audio_chat);
}
final View secondaryActionViewContainer = views.secondaryActionViewContainer;
if (entry.secondaryIntent != null && secondaryActionIcon != null) {
secondaryActionView.setImageDrawable(secondaryActionIcon);
secondaryActionView.setContentDescription(secondaryActionDescription);
secondaryActionViewContainer.setTag(entry);
secondaryActionViewContainer.setVisibility(View.VISIBLE);
views.secondaryActionDivider.setVisibility(View.VISIBLE);
} else {
secondaryActionViewContainer.setVisibility(View.GONE);
views.secondaryActionDivider.setVisibility(View.GONE);
}
// Right and left padding should not have "pressed" effect.
view.setPadding(
entry.isInSubSection()
? mViewEntryDimensions.getWidePaddingLeft()
: mViewEntryDimensions.getPaddingLeft(),
0, mViewEntryDimensions.getPaddingRight(), 0);
// Top and bottom padding should have "pressed" effect.
final View primaryActionView = views.primaryActionView;
primaryActionView.setPadding(
primaryActionView.getPaddingLeft(),
mViewEntryDimensions.getPaddingTop(),
primaryActionView.getPaddingRight(),
mViewEntryDimensions.getPaddingBottom());
secondaryActionViewContainer.setPadding(
secondaryActionViewContainer.getPaddingLeft(),
mViewEntryDimensions.getPaddingTop(),
secondaryActionViewContainer.getPaddingRight(),
mViewEntryDimensions.getPaddingBottom());
}
private void setMaxLines(TextView textView, int maxLines) {
if (maxLines == 1) {
textView.setSingleLine(true);
textView.setEllipsize(TextUtils.TruncateAt.END);
} else {
textView.setSingleLine(false);
textView.setMaxLines(maxLines);
textView.setEllipsize(null);
}
}
private final OnClickListener mPrimaryActionClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
if (mListener == null) return;
final ViewEntry entry = (ViewEntry) view.getTag();
if (entry == null) return;
entry.click(view, mListener);
}
};
private final OnClickListener mSecondaryActionClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
if (mListener == null) return;
if (view == null) return;
final ViewEntry entry = (ViewEntry) view.getTag();
if (entry == null || !(entry instanceof DetailViewEntry)) return;
final DetailViewEntry detailViewEntry = (DetailViewEntry) entry;
final Intent intent = detailViewEntry.secondaryIntent;
if (intent == null) return;
mListener.onItemClicked(intent);
}
};
@Override
public int getCount() {
return mAllEntries.size();
}
@Override
public ViewEntry getItem(int position) {
return mAllEntries.get(position);
}
@Override
public int getItemViewType(int position) {
return mAllEntries.get(position).getViewType();
}
@Override
public int getViewTypeCount() {
return VIEW_TYPE_COUNT;
}
@Override
public long getItemId(int position) {
final ViewEntry entry = mAllEntries.get(position);
if (entry != null) {
return entry.getId();
}
return -1;
}
@Override
public boolean areAllItemsEnabled() {
// Header will always be an item that is not enabled.
return false;
}
@Override
public boolean isEnabled(int position) {
return getItem(position).isEnabled();
}
}
@Override
public void onAccountSelectorCancelled() {
}
@Override
public void onAccountChosen(AccountWithDataSet account, Bundle extraArgs) {
createCopy(account);
}
private void createCopy(AccountWithDataSet account) {
if (mListener != null) {
mListener.onCreateRawContactRequested(mContactData.getContentValues(), account);
}
}
/**
* Default (fallback) list item click listener. Note the click event for DetailViewEntry is
* caught by individual views in the list item view to distinguish the primary action and the
* secondary action, so this method won't be invoked for that. (The listener is set in the
* bindview in the adapter)
* This listener is used for other kind of entries.
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mListener == null) return;
final ViewEntry entry = mAdapter.getItem(position);
if (entry == null) return;
entry.click(view, mListener);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
DetailViewEntry selectedEntry = (DetailViewEntry) mAllEntries.get(info.position);
menu.setHeaderTitle(selectedEntry.data);
menu.add(ContextMenu.NONE, ContextMenuIds.COPY_TEXT,
ContextMenu.NONE, getString(R.string.copy_text));
String selectedMimeType = selectedEntry.mimetype;
// Defaults to true will only enable the detail to be copied to the clipboard.
boolean isUniqueMimeType = true;
// Only allow primary support for Phone and Email content types
if (Phone.CONTENT_ITEM_TYPE.equals(selectedMimeType)) {
isUniqueMimeType = mIsUniqueNumber;
} else if (Email.CONTENT_ITEM_TYPE.equals(selectedMimeType)) {
isUniqueMimeType = mIsUniqueEmail;
}
// Checking for previously set default
if (selectedEntry.isPrimary) {
menu.add(ContextMenu.NONE, ContextMenuIds.CLEAR_DEFAULT,
ContextMenu.NONE, getString(R.string.clear_default));
} else if (!isUniqueMimeType) {
menu.add(ContextMenu.NONE, ContextMenuIds.SET_DEFAULT,
ContextMenu.NONE, getString(R.string.set_default));
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo menuInfo;
try {
menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo", e);
return false;
}
switch (item.getItemId()) {
case ContextMenuIds.COPY_TEXT:
copyToClipboard(menuInfo.position);
return true;
case ContextMenuIds.SET_DEFAULT:
setDefaultContactMethod(mListView.getItemIdAtPosition(menuInfo.position));
return true;
case ContextMenuIds.CLEAR_DEFAULT:
clearDefaultContactMethod(mListView.getItemIdAtPosition(menuInfo.position));
return true;
default:
throw new IllegalArgumentException("Unknown menu option " + item.getItemId());
}
}
private void setDefaultContactMethod(long id) {
Intent setIntent = ContactSaveService.createSetSuperPrimaryIntent(mContext, id);
mContext.startService(setIntent);
}
private void clearDefaultContactMethod(long id) {
Intent clearIntent = ContactSaveService.createClearPrimaryIntent(mContext, id);
mContext.startService(clearIntent);
}
private void copyToClipboard(int viewEntryPosition) {
// Getting the text to copied
DetailViewEntry detailViewEntry = (DetailViewEntry) mAllEntries.get(viewEntryPosition);
CharSequence textToCopy = detailViewEntry.data;
// Checking for empty string
if (TextUtils.isEmpty(textToCopy)) return;
ClipboardUtils.copyText(getActivity(), detailViewEntry.typeString, textToCopy, true);
}
@Override
public boolean handleKeyDown(int keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_CALL: {
try {
ITelephony phone = ITelephony.Stub.asInterface(
ServiceManager.checkService("phone"));
if (phone != null && !phone.isIdle()) {
// Skip out and let the key be handled at a higher level
break;
}
} catch (RemoteException re) {
// Fall through and try to call the contact
}
int index = mListView.getSelectedItemPosition();
if (index != -1) {
final DetailViewEntry entry = (DetailViewEntry) mAdapter.getItem(index);
if (entry != null && entry.intent != null &&
entry.intent.getAction() == Intent.ACTION_CALL_PRIVILEGED) {
mContext.startActivity(entry.intent);
return true;
}
} else if (mPrimaryPhoneUri != null) {
// There isn't anything selected, call the default number
mContext.startActivity(ContactsUtils.getCallIntent(mPrimaryPhoneUri));
return true;
}
return false;
}
}
return false;
}
/**
* Base class for QuickFixes. QuickFixes quickly fix issues with the Contact without
* requiring the user to go to the editor. Example: Add to My Contacts.
*/
private static abstract class QuickFix {
public abstract boolean isApplicable();
public abstract String getTitle();
public abstract void execute();
}
private class AddToMyContactsQuickFix extends QuickFix {
@Override
public boolean isApplicable() {
// Only local contacts
if (mContactData == null || mContactData.isDirectoryEntry()) return false;
// User profile cannot be added to contacts
if (mContactData.isUserProfile()) return false;
// Only if exactly one raw contact
if (mContactData.getRawContacts().size() != 1) return false;
// test if the default group is assigned
final List<GroupMetaData> groups = mContactData.getGroupMetaData();
// For accounts without group support, groups is null
if (groups == null) return false;
// remember the default group id. no default group? bail out early
final long defaultGroupId = getDefaultGroupId(groups);
if (defaultGroupId == -1) return false;
final RawContact rawContact = (RawContact) mContactData.getRawContacts().get(0);
final AccountType type = rawContact.getAccountType();
// Offline or non-writeable account? Nothing to fix
if (type == null || !type.areContactsWritable()) return false;
// Check whether the contact is in the default group
boolean isInDefaultGroup = false;
for (DataItem dataItem : Iterables.filter(
rawContact.getDataItems(), GroupMembershipDataItem.class)) {
GroupMembershipDataItem groupMembership = (GroupMembershipDataItem) dataItem;
final Long groupId = groupMembership.getGroupRowId();
if (groupId == defaultGroupId) {
isInDefaultGroup = true;
break;
}
}
return !isInDefaultGroup;
}
@Override
public String getTitle() {
return getString(R.string.add_to_my_contacts);
}
@Override
public void execute() {
final long defaultGroupId = getDefaultGroupId(mContactData.getGroupMetaData());
// there should always be a default group (otherwise the button would be invisible),
// but let's be safe here
if (defaultGroupId == -1) return;
// add the group membership to the current state
final RawContactDeltaList contactDeltaList = mContactData.createRawContactDeltaList();
final RawContactDelta rawContactEntityDelta = contactDeltaList.get(0);
final AccountTypeManager accountTypes = AccountTypeManager.getInstance(mContext);
final AccountType type = rawContactEntityDelta.getAccountType(accountTypes);
final DataKind groupMembershipKind = type.getKindForMimetype(
GroupMembership.CONTENT_ITEM_TYPE);
final ValuesDelta entry = RawContactModifier.insertChild(rawContactEntityDelta,
groupMembershipKind);
entry.setGroupRowId(defaultGroupId);
// and fire off the intent. we don't need a callback, as the database listener
// should update the ui
final Intent intent = ContactSaveService.createSaveContactIntent(getActivity(),
contactDeltaList, "", 0, false, getActivity().getClass(),
Intent.ACTION_VIEW, null);
getActivity().startService(intent);
}
}
private class MakeLocalCopyQuickFix extends QuickFix {
@Override
public boolean isApplicable() {
// Not a directory contact? Nothing to fix here
if (mContactData == null || !mContactData.isDirectoryEntry()) return false;
// No export support? Too bad
if (mContactData.getDirectoryExportSupport() == Directory.EXPORT_SUPPORT_NONE) {
return false;
}
return true;
}
@Override
public String getTitle() {
return getString(R.string.menu_copyContact);
}
@Override
public void execute() {
if (mListener == null) {
return;
}
int exportSupport = mContactData.getDirectoryExportSupport();
switch (exportSupport) {
case Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY: {
createCopy(new AccountWithDataSet(mContactData.getDirectoryAccountName(),
mContactData.getDirectoryAccountType(), null));
break;
}
case Directory.EXPORT_SUPPORT_ANY_ACCOUNT: {
final List<AccountWithDataSet> accounts =
AccountTypeManager.getInstance(mContext).getAccounts(true);
if (accounts.isEmpty()) {
createCopy(null);
return; // Don't show a dialog.
}
// In the common case of a single writable account, auto-select
// it without showing a dialog.
if (accounts.size() == 1) {
createCopy(accounts.get(0));
return; // Don't show a dialog.
}
SelectAccountDialogFragment.show(getFragmentManager(),
ContactDetailFragment.this, R.string.dialog_new_contact_account,
AccountListFilter.ACCOUNTS_CONTACT_WRITABLE, null);
break;
}
}
}
}
/**
* This class loads the correct padding values for a contact detail item so they can be applied
* dynamically. For example, this supports the case where some detail items can be indented and
* need extra padding.
*/
private static class ViewEntryDimensions {
private final int mWidePaddingLeft;
private final int mPaddingLeft;
private final int mPaddingRight;
private final int mPaddingTop;
private final int mPaddingBottom;
public ViewEntryDimensions(Resources resources) {
mPaddingLeft = resources.getDimensionPixelSize(
R.dimen.detail_item_side_margin);
mPaddingTop = resources.getDimensionPixelSize(
R.dimen.detail_item_vertical_margin);
mWidePaddingLeft = mPaddingLeft +
resources.getDimensionPixelSize(R.dimen.detail_item_icon_margin) +
resources.getDimensionPixelSize(R.dimen.detail_network_icon_size);
mPaddingRight = mPaddingLeft;
mPaddingBottom = mPaddingTop;
}
public int getWidePaddingLeft() {
return mWidePaddingLeft;
}
public int getPaddingLeft() {
return mPaddingLeft;
}
public int getPaddingRight() {
return mPaddingRight;
}
public int getPaddingTop() {
return mPaddingTop;
}
public int getPaddingBottom() {
return mPaddingBottom;
}
}
public static interface Listener {
/**
* User clicked a single item (e.g. mail). The intent passed in could be null.
*/
public void onItemClicked(Intent intent);
/**
* User requested creation of a new contact with the specified values.
*
* @param values ContentValues containing data rows for the new contact.
* @param account Account where the new contact should be created.
*/
public void onCreateRawContactRequested(ArrayList<ContentValues> values,
AccountWithDataSet account);
}
/**
* Adapter for the invitable account types; used for the invitable account type list popup.
*/
private final static class InvitableAccountTypesAdapter extends BaseAdapter {
private final Context mContext;
private final LayoutInflater mInflater;
private final ArrayList<AccountType> mAccountTypes;
public InvitableAccountTypesAdapter(Context context, Contact contactData) {
mContext = context;
mInflater = LayoutInflater.from(context);
final List<AccountType> types = contactData.getInvitableAccountTypes();
mAccountTypes = new ArrayList<AccountType>(types.size());
for (int i = 0; i < types.size(); i++) {
mAccountTypes.add(types.get(i));
}
Collections.sort(mAccountTypes, new AccountType.DisplayLabelComparator(mContext));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View resultView =
(convertView != null) ? convertView
: mInflater.inflate(R.layout.account_selector_list_item, parent, false);
final TextView text1 = (TextView)resultView.findViewById(android.R.id.text1);
final TextView text2 = (TextView)resultView.findViewById(android.R.id.text2);
final ImageView icon = (ImageView)resultView.findViewById(android.R.id.icon);
final AccountType accountType = mAccountTypes.get(position);
CharSequence action = accountType.getInviteContactActionLabel(mContext);
CharSequence label = accountType.getDisplayLabel(mContext);
if (TextUtils.isEmpty(action)) {
text1.setText(label);
text2.setVisibility(View.GONE);
} else {
text1.setText(action);
text2.setVisibility(View.VISIBLE);
text2.setText(label);
}
icon.setImageDrawable(accountType.getDisplayIcon(mContext));
return resultView;
}
@Override
public int getCount() {
return mAccountTypes.size();
}
@Override
public AccountType getItem(int position) {
return mAccountTypes.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
}
| true | true | private final void buildEntries() {
mHasPhone = PhoneCapabilityTester.isPhone(mContext);
mHasSms = PhoneCapabilityTester.isSmsIntentRegistered(mContext);
mHasSip = PhoneCapabilityTester.isSipPhone(mContext);
// Clear out the old entries
mAllEntries.clear();
mPrimaryPhoneUri = null;
// Build up method entries
if (mContactData == null) {
return;
}
ArrayList<String> groups = new ArrayList<String>();
for (RawContact rawContact: mContactData.getRawContacts()) {
final long rawContactId = rawContact.getId();
for (DataItem dataItem : rawContact.getDataItems()) {
dataItem.setRawContactId(rawContactId);
if (dataItem.getMimeType() == null) continue;
if (dataItem instanceof GroupMembershipDataItem) {
GroupMembershipDataItem groupMembership =
(GroupMembershipDataItem) dataItem;
Long groupId = groupMembership.getGroupRowId();
if (groupId != null) {
handleGroupMembership(groups, mContactData.getGroupMetaData(), groupId);
}
continue;
}
final DataKind kind = dataItem.getDataKind();
if (kind == null) continue;
final DetailViewEntry entry = DetailViewEntry.fromValues(mContext, dataItem,
mContactData.isDirectoryEntry(), mContactData.getDirectoryId());
entry.maxLines = kind.maxLinesForDisplay;
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = dataItem.isSuperPrimary();
if (dataItem instanceof StructuredNameDataItem) {
// Always ignore the name. It is shown in the header if set
} else if (dataItem instanceof PhoneDataItem && hasData) {
PhoneDataItem phone = (PhoneDataItem) dataItem;
// Build phone entries
entry.data = phone.getFormattedPhoneNumber();
final Intent phoneIntent = mHasPhone ?
ContactsUtils.getCallIntent(entry.data) : null;
final Intent smsIntent = mHasSms ? new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null)) : null;
// Configure Icons and Intents.
if (mHasPhone && mHasSms) {
entry.intent = phoneIntent;
entry.secondaryIntent = smsIntent;
entry.secondaryActionIcon = kind.iconAltRes;
entry.secondaryActionDescription = kind.iconAltDescriptionRes;
} else if (mHasPhone) {
entry.intent = phoneIntent;
} else if (mHasSms) {
entry.intent = smsIntent;
} else {
entry.intent = null;
}
// Remember super-primary phone
if (isSuperPrimary) mPrimaryPhoneUri = entry.uri;
entry.isPrimary = isSuperPrimary;
// If the entry is a primary entry, then render it first in the view.
if (entry.isPrimary) {
// add to beginning of list so that this phone number shows up first
mPhoneEntries.add(0, entry);
} else {
// add to end of list
mPhoneEntries.add(entry);
}
} else if (dataItem instanceof EmailDataItem && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
// If entry is a primary entry, then render it first in the view.
if (entry.isPrimary) {
mEmailEntries.add(0, entry);
} else {
mEmailEntries.add(entry);
}
// When Email rows have status, create additional Im row
final DataStatus status = mContactData.getStatuses().get(entry.id);
if (status != null) {
EmailDataItem email = (EmailDataItem) dataItem;
ImDataItem im = ImDataItem.createFromEmail(email);
final DetailViewEntry imEntry = DetailViewEntry.fromValues(mContext, im,
mContactData.isDirectoryEntry(), mContactData.getDirectoryId());
buildImActions(mContext, imEntry, im);
imEntry.setPresence(status.getPresence());
imEntry.maxLines = kind.maxLinesForDisplay;
mImEntries.add(imEntry);
}
} else if (dataItem instanceof StructuredPostalDataItem && hasData) {
// Build postal entries
entry.intent = StructuredPostalUtils.getViewPostalAddressIntent(entry.data);
mPostalEntries.add(entry);
} else if (dataItem instanceof ImDataItem && hasData) {
// Build IM entries
buildImActions(mContext, entry, (ImDataItem) dataItem);
// Apply presence when available
final DataStatus status = mContactData.getStatuses().get(entry.id);
if (status != null) {
entry.setPresence(status.getPresence());
}
mImEntries.add(entry);
} else if (dataItem instanceof OrganizationDataItem) {
// Organizations are not shown. The first one is shown in the header
// and subsequent ones are not supported anymore
} else if (dataItem instanceof NicknameDataItem && hasData) {
// Build nickname entries
final boolean isNameRawContact =
(mContactData.getNameRawContactId() == rawContactId);
final boolean duplicatesTitle =
isNameRawContact
&& mContactData.getDisplayNameSource() == DisplayNameSources.NICKNAME;
if (!duplicatesTitle) {
entry.uri = null;
mNicknameEntries.add(entry);
}
} else if (dataItem instanceof NoteDataItem && hasData) {
// Build note entries
entry.uri = null;
mNoteEntries.add(entry);
} else if (dataItem instanceof WebsiteDataItem && hasData) {
// Build Website entries
entry.uri = null;
try {
WebAddress webAddress = new WebAddress(entry.data);
entry.intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(webAddress.toString()));
} catch (ParseException e) {
Log.e(TAG, "Couldn't parse website: " + entry.data);
}
mWebsiteEntries.add(entry);
} else if (dataItem instanceof SipAddressDataItem && hasData) {
// Build SipAddress entries
entry.uri = null;
if (mHasSip) {
entry.intent = ContactsUtils.getCallIntent(
Uri.fromParts(Constants.SCHEME_SIP, entry.data, null));
} else {
entry.intent = null;
}
mSipEntries.add(entry);
// TODO: Now that SipAddress is in its own list of entries
// (instead of grouped in mOtherEntries), consider
// repositioning it right under the phone number.
// (Then, we'd also update FallbackAccountType.java to set
// secondary=false for this field, and tweak the weight
// of its DataKind.)
} else if (dataItem instanceof EventDataItem && hasData) {
entry.data = DateUtils.formatDate(mContext, entry.data);
entry.uri = null;
mEventEntries.add(entry);
} else if (dataItem instanceof RelationDataItem && hasData) {
entry.intent = new Intent(Intent.ACTION_SEARCH);
entry.intent.putExtra(SearchManager.QUERY, entry.data);
entry.intent.setType(Contacts.CONTENT_TYPE);
mRelationEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW);
entry.intent.setDataAndType(entry.uri, entry.mimetype);
entry.data = dataItem.buildDataString();
if (!TextUtils.isEmpty(entry.data)) {
// If the account type exists in the hash map, add it as another entry for
// that account type
AccountType type = dataItem.getAccountType();
if (mOtherEntriesMap.containsKey(type)) {
List<DetailViewEntry> listEntries = mOtherEntriesMap.get(type);
listEntries.add(entry);
} else {
// Otherwise create a new list with the entry and add it to the hash map
List<DetailViewEntry> listEntries = new ArrayList<DetailViewEntry>();
listEntries.add(entry);
mOtherEntriesMap.put(type, listEntries);
}
}
}
}
}
if (!groups.isEmpty()) {
DetailViewEntry entry = new DetailViewEntry();
Collections.sort(groups);
StringBuilder sb = new StringBuilder();
int size = groups.size();
for (int i = 0; i < size; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(groups.get(i));
}
entry.mimetype = GroupMembership.MIMETYPE;
entry.kind = mContext.getString(R.string.groupsLabel);
entry.data = sb.toString();
mGroupEntries.add(entry);
}
}
| private final void buildEntries() {
mHasPhone = PhoneCapabilityTester.isPhone(mContext);
mHasSms = PhoneCapabilityTester.isSmsIntentRegistered(mContext);
mHasSip = PhoneCapabilityTester.isSipPhone(mContext);
// Clear out the old entries
mAllEntries.clear();
mPrimaryPhoneUri = null;
// Build up method entries
if (mContactData == null) {
return;
}
ArrayList<String> groups = new ArrayList<String>();
for (RawContact rawContact: mContactData.getRawContacts()) {
final long rawContactId = rawContact.getId();
for (DataItem dataItem : rawContact.getDataItems()) {
dataItem.setRawContactId(rawContactId);
if (dataItem.getMimeType() == null) continue;
if (dataItem instanceof GroupMembershipDataItem) {
GroupMembershipDataItem groupMembership =
(GroupMembershipDataItem) dataItem;
Long groupId = groupMembership.getGroupRowId();
if (groupId != null) {
handleGroupMembership(groups, mContactData.getGroupMetaData(), groupId);
}
continue;
}
final DataKind kind = dataItem.getDataKind();
if (kind == null) continue;
final DetailViewEntry entry = DetailViewEntry.fromValues(mContext, dataItem,
mContactData.isDirectoryEntry(), mContactData.getDirectoryId());
entry.maxLines = kind.maxLinesForDisplay;
final boolean hasData = !TextUtils.isEmpty(entry.data);
final boolean isSuperPrimary = dataItem.isSuperPrimary();
if (dataItem instanceof StructuredNameDataItem) {
// Always ignore the name. It is shown in the header if set
} else if (dataItem instanceof PhoneDataItem && hasData) {
PhoneDataItem phone = (PhoneDataItem) dataItem;
// Build phone entries
entry.data = phone.getFormattedPhoneNumber();
if (entry.data == null) {
// This case happens when the quick contact was opened from the contact
// list, and then, the user touches the quick contact image and brings the
// user to the detail card. In this case, the Contact object that was
// loaded from quick contacts does not contain the formatted phone number,
// so it must be loaded here.
phone.computeFormattedPhoneNumber(mDefaultCountryIso);
entry.data = phone.getFormattedPhoneNumber();
}
final Intent phoneIntent = mHasPhone ?
ContactsUtils.getCallIntent(entry.data) : null;
final Intent smsIntent = mHasSms ? new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null)) : null;
// Configure Icons and Intents.
if (mHasPhone && mHasSms) {
entry.intent = phoneIntent;
entry.secondaryIntent = smsIntent;
entry.secondaryActionIcon = kind.iconAltRes;
entry.secondaryActionDescription = kind.iconAltDescriptionRes;
} else if (mHasPhone) {
entry.intent = phoneIntent;
} else if (mHasSms) {
entry.intent = smsIntent;
} else {
entry.intent = null;
}
// Remember super-primary phone
if (isSuperPrimary) mPrimaryPhoneUri = entry.uri;
entry.isPrimary = isSuperPrimary;
// If the entry is a primary entry, then render it first in the view.
if (entry.isPrimary) {
// add to beginning of list so that this phone number shows up first
mPhoneEntries.add(0, entry);
} else {
// add to end of list
mPhoneEntries.add(entry);
}
} else if (dataItem instanceof EmailDataItem && hasData) {
// Build email entries
entry.intent = new Intent(Intent.ACTION_SENDTO,
Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null));
entry.isPrimary = isSuperPrimary;
// If entry is a primary entry, then render it first in the view.
if (entry.isPrimary) {
mEmailEntries.add(0, entry);
} else {
mEmailEntries.add(entry);
}
// When Email rows have status, create additional Im row
final DataStatus status = mContactData.getStatuses().get(entry.id);
if (status != null) {
EmailDataItem email = (EmailDataItem) dataItem;
ImDataItem im = ImDataItem.createFromEmail(email);
final DetailViewEntry imEntry = DetailViewEntry.fromValues(mContext, im,
mContactData.isDirectoryEntry(), mContactData.getDirectoryId());
buildImActions(mContext, imEntry, im);
imEntry.setPresence(status.getPresence());
imEntry.maxLines = kind.maxLinesForDisplay;
mImEntries.add(imEntry);
}
} else if (dataItem instanceof StructuredPostalDataItem && hasData) {
// Build postal entries
entry.intent = StructuredPostalUtils.getViewPostalAddressIntent(entry.data);
mPostalEntries.add(entry);
} else if (dataItem instanceof ImDataItem && hasData) {
// Build IM entries
buildImActions(mContext, entry, (ImDataItem) dataItem);
// Apply presence when available
final DataStatus status = mContactData.getStatuses().get(entry.id);
if (status != null) {
entry.setPresence(status.getPresence());
}
mImEntries.add(entry);
} else if (dataItem instanceof OrganizationDataItem) {
// Organizations are not shown. The first one is shown in the header
// and subsequent ones are not supported anymore
} else if (dataItem instanceof NicknameDataItem && hasData) {
// Build nickname entries
final boolean isNameRawContact =
(mContactData.getNameRawContactId() == rawContactId);
final boolean duplicatesTitle =
isNameRawContact
&& mContactData.getDisplayNameSource() == DisplayNameSources.NICKNAME;
if (!duplicatesTitle) {
entry.uri = null;
mNicknameEntries.add(entry);
}
} else if (dataItem instanceof NoteDataItem && hasData) {
// Build note entries
entry.uri = null;
mNoteEntries.add(entry);
} else if (dataItem instanceof WebsiteDataItem && hasData) {
// Build Website entries
entry.uri = null;
try {
WebAddress webAddress = new WebAddress(entry.data);
entry.intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(webAddress.toString()));
} catch (ParseException e) {
Log.e(TAG, "Couldn't parse website: " + entry.data);
}
mWebsiteEntries.add(entry);
} else if (dataItem instanceof SipAddressDataItem && hasData) {
// Build SipAddress entries
entry.uri = null;
if (mHasSip) {
entry.intent = ContactsUtils.getCallIntent(
Uri.fromParts(Constants.SCHEME_SIP, entry.data, null));
} else {
entry.intent = null;
}
mSipEntries.add(entry);
// TODO: Now that SipAddress is in its own list of entries
// (instead of grouped in mOtherEntries), consider
// repositioning it right under the phone number.
// (Then, we'd also update FallbackAccountType.java to set
// secondary=false for this field, and tweak the weight
// of its DataKind.)
} else if (dataItem instanceof EventDataItem && hasData) {
entry.data = DateUtils.formatDate(mContext, entry.data);
entry.uri = null;
mEventEntries.add(entry);
} else if (dataItem instanceof RelationDataItem && hasData) {
entry.intent = new Intent(Intent.ACTION_SEARCH);
entry.intent.putExtra(SearchManager.QUERY, entry.data);
entry.intent.setType(Contacts.CONTENT_TYPE);
mRelationEntries.add(entry);
} else {
// Handle showing custom rows
entry.intent = new Intent(Intent.ACTION_VIEW);
entry.intent.setDataAndType(entry.uri, entry.mimetype);
entry.data = dataItem.buildDataString();
if (!TextUtils.isEmpty(entry.data)) {
// If the account type exists in the hash map, add it as another entry for
// that account type
AccountType type = dataItem.getAccountType();
if (mOtherEntriesMap.containsKey(type)) {
List<DetailViewEntry> listEntries = mOtherEntriesMap.get(type);
listEntries.add(entry);
} else {
// Otherwise create a new list with the entry and add it to the hash map
List<DetailViewEntry> listEntries = new ArrayList<DetailViewEntry>();
listEntries.add(entry);
mOtherEntriesMap.put(type, listEntries);
}
}
}
}
}
if (!groups.isEmpty()) {
DetailViewEntry entry = new DetailViewEntry();
Collections.sort(groups);
StringBuilder sb = new StringBuilder();
int size = groups.size();
for (int i = 0; i < size; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(groups.get(i));
}
entry.mimetype = GroupMembership.MIMETYPE;
entry.kind = mContext.getString(R.string.groupsLabel);
entry.data = sb.toString();
mGroupEntries.add(entry);
}
}
|
diff --git a/src/java/uk/org/ponder/darwin/rsf/producers/NavFrameProducer.java b/src/java/uk/org/ponder/darwin/rsf/producers/NavFrameProducer.java
index 15453f7..3a98dbd 100644
--- a/src/java/uk/org/ponder/darwin/rsf/producers/NavFrameProducer.java
+++ b/src/java/uk/org/ponder/darwin/rsf/producers/NavFrameProducer.java
@@ -1,153 +1,153 @@
/*
* Created on 14-Dec-2005
*/
package uk.org.ponder.darwin.rsf.producers;
import uk.org.ponder.darwin.item.ItemCollection;
import uk.org.ponder.darwin.item.ItemDetails;
import uk.org.ponder.darwin.item.PageInfo;
import uk.org.ponder.darwin.parse.URLMapper;
import uk.org.ponder.darwin.rsf.ViewParamGetter;
import uk.org.ponder.darwin.rsf.params.AdvancedSearchParams;
import uk.org.ponder.darwin.rsf.params.NavParams;
import uk.org.ponder.darwin.rsf.params.SearchResultsParams;
import uk.org.ponder.darwin.rsf.params.TextBlockRenderParams;
import uk.org.ponder.rsac.RSACBeanLocator;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParamsReporter;
import uk.org.ponder.rsf.viewstate.ViewStateHandler;
/**
* @author Antranig Basman ([email protected])
*
*/
public class NavFrameProducer implements ViewComponentProducer, ViewParamsReporter {
public static final String VIEWID = "nav-frame";
private ItemCollection collection;
private URLMapper urlmapper;
private ViewStateHandler viewStateHandler;
public String getViewID() {
return VIEWID;
}
public void setURLMapper(URLMapper urlmapper) {
this.urlmapper = urlmapper;
}
public void setItemCollection(ItemCollection collection) {
this.collection = collection;
}
public void setViewStateHandler(ViewStateHandler viewStateHandler) {
this.viewStateHandler = viewStateHandler;
}
public void fillComponents(UIContainer tofill, ViewParameters origviewparams,
ComponentChecker checker) {
NavParams navparams = (NavParams) origviewparams;
ItemDetails item = collection.getItem(navparams.itemID);
AdvancedSearchParams bibparams = new AdvancedSearchParams();
bibparams.published = true;
UIInternalLink.make(tofill, "search-bibliography", bibparams);
AdvancedSearchParams manparams = new AdvancedSearchParams();
- bibparams.manuscript = true;
+ manparams.manuscript = true;
UIInternalLink.make(tofill, "search-manuscripts", manparams);
if (navparams.viewtype.equals(NavParams.TEXT_VIEW)
|| navparams.viewtype.equals(NavParams.SIDE_VIEW)) {
TextBlockRenderParams contentparams = new TextBlockRenderParams();
contentparams.itemID = navparams.itemID;
for (int i = 1; i < item.pages.size(); ++i) {
PageInfo page = (PageInfo) item.pages.get(i);
contentparams.pageseq = new Integer(page.sequence);
contentparams.keywords = navparams.keywords;
contentparams.viewtype = navparams.viewtype;
contentparams.hitpage = navparams.pageseq;
ViewParamGetter.fillTextParams(collection, contentparams);
String texturl = viewStateHandler.getFullURL(contentparams);
UIOutput.make(tofill, ComponentIDs.TEXT_TARGET + i, texturl);
}
}
if (navparams.viewtype.equals(NavParams.IMAGE_VIEW)
|| navparams.viewtype.equals(NavParams.SIDE_VIEW)) {
for (int i = 1; i < item.pages.size(); ++i) {
// PageRenderParams contentparams = new PageRenderParams();
// contentparams.itemID = navparams.itemID;
// contentparams.viewtype = PageRenderParams.IMAGE_VIEW;
PageInfo page = (PageInfo) item.pages.get(i);
// contentparams.pageseq = page.sequence;
// String imageurl = vsh.getFullURL(contentparams);
String imageurl = (page == null || page.imagefile == null) ? "#"
: urlmapper.fileToURL(page.imagefile);
UIOutput.make(tofill, ComponentIDs.IMAGE_TARGET + i, imageurl);
}
}
String[] values = new String[item.pages.size() - 1];
String[] labels = new String[item.pages.size() - 1];
for (int i = 1; i < item.pages.size(); ++i) {
PageInfo page = (PageInfo) item.pages.get(i);
values[i - 1] = Integer.toString(page.sequence);
String text = page.text == null ? (item.hastext ? ""
: " image ") + values[i - 1] : page.text.trim();
if (text.length() == 0) {
text = "[unnumbered]";
}
labels[i - 1] = text;
}
int page = navparams.pageseq;
UIOutput.make(tofill, ComponentIDs.CURRENT_PAGE, "" + page);
UIOutput.make(tofill, ComponentIDs.LAST_PAGE, "" + values.length);
UIOutput.make(tofill, ComponentIDs.VIEW_TYPE, navparams.viewtype);
UISelect.make(tofill, ComponentIDs.PAGE_SELECT, values, labels,
values[page - 1]);
boolean switchany = false;
if (!(navparams.viewtype.equals(NavParams.SIDE_VIEW)) && item.hasimage
&& item.hastext) {
NavParams sideparams = (NavParams) navparams.copyBase();
sideparams.viewtype = NavParams.SIDE_VIEW;
sideparams.viewID = FramesetProducer.VIEWID;
UIInternalLink.make(tofill, "switch-side", sideparams);
switchany = true;
}
if (!(navparams.viewtype.equals(NavParams.IMAGE_VIEW)) && item.hasimage) {
NavParams sideparams = (NavParams) navparams.copyBase();
sideparams.viewtype = NavParams.IMAGE_VIEW;
sideparams.viewID = FramesetProducer.VIEWID;
UIInternalLink.make(tofill, "switch-image", sideparams);
switchany = true;
}
if (!(navparams.viewtype.equals(NavParams.TEXT_VIEW)) && item.hastext) {
NavParams sideparams = (NavParams) navparams.copyBase();
sideparams.viewtype = NavParams.TEXT_VIEW;
sideparams.viewID = FramesetProducer.VIEWID;
UIInternalLink.make(tofill, "switch-text", sideparams);
switchany = true;
}
if (switchany) {
UIOutput.make(tofill, "switch-any");
}
UIInternalLink.make(tofill, "advanced-search", new AdvancedSearchParams());
UIInternalLink.make(tofill, "search-submit", new SearchResultsParams());
}
public ViewParameters getViewParameters() {
return new NavParams();
}
}
| true | true | public void fillComponents(UIContainer tofill, ViewParameters origviewparams,
ComponentChecker checker) {
NavParams navparams = (NavParams) origviewparams;
ItemDetails item = collection.getItem(navparams.itemID);
AdvancedSearchParams bibparams = new AdvancedSearchParams();
bibparams.published = true;
UIInternalLink.make(tofill, "search-bibliography", bibparams);
AdvancedSearchParams manparams = new AdvancedSearchParams();
bibparams.manuscript = true;
UIInternalLink.make(tofill, "search-manuscripts", manparams);
if (navparams.viewtype.equals(NavParams.TEXT_VIEW)
|| navparams.viewtype.equals(NavParams.SIDE_VIEW)) {
TextBlockRenderParams contentparams = new TextBlockRenderParams();
contentparams.itemID = navparams.itemID;
for (int i = 1; i < item.pages.size(); ++i) {
PageInfo page = (PageInfo) item.pages.get(i);
contentparams.pageseq = new Integer(page.sequence);
contentparams.keywords = navparams.keywords;
contentparams.viewtype = navparams.viewtype;
contentparams.hitpage = navparams.pageseq;
ViewParamGetter.fillTextParams(collection, contentparams);
String texturl = viewStateHandler.getFullURL(contentparams);
UIOutput.make(tofill, ComponentIDs.TEXT_TARGET + i, texturl);
}
}
if (navparams.viewtype.equals(NavParams.IMAGE_VIEW)
|| navparams.viewtype.equals(NavParams.SIDE_VIEW)) {
for (int i = 1; i < item.pages.size(); ++i) {
// PageRenderParams contentparams = new PageRenderParams();
// contentparams.itemID = navparams.itemID;
// contentparams.viewtype = PageRenderParams.IMAGE_VIEW;
PageInfo page = (PageInfo) item.pages.get(i);
// contentparams.pageseq = page.sequence;
// String imageurl = vsh.getFullURL(contentparams);
String imageurl = (page == null || page.imagefile == null) ? "#"
: urlmapper.fileToURL(page.imagefile);
UIOutput.make(tofill, ComponentIDs.IMAGE_TARGET + i, imageurl);
}
}
String[] values = new String[item.pages.size() - 1];
String[] labels = new String[item.pages.size() - 1];
for (int i = 1; i < item.pages.size(); ++i) {
PageInfo page = (PageInfo) item.pages.get(i);
values[i - 1] = Integer.toString(page.sequence);
String text = page.text == null ? (item.hastext ? ""
: " image ") + values[i - 1] : page.text.trim();
if (text.length() == 0) {
text = "[unnumbered]";
}
labels[i - 1] = text;
}
int page = navparams.pageseq;
UIOutput.make(tofill, ComponentIDs.CURRENT_PAGE, "" + page);
UIOutput.make(tofill, ComponentIDs.LAST_PAGE, "" + values.length);
UIOutput.make(tofill, ComponentIDs.VIEW_TYPE, navparams.viewtype);
UISelect.make(tofill, ComponentIDs.PAGE_SELECT, values, labels,
values[page - 1]);
boolean switchany = false;
if (!(navparams.viewtype.equals(NavParams.SIDE_VIEW)) && item.hasimage
&& item.hastext) {
NavParams sideparams = (NavParams) navparams.copyBase();
sideparams.viewtype = NavParams.SIDE_VIEW;
sideparams.viewID = FramesetProducer.VIEWID;
UIInternalLink.make(tofill, "switch-side", sideparams);
switchany = true;
}
if (!(navparams.viewtype.equals(NavParams.IMAGE_VIEW)) && item.hasimage) {
NavParams sideparams = (NavParams) navparams.copyBase();
sideparams.viewtype = NavParams.IMAGE_VIEW;
sideparams.viewID = FramesetProducer.VIEWID;
UIInternalLink.make(tofill, "switch-image", sideparams);
switchany = true;
}
if (!(navparams.viewtype.equals(NavParams.TEXT_VIEW)) && item.hastext) {
NavParams sideparams = (NavParams) navparams.copyBase();
sideparams.viewtype = NavParams.TEXT_VIEW;
sideparams.viewID = FramesetProducer.VIEWID;
UIInternalLink.make(tofill, "switch-text", sideparams);
switchany = true;
}
if (switchany) {
UIOutput.make(tofill, "switch-any");
}
UIInternalLink.make(tofill, "advanced-search", new AdvancedSearchParams());
UIInternalLink.make(tofill, "search-submit", new SearchResultsParams());
}
| public void fillComponents(UIContainer tofill, ViewParameters origviewparams,
ComponentChecker checker) {
NavParams navparams = (NavParams) origviewparams;
ItemDetails item = collection.getItem(navparams.itemID);
AdvancedSearchParams bibparams = new AdvancedSearchParams();
bibparams.published = true;
UIInternalLink.make(tofill, "search-bibliography", bibparams);
AdvancedSearchParams manparams = new AdvancedSearchParams();
manparams.manuscript = true;
UIInternalLink.make(tofill, "search-manuscripts", manparams);
if (navparams.viewtype.equals(NavParams.TEXT_VIEW)
|| navparams.viewtype.equals(NavParams.SIDE_VIEW)) {
TextBlockRenderParams contentparams = new TextBlockRenderParams();
contentparams.itemID = navparams.itemID;
for (int i = 1; i < item.pages.size(); ++i) {
PageInfo page = (PageInfo) item.pages.get(i);
contentparams.pageseq = new Integer(page.sequence);
contentparams.keywords = navparams.keywords;
contentparams.viewtype = navparams.viewtype;
contentparams.hitpage = navparams.pageseq;
ViewParamGetter.fillTextParams(collection, contentparams);
String texturl = viewStateHandler.getFullURL(contentparams);
UIOutput.make(tofill, ComponentIDs.TEXT_TARGET + i, texturl);
}
}
if (navparams.viewtype.equals(NavParams.IMAGE_VIEW)
|| navparams.viewtype.equals(NavParams.SIDE_VIEW)) {
for (int i = 1; i < item.pages.size(); ++i) {
// PageRenderParams contentparams = new PageRenderParams();
// contentparams.itemID = navparams.itemID;
// contentparams.viewtype = PageRenderParams.IMAGE_VIEW;
PageInfo page = (PageInfo) item.pages.get(i);
// contentparams.pageseq = page.sequence;
// String imageurl = vsh.getFullURL(contentparams);
String imageurl = (page == null || page.imagefile == null) ? "#"
: urlmapper.fileToURL(page.imagefile);
UIOutput.make(tofill, ComponentIDs.IMAGE_TARGET + i, imageurl);
}
}
String[] values = new String[item.pages.size() - 1];
String[] labels = new String[item.pages.size() - 1];
for (int i = 1; i < item.pages.size(); ++i) {
PageInfo page = (PageInfo) item.pages.get(i);
values[i - 1] = Integer.toString(page.sequence);
String text = page.text == null ? (item.hastext ? ""
: " image ") + values[i - 1] : page.text.trim();
if (text.length() == 0) {
text = "[unnumbered]";
}
labels[i - 1] = text;
}
int page = navparams.pageseq;
UIOutput.make(tofill, ComponentIDs.CURRENT_PAGE, "" + page);
UIOutput.make(tofill, ComponentIDs.LAST_PAGE, "" + values.length);
UIOutput.make(tofill, ComponentIDs.VIEW_TYPE, navparams.viewtype);
UISelect.make(tofill, ComponentIDs.PAGE_SELECT, values, labels,
values[page - 1]);
boolean switchany = false;
if (!(navparams.viewtype.equals(NavParams.SIDE_VIEW)) && item.hasimage
&& item.hastext) {
NavParams sideparams = (NavParams) navparams.copyBase();
sideparams.viewtype = NavParams.SIDE_VIEW;
sideparams.viewID = FramesetProducer.VIEWID;
UIInternalLink.make(tofill, "switch-side", sideparams);
switchany = true;
}
if (!(navparams.viewtype.equals(NavParams.IMAGE_VIEW)) && item.hasimage) {
NavParams sideparams = (NavParams) navparams.copyBase();
sideparams.viewtype = NavParams.IMAGE_VIEW;
sideparams.viewID = FramesetProducer.VIEWID;
UIInternalLink.make(tofill, "switch-image", sideparams);
switchany = true;
}
if (!(navparams.viewtype.equals(NavParams.TEXT_VIEW)) && item.hastext) {
NavParams sideparams = (NavParams) navparams.copyBase();
sideparams.viewtype = NavParams.TEXT_VIEW;
sideparams.viewID = FramesetProducer.VIEWID;
UIInternalLink.make(tofill, "switch-text", sideparams);
switchany = true;
}
if (switchany) {
UIOutput.make(tofill, "switch-any");
}
UIInternalLink.make(tofill, "advanced-search", new AdvancedSearchParams());
UIInternalLink.make(tofill, "search-submit", new SearchResultsParams());
}
|
diff --git a/src/test/java/com/wikia/webdriver/PageObjects/PageObject/ForumPageObject/ForumManageBoardsPageObject.java b/src/test/java/com/wikia/webdriver/PageObjects/PageObject/ForumPageObject/ForumManageBoardsPageObject.java
index 392491e..21f3b16 100644
--- a/src/test/java/com/wikia/webdriver/PageObjects/PageObject/ForumPageObject/ForumManageBoardsPageObject.java
+++ b/src/test/java/com/wikia/webdriver/PageObjects/PageObject/ForumPageObject/ForumManageBoardsPageObject.java
@@ -1,185 +1,185 @@
package com.wikia.webdriver.PageObjects.PageObject.ForumPageObject;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import com.wikia.webdriver.Common.Core.Assertion;
import com.wikia.webdriver.Common.Core.Global;
import com.wikia.webdriver.Common.Logging.PageObjectLogging;
import com.wikia.webdriver.PageObjects.PageObject.BasePageObject;
public class ForumManageBoardsPageObject extends BasePageObject{
public ForumManageBoardsPageObject(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
@FindBy(css="#CreateNewBoardButton")
private WebElement createBoardButton;
@FindBy(xpath="//section[@id='modalWrapper' and contains(text(), 'Create a new board')]")
private WebElement createBoardModalHeader;
@FindBy(css="[name='boardTitle']")
private WebElement boardTitleField;
@FindBy(css="[name='boardDescription']")
private WebElement boardDescriptionField;
@FindBy(css=".submit")
private WebElement boardSubmitButton;
@FindBy(css="[name='boardTitle']")
private WebElement deleteBoardConfirmationField;
@FindBy(css="[name='destinationBoardId']")
private WebElement mergeToBoard;
@FindBy(css=".modalToolbar .submit")
private WebElement deleteAndMergeButton;
@FindBy(xpath="//ul[@class='boards']/li//a")
private WebElement firstForumLink;
@FindBy(xpath="//ul[@class='boards']//li[2]//a")
private WebElement secondForumLink;
private void openCreateNewBoardForm(){
waitForElementByElement(createBoardButton);
createBoardButton.click();
PageObjectLogging.log("openCreateNewBoardForm", "create new board form opened", true, driver);
}
private void typeBoardTitle(String title){
waitForElementByElement(boardTitleField);
boardTitleField.sendKeys(title);
PageObjectLogging.log("typeBoardTitle", "board title typed in", true);
}
private void typeBoradDescription(String description){
waitForElementByElement(boardDescriptionField);
boardDescriptionField.sendKeys(description);
PageObjectLogging.log("typeBoardDescription", "board description typed in", true);
}
private void submitNewBoard(){
waitForElementByElement(boardSubmitButton);
clickAndWait(boardSubmitButton);
PageObjectLogging.log("submitNewBoard", "new board submitted", true, driver);
}
public void createNewBoard(String title, String description){
openCreateNewBoardForm();
typeBoardTitle(title);
typeBoradDescription(description);
submitNewBoard();
}
public void verifyBoardCreated(String title, String description){
waitForElementByXPath("//ul/li//a[contains(text(), '"+title.replaceAll("_", " ")+"')]/../../../p[contains(text(), '"+description+"')]");
PageObjectLogging.log("verifyBoardCreated", "recently created board verified", true);
}
private void clickDeleteForum(String name){
WebElement deleteButton = waitForElementByXPath("//a[contains(text(), '"+name+"')]/../..//img[@class='sprite trash']");
clickAndWait(deleteButton);
PageObjectLogging.log("clickDeleteForum", "delete forum button clicked", true, driver);
}
private void confirmDeleteForum(String deletedName, String mergerdName){
waitForElementByElement(deleteBoardConfirmationField);
deleteBoardConfirmationField.sendKeys(deletedName);
Select select = new Select(mergeToBoard);
select.selectByVisibleText(mergerdName);
PageObjectLogging.log("confirmDeleteForum", "delete forum form populated", true, driver);
}
private void clickDeleteAndMergeForum(){
waitForElementByElement(deleteAndMergeButton);
clickAndWait(deleteAndMergeButton);
PageObjectLogging.log("confirmDeleteForum", "delete forum form populated", true, driver);
}
private void verifyForumDeletedText(String deletedName){
waitForElementByXPath("//div[@class='global-notification confirm']" +
"/div[@class='msg' and contains(text(), '\"Board:"+deletedName+"\" has been deleted.')]");
PageObjectLogging.log("verifyForumDeletedText", "forum deleted text verified", true);
}
public void deleteForum(String sourceForumName, String destinationForumName){
clickDeleteForum(sourceForumName);
confirmDeleteForum(sourceForumName, destinationForumName);
clickDeleteAndMergeForum();
verifyForumDeletedText(sourceForumName);
}
public String getFirstForumName(){
waitForElementByElement(firstForumLink);
return firstForumLink.getText();
}
public String getSecondForumName(){
waitForElementByElement(secondForumLink);
return secondForumLink.getText();
}
public void verifyForumExists(String forumName){
String temp = driver.getCurrentUrl();
try {
getUrl(Global.DOMAIN+"wiki/Board:"+URLEncoder.encode(forumName, "UTF-8").replace("+", "_"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
- waitForElementByXPath("//h1[contains(text(), '"+forumName+"')]");
+ waitForElementByXPath("//h1[contains(text(), '"+forumName.replace("_", " ")+"')]");
getUrl(temp);
PageObjectLogging.log("verifyForumExists", "verified forum exists", true, driver);
}
public void verifyForumNotExists(String forumName){
try {
getUrl(Global.DOMAIN+"wiki/Board:"+URLEncoder.encode(forumName, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
waitForElementByXPath("//div[@class='msg' and contains(text(), \"The board you're looking for was not found\")]");
PageObjectLogging.log("verifyForumNotExists", "verified forum not exists", true, driver);
}
private void clickModifyForum(String forumName){
WebElement editPecil = waitForElementByXPath("//a[contains(text(), '"+forumName+"')]/../..//img[@class='sprite edit-pencil']");
clickAndWait(editPecil);
PageObjectLogging.log("clickModifyForum", "modify forum button clicked", true, driver);
}
private void clearEditBoardFields(){
waitForElementByElement(boardTitleField);
waitForElementByElement(boardDescriptionField);
boardTitleField.clear();
boardDescriptionField.clear();
PageObjectLogging.log("clickEditBoardFields", "edit boards fields cleared", true, driver);
}
public void editForum(String forumName, String newTitle, String newDescription){
clickModifyForum(forumName);
clearEditBoardFields();
typeBoardTitle(newTitle);
typeBoradDescription(newDescription);
submitNewBoard();
}
public void clickMoveDown(String forumName){
String temp = getFirstForumName();
WebElement down = waitForElementByXPath("//a[contains(text(), '"+forumName+"')]/../..//span[@class='movedown']");
down.click();
Assertion.assertEquals(temp, getSecondForumName());
PageObjectLogging.log("clickMoveDown", "move down button clicked", true, driver);
}
public void clickMoveUp(String forumName){
String temp = getSecondForumName();
WebElement up = waitForElementByXPath("//a[contains(text(), '"+forumName+"')]/../..//span[@class='moveup']");
up.click();
Assertion.assertEquals(temp, getFirstForumName());
PageObjectLogging.log("clickMoveDown", "move up button clicked", true, driver);
}
}
| true | true | public void verifyForumExists(String forumName){
String temp = driver.getCurrentUrl();
try {
getUrl(Global.DOMAIN+"wiki/Board:"+URLEncoder.encode(forumName, "UTF-8").replace("+", "_"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
waitForElementByXPath("//h1[contains(text(), '"+forumName+"')]");
getUrl(temp);
PageObjectLogging.log("verifyForumExists", "verified forum exists", true, driver);
}
| public void verifyForumExists(String forumName){
String temp = driver.getCurrentUrl();
try {
getUrl(Global.DOMAIN+"wiki/Board:"+URLEncoder.encode(forumName, "UTF-8").replace("+", "_"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
waitForElementByXPath("//h1[contains(text(), '"+forumName.replace("_", " ")+"')]");
getUrl(temp);
PageObjectLogging.log("verifyForumExists", "verified forum exists", true, driver);
}
|
diff --git a/classes/com/sapienter/jbilling/server/user/EntitySignup.java b/classes/com/sapienter/jbilling/server/user/EntitySignup.java
index a4155ed8..aaef467c 100644
--- a/classes/com/sapienter/jbilling/server/user/EntitySignup.java
+++ b/classes/com/sapienter/jbilling/server/user/EntitySignup.java
@@ -1,866 +1,866 @@
/*
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): ______________________________________.
*/
package com.sapienter.jbilling.server.user;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Calendar;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.common.CommonConstants;
import com.sapienter.jbilling.common.JBCrypto;
import com.sapienter.jbilling.common.JNDILookup;
import com.sapienter.jbilling.common.Util;
import com.sapienter.jbilling.server.entity.ContactDTO;
import com.sapienter.jbilling.server.util.Constants;
/**
* @author emilc
*/
public final class EntitySignup {
private Connection conn = null;
private UserDTOEx user;
private ContactDTO contact;
private Integer languageId;
class Table {
String name;
String columns[];
String data[][];
String international_columns[][][];
boolean isMassive;
int maxRows;
int minRows;
Column columnsMetaData[];
int nextId;
int index;
}
class Column {
String dataType;
int intRange1;
int intRange2;
String dateRange1;
int dateRangeDays;
boolean isNull;
String constantValue;
float floatFactor;
}
/**
*
* @param root
* It uses only the user name and password
* @param contact
* @param languageId
*/
public EntitySignup(UserDTOEx root, ContactDTO contact,
Integer languageId) {
checkMainRole(root);
this.user = root;
this.contact = contact;
this.languageId = languageId;
}
public int process() throws Exception {
try {
JNDILookup jndi = JNDILookup.getFactory();
// the connection will be closed by the RowSet as soon as it
// finished executing the command
conn = jndi.lookUpDataSource().getConnection();
int newEntity = initData();
conn.close();
return newEntity;
} catch (Exception e) {
try {
conn.close();
} catch(Exception x) {}
throw new Exception(e);
}
}
void processTable(Table table)
throws Exception {
StringBuffer sql = new StringBuffer();
if (table.columns[0].equals("i_id")) {
initTable(table);
}
int rowIdx = table.nextId;
try {
System.out.println("Now processing " +
table.name + " [" + table.index + "]");
// generate the INSERT string with this table's columns
sql.append("insert into " + table.name + " (");
for (int columnsIdx = 0; columnsIdx < table.columns.length;) {
sql.append(table.columns[columnsIdx].substring(2));
columnsIdx++;
if (columnsIdx < table.columns.length) {
sql.append(",");
}
}
sql.append(") values (");
for (int columnsIdx = 0; columnsIdx < table.columns.length;) {
sql.append("?");
columnsIdx++;
if (columnsIdx < table.columns.length) {
sql.append(",");
}
}
sql.append(")");
System.out.println(sql.toString());
PreparedStatement stmt = conn.prepareStatement(sql.toString());
// for each row to be inserted, apply the data to the '?'
int rowCount = 0;
for (rowCount = 0; table.data != null && rowCount < table.data.length;
rowCount++, rowIdx++) {
// normal tables don't have data for the first column (the id)
// but map tables have data for every column
int idxDifference = 0; // this will be for a map table
for (int columnIdx = 0;
columnIdx < table.columns.length;
columnIdx++) {
String field;
if (table.columns[columnIdx].equals("i_id")) {
// this is the id, which is automatically generated
idxDifference = 1; // this is a normal table
stmt.setInt(columnIdx + 1, rowIdx);
} else {
String type = table.columns[columnIdx].substring(0, 2);
field = table.data[rowCount][columnIdx - idxDifference];
if (type.equals("d_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.DATE);
} else {
java.sql.Date dateField = new Date(Util.parseDate(field).getTime());
stmt.setDate(columnIdx + 1, dateField);
}
} else if (type.equals("s_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.VARCHAR);
} else {
stmt.setString(columnIdx + 1, field);
}
} else if (type.equals("i_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.INTEGER);
} else {
stmt.setInt(columnIdx + 1, Integer.valueOf(field));
}
} else if (type.equals("f_")) {
if (field == null) {
stmt.setNull(columnIdx + 1, Types.FLOAT);
} else {
stmt.setFloat(columnIdx + 1, Float.valueOf(field));
}
} else {
throw new Exception("Don't know the type " + type);
}
}
}
if (stmt.executeUpdate() != 1) {
throw new Exception(
"insert failed. Row "
+ rowIdx
+ " table "
+ table.name);
}
// now take care of the pseudo columns with international
// text
if (table.international_columns != null) {
insertPseudoColumns(
table.index,
rowIdx,
table.international_columns[rowCount]);
}
}
System.out.println("inserted " + rowCount + " rows");
stmt.close();
updateBettyTablesRows(table.index, rowIdx);
table.nextId = rowIdx;
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
throw new Exception("Error inserting table " + table.name +
" row " + (rowIdx + 1));
}
}
Table addTable(String name, String columns[],
String data[][], boolean massive) {
return addTable(name, columns, data, null, massive);
}
Table addTable(String name, String columns[], String data[][],
String intColumns[][][], boolean massive) {
return addTable(name, columns, data, intColumns, massive, null, 0, 0);
}
Table addTable(
String name,
String columns[],
String data[][],
String intColumns[][][],
boolean massive,
Column metaData[],
int min, int max) {
Table table;
table = new Table();
table.name = name;
table.columns = columns;
table.data = data;
table.international_columns = intColumns;
table.isMassive = massive;
table.columnsMetaData = metaData;
table.maxRows = max;
table.minRows = min;
return table;
}
void updateBettyTablesRows(int tableId, int totalRows)
throws SQLException {
PreparedStatement stmt =
conn.prepareStatement(
"update jbilling_table set next_id = ? " + " where id = ?");
stmt.setInt(1, totalRows);
stmt.setInt(2, tableId);
stmt.executeUpdate();
stmt.close();
}
void initTable(Table table)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"select next_id, id from jbilling_table " +
" where name = ?");
stmt.setString(1, table.name);
ResultSet res = stmt.executeQuery();
if (res.next()) {
table.nextId = res.getInt(1);
table.index = res.getInt(2);
stmt = conn.prepareStatement(
"select max(id) from " + table.name);
res = stmt.executeQuery();
res.next();
int maxId = res.getInt(1);
if (table.nextId <= maxId) {
table.nextId = maxId + 1;
}
} else {
throw new SQLException("No rows for table " + table.name);
}
res.close();
stmt.close();
}
void insertPseudoColumns(int tableId, int rowId, String data[][])
throws SQLException {
String sql = "insert into international_description "
+ "(table_id, foreign_id, psudo_column,language_id,content) "
+ "values (?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, tableId);
stmt.setInt(2, rowId);
for (int entry = 0; entry < data.length; entry++) {
// this would be the pseudo column
stmt.setString(3, data[entry][0]);
// and this the actual content
stmt.setString(5, data[entry][1]);
String language = null;
if (data[entry].length < 3 || data[entry][2] == null) {
language = "1"; //defaults to english
} else {
language = data[entry][2];
}
stmt.setInt(4, Integer.valueOf(language));
if (stmt.executeUpdate() != 1) {
throw new SQLException("Should've insterted one row into international_description");
}
}
stmt.close();
}
// idealy, this should be loaded from betty-schema.xml
int initData() throws Exception {
String now = Util.parseDate(Calendar.getInstance().getTime());
//ENTITY
// defaults currency to US dollars
String entityColumns[] =
{ "i_id", "i_external_id", "s_description", "d_create_datetime", "i_language_id", "i_currency_id" };
String entityData[][] = {
{ null, contact.getOrganizationName(), now, languageId.toString(), "1" },
};
Table table = addTable(Constants.TABLE_ENTITY, entityColumns,
entityData, false);
processTable(table);
int newEntityId = table.nextId - 1;
//BASE_USER
String userColumns[] = {
"i_id",
"i_entity_id",
"s_user_name",
"s_password",
"i_deleted",
"i_status_id",
"i_currency_id",
"d_create_datetime",
"d_last_status_change",
"i_language_id"
};
String userData[][] = {
{ String.valueOf(newEntityId), user.getUserName(),
getDBPassword(user), "0", "1", "1", now, null,
languageId.toString() }, //1
};
table = addTable(Constants.TABLE_BASE_USER, userColumns, userData, false);
processTable(table);
int rootUserId = table.nextId - 1;
//USER_ROLE_MAP
String userRoleColumns[] =
{
"i_user_id",
"i_role_id",
};
String userRoleData[][] = {
{ String.valueOf(rootUserId), "2"},
};
table = addTable(Constants.TABLE_USER_ROLE_MAP,
userRoleColumns, userRoleData, false);
processTable(table);
//CONTACT_TYPE
String contactType[] = { "i_id", "i_entity_id", "i_is_primary" };
String contactTypeData[][] = new String[1][2];
String contactTypeIntColumns[][][] = new String [1][1][2];
contactTypeData[0][0] = String.valueOf(newEntityId);
contactTypeData[0][1] = "1";
contactTypeIntColumns[0][0][0] = "description";
contactTypeIntColumns[0][0][1] = "Primary";
table = addTable(Constants.TABLE_CONTACT_TYPE, contactType, contactTypeData,
contactTypeIntColumns, false);
processTable(table);
int pContactType = table.nextId - 1;
//CONTACT
String contactColumns[] = {
"i_id",
"s_ORGANIZATION_NAME",
"s_STREET_ADDRES1",
"s_STREET_ADDRES2",
"s_CITY",
"s_STATE_PROVINCE",
"s_POSTAL_CODE",
"s_COUNTRY_CODE",
"s_LAST_NAME",
"s_FIRST_NAME",
"s_PERSON_INITIAL",
"s_PERSON_TITLE",
"i_PHONE_COUNTRY_CODE",
"i_PHONE_AREA_CODE",
"s_PHONE_PHONE_NUMBER",
"i_FAX_COUNTRY_CODE",
"i_FAX_AREA_CODE",
"s_FAX_PHONE_NUMBER",
"s_EMAIL",
"d_CREATE_DATETIME",
"i_deleted",
"i_user_id"
};
String contactData[][] = {
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
null,
null,
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
null
},
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getLastName(),
contact.getFirstName(),
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
String.valueOf(rootUserId)
},
};
table = addTable(Constants.TABLE_CONTACT, contactColumns, contactData, false);
processTable(table);
int contactId = table.nextId - 2;
//CONTACT_MAP
String contactMapColumns[] =
{ "i_id", "i_contact_id", "i_type_id", "i_table_id", "i_foreign_id" };
String contactMapData[][] = {
{ String.valueOf(contactId), "1", "5", String.valueOf(newEntityId) }, // the contact for the entity
{ String.valueOf(contactId + 1), String.valueOf(pContactType), "10", String.valueOf(rootUserId) },
};
table = addTable(Constants.TABLE_CONTACT_MAP, contactMapColumns, contactMapData, false);
processTable(table);
//ORDER_PERIODS
// puts only monthly now
String orderPeriod[] = { "i_id", "i_entity_id", "i_value", "i_unit_id" };
String orderPeriodData[][] = new String[1][3];
String orderPeriodIntColumns[][][] = new String [1][1][2];
orderPeriodData[0][0] = String.valueOf(newEntityId);
orderPeriodData[0][1] = "1";
orderPeriodData[0][2] = "1"; // month
orderPeriodIntColumns[0][0][0] = "description";
orderPeriodIntColumns[0][0][1] = "Monthly";
table = addTable(Constants.TABLE_ORDER_PERIOD, orderPeriod, orderPeriodData,
orderPeriodIntColumns, false);
processTable(table);
//PLUGGABLE_TASK
String pluggableTaskColumns[] =
{ "i_id", "i_entity_id", "i_type_id", "i_processing_order" };
String pluggableTaskData[][] =
{
{ String.valueOf(newEntityId), "21","1" }, // Fake payment processor
{ String.valueOf(newEntityId), "1", "1" }, // BasicLineTotalTask
{ String.valueOf(newEntityId), "3", "1" }, // CalculateDueDate
{ String.valueOf(newEntityId), "4", "2" }, // BasicCompositionTask
{ String.valueOf(newEntityId), "5", "1" }, // BasicOrderFilterTask
{ String.valueOf(newEntityId), "6", "1" }, // BasicInvoiceFilterTask
{ String.valueOf(newEntityId), "7", "1" }, // BasicOrderPeriodTask
{ String.valueOf(newEntityId), "9", "1" }, // BasicEmailNotificationTask
{ String.valueOf(newEntityId), "10","1" }, // BasicPaymentInfoTask cc info fetcher
{ String.valueOf(newEntityId), "12","2" }, // Paper invoice (for download PDF).
{ String.valueOf(newEntityId), "23","1" }, // Subscriber status manager
{ String.valueOf(newEntityId), "25","1" }, // Async payment processing (no parameters)
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK, pluggableTaskColumns, pluggableTaskData, false);
processTable(table);
int lastCommonPT = table.nextId - 1;
updateBettyTablesRows(table.index, table.nextId);
// the parameters of these tasks
//PLUGGABLE_TASK_PARAMETER
String pluggableTaskParameterColumns[] =
{
"i_id",
"i_task_id",
"s_name",
"i_int_value",
"s_str_value",
"f_float_value"
};
// paper invoice
String pluggableTaskParameterData[][] = {
- { String.valueOf(lastCommonPT - 1), "design", null, "simple_invoice_b2b", null},
+ { String.valueOf(lastCommonPT - 2), "design", null, "simple_invoice_b2b", null},
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK_PARAMETER, pluggableTaskParameterColumns,
pluggableTaskParameterData, false);
processTable(table);
// fake payment processor
addTaskParameter(table,lastCommonPT - 11, "all", null, "yes", null);
// email parameters. They are all optional
- addTaskParameter(table, lastCommonPT - 3, "smtp_server", null,
+ addTaskParameter(table, lastCommonPT - 4, "smtp_server", null,
null, null);
- addTaskParameter(table, lastCommonPT - 3, "from", null,
+ addTaskParameter(table, lastCommonPT - 4, "from", null,
contact.getEmail(), null);
- addTaskParameter(table, lastCommonPT - 3, "username", null,
+ addTaskParameter(table, lastCommonPT - 4, "username", null,
null, null);
- addTaskParameter(table, lastCommonPT - 3, "password", null,
+ addTaskParameter(table, lastCommonPT - 4, "password", null,
null, null);
- addTaskParameter(table, lastCommonPT - 3, "port", null,
+ addTaskParameter(table, lastCommonPT - 4, "port", null,
null, null);
- addTaskParameter(table, lastCommonPT - 3, "reply_to", null,
+ addTaskParameter(table, lastCommonPT - 4, "reply_to", null,
null, null);
- addTaskParameter(table, lastCommonPT - 3, "bcc_to", null,
+ addTaskParameter(table, lastCommonPT - 4, "bcc_to", null,
null, null);
- addTaskParameter(table, lastCommonPT - 3, "from_name", null,
+ addTaskParameter(table, lastCommonPT - 4, "from_name", null,
contact.getOrganizationName(), null);
updateBettyTablesRows(table.index, table.nextId);
// PAYMENT METHODS
//ENTITY_PAYMENT_METHOD_MAP
String entityPaymentMethodMapColumns[] =
{
"i_entity_id",
"i_payment_method_id",
};
String entityPaymentMethodMapData[][] = new String[3][2];
entityPaymentMethodMapData[0][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[0][1] = "1"; // cheque
entityPaymentMethodMapData[1][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[1][1] = "2"; // visa
entityPaymentMethodMapData[2][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[2][1] = "3"; // mc
table = addTable(Constants.TABLE_ENTITY_PAYMENT_METHOD_MAP,
entityPaymentMethodMapColumns,
entityPaymentMethodMapData, false);
processTable(table);
//PREFERENCE
String preferenceColumns[] =
{
"i_id",
"i_type_id",
"i_table_id",
"i_foreign_id",
"i_int_value",
"s_str_value",
"f_float_value"
};
// the table_id = 5, foregin_id = 1, means entity = 1
String preferenceData[][] = {
{"1", "5", String.valueOf(newEntityId), "0", null, null }, // no automatic processing by default
{"2", "5", String.valueOf(newEntityId), null, "/billing/css/jbilling.css", null },
{"3", "5", String.valueOf(newEntityId), null, "/billing/graphics/jbilling.jpg", null },
{"4", "5", String.valueOf(newEntityId), "5", null, null }, // grace period
{"5", "5", String.valueOf(newEntityId), null, null, "10" },
{"6", "5", String.valueOf(newEntityId), null, null, "0" },
{"7", "5", String.valueOf(newEntityId), "0", null, null },
{"8", "5", String.valueOf(newEntityId), "1", null, null },
{"9", "5", String.valueOf(newEntityId), "1", null, null },
{"10","5", String.valueOf(newEntityId), "0", null, null },
{"11","5", String.valueOf(newEntityId), String.valueOf(rootUserId), null, null },
{"12","5", String.valueOf(newEntityId), "1", null, null },
{"13","5", String.valueOf(newEntityId), "1", null, null },
{"14","5", String.valueOf(newEntityId), "0", null, null },
};
table = addTable(Constants.TABLE_PREFERENCE, preferenceColumns,
preferenceData, false);
processTable(table);
//REPORT_ENTITY_MAP
String reportEntityColumns[] =
{
"i_entity_id",
"i_report_id",
};
String reportEntityData[][] = {
{String.valueOf(newEntityId),"1"},
{String.valueOf(newEntityId),"2"},
{String.valueOf(newEntityId),"3"},
{String.valueOf(newEntityId),"4"},
{String.valueOf(newEntityId),"5"},
{String.valueOf(newEntityId),"6"},
{String.valueOf(newEntityId),"7"},
{String.valueOf(newEntityId),"8"},
{String.valueOf(newEntityId),"9"},
{String.valueOf(newEntityId),"10"},
{String.valueOf(newEntityId),"11"},
{String.valueOf(newEntityId),"12"},
{String.valueOf(newEntityId),"13"},
{String.valueOf(newEntityId),"14"},
{String.valueOf(newEntityId),"15"},
{String.valueOf(newEntityId),"16"},
{String.valueOf(newEntityId),"17"},
{String.valueOf(newEntityId),"18"},
{String.valueOf(newEntityId),"20"},
{String.valueOf(newEntityId),"22"},
};
table = addTable(Constants.TABLE_REPORT_ENTITY_MAP,
reportEntityColumns,
reportEntityData, false);
processTable(table);
//AGEING_ENTITY_STEP
String ageingEntityStepColumns[] =
{"i_id", "i_entity_id", "i_status_id", "i_days"};
String ageingEntityStepMessageData[][] = {
{String.valueOf(newEntityId), "1", "0"}, // active (for the welcome message)
};
String ageingEntityStepIntColumns[][][] =
{
{ { "welcome_message", "<div> <br/> <p style='font-size:19px; font-weight: bold;'>Welcome to " +
contact.getOrganizationName() + " Billing!</p> <br/> <p style='font-size:14px; text-align=left; padding-left: 15;'>From here, you can review your latest invoice and get it paid instantly. You can also view all your previous invoices and payments, and set up the system for automatic payment with your credit card.</p> <p style='font-size:14px; text-align=left; padding-left: 15;'>What would you like to do today? </p> <ul style='font-size:13px; text-align=left; padding-left: 25;'> <li >To submit a credit card payment, follow the link on the left bar.</li> <li >To view a list of your invoices, click on the �Invoices� menu option. The first invoice on the list is your latest invoice. Click on it to see its details.</li> <li>To view a list of your payments, click on the �Payments� menu option. The first payment on the list is your latest payment. Click on it to see its details.</li> <li>To provide a credit card to enable automatic payment, click on the menu option 'Account', and then on 'Edit Credit Card'.</li> </ul> </div>" }, }, // act
};
table = addTable(Constants.TABLE_AGEING_ENTITY_STEP,
ageingEntityStepColumns,
ageingEntityStepMessageData,
ageingEntityStepIntColumns, false);
processTable(table);
//BILLING_PROCESS_CONFIGURATION
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
String inAMonth = Util.parseDate(cal.getTime());
String billingProcessConfigurationColumns[] =
{
"i_id",
"i_entity_id",
"d_next_run_date",
"i_generate_report",
"i_retries",
"i_days_for_retry",
"i_days_for_report",
"i_review_status",
"i_period_unit_id",
"i_period_value",
"i_due_date_unit_id",
"i_due_date_value",
"i_only_recurring",
"i_invoice_date_process",
"i_auto_payment"
};
String billingProcessConfigurationData[][] = {
{ String.valueOf(newEntityId), inAMonth,
"1", "0", "1", "3", "1", "2", "1", "1", "1", "1", "0", "0" },
};
table = addTable(Constants.TABLE_BILLING_PROCESS_CONFIGURATION,
billingProcessConfigurationColumns,
billingProcessConfigurationData, false);
processTable(table);
// CURRENCY_ENTITY_MAP
String currencyEntityMapColumns[] =
{ "i_entity_id", "i_currency_id", };
String currencyEntityMapData[][] = {
{ String.valueOf(newEntityId), "1", },
};
table = addTable(Constants.TABLE_CURRENCY_ENTITY_MAP, currencyEntityMapColumns,
currencyEntityMapData, false);
processTable(table);
//NOTIFICATION_MESSAGE
String messageColumns[] = {
"i_id",
"i_type_id",
"i_entity_id",
"i_language_id",
};
// we provide at least those for english
String messageData[][] = {
{ "1", String.valueOf(newEntityId), "1"}, // invoice email
{ "2", String.valueOf(newEntityId), "1"}, // user reactivatesd
{ "3", String.valueOf(newEntityId), "1"}, // user overdue
{ "13", String.valueOf(newEntityId), "1"}, // order expiring
{ "16", String.valueOf(newEntityId), "1"}, // payment ok
{ "17", String.valueOf(newEntityId), "1"}, // payment failed
{ "18", String.valueOf(newEntityId), "1"}, // invoice reminder
{ "19", String.valueOf(newEntityId), "1"}, // credit card expi
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE, messageColumns,
messageData, false);
processTable(table);
int messageId = table.nextId - 8;
//NOTIFICATION_MESSAGE_SECTION
String sectionColumns[] = {
"i_id",
"i_message_id",
"i_section",
};
String sectionData[][] = {
{ String.valueOf(messageId), "1"},
{ String.valueOf(messageId), "2"},
{ String.valueOf(messageId + 1), "1"},
{ String.valueOf(messageId + 1), "2"},
{ String.valueOf(messageId + 2), "1"},
{ String.valueOf(messageId + 2), "2"},
{ String.valueOf(messageId + 3), "1"},
{ String.valueOf(messageId + 3), "2"},
{ String.valueOf(messageId + 4), "1"},
{ String.valueOf(messageId + 4), "2"},
{ String.valueOf(messageId + 5), "1"},
{ String.valueOf(messageId + 5), "2"},
{ String.valueOf(messageId + 6), "1"},
{ String.valueOf(messageId + 6), "2"},
{ String.valueOf(messageId + 7), "1"},
{ String.valueOf(messageId + 7), "2"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_SECTION,
sectionColumns, sectionData, false);
processTable(table);
int sectionId = table.nextId - 16;
//NOTIFICATION_MESSAGE_LINE
String lineColumns[] = {
"i_id",
"i_message_section_id",
"s_content",
};
String lineData[][] = {
{ String.valueOf(sectionId), "Billing Statement from |company_name|"},
{ String.valueOf(sectionId + 1), "Dear |first_name| |last_name|,\n\n This is to notify you that your latest invoice (number |number|) is now available. The total amount due is: |total|. You can view it by login in to:\n\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n \n After logging in, please click on the menu option �List�, to see all your invoices. You can also see your payment history, your current purchase orders, as well as update your payment information and submit online payments.\n\n\nThank you for choosing |company_name|, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 2), "You account is now up to date"},
{ String.valueOf(sectionId + 3), "Dear |first_name| |last_name|,\n\n This email is to notify you that we have received your latest payment and your account no longer has an overdue balance.\n\n Thank you for keeping your account up to date,\n\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 4), "Overdue Balance"},
{ String.valueOf(sectionId + 5), "Dear |first_name| |last_name|,\n\nOur records show that you have an overdue balance on your account. Please submit a payment as soon as possible.\n\nBest regards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 6), "Your service from |company_name| is about to expire"},
{ String.valueOf(sectionId + 7), "Dear |first_name| |last_name|,\n\nYour service with us will expire on |period_end|. Please make sure to contact customer service for a renewal.\n\nRegards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 8), "Thank you for your payment"},
{ String.valueOf(sectionId + 9), "Dear |first_name| |last_name|\n\n We have received your payment made with |method| for a total of |total|.\n\n Thank you, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 10), "Payment failed"},
{ String.valueOf(sectionId + 11), "Dear |first_name| |last_name|\n\n A payment with |method| was attempted for a total of |total|, but it has been rejected by the payment processor.\nYou can update your payment information and submit an online payment by login into :\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n\nThank you,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 12), "Invoice reminder"},
{ String.valueOf(sectionId + 13), "Dear |first_name| |last_name|\n\n This is a reminder that the invoice number |number| remains unpaid. It was sent to you on |date|, and its total is |total|. Although you still have |days| days to pay it (its due date is |dueDate|), we would greatly appreciate if you can pay it at your earliest convenience.\n\nYours truly,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 14), "It is time to update your credit card"},
{ String.valueOf(sectionId + 15), "Dear |first_name| |last_name|,\n\nWe want to remind you that the credit card that we have in our records for your account is about to expire. Its expiration date is |expiry_date|.\n\nUpdating your credit card is easy. Just login into " + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|. using your user name: |username| and password: |password|. After logging in, click on 'Account' and then 'Edit Credit Card'. \nThank you for keeping your account up to date.\n\nBilling Department\n|company_name|"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_LINE,
lineColumns, lineData, false);
processTable(table);
//ENTITY_DELIVERY_METHOD_MAP
String methodsColumns[] = {
"i_entity_id",
"i_method_id",
};
String methodsData[][] = {
{ String.valueOf(newEntityId), "1"},
{ String.valueOf(newEntityId), "2"},
{ String.valueOf(newEntityId), "3"},
};
table = addTable(Constants.TABLE_ENTITY_DELIVERY_METHOD_MAP,
methodsColumns, methodsData, false);
processTable(table);
return newEntityId;
}
void addTaskParameter(Table ptTable, int taskId,
String desc, Integer intP, String strP, Float floP)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"insert into pluggable_task_parameter " +
"(id, task_id, name, int_value, str_value, float_value)" +
" values(?, ?, ?, ?, ?, ?)");
stmt.setInt(1, ptTable.nextId);
stmt.setInt(2, taskId);
stmt.setString(3, desc);
if (intP != null) {
stmt.setInt(4, intP.intValue());
} else {
stmt.setNull(4, Types.INTEGER);
}
stmt.setString(5, strP);
if (floP != null) {
stmt.setFloat(6, floP.floatValue());
} else {
stmt.setNull(6, Types.FLOAT);
}
stmt.executeUpdate();
stmt.close();
ptTable.nextId++;
}
void addTask(Table ptTable, int entityId, int type, int position)
throws SQLException {
PreparedStatement stmt = conn.prepareStatement(
"insert into pluggable_task (id, entity_id, type_id, processing_order)" +
" values(?, ?, ?, ?)");
stmt.setInt(1, ptTable.nextId);
stmt.setInt(2, entityId);
stmt.setInt(3, type);
stmt.setInt(4, position);
stmt.executeUpdate();
stmt.close();
ptTable.nextId++;
}
private static void checkMainRole(UserDTOEx root){
if (CommonConstants.TYPE_ROOT.equals(root.getMainRoleId())){
Logger.getLogger(EntitySignup.class).warn("Attention: Root user passed with roleId: " + root.getMainRoleId());
}
root.setMainRoleId(CommonConstants.TYPE_ROOT);
}
private static String getDBPassword(UserDTOEx root){
checkMainRole(root);
JBCrypto crypto = JBCrypto.getPasswordCrypto(root.getMainRoleId());
return crypto.encrypt(root.getPassword());
}
}
| false | true | int initData() throws Exception {
String now = Util.parseDate(Calendar.getInstance().getTime());
//ENTITY
// defaults currency to US dollars
String entityColumns[] =
{ "i_id", "i_external_id", "s_description", "d_create_datetime", "i_language_id", "i_currency_id" };
String entityData[][] = {
{ null, contact.getOrganizationName(), now, languageId.toString(), "1" },
};
Table table = addTable(Constants.TABLE_ENTITY, entityColumns,
entityData, false);
processTable(table);
int newEntityId = table.nextId - 1;
//BASE_USER
String userColumns[] = {
"i_id",
"i_entity_id",
"s_user_name",
"s_password",
"i_deleted",
"i_status_id",
"i_currency_id",
"d_create_datetime",
"d_last_status_change",
"i_language_id"
};
String userData[][] = {
{ String.valueOf(newEntityId), user.getUserName(),
getDBPassword(user), "0", "1", "1", now, null,
languageId.toString() }, //1
};
table = addTable(Constants.TABLE_BASE_USER, userColumns, userData, false);
processTable(table);
int rootUserId = table.nextId - 1;
//USER_ROLE_MAP
String userRoleColumns[] =
{
"i_user_id",
"i_role_id",
};
String userRoleData[][] = {
{ String.valueOf(rootUserId), "2"},
};
table = addTable(Constants.TABLE_USER_ROLE_MAP,
userRoleColumns, userRoleData, false);
processTable(table);
//CONTACT_TYPE
String contactType[] = { "i_id", "i_entity_id", "i_is_primary" };
String contactTypeData[][] = new String[1][2];
String contactTypeIntColumns[][][] = new String [1][1][2];
contactTypeData[0][0] = String.valueOf(newEntityId);
contactTypeData[0][1] = "1";
contactTypeIntColumns[0][0][0] = "description";
contactTypeIntColumns[0][0][1] = "Primary";
table = addTable(Constants.TABLE_CONTACT_TYPE, contactType, contactTypeData,
contactTypeIntColumns, false);
processTable(table);
int pContactType = table.nextId - 1;
//CONTACT
String contactColumns[] = {
"i_id",
"s_ORGANIZATION_NAME",
"s_STREET_ADDRES1",
"s_STREET_ADDRES2",
"s_CITY",
"s_STATE_PROVINCE",
"s_POSTAL_CODE",
"s_COUNTRY_CODE",
"s_LAST_NAME",
"s_FIRST_NAME",
"s_PERSON_INITIAL",
"s_PERSON_TITLE",
"i_PHONE_COUNTRY_CODE",
"i_PHONE_AREA_CODE",
"s_PHONE_PHONE_NUMBER",
"i_FAX_COUNTRY_CODE",
"i_FAX_AREA_CODE",
"s_FAX_PHONE_NUMBER",
"s_EMAIL",
"d_CREATE_DATETIME",
"i_deleted",
"i_user_id"
};
String contactData[][] = {
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
null,
null,
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
null
},
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getLastName(),
contact.getFirstName(),
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
String.valueOf(rootUserId)
},
};
table = addTable(Constants.TABLE_CONTACT, contactColumns, contactData, false);
processTable(table);
int contactId = table.nextId - 2;
//CONTACT_MAP
String contactMapColumns[] =
{ "i_id", "i_contact_id", "i_type_id", "i_table_id", "i_foreign_id" };
String contactMapData[][] = {
{ String.valueOf(contactId), "1", "5", String.valueOf(newEntityId) }, // the contact for the entity
{ String.valueOf(contactId + 1), String.valueOf(pContactType), "10", String.valueOf(rootUserId) },
};
table = addTable(Constants.TABLE_CONTACT_MAP, contactMapColumns, contactMapData, false);
processTable(table);
//ORDER_PERIODS
// puts only monthly now
String orderPeriod[] = { "i_id", "i_entity_id", "i_value", "i_unit_id" };
String orderPeriodData[][] = new String[1][3];
String orderPeriodIntColumns[][][] = new String [1][1][2];
orderPeriodData[0][0] = String.valueOf(newEntityId);
orderPeriodData[0][1] = "1";
orderPeriodData[0][2] = "1"; // month
orderPeriodIntColumns[0][0][0] = "description";
orderPeriodIntColumns[0][0][1] = "Monthly";
table = addTable(Constants.TABLE_ORDER_PERIOD, orderPeriod, orderPeriodData,
orderPeriodIntColumns, false);
processTable(table);
//PLUGGABLE_TASK
String pluggableTaskColumns[] =
{ "i_id", "i_entity_id", "i_type_id", "i_processing_order" };
String pluggableTaskData[][] =
{
{ String.valueOf(newEntityId), "21","1" }, // Fake payment processor
{ String.valueOf(newEntityId), "1", "1" }, // BasicLineTotalTask
{ String.valueOf(newEntityId), "3", "1" }, // CalculateDueDate
{ String.valueOf(newEntityId), "4", "2" }, // BasicCompositionTask
{ String.valueOf(newEntityId), "5", "1" }, // BasicOrderFilterTask
{ String.valueOf(newEntityId), "6", "1" }, // BasicInvoiceFilterTask
{ String.valueOf(newEntityId), "7", "1" }, // BasicOrderPeriodTask
{ String.valueOf(newEntityId), "9", "1" }, // BasicEmailNotificationTask
{ String.valueOf(newEntityId), "10","1" }, // BasicPaymentInfoTask cc info fetcher
{ String.valueOf(newEntityId), "12","2" }, // Paper invoice (for download PDF).
{ String.valueOf(newEntityId), "23","1" }, // Subscriber status manager
{ String.valueOf(newEntityId), "25","1" }, // Async payment processing (no parameters)
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK, pluggableTaskColumns, pluggableTaskData, false);
processTable(table);
int lastCommonPT = table.nextId - 1;
updateBettyTablesRows(table.index, table.nextId);
// the parameters of these tasks
//PLUGGABLE_TASK_PARAMETER
String pluggableTaskParameterColumns[] =
{
"i_id",
"i_task_id",
"s_name",
"i_int_value",
"s_str_value",
"f_float_value"
};
// paper invoice
String pluggableTaskParameterData[][] = {
{ String.valueOf(lastCommonPT - 1), "design", null, "simple_invoice_b2b", null},
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK_PARAMETER, pluggableTaskParameterColumns,
pluggableTaskParameterData, false);
processTable(table);
// fake payment processor
addTaskParameter(table,lastCommonPT - 11, "all", null, "yes", null);
// email parameters. They are all optional
addTaskParameter(table, lastCommonPT - 3, "smtp_server", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "from", null,
contact.getEmail(), null);
addTaskParameter(table, lastCommonPT - 3, "username", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "password", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "port", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "reply_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "bcc_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 3, "from_name", null,
contact.getOrganizationName(), null);
updateBettyTablesRows(table.index, table.nextId);
// PAYMENT METHODS
//ENTITY_PAYMENT_METHOD_MAP
String entityPaymentMethodMapColumns[] =
{
"i_entity_id",
"i_payment_method_id",
};
String entityPaymentMethodMapData[][] = new String[3][2];
entityPaymentMethodMapData[0][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[0][1] = "1"; // cheque
entityPaymentMethodMapData[1][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[1][1] = "2"; // visa
entityPaymentMethodMapData[2][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[2][1] = "3"; // mc
table = addTable(Constants.TABLE_ENTITY_PAYMENT_METHOD_MAP,
entityPaymentMethodMapColumns,
entityPaymentMethodMapData, false);
processTable(table);
//PREFERENCE
String preferenceColumns[] =
{
"i_id",
"i_type_id",
"i_table_id",
"i_foreign_id",
"i_int_value",
"s_str_value",
"f_float_value"
};
// the table_id = 5, foregin_id = 1, means entity = 1
String preferenceData[][] = {
{"1", "5", String.valueOf(newEntityId), "0", null, null }, // no automatic processing by default
{"2", "5", String.valueOf(newEntityId), null, "/billing/css/jbilling.css", null },
{"3", "5", String.valueOf(newEntityId), null, "/billing/graphics/jbilling.jpg", null },
{"4", "5", String.valueOf(newEntityId), "5", null, null }, // grace period
{"5", "5", String.valueOf(newEntityId), null, null, "10" },
{"6", "5", String.valueOf(newEntityId), null, null, "0" },
{"7", "5", String.valueOf(newEntityId), "0", null, null },
{"8", "5", String.valueOf(newEntityId), "1", null, null },
{"9", "5", String.valueOf(newEntityId), "1", null, null },
{"10","5", String.valueOf(newEntityId), "0", null, null },
{"11","5", String.valueOf(newEntityId), String.valueOf(rootUserId), null, null },
{"12","5", String.valueOf(newEntityId), "1", null, null },
{"13","5", String.valueOf(newEntityId), "1", null, null },
{"14","5", String.valueOf(newEntityId), "0", null, null },
};
table = addTable(Constants.TABLE_PREFERENCE, preferenceColumns,
preferenceData, false);
processTable(table);
//REPORT_ENTITY_MAP
String reportEntityColumns[] =
{
"i_entity_id",
"i_report_id",
};
String reportEntityData[][] = {
{String.valueOf(newEntityId),"1"},
{String.valueOf(newEntityId),"2"},
{String.valueOf(newEntityId),"3"},
{String.valueOf(newEntityId),"4"},
{String.valueOf(newEntityId),"5"},
{String.valueOf(newEntityId),"6"},
{String.valueOf(newEntityId),"7"},
{String.valueOf(newEntityId),"8"},
{String.valueOf(newEntityId),"9"},
{String.valueOf(newEntityId),"10"},
{String.valueOf(newEntityId),"11"},
{String.valueOf(newEntityId),"12"},
{String.valueOf(newEntityId),"13"},
{String.valueOf(newEntityId),"14"},
{String.valueOf(newEntityId),"15"},
{String.valueOf(newEntityId),"16"},
{String.valueOf(newEntityId),"17"},
{String.valueOf(newEntityId),"18"},
{String.valueOf(newEntityId),"20"},
{String.valueOf(newEntityId),"22"},
};
table = addTable(Constants.TABLE_REPORT_ENTITY_MAP,
reportEntityColumns,
reportEntityData, false);
processTable(table);
//AGEING_ENTITY_STEP
String ageingEntityStepColumns[] =
{"i_id", "i_entity_id", "i_status_id", "i_days"};
String ageingEntityStepMessageData[][] = {
{String.valueOf(newEntityId), "1", "0"}, // active (for the welcome message)
};
String ageingEntityStepIntColumns[][][] =
{
{ { "welcome_message", "<div> <br/> <p style='font-size:19px; font-weight: bold;'>Welcome to " +
contact.getOrganizationName() + " Billing!</p> <br/> <p style='font-size:14px; text-align=left; padding-left: 15;'>From here, you can review your latest invoice and get it paid instantly. You can also view all your previous invoices and payments, and set up the system for automatic payment with your credit card.</p> <p style='font-size:14px; text-align=left; padding-left: 15;'>What would you like to do today? </p> <ul style='font-size:13px; text-align=left; padding-left: 25;'> <li >To submit a credit card payment, follow the link on the left bar.</li> <li >To view a list of your invoices, click on the �Invoices� menu option. The first invoice on the list is your latest invoice. Click on it to see its details.</li> <li>To view a list of your payments, click on the �Payments� menu option. The first payment on the list is your latest payment. Click on it to see its details.</li> <li>To provide a credit card to enable automatic payment, click on the menu option 'Account', and then on 'Edit Credit Card'.</li> </ul> </div>" }, }, // act
};
table = addTable(Constants.TABLE_AGEING_ENTITY_STEP,
ageingEntityStepColumns,
ageingEntityStepMessageData,
ageingEntityStepIntColumns, false);
processTable(table);
//BILLING_PROCESS_CONFIGURATION
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
String inAMonth = Util.parseDate(cal.getTime());
String billingProcessConfigurationColumns[] =
{
"i_id",
"i_entity_id",
"d_next_run_date",
"i_generate_report",
"i_retries",
"i_days_for_retry",
"i_days_for_report",
"i_review_status",
"i_period_unit_id",
"i_period_value",
"i_due_date_unit_id",
"i_due_date_value",
"i_only_recurring",
"i_invoice_date_process",
"i_auto_payment"
};
String billingProcessConfigurationData[][] = {
{ String.valueOf(newEntityId), inAMonth,
"1", "0", "1", "3", "1", "2", "1", "1", "1", "1", "0", "0" },
};
table = addTable(Constants.TABLE_BILLING_PROCESS_CONFIGURATION,
billingProcessConfigurationColumns,
billingProcessConfigurationData, false);
processTable(table);
// CURRENCY_ENTITY_MAP
String currencyEntityMapColumns[] =
{ "i_entity_id", "i_currency_id", };
String currencyEntityMapData[][] = {
{ String.valueOf(newEntityId), "1", },
};
table = addTable(Constants.TABLE_CURRENCY_ENTITY_MAP, currencyEntityMapColumns,
currencyEntityMapData, false);
processTable(table);
//NOTIFICATION_MESSAGE
String messageColumns[] = {
"i_id",
"i_type_id",
"i_entity_id",
"i_language_id",
};
// we provide at least those for english
String messageData[][] = {
{ "1", String.valueOf(newEntityId), "1"}, // invoice email
{ "2", String.valueOf(newEntityId), "1"}, // user reactivatesd
{ "3", String.valueOf(newEntityId), "1"}, // user overdue
{ "13", String.valueOf(newEntityId), "1"}, // order expiring
{ "16", String.valueOf(newEntityId), "1"}, // payment ok
{ "17", String.valueOf(newEntityId), "1"}, // payment failed
{ "18", String.valueOf(newEntityId), "1"}, // invoice reminder
{ "19", String.valueOf(newEntityId), "1"}, // credit card expi
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE, messageColumns,
messageData, false);
processTable(table);
int messageId = table.nextId - 8;
//NOTIFICATION_MESSAGE_SECTION
String sectionColumns[] = {
"i_id",
"i_message_id",
"i_section",
};
String sectionData[][] = {
{ String.valueOf(messageId), "1"},
{ String.valueOf(messageId), "2"},
{ String.valueOf(messageId + 1), "1"},
{ String.valueOf(messageId + 1), "2"},
{ String.valueOf(messageId + 2), "1"},
{ String.valueOf(messageId + 2), "2"},
{ String.valueOf(messageId + 3), "1"},
{ String.valueOf(messageId + 3), "2"},
{ String.valueOf(messageId + 4), "1"},
{ String.valueOf(messageId + 4), "2"},
{ String.valueOf(messageId + 5), "1"},
{ String.valueOf(messageId + 5), "2"},
{ String.valueOf(messageId + 6), "1"},
{ String.valueOf(messageId + 6), "2"},
{ String.valueOf(messageId + 7), "1"},
{ String.valueOf(messageId + 7), "2"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_SECTION,
sectionColumns, sectionData, false);
processTable(table);
int sectionId = table.nextId - 16;
//NOTIFICATION_MESSAGE_LINE
String lineColumns[] = {
"i_id",
"i_message_section_id",
"s_content",
};
String lineData[][] = {
{ String.valueOf(sectionId), "Billing Statement from |company_name|"},
{ String.valueOf(sectionId + 1), "Dear |first_name| |last_name|,\n\n This is to notify you that your latest invoice (number |number|) is now available. The total amount due is: |total|. You can view it by login in to:\n\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n \n After logging in, please click on the menu option �List�, to see all your invoices. You can also see your payment history, your current purchase orders, as well as update your payment information and submit online payments.\n\n\nThank you for choosing |company_name|, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 2), "You account is now up to date"},
{ String.valueOf(sectionId + 3), "Dear |first_name| |last_name|,\n\n This email is to notify you that we have received your latest payment and your account no longer has an overdue balance.\n\n Thank you for keeping your account up to date,\n\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 4), "Overdue Balance"},
{ String.valueOf(sectionId + 5), "Dear |first_name| |last_name|,\n\nOur records show that you have an overdue balance on your account. Please submit a payment as soon as possible.\n\nBest regards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 6), "Your service from |company_name| is about to expire"},
{ String.valueOf(sectionId + 7), "Dear |first_name| |last_name|,\n\nYour service with us will expire on |period_end|. Please make sure to contact customer service for a renewal.\n\nRegards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 8), "Thank you for your payment"},
{ String.valueOf(sectionId + 9), "Dear |first_name| |last_name|\n\n We have received your payment made with |method| for a total of |total|.\n\n Thank you, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 10), "Payment failed"},
{ String.valueOf(sectionId + 11), "Dear |first_name| |last_name|\n\n A payment with |method| was attempted for a total of |total|, but it has been rejected by the payment processor.\nYou can update your payment information and submit an online payment by login into :\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n\nThank you,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 12), "Invoice reminder"},
{ String.valueOf(sectionId + 13), "Dear |first_name| |last_name|\n\n This is a reminder that the invoice number |number| remains unpaid. It was sent to you on |date|, and its total is |total|. Although you still have |days| days to pay it (its due date is |dueDate|), we would greatly appreciate if you can pay it at your earliest convenience.\n\nYours truly,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 14), "It is time to update your credit card"},
{ String.valueOf(sectionId + 15), "Dear |first_name| |last_name|,\n\nWe want to remind you that the credit card that we have in our records for your account is about to expire. Its expiration date is |expiry_date|.\n\nUpdating your credit card is easy. Just login into " + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|. using your user name: |username| and password: |password|. After logging in, click on 'Account' and then 'Edit Credit Card'. \nThank you for keeping your account up to date.\n\nBilling Department\n|company_name|"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_LINE,
lineColumns, lineData, false);
processTable(table);
//ENTITY_DELIVERY_METHOD_MAP
String methodsColumns[] = {
"i_entity_id",
"i_method_id",
};
String methodsData[][] = {
{ String.valueOf(newEntityId), "1"},
{ String.valueOf(newEntityId), "2"},
{ String.valueOf(newEntityId), "3"},
};
table = addTable(Constants.TABLE_ENTITY_DELIVERY_METHOD_MAP,
methodsColumns, methodsData, false);
processTable(table);
return newEntityId;
}
| int initData() throws Exception {
String now = Util.parseDate(Calendar.getInstance().getTime());
//ENTITY
// defaults currency to US dollars
String entityColumns[] =
{ "i_id", "i_external_id", "s_description", "d_create_datetime", "i_language_id", "i_currency_id" };
String entityData[][] = {
{ null, contact.getOrganizationName(), now, languageId.toString(), "1" },
};
Table table = addTable(Constants.TABLE_ENTITY, entityColumns,
entityData, false);
processTable(table);
int newEntityId = table.nextId - 1;
//BASE_USER
String userColumns[] = {
"i_id",
"i_entity_id",
"s_user_name",
"s_password",
"i_deleted",
"i_status_id",
"i_currency_id",
"d_create_datetime",
"d_last_status_change",
"i_language_id"
};
String userData[][] = {
{ String.valueOf(newEntityId), user.getUserName(),
getDBPassword(user), "0", "1", "1", now, null,
languageId.toString() }, //1
};
table = addTable(Constants.TABLE_BASE_USER, userColumns, userData, false);
processTable(table);
int rootUserId = table.nextId - 1;
//USER_ROLE_MAP
String userRoleColumns[] =
{
"i_user_id",
"i_role_id",
};
String userRoleData[][] = {
{ String.valueOf(rootUserId), "2"},
};
table = addTable(Constants.TABLE_USER_ROLE_MAP,
userRoleColumns, userRoleData, false);
processTable(table);
//CONTACT_TYPE
String contactType[] = { "i_id", "i_entity_id", "i_is_primary" };
String contactTypeData[][] = new String[1][2];
String contactTypeIntColumns[][][] = new String [1][1][2];
contactTypeData[0][0] = String.valueOf(newEntityId);
contactTypeData[0][1] = "1";
contactTypeIntColumns[0][0][0] = "description";
contactTypeIntColumns[0][0][1] = "Primary";
table = addTable(Constants.TABLE_CONTACT_TYPE, contactType, contactTypeData,
contactTypeIntColumns, false);
processTable(table);
int pContactType = table.nextId - 1;
//CONTACT
String contactColumns[] = {
"i_id",
"s_ORGANIZATION_NAME",
"s_STREET_ADDRES1",
"s_STREET_ADDRES2",
"s_CITY",
"s_STATE_PROVINCE",
"s_POSTAL_CODE",
"s_COUNTRY_CODE",
"s_LAST_NAME",
"s_FIRST_NAME",
"s_PERSON_INITIAL",
"s_PERSON_TITLE",
"i_PHONE_COUNTRY_CODE",
"i_PHONE_AREA_CODE",
"s_PHONE_PHONE_NUMBER",
"i_FAX_COUNTRY_CODE",
"i_FAX_AREA_CODE",
"s_FAX_PHONE_NUMBER",
"s_EMAIL",
"d_CREATE_DATETIME",
"i_deleted",
"i_user_id"
};
String contactData[][] = {
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
null,
null,
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
null
},
{
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getLastName(),
contact.getFirstName(),
null,
null,
(contact.getPhoneCountryCode() == null) ? null :
contact.getPhoneCountryCode().toString(),
(contact.getPhoneAreaCode() == null) ? null :
contact.getPhoneAreaCode().toString(),
contact.getPhoneNumber(),
null, //fax
null,
null,
contact.getEmail(),
now,
"0",
String.valueOf(rootUserId)
},
};
table = addTable(Constants.TABLE_CONTACT, contactColumns, contactData, false);
processTable(table);
int contactId = table.nextId - 2;
//CONTACT_MAP
String contactMapColumns[] =
{ "i_id", "i_contact_id", "i_type_id", "i_table_id", "i_foreign_id" };
String contactMapData[][] = {
{ String.valueOf(contactId), "1", "5", String.valueOf(newEntityId) }, // the contact for the entity
{ String.valueOf(contactId + 1), String.valueOf(pContactType), "10", String.valueOf(rootUserId) },
};
table = addTable(Constants.TABLE_CONTACT_MAP, contactMapColumns, contactMapData, false);
processTable(table);
//ORDER_PERIODS
// puts only monthly now
String orderPeriod[] = { "i_id", "i_entity_id", "i_value", "i_unit_id" };
String orderPeriodData[][] = new String[1][3];
String orderPeriodIntColumns[][][] = new String [1][1][2];
orderPeriodData[0][0] = String.valueOf(newEntityId);
orderPeriodData[0][1] = "1";
orderPeriodData[0][2] = "1"; // month
orderPeriodIntColumns[0][0][0] = "description";
orderPeriodIntColumns[0][0][1] = "Monthly";
table = addTable(Constants.TABLE_ORDER_PERIOD, orderPeriod, orderPeriodData,
orderPeriodIntColumns, false);
processTable(table);
//PLUGGABLE_TASK
String pluggableTaskColumns[] =
{ "i_id", "i_entity_id", "i_type_id", "i_processing_order" };
String pluggableTaskData[][] =
{
{ String.valueOf(newEntityId), "21","1" }, // Fake payment processor
{ String.valueOf(newEntityId), "1", "1" }, // BasicLineTotalTask
{ String.valueOf(newEntityId), "3", "1" }, // CalculateDueDate
{ String.valueOf(newEntityId), "4", "2" }, // BasicCompositionTask
{ String.valueOf(newEntityId), "5", "1" }, // BasicOrderFilterTask
{ String.valueOf(newEntityId), "6", "1" }, // BasicInvoiceFilterTask
{ String.valueOf(newEntityId), "7", "1" }, // BasicOrderPeriodTask
{ String.valueOf(newEntityId), "9", "1" }, // BasicEmailNotificationTask
{ String.valueOf(newEntityId), "10","1" }, // BasicPaymentInfoTask cc info fetcher
{ String.valueOf(newEntityId), "12","2" }, // Paper invoice (for download PDF).
{ String.valueOf(newEntityId), "23","1" }, // Subscriber status manager
{ String.valueOf(newEntityId), "25","1" }, // Async payment processing (no parameters)
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK, pluggableTaskColumns, pluggableTaskData, false);
processTable(table);
int lastCommonPT = table.nextId - 1;
updateBettyTablesRows(table.index, table.nextId);
// the parameters of these tasks
//PLUGGABLE_TASK_PARAMETER
String pluggableTaskParameterColumns[] =
{
"i_id",
"i_task_id",
"s_name",
"i_int_value",
"s_str_value",
"f_float_value"
};
// paper invoice
String pluggableTaskParameterData[][] = {
{ String.valueOf(lastCommonPT - 2), "design", null, "simple_invoice_b2b", null},
};
table = addTable(Constants.TABLE_PLUGGABLE_TASK_PARAMETER, pluggableTaskParameterColumns,
pluggableTaskParameterData, false);
processTable(table);
// fake payment processor
addTaskParameter(table,lastCommonPT - 11, "all", null, "yes", null);
// email parameters. They are all optional
addTaskParameter(table, lastCommonPT - 4, "smtp_server", null,
null, null);
addTaskParameter(table, lastCommonPT - 4, "from", null,
contact.getEmail(), null);
addTaskParameter(table, lastCommonPT - 4, "username", null,
null, null);
addTaskParameter(table, lastCommonPT - 4, "password", null,
null, null);
addTaskParameter(table, lastCommonPT - 4, "port", null,
null, null);
addTaskParameter(table, lastCommonPT - 4, "reply_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 4, "bcc_to", null,
null, null);
addTaskParameter(table, lastCommonPT - 4, "from_name", null,
contact.getOrganizationName(), null);
updateBettyTablesRows(table.index, table.nextId);
// PAYMENT METHODS
//ENTITY_PAYMENT_METHOD_MAP
String entityPaymentMethodMapColumns[] =
{
"i_entity_id",
"i_payment_method_id",
};
String entityPaymentMethodMapData[][] = new String[3][2];
entityPaymentMethodMapData[0][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[0][1] = "1"; // cheque
entityPaymentMethodMapData[1][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[1][1] = "2"; // visa
entityPaymentMethodMapData[2][0] = String.valueOf(newEntityId);
entityPaymentMethodMapData[2][1] = "3"; // mc
table = addTable(Constants.TABLE_ENTITY_PAYMENT_METHOD_MAP,
entityPaymentMethodMapColumns,
entityPaymentMethodMapData, false);
processTable(table);
//PREFERENCE
String preferenceColumns[] =
{
"i_id",
"i_type_id",
"i_table_id",
"i_foreign_id",
"i_int_value",
"s_str_value",
"f_float_value"
};
// the table_id = 5, foregin_id = 1, means entity = 1
String preferenceData[][] = {
{"1", "5", String.valueOf(newEntityId), "0", null, null }, // no automatic processing by default
{"2", "5", String.valueOf(newEntityId), null, "/billing/css/jbilling.css", null },
{"3", "5", String.valueOf(newEntityId), null, "/billing/graphics/jbilling.jpg", null },
{"4", "5", String.valueOf(newEntityId), "5", null, null }, // grace period
{"5", "5", String.valueOf(newEntityId), null, null, "10" },
{"6", "5", String.valueOf(newEntityId), null, null, "0" },
{"7", "5", String.valueOf(newEntityId), "0", null, null },
{"8", "5", String.valueOf(newEntityId), "1", null, null },
{"9", "5", String.valueOf(newEntityId), "1", null, null },
{"10","5", String.valueOf(newEntityId), "0", null, null },
{"11","5", String.valueOf(newEntityId), String.valueOf(rootUserId), null, null },
{"12","5", String.valueOf(newEntityId), "1", null, null },
{"13","5", String.valueOf(newEntityId), "1", null, null },
{"14","5", String.valueOf(newEntityId), "0", null, null },
};
table = addTable(Constants.TABLE_PREFERENCE, preferenceColumns,
preferenceData, false);
processTable(table);
//REPORT_ENTITY_MAP
String reportEntityColumns[] =
{
"i_entity_id",
"i_report_id",
};
String reportEntityData[][] = {
{String.valueOf(newEntityId),"1"},
{String.valueOf(newEntityId),"2"},
{String.valueOf(newEntityId),"3"},
{String.valueOf(newEntityId),"4"},
{String.valueOf(newEntityId),"5"},
{String.valueOf(newEntityId),"6"},
{String.valueOf(newEntityId),"7"},
{String.valueOf(newEntityId),"8"},
{String.valueOf(newEntityId),"9"},
{String.valueOf(newEntityId),"10"},
{String.valueOf(newEntityId),"11"},
{String.valueOf(newEntityId),"12"},
{String.valueOf(newEntityId),"13"},
{String.valueOf(newEntityId),"14"},
{String.valueOf(newEntityId),"15"},
{String.valueOf(newEntityId),"16"},
{String.valueOf(newEntityId),"17"},
{String.valueOf(newEntityId),"18"},
{String.valueOf(newEntityId),"20"},
{String.valueOf(newEntityId),"22"},
};
table = addTable(Constants.TABLE_REPORT_ENTITY_MAP,
reportEntityColumns,
reportEntityData, false);
processTable(table);
//AGEING_ENTITY_STEP
String ageingEntityStepColumns[] =
{"i_id", "i_entity_id", "i_status_id", "i_days"};
String ageingEntityStepMessageData[][] = {
{String.valueOf(newEntityId), "1", "0"}, // active (for the welcome message)
};
String ageingEntityStepIntColumns[][][] =
{
{ { "welcome_message", "<div> <br/> <p style='font-size:19px; font-weight: bold;'>Welcome to " +
contact.getOrganizationName() + " Billing!</p> <br/> <p style='font-size:14px; text-align=left; padding-left: 15;'>From here, you can review your latest invoice and get it paid instantly. You can also view all your previous invoices and payments, and set up the system for automatic payment with your credit card.</p> <p style='font-size:14px; text-align=left; padding-left: 15;'>What would you like to do today? </p> <ul style='font-size:13px; text-align=left; padding-left: 25;'> <li >To submit a credit card payment, follow the link on the left bar.</li> <li >To view a list of your invoices, click on the �Invoices� menu option. The first invoice on the list is your latest invoice. Click on it to see its details.</li> <li>To view a list of your payments, click on the �Payments� menu option. The first payment on the list is your latest payment. Click on it to see its details.</li> <li>To provide a credit card to enable automatic payment, click on the menu option 'Account', and then on 'Edit Credit Card'.</li> </ul> </div>" }, }, // act
};
table = addTable(Constants.TABLE_AGEING_ENTITY_STEP,
ageingEntityStepColumns,
ageingEntityStepMessageData,
ageingEntityStepIntColumns, false);
processTable(table);
//BILLING_PROCESS_CONFIGURATION
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
String inAMonth = Util.parseDate(cal.getTime());
String billingProcessConfigurationColumns[] =
{
"i_id",
"i_entity_id",
"d_next_run_date",
"i_generate_report",
"i_retries",
"i_days_for_retry",
"i_days_for_report",
"i_review_status",
"i_period_unit_id",
"i_period_value",
"i_due_date_unit_id",
"i_due_date_value",
"i_only_recurring",
"i_invoice_date_process",
"i_auto_payment"
};
String billingProcessConfigurationData[][] = {
{ String.valueOf(newEntityId), inAMonth,
"1", "0", "1", "3", "1", "2", "1", "1", "1", "1", "0", "0" },
};
table = addTable(Constants.TABLE_BILLING_PROCESS_CONFIGURATION,
billingProcessConfigurationColumns,
billingProcessConfigurationData, false);
processTable(table);
// CURRENCY_ENTITY_MAP
String currencyEntityMapColumns[] =
{ "i_entity_id", "i_currency_id", };
String currencyEntityMapData[][] = {
{ String.valueOf(newEntityId), "1", },
};
table = addTable(Constants.TABLE_CURRENCY_ENTITY_MAP, currencyEntityMapColumns,
currencyEntityMapData, false);
processTable(table);
//NOTIFICATION_MESSAGE
String messageColumns[] = {
"i_id",
"i_type_id",
"i_entity_id",
"i_language_id",
};
// we provide at least those for english
String messageData[][] = {
{ "1", String.valueOf(newEntityId), "1"}, // invoice email
{ "2", String.valueOf(newEntityId), "1"}, // user reactivatesd
{ "3", String.valueOf(newEntityId), "1"}, // user overdue
{ "13", String.valueOf(newEntityId), "1"}, // order expiring
{ "16", String.valueOf(newEntityId), "1"}, // payment ok
{ "17", String.valueOf(newEntityId), "1"}, // payment failed
{ "18", String.valueOf(newEntityId), "1"}, // invoice reminder
{ "19", String.valueOf(newEntityId), "1"}, // credit card expi
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE, messageColumns,
messageData, false);
processTable(table);
int messageId = table.nextId - 8;
//NOTIFICATION_MESSAGE_SECTION
String sectionColumns[] = {
"i_id",
"i_message_id",
"i_section",
};
String sectionData[][] = {
{ String.valueOf(messageId), "1"},
{ String.valueOf(messageId), "2"},
{ String.valueOf(messageId + 1), "1"},
{ String.valueOf(messageId + 1), "2"},
{ String.valueOf(messageId + 2), "1"},
{ String.valueOf(messageId + 2), "2"},
{ String.valueOf(messageId + 3), "1"},
{ String.valueOf(messageId + 3), "2"},
{ String.valueOf(messageId + 4), "1"},
{ String.valueOf(messageId + 4), "2"},
{ String.valueOf(messageId + 5), "1"},
{ String.valueOf(messageId + 5), "2"},
{ String.valueOf(messageId + 6), "1"},
{ String.valueOf(messageId + 6), "2"},
{ String.valueOf(messageId + 7), "1"},
{ String.valueOf(messageId + 7), "2"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_SECTION,
sectionColumns, sectionData, false);
processTable(table);
int sectionId = table.nextId - 16;
//NOTIFICATION_MESSAGE_LINE
String lineColumns[] = {
"i_id",
"i_message_section_id",
"s_content",
};
String lineData[][] = {
{ String.valueOf(sectionId), "Billing Statement from |company_name|"},
{ String.valueOf(sectionId + 1), "Dear |first_name| |last_name|,\n\n This is to notify you that your latest invoice (number |number|) is now available. The total amount due is: |total|. You can view it by login in to:\n\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n \n After logging in, please click on the menu option �List�, to see all your invoices. You can also see your payment history, your current purchase orders, as well as update your payment information and submit online payments.\n\n\nThank you for choosing |company_name|, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 2), "You account is now up to date"},
{ String.valueOf(sectionId + 3), "Dear |first_name| |last_name|,\n\n This email is to notify you that we have received your latest payment and your account no longer has an overdue balance.\n\n Thank you for keeping your account up to date,\n\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 4), "Overdue Balance"},
{ String.valueOf(sectionId + 5), "Dear |first_name| |last_name|,\n\nOur records show that you have an overdue balance on your account. Please submit a payment as soon as possible.\n\nBest regards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 6), "Your service from |company_name| is about to expire"},
{ String.valueOf(sectionId + 7), "Dear |first_name| |last_name|,\n\nYour service with us will expire on |period_end|. Please make sure to contact customer service for a renewal.\n\nRegards,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 8), "Thank you for your payment"},
{ String.valueOf(sectionId + 9), "Dear |first_name| |last_name|\n\n We have received your payment made with |method| for a total of |total|.\n\n Thank you, we appreciate your business,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 10), "Payment failed"},
{ String.valueOf(sectionId + 11), "Dear |first_name| |last_name|\n\n A payment with |method| was attempted for a total of |total|, but it has been rejected by the payment processor.\nYou can update your payment information and submit an online payment by login into :\n" + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|\n\nFor security reasons, your statement is password protected.\nTo login in, you will need your user name: |username| and your account password: |password|\n\nThank you,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 12), "Invoice reminder"},
{ String.valueOf(sectionId + 13), "Dear |first_name| |last_name|\n\n This is a reminder that the invoice number |number| remains unpaid. It was sent to you on |date|, and its total is |total|. Although you still have |days| days to pay it (its due date is |dueDate|), we would greatly appreciate if you can pay it at your earliest convenience.\n\nYours truly,\n\nBilling Department\n|company_name|"},
{ String.valueOf(sectionId + 14), "It is time to update your credit card"},
{ String.valueOf(sectionId + 15), "Dear |first_name| |last_name|,\n\nWe want to remind you that the credit card that we have in our records for your account is about to expire. Its expiration date is |expiry_date|.\n\nUpdating your credit card is easy. Just login into " + Util.getSysProp("url") + "/billing/user/login.jsp?entityId=|company_id|. using your user name: |username| and password: |password|. After logging in, click on 'Account' and then 'Edit Credit Card'. \nThank you for keeping your account up to date.\n\nBilling Department\n|company_name|"},
};
table = addTable(Constants.TABLE_NOTIFICATION_MESSAGE_LINE,
lineColumns, lineData, false);
processTable(table);
//ENTITY_DELIVERY_METHOD_MAP
String methodsColumns[] = {
"i_entity_id",
"i_method_id",
};
String methodsData[][] = {
{ String.valueOf(newEntityId), "1"},
{ String.valueOf(newEntityId), "2"},
{ String.valueOf(newEntityId), "3"},
};
table = addTable(Constants.TABLE_ENTITY_DELIVERY_METHOD_MAP,
methodsColumns, methodsData, false);
processTable(table);
return newEntityId;
}
|
diff --git a/src/org/granite/messaging/engine/AbstractEngine.java b/src/org/granite/messaging/engine/AbstractEngine.java
index c107b00..7281078 100644
--- a/src/org/granite/messaging/engine/AbstractEngine.java
+++ b/src/org/granite/messaging/engine/AbstractEngine.java
@@ -1,121 +1,120 @@
/*
GRANITE DATA SERVICES
Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
This file is part of Granite Data Services.
Granite Data Services 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.
Granite Data Services 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, see <http://www.gnu.org/licenses/>.
*/
package org.granite.messaging.engine;
import java.io.IOException;
import java.io.InputStream;
import org.granite.config.GraniteConfig;
import org.granite.config.flex.ServicesConfig;
/**
* @author Franck WOLFF
*/
public abstract class AbstractEngine implements Engine {
protected static final String CONTENT_TYPE = "application/x-amf";
protected boolean started = false;
protected GraniteConfig graniteConfig = null;
protected Configurator configurator = null;
protected ServicesConfig servicesConfig = null;
protected EngineStatusHandler statusHandler = new DefaultEngineStatusHandler();
protected String graniteStdConfigPath = "org/granite/messaging/engine/granite-config.xml";
protected String graniteConfigPath = null;
protected int maxIdleTime = 30000;
public EngineStatusHandler getStatusHandler() {
return statusHandler;
}
public void setStatusHandler(EngineStatusHandler statusHandler) {
if (statusHandler == null)
throw new NullPointerException("statusHandler cannot be null");
this.statusHandler = statusHandler;
}
public void setGraniteStdConfigPath(String graniteConfigPath) {
this.graniteStdConfigPath = graniteConfigPath;
}
public void setGraniteConfigPath(String graniteConfigPath) {
this.graniteConfigPath = graniteConfigPath;
}
public void setGraniteConfigurator(Configurator configurator) {
this.configurator = configurator;
}
public void setMaxIdleTime(int maxIdleTime) {
this.maxIdleTime = maxIdleTime;
}
@Override
public void start() {
if (started) {
statusHandler.handleException(new EngineException("Engine already started"));
return;
}
InputStream is = null;
try {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream("org/granite/messaging/engine/granite-config.xml");
- graniteConfig = new GraniteConfig(null, is, null, null);
if (graniteConfigPath != null)
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(graniteConfigPath);
graniteConfig = new GraniteConfig(graniteStdConfigPath, is, null, null);
if (configurator != null)
configurator.configure(graniteConfig);
servicesConfig = new ServicesConfig(null, null, false);
started = true;
}
catch (Exception e) {
graniteConfig = null;
servicesConfig = null;
statusHandler.handleException(new EngineException("Could not load default configuration", e));
}
finally {
if (is != null) try {
is.close();
}
catch (IOException e) {
}
}
}
public boolean isStarted() {
return started;
}
@Override
public void stop() {
if (!started)
statusHandler.handleException(new EngineException("Engine not started"));
else {
graniteConfig = null;
servicesConfig = null;
started = false;
}
}
}
| true | true | public void start() {
if (started) {
statusHandler.handleException(new EngineException("Engine already started"));
return;
}
InputStream is = null;
try {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream("org/granite/messaging/engine/granite-config.xml");
graniteConfig = new GraniteConfig(null, is, null, null);
if (graniteConfigPath != null)
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(graniteConfigPath);
graniteConfig = new GraniteConfig(graniteStdConfigPath, is, null, null);
if (configurator != null)
configurator.configure(graniteConfig);
servicesConfig = new ServicesConfig(null, null, false);
started = true;
}
catch (Exception e) {
graniteConfig = null;
servicesConfig = null;
statusHandler.handleException(new EngineException("Could not load default configuration", e));
}
finally {
if (is != null) try {
is.close();
}
catch (IOException e) {
}
}
}
| public void start() {
if (started) {
statusHandler.handleException(new EngineException("Engine already started"));
return;
}
InputStream is = null;
try {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream("org/granite/messaging/engine/granite-config.xml");
if (graniteConfigPath != null)
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(graniteConfigPath);
graniteConfig = new GraniteConfig(graniteStdConfigPath, is, null, null);
if (configurator != null)
configurator.configure(graniteConfig);
servicesConfig = new ServicesConfig(null, null, false);
started = true;
}
catch (Exception e) {
graniteConfig = null;
servicesConfig = null;
statusHandler.handleException(new EngineException("Could not load default configuration", e));
}
finally {
if (is != null) try {
is.close();
}
catch (IOException e) {
}
}
}
|
diff --git a/src/gov/nih/nci/ncicb/cadsr/loader/ui/FileSelectionPanelDescriptor.java b/src/gov/nih/nci/ncicb/cadsr/loader/ui/FileSelectionPanelDescriptor.java
index 9840e181..69cee32d 100755
--- a/src/gov/nih/nci/ncicb/cadsr/loader/ui/FileSelectionPanelDescriptor.java
+++ b/src/gov/nih/nci/ncicb/cadsr/loader/ui/FileSelectionPanelDescriptor.java
@@ -1,79 +1,81 @@
/*
* Copyright 2000-2003 Oracle, Inc. 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 Oracle, Inc. 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 "Oracle" 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 proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc.
*
* 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, ORACLE, 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
*/
package gov.nih.nci.ncicb.cadsr.loader.ui;
import gov.nih.nci.ncicb.cadsr.loader.UserSelections;
import gov.nih.nci.ncicb.cadsr.loader.util.RunMode;
import gov.nih.nci.ncicb.cadsr.loader.util.UserPreferences;
import java.awt.event.*;
import java.io.*;
import gov.nih.nci.ncicb.cadsr.loader.ui.event.*;
/**
*
* @author <a href="mailto:[email protected]">Christophe Ludet</a>
*/
public class FileSelectionPanelDescriptor
extends WizardPanelDescriptor
implements ActionListener {
public static final String IDENTIFIER = "FILE_SELECTION_PANEL";
private FileSelectionPanel panel;
private UserPreferences prefs = UserPreferences.getInstance();
public FileSelectionPanelDescriptor() {
panel = new FileSelectionPanel();
setPanelDescriptorIdentifier(IDENTIFIER);
setPanelComponent(panel);
nextPanelDescriptor = ProgressFileSelectionPanelDescriptor.IDENTIFIER;
}
public Object getBackPanelDescriptor() {
if(prefs.getModeSelection().equals(RunMode.GenerateReport.toString()))
backPanelDescriptor = PackageFilterSelectionPanelDescriptor.IDENTIFIER;
+ else if(prefs.getModeSelection().equals(RunMode.Roundtrip.toString()))
+ backPanelDescriptor = RoundtripPanelDescriptor.IDENTIFIER;
else
backPanelDescriptor = ModeSelectionPanelDescriptor.IDENTIFIER;
return backPanelDescriptor;
}
public void aboutToDisplayPanel()
{
setNextButtonAccordingToSelection();
}
public void init() {
panel.init();
panel.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
setNextButtonAccordingToSelection();
}
private void setNextButtonAccordingToSelection()
{
String path = panel.getSelection();
File f = new File(path);
getWizardModel().setNextButtonEnabled(new Boolean(f.exists()));
}
}
| true | true | public Object getBackPanelDescriptor() {
if(prefs.getModeSelection().equals(RunMode.GenerateReport.toString()))
backPanelDescriptor = PackageFilterSelectionPanelDescriptor.IDENTIFIER;
else
backPanelDescriptor = ModeSelectionPanelDescriptor.IDENTIFIER;
return backPanelDescriptor;
}
| public Object getBackPanelDescriptor() {
if(prefs.getModeSelection().equals(RunMode.GenerateReport.toString()))
backPanelDescriptor = PackageFilterSelectionPanelDescriptor.IDENTIFIER;
else if(prefs.getModeSelection().equals(RunMode.Roundtrip.toString()))
backPanelDescriptor = RoundtripPanelDescriptor.IDENTIFIER;
else
backPanelDescriptor = ModeSelectionPanelDescriptor.IDENTIFIER;
return backPanelDescriptor;
}
|
diff --git a/src/org/joedog/pinochle/view/BidDialog.java b/src/org/joedog/pinochle/view/BidDialog.java
index add4500..f78e642 100644
--- a/src/org/joedog/pinochle/view/BidDialog.java
+++ b/src/org/joedog/pinochle/view/BidDialog.java
@@ -1,209 +1,209 @@
package org.joedog.pinochle.view;
import java.awt.Container;
import java.awt.Component;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import java.beans.PropertyChangeEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.SwingUtilities;
import java.util.concurrent.atomic.AtomicBoolean;
import org.joedog.pinochle.control.*;
import org.joedog.pinochle.game.*;
public class BidDialog extends JFrame implements View {
private int x, y;
private int value;
private int bid;
private JComboBox bidList;
private JButton okay;
private JButton pass;
private Container dialog;
private JPanel buttons;
private JLabel header;
private JLabel suit;
public boolean paused;
private GameController controller;
/**
* Default constructor
* This is a custome dialog which captures and stores
* its position coordinates; the value returned from the
* dialog must be called from instance.getValue();
* <p>
* @param GameController reference to controller for storage
* @param int the current bid
* @return BidDialog
*/
public BidDialog(GameController controller, int bid) {
this.bid = bid;
this.value = -1;
this.controller = controller;
this.paused = true;
this.controller.addView(this);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
/**
* Returns a bid which was selected by the user
* <p>
* @param none
* @return int the selected bid
*/
public int getValue() {
while (true) {
if (this.paused) {
try {
Thread.sleep(1000);
} catch (Exception e) {}
} else {
this.setVisible(false);
this.controller.removeView(this);
return this.value;
}
}
}
public void modelPropertyChange(PropertyChangeEvent e) {
if (e.getNewValue() == null) return;
if (e.getPropertyName().equals(controller.RESET)) {
this.paused = false;
this.value = -1;
this.controller.removeView(this);
this.setVisible(false);
this.dispose();
}
}
private void createAndShowGui() {
this.dialog = this.getContentPane();
this.dialog.setLayout(null);
this.dialog.add(this.getSuitLabel(), null);
this.header = new JLabel();
this.header.setBounds(new Rectangle(70, 10, 120, 20));
this.header.setText("Select a bid:");
this.dialog.add(this.header, null);
this.dialog.add(getComboBox(bid), null);
this.buttons = new JPanel();
this.buttons.setBounds(new Rectangle(70, 60, 190, 35));
this.buttons.setLayout(new FlowLayout());
this.buttons.add(this.getOkayButton());
this.buttons.add(this.getPassButton());
this.dialog.add(buttons, null);
- this.setPreferredSize(new Dimension(268,132));
+ this.setPreferredSize(new Dimension(268,146));
JRootPane root = this.getRootPane();
root.setDefaultButton(okay);
this.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowLostFocus(WindowEvent e) {
toFront();
}
@Override
public void windowGainedFocus(WindowEvent e) {
okay.requestFocusInWindow();
}
});
this.addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
- x = getX();
- y = getY();
+ x = getX() + 10;
+ y = getY() + 10;
}
});
int xpos = controller.getIntProperty("DialogX");
int ypos = controller.getIntProperty("DialogY");
this.pack();
this.setVisible(true);
this.setLocation(xpos, ypos);
}
private int myX() {
return this.x;
}
private int myY() {
return this.y;
}
private JLabel getSuitLabel() {
if (suit == null) {
suit = new JLabel();
}
suit.setIcon(new TrumpIcon(Pinochle.SPADES));
suit.setBounds(new Rectangle(15,5,50,50));
return suit;
}
private JButton getOkayButton() {
if (okay == null) {
okay = new JButton();
okay.setText("Okay");
okay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
controller.setProperty("DialogX", Integer.toString(myX()));
controller.setProperty("DialogY", Integer.toString(myY()));
value = (Integer)bidList.getSelectedItem();
paused = false;
}
});
}
return okay;
}
private JButton getPassButton() {
if (pass == null) {
pass = new JButton();
pass.setText("Pass");
pass.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
controller.setProperty("DialogX", Integer.toString(myX()));
controller.setProperty("DialogY", Integer.toString(myY()));
value = -1;
paused = false;
}
});
}
return pass;
}
private JComboBox getComboBox(int bid) {
Integer bids[] = new Integer[16];
for (int i = 0; i < bids.length; i++) {
bids[i] = (bid+i+1);
}
if (bidList == null) {
bidList = new JComboBox(bids);
}
bidList.setSelectedIndex(0);
bidList.setPreferredSize(new Dimension(60,20));
bidList.setBounds(new Rectangle(70, 35, 160, 20));
bidList.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
value = (Integer)bidList.getSelectedItem();
}
});
return bidList;
}
}
| false | true | private void createAndShowGui() {
this.dialog = this.getContentPane();
this.dialog.setLayout(null);
this.dialog.add(this.getSuitLabel(), null);
this.header = new JLabel();
this.header.setBounds(new Rectangle(70, 10, 120, 20));
this.header.setText("Select a bid:");
this.dialog.add(this.header, null);
this.dialog.add(getComboBox(bid), null);
this.buttons = new JPanel();
this.buttons.setBounds(new Rectangle(70, 60, 190, 35));
this.buttons.setLayout(new FlowLayout());
this.buttons.add(this.getOkayButton());
this.buttons.add(this.getPassButton());
this.dialog.add(buttons, null);
this.setPreferredSize(new Dimension(268,132));
JRootPane root = this.getRootPane();
root.setDefaultButton(okay);
this.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowLostFocus(WindowEvent e) {
toFront();
}
@Override
public void windowGainedFocus(WindowEvent e) {
okay.requestFocusInWindow();
}
});
this.addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
x = getX();
y = getY();
}
});
int xpos = controller.getIntProperty("DialogX");
int ypos = controller.getIntProperty("DialogY");
this.pack();
this.setVisible(true);
this.setLocation(xpos, ypos);
}
| private void createAndShowGui() {
this.dialog = this.getContentPane();
this.dialog.setLayout(null);
this.dialog.add(this.getSuitLabel(), null);
this.header = new JLabel();
this.header.setBounds(new Rectangle(70, 10, 120, 20));
this.header.setText("Select a bid:");
this.dialog.add(this.header, null);
this.dialog.add(getComboBox(bid), null);
this.buttons = new JPanel();
this.buttons.setBounds(new Rectangle(70, 60, 190, 35));
this.buttons.setLayout(new FlowLayout());
this.buttons.add(this.getOkayButton());
this.buttons.add(this.getPassButton());
this.dialog.add(buttons, null);
this.setPreferredSize(new Dimension(268,146));
JRootPane root = this.getRootPane();
root.setDefaultButton(okay);
this.addWindowFocusListener(new WindowAdapter() {
@Override
public void windowLostFocus(WindowEvent e) {
toFront();
}
@Override
public void windowGainedFocus(WindowEvent e) {
okay.requestFocusInWindow();
}
});
this.addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
x = getX() + 10;
y = getY() + 10;
}
});
int xpos = controller.getIntProperty("DialogX");
int ypos = controller.getIntProperty("DialogY");
this.pack();
this.setVisible(true);
this.setLocation(xpos, ypos);
}
|
diff --git a/SimpleNotes/src/com/github/simplenotes/NotesDb.java b/SimpleNotes/src/com/github/simplenotes/NotesDb.java
index 8c5036e..4e993ab 100644
--- a/SimpleNotes/src/com/github/simplenotes/NotesDb.java
+++ b/SimpleNotes/src/com/github/simplenotes/NotesDb.java
@@ -1,114 +1,119 @@
package com.github.simplenotes;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.github.simplenotelib.Note;
public class NotesDb {
public static final String KEY_ROWID = "_id";
public static final String KEY_KEY = "key";
public static final String KEY_MODIFYDATE = "modifydate";
public static final String KEY_CREATEDATE = "createdate";
public static final String KEY_SYNCNUM = "syncnum";
public static final String KEY_VERSION = "version";
public static final String KEY_SYSTEMTAGS = "systemtags";
public static final String KEY_TAGS = "tags";
public static final String KEY_CONTENT = "content";
public static final String KEY_NOTEID = "noteid";
public static final String KEY_NAME = "name";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_NOTES_TABLE = "notes";
private static final String DATABASE_TAGS_TABLE = "tags";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_NOTES =
"create table " + DATABASE_NOTES_TABLE + " (" +
KEY_ROWID + " integer primary key autoincrement, " +
KEY_KEY + " text, " +
KEY_MODIFYDATE + " text, " +
KEY_CREATEDATE + " text, " +
KEY_SYNCNUM + " integer, " +
KEY_VERSION + " integer, " +
KEY_CONTENT + " text);";
private static final String DATABASE_CREATE_TAGS =
"create table " + DATABASE_TAGS_TABLE + " (" +
KEY_ROWID + " integer primary key autoincrement, " +
KEY_NAME + " text, " +
KEY_NOTEID + " integer, " +
"foreign key(" + KEY_NOTEID +
") references " + DATABASE_NOTES_TABLE + " (" + KEY_ROWID + ");";
private final Context mCtx;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_NOTES);
db.execSQL(DATABASE_CREATE_TAGS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public NotesDb(Context ctx) {
this.mCtx = ctx;
}
/**
* Open the notes database. If it cannot be opened, try to create a new
* instance of the database. If it cannot be created, throw an exception to
* signal the failure
*
* @return this (self reference, allowing this to be chained in an
* initialization call)
* @throws SQLException if the database could be neither opened or created
*/
public NotesDb open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(String content, List<String> tags) {
ContentValues values = new ContentValues();
values.put(KEY_CONTENT, content);
return mDb.insert(DATABASE_NOTES_TABLE, null, values);
}
public Note getNote(long id) {
Cursor cursor =
mDb.query(DATABASE_NOTES_TABLE,
new String[] {KEY_ROWID, KEY_KEY, KEY_CONTENT},
KEY_ROWID + "=" + id,
null, null, null, null);
+ if (!cursor.moveToFirst()) {
+ // Cursor is probably empty.
+ return null;
+ }
Note note = new Note();
note.setContent(cursor.getString(2));
+ cursor.close();
return note;
}
}
| false | true | public Note getNote(long id) {
Cursor cursor =
mDb.query(DATABASE_NOTES_TABLE,
new String[] {KEY_ROWID, KEY_KEY, KEY_CONTENT},
KEY_ROWID + "=" + id,
null, null, null, null);
Note note = new Note();
note.setContent(cursor.getString(2));
return note;
}
| public Note getNote(long id) {
Cursor cursor =
mDb.query(DATABASE_NOTES_TABLE,
new String[] {KEY_ROWID, KEY_KEY, KEY_CONTENT},
KEY_ROWID + "=" + id,
null, null, null, null);
if (!cursor.moveToFirst()) {
// Cursor is probably empty.
return null;
}
Note note = new Note();
note.setContent(cursor.getString(2));
cursor.close();
return note;
}
|
diff --git a/javafx/money-javafx-binding/src/main/java/net/java/javamoney/examples/javafx/BindingApp.java b/javafx/money-javafx-binding/src/main/java/net/java/javamoney/examples/javafx/BindingApp.java
index 43e37de..90494a9 100644
--- a/javafx/money-javafx-binding/src/main/java/net/java/javamoney/examples/javafx/BindingApp.java
+++ b/javafx/money-javafx-binding/src/main/java/net/java/javamoney/examples/javafx/BindingApp.java
@@ -1,43 +1,43 @@
/*
* JSR 354 JavaFX Binding Example
*/
package net.java.javamoney.examples.javafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Werner Keil
*
*/
public class BindingApp extends Application {
private static final Logger log = LoggerFactory.getLogger(BindingApp.class);
public static void main(String[] args) throws Exception {
launch(args);
}
public void start(Stage stage) throws Exception {
log.info("Starting Hello JavaFX and Maven demonstration application");
String fxmlFile = "/fxml/hello.fxml";
log.debug("Loading FXML for main view from: {}", fxmlFile);
FXMLLoader loader = new FXMLLoader();
Parent rootNode = (Parent) loader.load(getClass().getResourceAsStream(fxmlFile));
log.debug("Showing JFX scene");
Scene scene = new Scene(rootNode, 400, 200);
scene.getStylesheets().add("/styles/styles.css");
- stage.setTitle("Hello JavaFX and Maven");
+ stage.setTitle("Hello JavaFX and JSR 354");
stage.setScene(scene);
stage.show();
}
}
| true | true | public void start(Stage stage) throws Exception {
log.info("Starting Hello JavaFX and Maven demonstration application");
String fxmlFile = "/fxml/hello.fxml";
log.debug("Loading FXML for main view from: {}", fxmlFile);
FXMLLoader loader = new FXMLLoader();
Parent rootNode = (Parent) loader.load(getClass().getResourceAsStream(fxmlFile));
log.debug("Showing JFX scene");
Scene scene = new Scene(rootNode, 400, 200);
scene.getStylesheets().add("/styles/styles.css");
stage.setTitle("Hello JavaFX and Maven");
stage.setScene(scene);
stage.show();
}
| public void start(Stage stage) throws Exception {
log.info("Starting Hello JavaFX and Maven demonstration application");
String fxmlFile = "/fxml/hello.fxml";
log.debug("Loading FXML for main view from: {}", fxmlFile);
FXMLLoader loader = new FXMLLoader();
Parent rootNode = (Parent) loader.load(getClass().getResourceAsStream(fxmlFile));
log.debug("Showing JFX scene");
Scene scene = new Scene(rootNode, 400, 200);
scene.getStylesheets().add("/styles/styles.css");
stage.setTitle("Hello JavaFX and JSR 354");
stage.setScene(scene);
stage.show();
}
|
diff --git a/src/org/red5/server/context/PersistentSharedObject.java b/src/org/red5/server/context/PersistentSharedObject.java
index 9324399a..9cd5696d 100644
--- a/src/org/red5/server/context/PersistentSharedObject.java
+++ b/src/org/red5/server/context/PersistentSharedObject.java
@@ -1,240 +1,243 @@
package org.red5.server.context;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.red5.server.api.SharedObject;
import org.red5.server.net.rtmp.Channel;
import org.red5.server.net.rtmp.Connection;
import org.red5.server.net.rtmp.message.Constants;
import org.red5.server.net.rtmp.message.SharedObjectEvent;
import org.red5.server.SharedObjectPersistence;
public class PersistentSharedObject implements SharedObject, Constants {
protected static Log log =
LogFactory.getLog(PersistentSharedObject.class.getName());
protected String name;
protected SharedObjectPersistence persistence = null;
protected int version = 0;
protected boolean persistent = true;
protected HashMap data = new HashMap();
protected HashMap clients = new HashMap();
protected int updateCounter = 0;
protected boolean modified = false;
private org.red5.server.net.rtmp.message.SharedObject ownerMessage;
private org.red5.server.net.rtmp.message.SharedObject syncMessage;
public PersistentSharedObject(String name, boolean persistent, SharedObjectPersistence persistence) {
this.name = name;
this.persistent = persistent;
this.persistence = persistence;
this.ownerMessage = new org.red5.server.net.rtmp.message.SharedObject();
this.ownerMessage.setName(name);
this.ownerMessage.setTimestamp(0);
this.ownerMessage.setType(persistent ? 2 : 0);
this.syncMessage = new org.red5.server.net.rtmp.message.SharedObject();
this.syncMessage.setName(name);
this.syncMessage.setTimestamp(0);
this.syncMessage.setType(persistent ? 2 : 0);
}
public String getName() {
return this.name;
}
public boolean isPersistent() {
return this.persistent;
}
private void sendUpdates() {
Connection conn = (Connection) Scope.getClient();
if (!this.ownerMessage.getEvents().isEmpty()) {
// Send update to "owner" of this update request
this.ownerMessage.setSoId(this.version);
this.ownerMessage.setSealed(false);
Channel channel = Scope.getChannel();
- if (channel != null)
+ if (channel != null) {
channel.write(this.ownerMessage);
- else
+ log.debug("Owner: " + channel);
+ } else
log.warn("No channel found for owner changes!?");
this.ownerMessage.getEvents().clear();
}
if (!this.syncMessage.getEvents().isEmpty()) {
// Synchronize updates with all registered clients of this shared object
this.syncMessage.setSoId(this.version);
this.syncMessage.setSealed(false);
// Acquire the packet, this will stop the data inside being released
this.syncMessage.acquire();
HashMap all_clients = this.clients;
Iterator clients = all_clients.keySet().iterator();
while (clients.hasNext()) {
Connection connection = (Connection) clients.next();
if (connection == conn) {
// Don't re-send update to active client
log.debug("Skipped " + connection);
continue;
}
Iterator channels = ((HashSet) all_clients.get(connection)).iterator();
while (channels.hasNext()) {
Channel c = connection.getChannel(((Integer) channels.next()).byteValue());
+ log.debug("Send to " + c);
c.write(this.syncMessage);
+ this.syncMessage.setSealed(false);
}
}
// After sending the packet down all the channels we can release the packet,
// which in turn will allow the data buffer to be released
this.syncMessage.release();
this.syncMessage.getEvents().clear();
}
}
private void notifyModified() {
if (this.updateCounter > 0)
// we're inside a beginUpdate...endUpdate block
return;
if (this.modified)
// The client sent at least one update -> increase version of SO
this.updateVersion();
if (this.modified && this.persistence != null)
this.persistence.storeSharedObject(this);
this.sendUpdates();
}
public Object getAttribute(String name) {
return this.data.get(name);
}
public boolean updateAttribute(String name, Object value) {
Object old = this.data.get(name);
// Send confirmation to client
this.ownerMessage.addEvent(new SharedObjectEvent(SO_CLIENT_UPDATE_ATTRIBUTE, name, null));
if ((old == null) || (!old.equals(value))) {
this.data.put(name, value);
this.modified = true;
// only sync if the attribute changed
this.syncMessage.addEvent(new SharedObjectEvent(SO_CLIENT_UPDATE_DATA, name, value));
this.notifyModified();
return true;
} else {
this.notifyModified();
return false;
}
}
public boolean deleteAttribute(String name) {
boolean result = this.data.containsKey(name);
this.data.remove(name);
// Send confirmation to client
this.ownerMessage.addEvent(new SharedObjectEvent(SO_CLIENT_DELETE_DATA, name, null));
if (result) {
this.modified = true;
this.syncMessage.addEvent(new SharedObjectEvent(SO_CLIENT_DELETE_DATA, name, null));
}
this.notifyModified();
return result;
}
public void sendMessage(String handler, List arguments) {
this.ownerMessage.addEvent(new SharedObjectEvent(SO_CLIENT_SEND_MESSAGE, handler, arguments));
this.syncMessage.addEvent(new SharedObjectEvent(SO_CLIENT_SEND_MESSAGE, handler, arguments));
}
public void setData(Map data) {
this.data.clear();
this.data.putAll(data);
this.modified = false;
}
public HashMap getData() {
return this.data;
}
public int getVersion() {
return this.version;
}
private void updateVersion() {
this.version += 1;
}
public void clear() {
// TODO: there must be a direct way to clear the SO on the client side...
Iterator keys = this.data.keySet().iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
this.ownerMessage.addEvent(new SharedObjectEvent(SO_CLIENT_DELETE_DATA, key, null));
this.syncMessage.addEvent(new SharedObjectEvent(SO_CLIENT_DELETE_DATA, key, null));
}
this.data.clear();
this.modified = true;
this.notifyModified();
}
public void registerClient(Client client, int channel) {
if (!this.clients.containsKey(client))
this.clients.put(client, new HashSet());
HashSet channels = (HashSet) this.clients.get(client);
channels.add(new Integer(channel));
// prepare response for new client
this.ownerMessage.addEvent(new SharedObjectEvent(SO_CLIENT_INITIAL_DATA, null, null));
if (!this.data.isEmpty())
this.ownerMessage.addEvent(new SharedObjectEvent(SO_CLIENT_UPDATE_DATA, null, this.data));
// we call notifyModified here to send response if we're not in a beginUpdate block
this.notifyModified();
}
public void unregisterClient(Client client) {
this.clients.remove(client);
if (!this.persistent && this.clients.isEmpty()) {
log.info("Deleting shared object " + this.name + " because all clients disconnected.");
this.data.clear();
this.persistence.deleteSharedObject(this.name);
}
}
public void unregisterClient(Client client, int channel) {
if (!this.clients.containsKey(client))
// No channel registered for this client
return;
HashSet channels = (HashSet) this.clients.get(client);
channels.remove(new Integer(channel));
if (channels.isEmpty()) {
// Delete shared object in case of non-persistent SOs
this.unregisterClient(client);
}
}
public HashMap getClients() {
return this.clients;
}
public void beginUpdate() {
this.updateCounter += 1;
}
public void endUpdate() {
this.updateCounter -= 1;
if (this.updateCounter == 0)
this.notifyModified();
}
}
| false | true | private void sendUpdates() {
Connection conn = (Connection) Scope.getClient();
if (!this.ownerMessage.getEvents().isEmpty()) {
// Send update to "owner" of this update request
this.ownerMessage.setSoId(this.version);
this.ownerMessage.setSealed(false);
Channel channel = Scope.getChannel();
if (channel != null)
channel.write(this.ownerMessage);
else
log.warn("No channel found for owner changes!?");
this.ownerMessage.getEvents().clear();
}
if (!this.syncMessage.getEvents().isEmpty()) {
// Synchronize updates with all registered clients of this shared object
this.syncMessage.setSoId(this.version);
this.syncMessage.setSealed(false);
// Acquire the packet, this will stop the data inside being released
this.syncMessage.acquire();
HashMap all_clients = this.clients;
Iterator clients = all_clients.keySet().iterator();
while (clients.hasNext()) {
Connection connection = (Connection) clients.next();
if (connection == conn) {
// Don't re-send update to active client
log.debug("Skipped " + connection);
continue;
}
Iterator channels = ((HashSet) all_clients.get(connection)).iterator();
while (channels.hasNext()) {
Channel c = connection.getChannel(((Integer) channels.next()).byteValue());
c.write(this.syncMessage);
}
}
// After sending the packet down all the channels we can release the packet,
// which in turn will allow the data buffer to be released
this.syncMessage.release();
this.syncMessage.getEvents().clear();
}
}
| private void sendUpdates() {
Connection conn = (Connection) Scope.getClient();
if (!this.ownerMessage.getEvents().isEmpty()) {
// Send update to "owner" of this update request
this.ownerMessage.setSoId(this.version);
this.ownerMessage.setSealed(false);
Channel channel = Scope.getChannel();
if (channel != null) {
channel.write(this.ownerMessage);
log.debug("Owner: " + channel);
} else
log.warn("No channel found for owner changes!?");
this.ownerMessage.getEvents().clear();
}
if (!this.syncMessage.getEvents().isEmpty()) {
// Synchronize updates with all registered clients of this shared object
this.syncMessage.setSoId(this.version);
this.syncMessage.setSealed(false);
// Acquire the packet, this will stop the data inside being released
this.syncMessage.acquire();
HashMap all_clients = this.clients;
Iterator clients = all_clients.keySet().iterator();
while (clients.hasNext()) {
Connection connection = (Connection) clients.next();
if (connection == conn) {
// Don't re-send update to active client
log.debug("Skipped " + connection);
continue;
}
Iterator channels = ((HashSet) all_clients.get(connection)).iterator();
while (channels.hasNext()) {
Channel c = connection.getChannel(((Integer) channels.next()).byteValue());
log.debug("Send to " + c);
c.write(this.syncMessage);
this.syncMessage.setSealed(false);
}
}
// After sending the packet down all the channels we can release the packet,
// which in turn will allow the data buffer to be released
this.syncMessage.release();
this.syncMessage.getEvents().clear();
}
}
|
diff --git a/FlagsBlock/src/alshain01/FlagsBlock/FlagsBlock.java b/FlagsBlock/src/alshain01/FlagsBlock/FlagsBlock.java
index 2efd848..fad94cc 100644
--- a/FlagsBlock/src/alshain01/FlagsBlock/FlagsBlock.java
+++ b/FlagsBlock/src/alshain01/FlagsBlock/FlagsBlock.java
@@ -1,156 +1,156 @@
/* Copyright 2013 Kevin Seiden. All rights reserved.
This works is licensed under the Creative Commons Attribution-NonCommercial 3.0
You are Free to:
to Share � to copy, distribute and transmit the work
to Remix � to adapt the work
Under the following conditions:
Attribution � You must attribute the work in the manner specified by the author (but not in any way that suggests that they endorse you or your use of the work).
Non-commercial � You may not use this work for commercial purposes.
With the understanding that:
Waiver � Any of the above conditions can be waived if you get permission from the copyright holder.
Public Domain � Where the work or any of its elements is in the public domain under applicable law, that status is in no way affected by the license.
Other Rights � In no way are any of the following rights affected by the license:
Your fair dealing or fair use rights, or other applicable copyright exceptions and limitations;
The author's moral rights;
Rights other persons may have either in the work itself or in how the work is used, such as publicity or privacy rights.
Notice � For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page.
http://creativecommons.org/licenses/by-nc/3.0/
*/
package alshain01.FlagsBlock;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.plugin.java.JavaPlugin;
import alshain01.Flags.Flag;
import alshain01.Flags.Flags;
import alshain01.Flags.ModuleYML;
import alshain01.Flags.Registrar;
import alshain01.Flags.Director;
/**
* Flags - Block
* Module that adds block flags to the plug-in Flags.
*
* @author Alshain01
*/
public class FlagsBlock extends JavaPlugin {
/**
* Called when this module is enabled
*/
@Override
public void onEnable(){
// Connect to the data file
ModuleYML dataFile = new ModuleYML(this, "flags.yml");
// Register with Flags
Registrar flags = Flags.instance.getRegistrar();
for(String f : dataFile.getModuleData().getConfigurationSection("Flag").getKeys(false)) {
ConfigurationSection data = dataFile.getModuleData().getConfigurationSection("Flag." + f);
// The description that appears when using help commands.
String desc = data.getString("Description");
// Register it!
// Be sure to send a plug-in name or group description for the help command!
// It can be this.getName() or another string.
- flags.register(f, desc, true, "Core");
+ flags.register(f, desc, true, "Block");
}
// Load plug-in events and data
Bukkit.getServer().getPluginManager().registerEvents(new BlockListener(), this);
}
/*
* The event handlers for the flags we created earlier
*/
public class BlockListener implements Listener{
/*
* Snow and Ice form event handler
*/
@EventHandler(ignoreCancelled = true)
private void onBlockForm(BlockFormEvent e) {
Flag flag = null;
if (e.getNewState().getType() == Material.SNOW) {
flag = Flags.instance.getRegistrar().getFlag("Snow");
} else if (e.getNewState().getType() == Material.ICE) {
flag = Flags.instance.getRegistrar().getFlag("Ice");
}
if (flag != null) {
e.setCancelled(!Director.getAreaAt(e.getBlock().getLocation()).getValue(flag, false));
}
}
/*
* Snow and Ice melt event handler
*/
@EventHandler(ignoreCancelled = true)
private void onBlockFade(BlockFadeEvent e) {
Flag flag = null;
if (e.getBlock().getType() == Material.SNOW) {
flag = Flags.instance.getRegistrar().getFlag("SnowMelt");
} else if (e.getBlock().getType() == Material.ICE) {
flag = Flags.instance.getRegistrar().getFlag("IceMelt");
}
if (flag != null) {
e.setCancelled(!Director.getAreaAt(e.getBlock().getLocation()).getValue(flag, false));
}
}
/*
* Grass spread event handler
*/
@EventHandler(ignoreCancelled = true)
private void onBlockSpread(BlockSpreadEvent e) {
if (e.getNewState().getType() == Material.GRASS) {
Flag flag = Flags.instance.getRegistrar().getFlag("Grass");
if (flag != null) {
e.setCancelled(!Director.getAreaAt(e.getBlock().getLocation()).getValue(flag, false));
}
}
}
/*
* Dragon Egg Teleport handler
*/
@EventHandler(ignoreCancelled = true)
private void onBlockFromTo(BlockFromToEvent e) {
if (e.getBlock().getType() == Material.DRAGON_EGG) {
Flag flag = Flags.instance.getRegistrar().getFlag("DragonEggTp");
if (flag != null) {
e.setCancelled(!Director.getAreaAt(e.getBlock().getLocation()).getValue(flag, false));
}
}
}
/*
* Leaf Decay handler
*/
@EventHandler(ignoreCancelled = true)
private void onLeafDecay(LeavesDecayEvent e) {
Flag flag = Flags.instance.getRegistrar().getFlag("LeafDecay");
if (flag != null) {
e.setCancelled(!Director.getAreaAt(e.getBlock().getLocation()).getValue(flag, false));
}
}
}
}
| true | true | public void onEnable(){
// Connect to the data file
ModuleYML dataFile = new ModuleYML(this, "flags.yml");
// Register with Flags
Registrar flags = Flags.instance.getRegistrar();
for(String f : dataFile.getModuleData().getConfigurationSection("Flag").getKeys(false)) {
ConfigurationSection data = dataFile.getModuleData().getConfigurationSection("Flag." + f);
// The description that appears when using help commands.
String desc = data.getString("Description");
// Register it!
// Be sure to send a plug-in name or group description for the help command!
// It can be this.getName() or another string.
flags.register(f, desc, true, "Core");
}
// Load plug-in events and data
Bukkit.getServer().getPluginManager().registerEvents(new BlockListener(), this);
}
| public void onEnable(){
// Connect to the data file
ModuleYML dataFile = new ModuleYML(this, "flags.yml");
// Register with Flags
Registrar flags = Flags.instance.getRegistrar();
for(String f : dataFile.getModuleData().getConfigurationSection("Flag").getKeys(false)) {
ConfigurationSection data = dataFile.getModuleData().getConfigurationSection("Flag." + f);
// The description that appears when using help commands.
String desc = data.getString("Description");
// Register it!
// Be sure to send a plug-in name or group description for the help command!
// It can be this.getName() or another string.
flags.register(f, desc, true, "Block");
}
// Load plug-in events and data
Bukkit.getServer().getPluginManager().registerEvents(new BlockListener(), this);
}
|
diff --git a/JsTestDriver/src-test/com/google/jstestdriver/server/handlers/HomeHandlerTest.java b/JsTestDriver/src-test/com/google/jstestdriver/server/handlers/HomeHandlerTest.java
index f1b41458..1cdb7db5 100644
--- a/JsTestDriver/src-test/com/google/jstestdriver/server/handlers/HomeHandlerTest.java
+++ b/JsTestDriver/src-test/com/google/jstestdriver/server/handlers/HomeHandlerTest.java
@@ -1,79 +1,92 @@
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.jstestdriver.server.handlers;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import org.joda.time.Instant;
import com.google.jstestdriver.BrowserInfo;
import com.google.jstestdriver.CapturedBrowsers;
import com.google.jstestdriver.MockTime;
import com.google.jstestdriver.SlaveBrowser;
import com.google.jstestdriver.SlaveBrowser.BrowserState;
import com.google.jstestdriver.browser.BrowserIdStrategy;
import com.google.jstestdriver.runner.RunnerType;
/**
* @author [email protected] (Jeremie Lenfant-Engelmann)
*/
public class HomeHandlerTest extends TestCase {
public void testDisplayInfo() throws Exception {
CapturedBrowsers capturedBrowsers =
new CapturedBrowsers(new BrowserIdStrategy(new MockTime(0)));
BrowserInfo browserInfo = new BrowserInfo();
browserInfo.setId(1L);
browserInfo.setName("browser");
browserInfo.setOs("OS");
browserInfo.setVersion("1.0");
SlaveBrowser slave = new SlaveBrowser(new MockTime(0),
"1",
browserInfo,
SlaveBrowser.TIMEOUT,
null,
CaptureHandler.QUIRKS,
RunnerType.CLIENT,
BrowserState.CAPTURED,
new Instant(0));
capturedBrowsers.addSlave(slave);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(stream);
HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
HomeHandler handler = new HomeHandler(capturedBrowsers, response, writer);
/* expect */response.setContentType("text/html");
EasyMock.replay(response);
handler.handleIt();
- assertEquals("<html><head><title>JsTestDriver</title></head><body>"
+ assertEquals("<html><head><title>JsTestDriver</title><script>"
+ + "function getEl(id){return document.getElementById(id);}"
+ + "function toggle(id) {\n"
+ + "if (getEl(id).style.display=='block') {"
+ + "getEl(id).style.display='none';"
+ + "} else {"
+ + "getEl(id).style.display='block';}"
+ + "}</script>"
+ + "</head><body>"
+ "<a href=\"/capture\">Capture This Browser</a><br/>"
+ "<a href=\"/capture?strict\">Capture This Browser in strict mode</a>"
+ "<br/><p><strong>Captured Browsers: (1)</strong></p>"
+ "<div>Id: 1<br/>Name: browser<br/>Version: 1.0"
- + "<br/>Operating System: OS<br/>Currently waiting...<br/>"
- + "<ul style='display:none'></ul></div></body></html>", stream.toString());
+ + "<br/>Operating System: OS<br/>In use.<br/>RunnerType CLIENT <br/>"
+ + "Currently waiting...<br/>"
+ + "<input type='button' value='List Files' onclick=\"toggle('f1')\"/>"
+ + "<ul style='display:none' id='f1'></ul>"
+ + "<input type='button' value='Show Responses' "
+ + "onclick=\"toggle('r1')\"/><pre id='r1' style='display:none'>[]</pre>"
+ + "</div></body></html>", stream.toString());
EasyMock.verify(response);
}
}
| false | true | public void testDisplayInfo() throws Exception {
CapturedBrowsers capturedBrowsers =
new CapturedBrowsers(new BrowserIdStrategy(new MockTime(0)));
BrowserInfo browserInfo = new BrowserInfo();
browserInfo.setId(1L);
browserInfo.setName("browser");
browserInfo.setOs("OS");
browserInfo.setVersion("1.0");
SlaveBrowser slave = new SlaveBrowser(new MockTime(0),
"1",
browserInfo,
SlaveBrowser.TIMEOUT,
null,
CaptureHandler.QUIRKS,
RunnerType.CLIENT,
BrowserState.CAPTURED,
new Instant(0));
capturedBrowsers.addSlave(slave);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(stream);
HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
HomeHandler handler = new HomeHandler(capturedBrowsers, response, writer);
/* expect */response.setContentType("text/html");
EasyMock.replay(response);
handler.handleIt();
assertEquals("<html><head><title>JsTestDriver</title></head><body>"
+ "<a href=\"/capture\">Capture This Browser</a><br/>"
+ "<a href=\"/capture?strict\">Capture This Browser in strict mode</a>"
+ "<br/><p><strong>Captured Browsers: (1)</strong></p>"
+ "<div>Id: 1<br/>Name: browser<br/>Version: 1.0"
+ "<br/>Operating System: OS<br/>Currently waiting...<br/>"
+ "<ul style='display:none'></ul></div></body></html>", stream.toString());
EasyMock.verify(response);
}
| public void testDisplayInfo() throws Exception {
CapturedBrowsers capturedBrowsers =
new CapturedBrowsers(new BrowserIdStrategy(new MockTime(0)));
BrowserInfo browserInfo = new BrowserInfo();
browserInfo.setId(1L);
browserInfo.setName("browser");
browserInfo.setOs("OS");
browserInfo.setVersion("1.0");
SlaveBrowser slave = new SlaveBrowser(new MockTime(0),
"1",
browserInfo,
SlaveBrowser.TIMEOUT,
null,
CaptureHandler.QUIRKS,
RunnerType.CLIENT,
BrowserState.CAPTURED,
new Instant(0));
capturedBrowsers.addSlave(slave);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(stream);
HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
HomeHandler handler = new HomeHandler(capturedBrowsers, response, writer);
/* expect */response.setContentType("text/html");
EasyMock.replay(response);
handler.handleIt();
assertEquals("<html><head><title>JsTestDriver</title><script>"
+ "function getEl(id){return document.getElementById(id);}"
+ "function toggle(id) {\n"
+ "if (getEl(id).style.display=='block') {"
+ "getEl(id).style.display='none';"
+ "} else {"
+ "getEl(id).style.display='block';}"
+ "}</script>"
+ "</head><body>"
+ "<a href=\"/capture\">Capture This Browser</a><br/>"
+ "<a href=\"/capture?strict\">Capture This Browser in strict mode</a>"
+ "<br/><p><strong>Captured Browsers: (1)</strong></p>"
+ "<div>Id: 1<br/>Name: browser<br/>Version: 1.0"
+ "<br/>Operating System: OS<br/>In use.<br/>RunnerType CLIENT <br/>"
+ "Currently waiting...<br/>"
+ "<input type='button' value='List Files' onclick=\"toggle('f1')\"/>"
+ "<ul style='display:none' id='f1'></ul>"
+ "<input type='button' value='Show Responses' "
+ "onclick=\"toggle('r1')\"/><pre id='r1' style='display:none'>[]</pre>"
+ "</div></body></html>", stream.toString());
EasyMock.verify(response);
}
|
diff --git a/DesktopImport/src/org/gephi/desktop/importer/ReportPanel.java b/DesktopImport/src/org/gephi/desktop/importer/ReportPanel.java
index 36c9ddbde..306d14033 100644
--- a/DesktopImport/src/org/gephi/desktop/importer/ReportPanel.java
+++ b/DesktopImport/src/org/gephi/desktop/importer/ReportPanel.java
@@ -1,590 +1,590 @@
/*
Copyright 2008 WebAtlas
Authors : Mathieu Bastian, Mathieu Jacomy, Julian Bilcke
Website : http://www.gephi.org
This file is part of Gephi.
Gephi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Gephi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.desktop.importer;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.Insets;
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.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
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.EdgeDefault;
import org.gephi.io.importer.api.Issue;
import org.gephi.io.importer.api.Report;
import org.gephi.io.processor.spi.Processor;
import org.gephi.ui.utils.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.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 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() {
public void run() {
initComponents();
initIcons();
initProcessors();
}
});
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
} catch (InvocationTargetException ex) {
Exceptions.printStackTrace(ex);
}
fillingThreads = new ThreadGroup("Report Panel Issues");
graphTypeCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int g = graphTypeCombo.getSelectedIndex();
switch (g) {
case 0:
container.getLoader().setEdgeDefault(EdgeDefault.DIRECTED);
break;
case 1:
container.getLoader().setEdgeDefault(EdgeDefault.UNDIRECTED);
break;
case 2:
container.getLoader().setEdgeDefault(EdgeDefault.MIXED);
break;
}
}
});
autoscaleCheckbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (autoscaleCheckbox.isSelected() != container.isAutoScale()) {
container.setAutoScale(autoscaleCheckbox.isSelected());
}
}
});
createMissingNodesCheckbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (createMissingNodesCheckbox.isSelected() != container.getUnloader().allowAutoNode()) {
container.setAllowAutoNode(createMissingNodesCheckbox.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;
fillIssues(report);
fillReport(report);
fillStats(container);
autoscaleCheckbox.setSelected(container.isAutoScale());
createMissingNodesCheckbox.setSelected(container.getUnloader().allowAutoNode());
}
private void fillIssues(Report report) {
final List<Issue> issues = report.getIssues();
if (issues.isEmpty()) {
JLabel label = new JLabel("No issue found during import");
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() {
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() {
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() {
public void run() {
final String str = report.getText();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
reportEditor.setText(str);
}
});
}
}, "Report Panel Issues Report");
if (NbPreferences.forModule(ReportPanel.class).getBoolean(SHOW_REPORT, true)) {
thread.start();
}
}
private void fillStats(final Container container) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Source
sourceLabel.setText(container.getSource());
//Autoscale
autoscaleCheckbox.setSelected(container.isAutoScale());
ContainerUnloader unloader = container.getUnloader();
//Node & Edge count
int nodeCount = unloader.getNodes().size();
int edgeCount = unloader.getEdges().size();
nodeCountLabel.setText("" + nodeCount);
edgeCountLabel.setText("" + edgeCount);
switch (unloader.getEdgeDefault()) {
case DIRECTED:
graphTypeCombo.setSelectedIndex(0);
break;
case UNDIRECTED:
graphTypeCombo.setSelectedIndex(1);
break;
case MIXED:
graphTypeCombo.setSelectedIndex(2);
break;
}
//Dynamic & Hierarchical graph
dynamicLabel.setText(container.isDynamicGraph() ? "yes" : "no");
hierarchicalLabel.setText(container.isHierarchicalGraph() ? "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, 1, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
processorPanel.add(radio, constraints);
}
}
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;
}
/** 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();
autoscaleCheckbox = new javax.swing.JCheckBox();
processorPanel = new javax.swing.JPanel();
createMissingNodesCheckbox = new javax.swing.JCheckBox();
jPanel1 = 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();
hierarchicalLabel = new javax.swing.JLabel();
labelHierarchical = new javax.swing.JLabel();
labelDynamic = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
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
graphTypeCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Directed", "Undirected", "Mixed" }));
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
processorPanel.setLayout(new java.awt.GridBagLayout());
createMissingNodesCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.text")); // NOI18N
jPanel1.setLayout(new java.awt.GridBagLayout());
labelNodeCount.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
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);
jPanel1.add(labelNodeCount, gridBagConstraints);
labelEdgeCount.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
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);
jPanel1.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);
jPanel1.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);
jPanel1.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);
jPanel1.add(dynamicLabel, gridBagConstraints);
hierarchicalLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.hierarchicalLabel.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, 0, 0);
jPanel1.add(hierarchicalLabel, gridBagConstraints);
labelHierarchical.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelHierarchical.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(labelHierarchical, 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);
jPanel1.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 = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
jPanel1.add(jLabel1, gridBagConstraints);
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, 545, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSrc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sourceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelGraphType)
.addGap(49, 49, 49)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 216, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 122, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(createMissingNodesCheckbox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(autoscaleCheckbox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE))
.addComponent(processorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSrc)
.addComponent(sourceLabel))
.addGap(18, 18, 18)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelGraphType)
.addComponent(autoscaleCheckbox)
.addComponent(graphTypeCombo, 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.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(createMissingNodesCheckbox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
- .addComponent(processorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
- .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addContainerGap())
+ .addComponent(processorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE)
+ .addContainerGap())
+ .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
}// </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 dynamicLabel;
private javax.swing.JLabel edgeCountLabel;
private javax.swing.JComboBox graphTypeCombo;
private javax.swing.JLabel hierarchicalLabel;
private org.netbeans.swing.outline.Outline issuesOutline;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel labelDynamic;
private javax.swing.JLabel labelEdgeCount;
private javax.swing.JLabel labelGraphType;
private javax.swing.JLabel labelHierarchical;
private javax.swing.JLabel labelNodeCount;
private javax.swing.JLabel labelSrc;
private javax.swing.JLabel nodeCountLabel;
private javax.swing.JPanel processorPanel;
private javax.swing.ButtonGroup processorStrategyRadio;
private javax.swing.JEditorPane reportEditor;
private javax.swing.JLabel sourceLabel;
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;
}
public Object getRoot() {
return "root";
}
public Object getChild(Object parent, int index) {
return issues.get(index);
}
public int getChildCount(Object parent) {
return issues.size();
}
public boolean isLeaf(Object node) {
if (node instanceof Issue) {
return true;
}
return false;
}
public void valueForPathChanged(TreePath path, Object newValue) {
}
public int getIndexOfChild(Object parent, Object child) {
return issues.indexOf(child);
}
public void addTreeModelListener(TreeModelListener l) {
}
public void removeTreeModelListener(TreeModelListener l) {
}
}
private class IssueRowModel implements RowModel {
public int getColumnCount() {
return 1;
}
public Object getValueFor(Object node, int column) {
if (node instanceof Issue) {
Issue issue = (Issue) node;
return issue.getLevel().toString();
}
return "";
}
public Class getColumnClass(int column) {
return String.class;
}
public boolean isCellEditable(Object node, int column) {
return false;
}
public void setValueFor(Object node, int column, Object value) {
}
public String getColumnName(int column) {
return "Issues";
}
}
private class IssueRenderer implements RenderDataProvider {
public String getDisplayName(Object o) {
Issue issue = (Issue) o;
return issue.getMessage();
}
public boolean isHtmlDisplayName(Object o) {
return false;
}
public Color getBackground(Object o) {
return null;
}
public Color getForeground(Object o) {
return null;
}
public String getTooltipText(Object o) {
return "";
}
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;
}
}
}
| true | 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();
autoscaleCheckbox = new javax.swing.JCheckBox();
processorPanel = new javax.swing.JPanel();
createMissingNodesCheckbox = new javax.swing.JCheckBox();
jPanel1 = 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();
hierarchicalLabel = new javax.swing.JLabel();
labelHierarchical = new javax.swing.JLabel();
labelDynamic = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
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
graphTypeCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Directed", "Undirected", "Mixed" }));
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
processorPanel.setLayout(new java.awt.GridBagLayout());
createMissingNodesCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.text")); // NOI18N
jPanel1.setLayout(new java.awt.GridBagLayout());
labelNodeCount.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
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);
jPanel1.add(labelNodeCount, gridBagConstraints);
labelEdgeCount.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
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);
jPanel1.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);
jPanel1.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);
jPanel1.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);
jPanel1.add(dynamicLabel, gridBagConstraints);
hierarchicalLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.hierarchicalLabel.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, 0, 0);
jPanel1.add(hierarchicalLabel, gridBagConstraints);
labelHierarchical.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelHierarchical.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(labelHierarchical, 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);
jPanel1.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 = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
jPanel1.add(jLabel1, gridBagConstraints);
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, 545, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSrc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sourceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelGraphType)
.addGap(49, 49, 49)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 216, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 122, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(createMissingNodesCheckbox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(autoscaleCheckbox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE))
.addComponent(processorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSrc)
.addComponent(sourceLabel))
.addGap(18, 18, 18)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelGraphType)
.addComponent(autoscaleCheckbox)
.addComponent(graphTypeCombo, 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.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(createMissingNodesCheckbox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(processorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
}// </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();
autoscaleCheckbox = new javax.swing.JCheckBox();
processorPanel = new javax.swing.JPanel();
createMissingNodesCheckbox = new javax.swing.JCheckBox();
jPanel1 = 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();
hierarchicalLabel = new javax.swing.JLabel();
labelHierarchical = new javax.swing.JLabel();
labelDynamic = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
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
graphTypeCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Directed", "Undirected", "Mixed" }));
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
processorPanel.setLayout(new java.awt.GridBagLayout());
createMissingNodesCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.text")); // NOI18N
jPanel1.setLayout(new java.awt.GridBagLayout());
labelNodeCount.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
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);
jPanel1.add(labelNodeCount, gridBagConstraints);
labelEdgeCount.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
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);
jPanel1.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);
jPanel1.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);
jPanel1.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);
jPanel1.add(dynamicLabel, gridBagConstraints);
hierarchicalLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.hierarchicalLabel.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, 0, 0);
jPanel1.add(hierarchicalLabel, gridBagConstraints);
labelHierarchical.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelHierarchical.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(labelHierarchical, 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);
jPanel1.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 = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
jPanel1.add(jLabel1, gridBagConstraints);
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, 545, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSrc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sourceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelGraphType)
.addGap(49, 49, 49)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 216, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 122, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(createMissingNodesCheckbox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(autoscaleCheckbox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE))
.addComponent(processorPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSrc)
.addComponent(sourceLabel))
.addGap(18, 18, 18)
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelGraphType)
.addComponent(autoscaleCheckbox)
.addComponent(graphTypeCombo, 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.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(createMissingNodesCheckbox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(processorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE)
.addContainerGap())
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/com/deliciousdroid/authenticator/OauthUtilities.java b/src/com/deliciousdroid/authenticator/OauthUtilities.java
index fe906aa..a89ddce 100644
--- a/src/com/deliciousdroid/authenticator/OauthUtilities.java
+++ b/src/com/deliciousdroid/authenticator/OauthUtilities.java
@@ -1,112 +1,112 @@
/*
* DeliciousDroid - http://code.google.com/p/DeliciousDroid/
*
* Copyright (C) 2010 Matt Schmidt
*
* DeliciousDroid 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.
*
* DeliciousDroid 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 DeliciousDroid; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package com.deliciousdroid.authenticator;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Random;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.http.client.methods.HttpGet;
import android.util.Log;
import com.deliciousdroid.Constants;
import com.deliciousdroid.util.Base64;
public class OauthUtilities {
public static HttpGet signRequest(HttpGet request, TreeMap<String, String> params, String authtoken,
String tokenSecret){
Random r = new Random();
String nonce = Long.toString(Math.abs(r.nextLong()), 36);
Date d = new Date();
String timestamp = Long.toString(d.getTime() / 1000);
params.put(Constants.OAUTH_COMSUMER_KEY_PROPERTY, Constants.OAUTH_CONSUMER_KEY);
params.put(Constants.OAUTH_NONCE_PROPERTY, nonce);
params.put(Constants.OAUTH_SIGNATURE_METHOD_PROPERTY, Constants.OAUTH_SIGNATURE_METHOD_HMAC);
params.put(Constants.OAUTH_TIMESTAMP_PROPERTY, timestamp);
params.put(Constants.OAUTH_TOKEN_PROPERTY, authtoken);
params.put(Constants.OAUTH_VERSION_PROPERTY, Constants.OAUTH_VERSION);
URI u = request.getURI();
String url = u.getScheme() + "://" + u.getAuthority() + u.getPath();
StringBuilder sb = new StringBuilder();
sb.append("GET");
sb.append("&" + URLEncoder.encode(url));
for(String key : params.keySet()){
if(params.firstKey() == key){
sb.append("&");
} else {
sb.append("%26");
}
sb.append(URLEncoder.encode(key) + "%3D");
- sb.append(URLEncoder.encode(params.get(key)).replace("+", "%2B").replace("%7C", "%257C"));
+ sb.append(URLEncoder.encode(params.get(key)).replace("+", "%2B").replace("%7C", "%257C").replace("%2C", "%252C"));
}
Log.d("base string", sb.toString().replace("%23", "%2523"));
String keystring = Constants.OAUTH_SHARED_SECRET + "&" + tokenSecret;
SecretKeySpec sha1key = new SecretKeySpec(keystring.getBytes(), "HmacSHA1");
String signature = null;
try{
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(sha1key);
byte[] sigBytes = mac.doFinal(sb.toString().replace("%23", "%2523").getBytes());
signature = Base64.encodeBytes(sigBytes);
}
catch(Exception e){
Log.e("Oauth Sign Request", "Hash Error");
}
StringBuilder authHeader = new StringBuilder();
authHeader.append("OAuth realm=\"yahooapis.com\"");
authHeader.append("," + Constants.OAUTH_COMSUMER_KEY_PROPERTY + "=");
authHeader.append("\"" + Constants.OAUTH_CONSUMER_KEY + "\"");
authHeader.append("," + Constants.OAUTH_NONCE_PROPERTY + "=");
authHeader.append("\"" + nonce + "\"");
authHeader.append("," + Constants.OAUTH_SIGNATURE_PROPERTY + "=");
authHeader.append("\"" + signature + "\"");
authHeader.append("," + Constants.OAUTH_SIGNATURE_METHOD_PROPERTY + "=");
authHeader.append("\"" + Constants.OAUTH_SIGNATURE_METHOD_HMAC + "\"");
authHeader.append("," + Constants.OAUTH_TIMESTAMP_PROPERTY + "=");
authHeader.append("\"" + timestamp + "\"");
authHeader.append("," + Constants.OAUTH_TOKEN_PROPERTY + "=");
authHeader.append("\"" + authtoken + "\"");
authHeader.append("," + Constants.OAUTH_VERSION_PROPERTY + "=");
authHeader.append("\"" + Constants.OAUTH_VERSION + "\"");
request.setHeader("Authorization", authHeader.toString());
return request;
}
}
| true | true | public static HttpGet signRequest(HttpGet request, TreeMap<String, String> params, String authtoken,
String tokenSecret){
Random r = new Random();
String nonce = Long.toString(Math.abs(r.nextLong()), 36);
Date d = new Date();
String timestamp = Long.toString(d.getTime() / 1000);
params.put(Constants.OAUTH_COMSUMER_KEY_PROPERTY, Constants.OAUTH_CONSUMER_KEY);
params.put(Constants.OAUTH_NONCE_PROPERTY, nonce);
params.put(Constants.OAUTH_SIGNATURE_METHOD_PROPERTY, Constants.OAUTH_SIGNATURE_METHOD_HMAC);
params.put(Constants.OAUTH_TIMESTAMP_PROPERTY, timestamp);
params.put(Constants.OAUTH_TOKEN_PROPERTY, authtoken);
params.put(Constants.OAUTH_VERSION_PROPERTY, Constants.OAUTH_VERSION);
URI u = request.getURI();
String url = u.getScheme() + "://" + u.getAuthority() + u.getPath();
StringBuilder sb = new StringBuilder();
sb.append("GET");
sb.append("&" + URLEncoder.encode(url));
for(String key : params.keySet()){
if(params.firstKey() == key){
sb.append("&");
} else {
sb.append("%26");
}
sb.append(URLEncoder.encode(key) + "%3D");
sb.append(URLEncoder.encode(params.get(key)).replace("+", "%2B").replace("%7C", "%257C"));
}
Log.d("base string", sb.toString().replace("%23", "%2523"));
String keystring = Constants.OAUTH_SHARED_SECRET + "&" + tokenSecret;
SecretKeySpec sha1key = new SecretKeySpec(keystring.getBytes(), "HmacSHA1");
String signature = null;
try{
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(sha1key);
byte[] sigBytes = mac.doFinal(sb.toString().replace("%23", "%2523").getBytes());
signature = Base64.encodeBytes(sigBytes);
}
catch(Exception e){
Log.e("Oauth Sign Request", "Hash Error");
}
StringBuilder authHeader = new StringBuilder();
authHeader.append("OAuth realm=\"yahooapis.com\"");
authHeader.append("," + Constants.OAUTH_COMSUMER_KEY_PROPERTY + "=");
authHeader.append("\"" + Constants.OAUTH_CONSUMER_KEY + "\"");
authHeader.append("," + Constants.OAUTH_NONCE_PROPERTY + "=");
authHeader.append("\"" + nonce + "\"");
authHeader.append("," + Constants.OAUTH_SIGNATURE_PROPERTY + "=");
authHeader.append("\"" + signature + "\"");
authHeader.append("," + Constants.OAUTH_SIGNATURE_METHOD_PROPERTY + "=");
authHeader.append("\"" + Constants.OAUTH_SIGNATURE_METHOD_HMAC + "\"");
authHeader.append("," + Constants.OAUTH_TIMESTAMP_PROPERTY + "=");
authHeader.append("\"" + timestamp + "\"");
authHeader.append("," + Constants.OAUTH_TOKEN_PROPERTY + "=");
authHeader.append("\"" + authtoken + "\"");
authHeader.append("," + Constants.OAUTH_VERSION_PROPERTY + "=");
authHeader.append("\"" + Constants.OAUTH_VERSION + "\"");
request.setHeader("Authorization", authHeader.toString());
return request;
}
| public static HttpGet signRequest(HttpGet request, TreeMap<String, String> params, String authtoken,
String tokenSecret){
Random r = new Random();
String nonce = Long.toString(Math.abs(r.nextLong()), 36);
Date d = new Date();
String timestamp = Long.toString(d.getTime() / 1000);
params.put(Constants.OAUTH_COMSUMER_KEY_PROPERTY, Constants.OAUTH_CONSUMER_KEY);
params.put(Constants.OAUTH_NONCE_PROPERTY, nonce);
params.put(Constants.OAUTH_SIGNATURE_METHOD_PROPERTY, Constants.OAUTH_SIGNATURE_METHOD_HMAC);
params.put(Constants.OAUTH_TIMESTAMP_PROPERTY, timestamp);
params.put(Constants.OAUTH_TOKEN_PROPERTY, authtoken);
params.put(Constants.OAUTH_VERSION_PROPERTY, Constants.OAUTH_VERSION);
URI u = request.getURI();
String url = u.getScheme() + "://" + u.getAuthority() + u.getPath();
StringBuilder sb = new StringBuilder();
sb.append("GET");
sb.append("&" + URLEncoder.encode(url));
for(String key : params.keySet()){
if(params.firstKey() == key){
sb.append("&");
} else {
sb.append("%26");
}
sb.append(URLEncoder.encode(key) + "%3D");
sb.append(URLEncoder.encode(params.get(key)).replace("+", "%2B").replace("%7C", "%257C").replace("%2C", "%252C"));
}
Log.d("base string", sb.toString().replace("%23", "%2523"));
String keystring = Constants.OAUTH_SHARED_SECRET + "&" + tokenSecret;
SecretKeySpec sha1key = new SecretKeySpec(keystring.getBytes(), "HmacSHA1");
String signature = null;
try{
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(sha1key);
byte[] sigBytes = mac.doFinal(sb.toString().replace("%23", "%2523").getBytes());
signature = Base64.encodeBytes(sigBytes);
}
catch(Exception e){
Log.e("Oauth Sign Request", "Hash Error");
}
StringBuilder authHeader = new StringBuilder();
authHeader.append("OAuth realm=\"yahooapis.com\"");
authHeader.append("," + Constants.OAUTH_COMSUMER_KEY_PROPERTY + "=");
authHeader.append("\"" + Constants.OAUTH_CONSUMER_KEY + "\"");
authHeader.append("," + Constants.OAUTH_NONCE_PROPERTY + "=");
authHeader.append("\"" + nonce + "\"");
authHeader.append("," + Constants.OAUTH_SIGNATURE_PROPERTY + "=");
authHeader.append("\"" + signature + "\"");
authHeader.append("," + Constants.OAUTH_SIGNATURE_METHOD_PROPERTY + "=");
authHeader.append("\"" + Constants.OAUTH_SIGNATURE_METHOD_HMAC + "\"");
authHeader.append("," + Constants.OAUTH_TIMESTAMP_PROPERTY + "=");
authHeader.append("\"" + timestamp + "\"");
authHeader.append("," + Constants.OAUTH_TOKEN_PROPERTY + "=");
authHeader.append("\"" + authtoken + "\"");
authHeader.append("," + Constants.OAUTH_VERSION_PROPERTY + "=");
authHeader.append("\"" + Constants.OAUTH_VERSION + "\"");
request.setHeader("Authorization", authHeader.toString());
return request;
}
|
diff --git a/Model/src/java/fr/cg95/cvq/service/request/impl/RequestActionService.java b/Model/src/java/fr/cg95/cvq/service/request/impl/RequestActionService.java
index c57e2d7e7..10abd2150 100644
--- a/Model/src/java/fr/cg95/cvq/service/request/impl/RequestActionService.java
+++ b/Model/src/java/fr/cg95/cvq/service/request/impl/RequestActionService.java
@@ -1,148 +1,149 @@
package fr.cg95.cvq.service.request.impl;
import fr.cg95.cvq.business.request.Request;
import fr.cg95.cvq.business.request.RequestAction;
import fr.cg95.cvq.business.request.RequestActionType;
import fr.cg95.cvq.business.request.RequestState;
import fr.cg95.cvq.business.request.ecitizen.VoCardRequest;
import fr.cg95.cvq.dao.request.IRequestActionDAO;
import fr.cg95.cvq.dao.request.IRequestDAO;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.exception.CvqObjectNotFoundException;
import fr.cg95.cvq.security.SecurityContext;
import fr.cg95.cvq.security.annotation.Context;
import fr.cg95.cvq.security.annotation.ContextPrivilege;
import fr.cg95.cvq.security.annotation.ContextType;
import fr.cg95.cvq.service.request.IRequestActionService;
import fr.cg95.cvq.service.request.annotation.IsRequest;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* @author [email protected]
*/
public class RequestActionService implements IRequestActionService {
private IRequestActionDAO requestActionDAO;
private IRequestDAO requestDAO;
@Override
@Context(type=ContextType.ECITIZEN_AGENT,privilege=ContextPrivilege.READ)
public List<RequestAction> getActions(final Long requestId)
throws CvqException {
return requestActionDAO.listByRequest(requestId);
}
@Override
@Context(type=ContextType.ECITIZEN_AGENT,privilege=ContextPrivilege.READ)
public RequestAction getAction(final Long id)
throws CvqObjectNotFoundException {
return
(RequestAction)requestActionDAO.findById(RequestAction.class, id);
}
@Context(type=ContextType.ECITIZEN_AGENT,privilege=ContextPrivilege.READ)
public RequestAction getLastWorkflowAction(@IsRequest final Long requestId)
throws CvqException {
return requestActionDAO.findLastAction(requestId,
RequestActionType.STATE_CHANGE);
}
@Override
@Context(type=ContextType.ECITIZEN_AGENT,privilege=ContextPrivilege.READ)
public RequestAction getActionByResultingState(final Long requestId,
final RequestState requestState) throws CvqException {
return requestActionDAO.findByRequestIdAndResultingState(requestId, requestState);
}
@Override
public boolean hasAction(final Long requestId, final RequestActionType type)
throws CvqException {
return requestActionDAO.hasAction(requestId, type);
}
@Override
@Context(type=ContextType.AGENT,privilege=ContextPrivilege.WRITE)
public void addAction(final Long requestId, final RequestActionType type,
final String message, final String note, final byte[] pdfData)
throws CvqException {
addActionTrace(type, message, note, new Date(), null, requestId, pdfData);
}
@Override
@Context(type=ContextType.SUPER_ADMIN,privilege=ContextPrivilege.WRITE)
public void addSystemAction(final Long requestId,
final RequestActionType type)
throws CvqException {
addActionTrace(type, null, null, new Date(), null, requestId, null);
}
@Override
public void addCreationAction(Long requestId, Date date, byte[] pdfData)
throws CvqException {
addActionTrace(RequestActionType.CREATION, null, null, date,
RequestState.PENDING, requestId, pdfData);
}
@Override
@Context(type=ContextType.ECITIZEN_AGENT,privilege=ContextPrivilege.WRITE)
public void addWorfklowAction(final Long requestId, final String note, final Date date,
final RequestState resultingState, final byte[] pdfData)
throws CvqException {
addActionTrace(RequestActionType.STATE_CHANGE, null, note, date,
resultingState, requestId, pdfData);
}
private void addActionTrace(final RequestActionType type, final String message,
final String note, final Date date, final RequestState resultingState,
final Long requestId, final byte[] pdfData)
throws CvqException {
Request request = (Request) requestDAO.findById(Request.class, requestId);
// retrieve user or agent id according to context
Long userId = SecurityContext.getCurrentUserId();
if (userId == null && request instanceof VoCardRequest) {
VoCardRequest vocr = (VoCardRequest) request;
// there can't be a logged in user at VO card request creation time
userId = vocr.getRequesterId();
}
RequestAction requestAction = new RequestAction();
requestAction.setAgentId(userId);
requestAction.setType(type);
requestAction.setMessage(message);
requestAction.setNote(note);
requestAction.setDate(date);
requestAction.setResultingState(resultingState);
requestAction.setFile(pdfData);
+ requestAction.setRequest(request);
if (request.getActions() == null) {
Set<RequestAction> actionsSet = new HashSet<RequestAction>();
actionsSet.add(requestAction);
request.setActions(actionsSet);
} else {
request.getActions().add(requestAction);
}
requestDAO.update(request);
}
public void setRequestActionDAO(IRequestActionDAO requestActionDAO) {
this.requestActionDAO = requestActionDAO;
}
public void setRequestDAO(IRequestDAO requestDAO) {
this.requestDAO = requestDAO;
}
}
| true | true | private void addActionTrace(final RequestActionType type, final String message,
final String note, final Date date, final RequestState resultingState,
final Long requestId, final byte[] pdfData)
throws CvqException {
Request request = (Request) requestDAO.findById(Request.class, requestId);
// retrieve user or agent id according to context
Long userId = SecurityContext.getCurrentUserId();
if (userId == null && request instanceof VoCardRequest) {
VoCardRequest vocr = (VoCardRequest) request;
// there can't be a logged in user at VO card request creation time
userId = vocr.getRequesterId();
}
RequestAction requestAction = new RequestAction();
requestAction.setAgentId(userId);
requestAction.setType(type);
requestAction.setMessage(message);
requestAction.setNote(note);
requestAction.setDate(date);
requestAction.setResultingState(resultingState);
requestAction.setFile(pdfData);
if (request.getActions() == null) {
Set<RequestAction> actionsSet = new HashSet<RequestAction>();
actionsSet.add(requestAction);
request.setActions(actionsSet);
} else {
request.getActions().add(requestAction);
}
requestDAO.update(request);
}
| private void addActionTrace(final RequestActionType type, final String message,
final String note, final Date date, final RequestState resultingState,
final Long requestId, final byte[] pdfData)
throws CvqException {
Request request = (Request) requestDAO.findById(Request.class, requestId);
// retrieve user or agent id according to context
Long userId = SecurityContext.getCurrentUserId();
if (userId == null && request instanceof VoCardRequest) {
VoCardRequest vocr = (VoCardRequest) request;
// there can't be a logged in user at VO card request creation time
userId = vocr.getRequesterId();
}
RequestAction requestAction = new RequestAction();
requestAction.setAgentId(userId);
requestAction.setType(type);
requestAction.setMessage(message);
requestAction.setNote(note);
requestAction.setDate(date);
requestAction.setResultingState(resultingState);
requestAction.setFile(pdfData);
requestAction.setRequest(request);
if (request.getActions() == null) {
Set<RequestAction> actionsSet = new HashSet<RequestAction>();
actionsSet.add(requestAction);
request.setActions(actionsSet);
} else {
request.getActions().add(requestAction);
}
requestDAO.update(request);
}
|
diff --git a/6.830-lab_1/test/simpledb/systemtest/TransactionTest.java b/6.830-lab_1/test/simpledb/systemtest/TransactionTest.java
index 4d69d70..57a8c34 100644
--- a/6.830-lab_1/test/simpledb/systemtest/TransactionTest.java
+++ b/6.830-lab_1/test/simpledb/systemtest/TransactionTest.java
@@ -1,268 +1,268 @@
package simpledb.systemtest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import simpledb.Database;
import simpledb.Transaction;
import simpledb.TransactionId;
import simpledb.exceptions.DbException;
import simpledb.exceptions.TransactionAbortedException;
import simpledb.file.DbFile;
import simpledb.file.DbFileIterator;
import simpledb.file.HeapFile;
import simpledb.operators.Delete;
import simpledb.operators.Insert;
import simpledb.operators.SeqScan;
import simpledb.operators.TupleIterator;
import simpledb.parser.Query;
import simpledb.tuple.IntField;
import simpledb.tuple.Tuple;
/**
* Tests running concurrent transactions.
* You do not need to pass this test until lab3.
*/
public class TransactionTest extends SimpleDbTestBase {
// Wait up to 10 minutes for the test to complete
private static final int TIMEOUT_MILLIS = 10 * 60 * 1000;
private void validateTransactions(int threads)
throws DbException, TransactionAbortedException, IOException {
// Create a table with a single integer value = 0
HashMap<Integer, Integer> columnSpecification = new HashMap<Integer, Integer>();
columnSpecification.put(0, 0);
DbFile table = SystemTestUtil.createRandomHeapFile(1, 1, columnSpecification, null);
ModifiableCyclicBarrier latch = new ModifiableCyclicBarrier(threads);
XactionTester[] list = new XactionTester[threads];
for(int i = 0; i < list.length; i++) {
list[i] = new XactionTester(table.getId(), latch);
list[i].start();
}
long stopTestTime = System.currentTimeMillis() + TIMEOUT_MILLIS;
for (XactionTester tester : list) {
long timeout = stopTestTime - System.currentTimeMillis();
if (timeout <= 0) {
fail("Timed out waiting for transaction to complete");
}
try {
tester.join(timeout);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (tester.isAlive()) {
fail("Timed out waiting for transaction to complete");
}
if (tester.exception != null) {
// Rethrow any exception from a child thread
assert tester.exception != null;
throw new RuntimeException("Child thread threw an exception.", tester.exception);
}
assert tester.completed;
}
// Check that the table has the correct value
TransactionId tid = new TransactionId();
DbFileIterator it = table.iterator(tid);
it.open();
Tuple tup = it.next();
assertEquals(threads, ((IntField) tup.getField(0)).getValue());
it.close();
Database.getBufferPool().transactionComplete(tid);
Database.getBufferPool().flushAllPages();
}
private static class XactionTester extends Thread {
private final int tableId;
private final ModifiableCyclicBarrier latch;
public Exception exception = null;
public boolean completed = false;
public XactionTester(int tableId, ModifiableCyclicBarrier latch) {
this.tableId = tableId;
this.latch = latch;
}
public void run() {
try {
// Try to increment the value until we manage to successfully commit
while (true) {
// Wait for all threads to be ready
latch.await();
Transaction tr = new Transaction();
try {
tr.start();
SeqScan ss1 = new SeqScan(tr.getId(), tableId, "");
SeqScan ss2 = new SeqScan(tr.getId(), tableId, "");
// read the value out of the table
Query q1 = new Query(ss1, tr.getId());
q1.start();
Tuple tup = q1.next();
IntField intf = (IntField) tup.getField(0);
int i = intf.getValue();
// create a Tuple so that Insert can insert this new value
// into the table.
Tuple t = new Tuple(SystemTestUtil.SINGLE_INT_DESCRIPTOR);
t.setField(0, new IntField(i+1));
// sleep to get some interesting thread interleavings
Thread.sleep(1);
// race the other threads to finish the transaction: one will win
q1.close();
// delete old values (i.e., just one row) from table
- Delete delOp = new Delete(tr.getId(), ss2);
+ Delete delOp = new Delete(tr.getId(),tableId, ss2);
Query q2 = new Query(delOp, tr.getId());
q2.start();
q2.next();
q2.close();
// set up a Set with a tuple that is one higher than the old one.
HashSet<Tuple> hs = new HashSet<Tuple>();
hs.add(t);
TupleIterator ti = new TupleIterator(t.getTupleDesc(), hs);
// insert this new tuple into the table
Insert insOp = new Insert(tr.getId(), ti, tableId);
Query q3 = new Query(insOp, tr.getId());
q3.start();
q3.next();
q3.close();
tr.commit();
break;
} catch (TransactionAbortedException te) {
//System.out.println("thread " + tr.getId() + " killed");
// give someone else a chance: abort the transaction
tr.transactionComplete(true);
latch.stillParticipating();
}
}
//System.out.println("thread " + id + " done");
} catch (Exception e) {
// Store exception for the master thread to handle
exception = e;
}
try {
latch.notParticipating();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
completed = true;
}
}
private static class ModifiableCyclicBarrier {
private CountDownLatch awaitLatch;
private CyclicBarrier participationLatch;
private AtomicInteger nextParticipants;
public ModifiableCyclicBarrier(int parties) {
reset(parties);
}
private void reset(int parties) {
nextParticipants = new AtomicInteger(0);
awaitLatch = new CountDownLatch(parties);
participationLatch = new CyclicBarrier(parties, new UpdateLatch(this, nextParticipants));
}
public void await() throws InterruptedException, BrokenBarrierException {
awaitLatch.countDown();
awaitLatch.await();
}
public void notParticipating() throws InterruptedException, BrokenBarrierException {
participationLatch.await();
}
public void stillParticipating() throws InterruptedException, BrokenBarrierException {
nextParticipants.incrementAndGet();
participationLatch.await();
}
private static class UpdateLatch implements Runnable {
ModifiableCyclicBarrier latch;
AtomicInteger nextParticipants;
public UpdateLatch(ModifiableCyclicBarrier latch, AtomicInteger nextParticipants) {
this.latch = latch;
this.nextParticipants = nextParticipants;
}
public void run() {
// Reset this barrier if there are threads still running
int participants = nextParticipants.get();
if (participants > 0) {
latch.reset(participants);
}
}
}
}
@Test public void testSingleThread()
throws IOException, DbException, TransactionAbortedException {
validateTransactions(1);
}
@Test public void testTwoThreads()
throws IOException, DbException, TransactionAbortedException {
validateTransactions(2);
}
@Test public void testFiveThreads()
throws IOException, DbException, TransactionAbortedException {
validateTransactions(5);
}
@Test public void testTenThreads()
throws IOException, DbException, TransactionAbortedException {
validateTransactions(10);
}
@Test public void testAllDirtyFails()
throws IOException, DbException, TransactionAbortedException {
// Allocate a file with ~10 pages of data
HeapFile f = SystemTestUtil.createRandomHeapFile(2, 512*10, null, null);
Database.resetBufferPool(1);
// BEGIN TRANSACTION
Transaction t = new Transaction();
t.start();
// Insert a new row
EvictionTest.insertRow(f, t);
// Scanning the table must fail because it can't evict the dirty page
try {
EvictionTest.findMagicTuple(f, t);
fail("Expected scan to run out of available buffer pages");
} catch (DbException e) {}
t.commit();
}
/** Make test compatible with older version of ant. */
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(TransactionTest.class);
}
}
| true | true | public void run() {
try {
// Try to increment the value until we manage to successfully commit
while (true) {
// Wait for all threads to be ready
latch.await();
Transaction tr = new Transaction();
try {
tr.start();
SeqScan ss1 = new SeqScan(tr.getId(), tableId, "");
SeqScan ss2 = new SeqScan(tr.getId(), tableId, "");
// read the value out of the table
Query q1 = new Query(ss1, tr.getId());
q1.start();
Tuple tup = q1.next();
IntField intf = (IntField) tup.getField(0);
int i = intf.getValue();
// create a Tuple so that Insert can insert this new value
// into the table.
Tuple t = new Tuple(SystemTestUtil.SINGLE_INT_DESCRIPTOR);
t.setField(0, new IntField(i+1));
// sleep to get some interesting thread interleavings
Thread.sleep(1);
// race the other threads to finish the transaction: one will win
q1.close();
// delete old values (i.e., just one row) from table
Delete delOp = new Delete(tr.getId(), ss2);
Query q2 = new Query(delOp, tr.getId());
q2.start();
q2.next();
q2.close();
// set up a Set with a tuple that is one higher than the old one.
HashSet<Tuple> hs = new HashSet<Tuple>();
hs.add(t);
TupleIterator ti = new TupleIterator(t.getTupleDesc(), hs);
// insert this new tuple into the table
Insert insOp = new Insert(tr.getId(), ti, tableId);
Query q3 = new Query(insOp, tr.getId());
q3.start();
q3.next();
q3.close();
tr.commit();
break;
} catch (TransactionAbortedException te) {
//System.out.println("thread " + tr.getId() + " killed");
// give someone else a chance: abort the transaction
tr.transactionComplete(true);
latch.stillParticipating();
}
}
//System.out.println("thread " + id + " done");
} catch (Exception e) {
// Store exception for the master thread to handle
exception = e;
}
try {
latch.notParticipating();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
completed = true;
}
| public void run() {
try {
// Try to increment the value until we manage to successfully commit
while (true) {
// Wait for all threads to be ready
latch.await();
Transaction tr = new Transaction();
try {
tr.start();
SeqScan ss1 = new SeqScan(tr.getId(), tableId, "");
SeqScan ss2 = new SeqScan(tr.getId(), tableId, "");
// read the value out of the table
Query q1 = new Query(ss1, tr.getId());
q1.start();
Tuple tup = q1.next();
IntField intf = (IntField) tup.getField(0);
int i = intf.getValue();
// create a Tuple so that Insert can insert this new value
// into the table.
Tuple t = new Tuple(SystemTestUtil.SINGLE_INT_DESCRIPTOR);
t.setField(0, new IntField(i+1));
// sleep to get some interesting thread interleavings
Thread.sleep(1);
// race the other threads to finish the transaction: one will win
q1.close();
// delete old values (i.e., just one row) from table
Delete delOp = new Delete(tr.getId(),tableId, ss2);
Query q2 = new Query(delOp, tr.getId());
q2.start();
q2.next();
q2.close();
// set up a Set with a tuple that is one higher than the old one.
HashSet<Tuple> hs = new HashSet<Tuple>();
hs.add(t);
TupleIterator ti = new TupleIterator(t.getTupleDesc(), hs);
// insert this new tuple into the table
Insert insOp = new Insert(tr.getId(), ti, tableId);
Query q3 = new Query(insOp, tr.getId());
q3.start();
q3.next();
q3.close();
tr.commit();
break;
} catch (TransactionAbortedException te) {
//System.out.println("thread " + tr.getId() + " killed");
// give someone else a chance: abort the transaction
tr.transactionComplete(true);
latch.stillParticipating();
}
}
//System.out.println("thread " + id + " done");
} catch (Exception e) {
// Store exception for the master thread to handle
exception = e;
}
try {
latch.notParticipating();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
completed = true;
}
|
diff --git a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java
index 9aaf9f898..7609b44d1 100644
--- a/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java
+++ b/driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java
@@ -1,197 +1,197 @@
/*
* Copyright (C) 2012 DataStax Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.driver.core.querybuilder;
import java.net.InetAddress;
import java.util.*;
import java.util.regex.Pattern;
// Static utilities private to the query builder
abstract class Utils {
private static final Pattern cnamePattern = Pattern.compile("\\w+(?:\\[.+\\])?", Pattern.CASE_INSENSITIVE);
private static final Pattern fctsPattern = Pattern.compile("(?:count|writetime|ttl|token)\\(.*", Pattern.CASE_INSENSITIVE);
static StringBuilder joinAndAppend(StringBuilder sb, String separator, List<? extends Appendeable> values) {
for (int i = 0; i < values.size(); i++) {
if (i > 0)
sb.append(separator);
values.get(i).appendTo(sb);
}
return sb;
}
static StringBuilder joinAndAppendNames(StringBuilder sb, String separator, List<String> values) {
for (int i = 0; i < values.size(); i++) {
if (i > 0)
sb.append(separator);
appendName(values.get(i), sb);
}
return sb;
}
static StringBuilder joinAndAppendValues(StringBuilder sb, String separator, List<Object> values) {
for (int i = 0; i < values.size(); i++) {
if (i > 0)
sb.append(separator);
appendValue(values.get(i), sb);
}
return sb;
}
static StringBuilder appendValue(Object value, StringBuilder sb) {
return appendValue(value, sb, false);
}
static StringBuilder appendFlatValue(Object value, StringBuilder sb) {
appendFlatValue(value, sb, false);
return sb;
}
private static StringBuilder appendValue(Object value, StringBuilder sb, boolean rawValue) {
// That is kind of lame but lacking a better solution
if (appendValueIfLiteral(value, sb))
return sb;
if (appendValueIfCollection(value, sb, rawValue))
return sb;
if (rawValue)
return sb.append(value.toString());
else
return appendValueString(value.toString(), sb);
}
private static void appendFlatValue(Object value, StringBuilder sb, boolean rawValue) {
if (appendValueIfLiteral(value, sb))
return;
if (rawValue)
sb.append(value.toString());
else
appendValueString(value.toString(), sb);
}
private static boolean appendValueIfLiteral(Object value, StringBuilder sb) {
- if (value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof UUID) {
+ if (value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof UUID || value instanceof Boolean) {
sb.append(value);
return true;
} else if (value instanceof InetAddress) {
sb.append(((InetAddress)value).getHostAddress());
return true;
} else if (value instanceof Date) {
sb.append(((Date)value).getTime());
return true;
} else if (value == QueryBuilder.BIND_MARKER) {
sb.append("?");
return true;
} else {
return false;
}
}
private static boolean appendValueIfCollection(Object value, StringBuilder sb, boolean rawValue) {
if (value instanceof List) {
appendList((List)value, sb, rawValue);
return true;
} else if (value instanceof Set) {
appendSet((Set)value, sb, rawValue);
return true;
} else if (value instanceof Map) {
appendMap((Map)value, sb, rawValue);
return true;
} else {
return false;
}
}
static StringBuilder appendCollection(Object value, StringBuilder sb) {
boolean wasCollection = appendValueIfCollection(value, sb, false);
assert wasCollection;
return sb;
}
static StringBuilder appendList(List<?> l, StringBuilder sb) {
return appendList(l, sb, false);
}
private static StringBuilder appendList(List<?> l, StringBuilder sb, boolean rawValue) {
sb.append("[");
for (int i = 0; i < l.size(); i++) {
if (i > 0)
sb.append(",");
appendFlatValue(l.get(i), sb, rawValue);
}
sb.append("]");
return sb;
}
static StringBuilder appendSet(Set<?> s, StringBuilder sb) {
return appendSet(s, sb, false);
}
private static StringBuilder appendSet(Set<?> s, StringBuilder sb, boolean rawValue) {
sb.append("{");
boolean first = true;
for (Object elt : s) {
if (first) first = false; else sb.append(",");
appendFlatValue(elt, sb, rawValue);
}
sb.append("}");
return sb;
}
static StringBuilder appendMap(Map<?, ?> m, StringBuilder sb) {
return appendMap(m, sb, false);
}
private static StringBuilder appendMap(Map<?, ?> m, StringBuilder sb, boolean rawValue) {
sb.append("{");
boolean first = true;
for (Map.Entry<?, ?> entry : m.entrySet()) {
if (first)
first = false;
else
sb.append(",");
appendFlatValue(entry.getKey(), sb, rawValue);
sb.append(":");
appendFlatValue(entry.getValue(), sb, rawValue);
}
sb.append("}");
return sb;
}
private static StringBuilder appendValueString(String value, StringBuilder sb) {
return sb.append("'").append(value.replace("'", "''")).append("'");
}
static String toRawString(Object value) {
return appendValue(value, new StringBuilder(), true).toString();
}
static StringBuilder appendName(String name, StringBuilder sb) {
name = name.trim();
if (cnamePattern.matcher(name).matches() || name.startsWith("\"") || fctsPattern.matcher(name).matches())
sb.append(name);
else
sb.append("\"").append(name).append("\"");
return sb;
}
static abstract class Appendeable {
abstract void appendTo(StringBuilder sb);
}
}
| true | true | private static boolean appendValueIfLiteral(Object value, StringBuilder sb) {
if (value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof UUID) {
sb.append(value);
return true;
} else if (value instanceof InetAddress) {
sb.append(((InetAddress)value).getHostAddress());
return true;
} else if (value instanceof Date) {
sb.append(((Date)value).getTime());
return true;
} else if (value == QueryBuilder.BIND_MARKER) {
sb.append("?");
return true;
} else {
return false;
}
}
| private static boolean appendValueIfLiteral(Object value, StringBuilder sb) {
if (value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof UUID || value instanceof Boolean) {
sb.append(value);
return true;
} else if (value instanceof InetAddress) {
sb.append(((InetAddress)value).getHostAddress());
return true;
} else if (value instanceof Date) {
sb.append(((Date)value).getTime());
return true;
} else if (value == QueryBuilder.BIND_MARKER) {
sb.append("?");
return true;
} else {
return false;
}
}
|
diff --git a/src/net/slipcor/pvparena/managers/SpawnManager.java b/src/net/slipcor/pvparena/managers/SpawnManager.java
index b18f0eef..6d2c0e76 100644
--- a/src/net/slipcor/pvparena/managers/SpawnManager.java
+++ b/src/net/slipcor/pvparena/managers/SpawnManager.java
@@ -1,282 +1,282 @@
package net.slipcor.pvparena.managers;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import net.slipcor.pvparena.PVPArena;
import net.slipcor.pvparena.arena.Arena;
import net.slipcor.pvparena.arena.ArenaPlayer;
import net.slipcor.pvparena.arena.ArenaTeam;
import net.slipcor.pvparena.classes.PABlockLocation;
import net.slipcor.pvparena.classes.PALocation;
import net.slipcor.pvparena.core.Config;
import net.slipcor.pvparena.core.Debug;
import org.bukkit.entity.Player;
/**
* <pre>Spawn Manager class</pre>
*
* Provides static methods to manage Spawns
*
* @author slipcor
*
* @version v0.9.6
*/
public class SpawnManager {
private static Debug db = new Debug(27);
public static HashSet<PABlockLocation> getBlocks(Arena arena, String sTeam) {
db.i("reading blocks of arena " + arena + " (" + sTeam + ")");
HashSet<PABlockLocation> result = new HashSet<PABlockLocation>();
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (sTeam.equals("flags")) {
if (!name.startsWith("flag")) {
continue;
}
} else if (name.endsWith("flag")) {
String sName = sTeam.replace("flag", "");
db.i("checking if " + name + " starts with " + sName);
if (!name.startsWith(sName)) {
continue;
}
} else if (sTeam.equals("free")) {
if (!name.startsWith("spawn")) {
continue;
}
} else if (name.contains("lounge")) {
continue;
} else if (sTeam.endsWith("flag") || sTeam.endsWith("pumpkin")) {
continue;
}
db.i(" - " + name);
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + name));
result.add(Config.parseBlockLocation( sLoc));
}
return result;
}
/**
* get the location from a coord string
*
* @param place
* the coord string
* @return the location of that string
*/
public static PALocation getCoords(Arena arena, String place) {
db.i("get coords: " + place);
if (place.equals("spawn") || place.equals("powerup")) {
HashMap<Integer, String> locs = new HashMap<Integer, String>();
int i = 0;
db.i("searching for spawns");
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (name.startsWith(place)) {
locs.put(i++, name);
db.i("found match: " + name);
}
}
Random r = new Random();
place = locs.get(r.nextInt(locs.size()));
} else if (arena.getArenaConfig().getUnsafe("spawns." + place) == null) {
db.i("guessing spawn");
place = PVPArena.instance.getAgm().guessSpawn(arena, place);
if (place == null) {
return null;
}
}
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + place));
db.i("parsing location: " + sLoc);
PALocation result;
- if (place.contains("flag")) {
+ if (place.contains("flag") || place.startsWith("switch")) {
result = new PALocation(Config.parseBlockLocation(sLoc).toLocation());
} else {
result = Config.parseLocation(sLoc);
}
return result.add(0.5, 0.5, 0.5);
}
/**
* get the nearest spawn location from a location
*
* @param hashSet
* the spawns to check
* @param location
* the location to check
* @return the spawn location next to the location
*/
public static PALocation getNearest(HashSet<PALocation> hashSet,
PALocation location) {
PALocation result = null;
for (PALocation loc : hashSet) {
if (result == null
|| result.getDistance(location) > loc.getDistance(location)) {
result = loc;
}
}
return result;
}
public static PABlockLocation getBlockNearest(HashSet<PABlockLocation> hashSet,
PABlockLocation location) {
PABlockLocation result = null;
for (PABlockLocation loc : hashSet) {
if (result == null
|| result.getDistance(location) > loc.getDistance(location)) {
result = loc;
}
}
return result;
}
/**
* get all (team) spawns of an arena
*
* @param arena
* the arena to check
* @param sTeam
* a team name or "flags" or "[team]pumpkin" or "[team]flag"
* @return a set of possible spawn matches
*/
public static HashSet<PALocation> getSpawns(Arena arena, String sTeam) {
db.i("reading spawns of arena " + arena + " (" + sTeam + ")");
HashSet<PALocation> result = new HashSet<PALocation>();
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (sTeam.equals("flags")) {
if (!name.startsWith("flag")) {
continue;
}
} else if (name.endsWith("flag") || name.endsWith("pumpkin")) {
String sName = sTeam.replace("flag", "");
sName = sName.replace("pumpkin", "");
db.i("checking if " + name + " starts with " + sName);
if (!name.startsWith(sName)) {
continue;
}
} else if (sTeam.equals("free")) {
if (!name.startsWith("spawn")) {
continue;
}
} else if (name.contains("lounge")) {
continue;
} else if (sTeam.endsWith("flag") || sTeam.endsWith("pumpkin")) {
continue;
}
db.i(" - " + name);
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + name));
result.add(Config.parseLocation(sLoc));
}
return result;
}
/**
* calculate the arena center, including all team spawn locations
*
* @param arena
* @return
*/
public static PABlockLocation getRegionCenter(Arena arena) {
HashSet<PALocation> locs = new HashSet<PALocation>();
for (ArenaTeam team : arena.getTeams()) {
String sTeam = team.getName();
for (PALocation loc : getSpawns(arena, sTeam)) {
locs.add(loc);
}
}
long x = 0;
long y = 0;
long z = 0;
for (PALocation loc : locs) {
x += loc.getX();
y += loc.getY();
z += loc.getZ();
}
return new PABlockLocation(arena.getWorld(),(int) x / locs.size(),(int) y / locs.size(),(int) z / locs.size());
}
/**
* is a player near a spawn?
*
* @param arena
* the arena to check
* @param player
* the player to check
* @param diff
* the distance to check
* @return true if the player is near, false otherwise
*/
public static boolean isNearSpawn(Arena arena, Player player, int diff) {
db.i("checking if arena is near a spawn");
if (!arena.hasPlayer(player)) {
return false;
}
ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName());
ArenaTeam team = ap.getArenaTeam();
if (team == null) {
return false;
}
HashSet<PALocation> spawns = getSpawns(arena, team.getName());
for (PALocation loc : spawns) {
if (loc.getDistance(new PALocation(player.getLocation())) <= diff) {
db.i("found near spawn: " + loc.toString());
return true;
}
}
return false;
}
/**
* set an arena coord to a given block
*
* @param loc
* the location to save
* @param place
* the coord name to save the location to
*/
public static void setBlock(Arena arena, PABlockLocation loc, String place) {
// "x,y,z,yaw,pitch"
String s = Config.parseToString(loc);
db.i("setting spawn " + place + " to " + s.toString());
arena.getArenaConfig().setManually("spawns." + place, s);
arena.getArenaConfig().save();
}
}
| true | true | public static PALocation getCoords(Arena arena, String place) {
db.i("get coords: " + place);
if (place.equals("spawn") || place.equals("powerup")) {
HashMap<Integer, String> locs = new HashMap<Integer, String>();
int i = 0;
db.i("searching for spawns");
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (name.startsWith(place)) {
locs.put(i++, name);
db.i("found match: " + name);
}
}
Random r = new Random();
place = locs.get(r.nextInt(locs.size()));
} else if (arena.getArenaConfig().getUnsafe("spawns." + place) == null) {
db.i("guessing spawn");
place = PVPArena.instance.getAgm().guessSpawn(arena, place);
if (place == null) {
return null;
}
}
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + place));
db.i("parsing location: " + sLoc);
PALocation result;
if (place.contains("flag")) {
result = new PALocation(Config.parseBlockLocation(sLoc).toLocation());
} else {
result = Config.parseLocation(sLoc);
}
return result.add(0.5, 0.5, 0.5);
}
| public static PALocation getCoords(Arena arena, String place) {
db.i("get coords: " + place);
if (place.equals("spawn") || place.equals("powerup")) {
HashMap<Integer, String> locs = new HashMap<Integer, String>();
int i = 0;
db.i("searching for spawns");
HashMap<String, Object> coords = (HashMap<String, Object>) arena.getArenaConfig()
.getYamlConfiguration().getConfigurationSection("spawns")
.getValues(false);
for (String name : coords.keySet()) {
if (name.startsWith(place)) {
locs.put(i++, name);
db.i("found match: " + name);
}
}
Random r = new Random();
place = locs.get(r.nextInt(locs.size()));
} else if (arena.getArenaConfig().getUnsafe("spawns." + place) == null) {
db.i("guessing spawn");
place = PVPArena.instance.getAgm().guessSpawn(arena, place);
if (place == null) {
return null;
}
}
String sLoc = String.valueOf(arena.getArenaConfig().getUnsafe("spawns." + place));
db.i("parsing location: " + sLoc);
PALocation result;
if (place.contains("flag") || place.startsWith("switch")) {
result = new PALocation(Config.parseBlockLocation(sLoc).toLocation());
} else {
result = Config.parseLocation(sLoc);
}
return result.add(0.5, 0.5, 0.5);
}
|
diff --git a/rewriter/src/org/sigwinch/xacml/parser/AbstractParser.java b/rewriter/src/org/sigwinch/xacml/parser/AbstractParser.java
index c0c6b49..cfbd387 100644
--- a/rewriter/src/org/sigwinch/xacml/parser/AbstractParser.java
+++ b/rewriter/src/org/sigwinch/xacml/parser/AbstractParser.java
@@ -1,198 +1,203 @@
package org.sigwinch.xacml.parser;
import java.util.HashMap;
import org.sigwinch.xacml.tree.DenyOverridesRule;
import org.sigwinch.xacml.tree.Error;
import org.sigwinch.xacml.tree.FirstApplicableRule;
import org.sigwinch.xacml.tree.OnlyOneRule;
import org.sigwinch.xacml.tree.PermitOverridesRule;
import org.sigwinch.xacml.tree.Predicate;
import org.sigwinch.xacml.tree.Scope;
import org.sigwinch.xacml.tree.SimplePredicate;
import org.sigwinch.xacml.tree.Tree;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* AbstractParser.java
*
*
* Created: Tue Oct 21 19:40:18 2003
*
* @author <a href="mailto:[email protected]">Graham Hughes</a>
* @version 1.0
*/
abstract public class AbstractParser extends XACMLParser {
static HashMap<String, HashMap<String, AbstractParser>> nodeLookup;
static HashMap<String, BinaryTreeCreator> ruleLookup;
static {
nodeLookup = new HashMap<String, HashMap<String, AbstractParser>>();
HashMap<String, AbstractParser> subtable = new HashMap<String, AbstractParser>();
nodeLookup.put(xacmlns, subtable);
subtable.put("Policy", new PolicyParser());
subtable.put("PolicySet", new PolicySetParser());
subtable.put("Rule", new RuleParser());
ruleLookup = new HashMap<String, BinaryTreeCreator>();
BinaryTreeCreator rule = new BinaryTreeCreator() {
public Tree go(Tree first, Tree second) {
return new DenyOverridesRule(first, second);
}
};
ruleLookup
.put(
"urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:deny-overrides",
rule);
ruleLookup
.put(
"urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:deny-overrides",
rule);
rule = new BinaryTreeCreator() {
public Tree go(Tree first, Tree second) {
return new PermitOverridesRule(first, second);
}
};
ruleLookup
.put(
"urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:permit-overrides",
rule);
ruleLookup
.put(
"urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:permit-overrides",
rule);
rule = new BinaryTreeCreator() {
public Tree go(Tree first, Tree second) {
return new OnlyOneRule(first, second);
}
};
ruleLookup
.put(
"urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:only-one-applicable",
rule);
ruleLookup
.put(
"urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:only-one-applicable",
rule);
rule = new BinaryTreeCreator() {
public Tree go(Tree first, Tree second) {
return new FirstApplicableRule(first, second);
}
};
ruleLookup
.put(
"urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:first-applicable",
rule);
ruleLookup
.put(
"urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable",
rule);
}
public Tree parseElement(Element e) {
System.out.println("{" + e.getNamespaceURI() + "}" + e.getNodeName());
return null;
}
protected Tree maybeScope(Element element, Tree node) {
Node target = findNode(getList(element, "Target"));
if (target == null)
return node;
return new Scope(node, parseScoping(target));
}
protected Tree maybeConditions(Element element, Tree node) {
Node target = findNode(getList(element, "Condition"));
if (target == null)
return node;
Tree result = new Scope(node, parseCondition(target));
Predicate error = parseError(target);
if (error == SimplePredicate.FALSE)
return result;
return new Error(result, error);
}
protected Node findNode(NodeList targets) {
Node target = null;
if (targets == null)
return target;
for (int i = 0; i < targets.getLength(); i++)
if (targets.item(i).getNodeType() == Node.ELEMENT_NODE) {
target = targets.item(i);
break;
}
return target;
}
protected Predicate parseCondition(Node target) {
return ExpressionParser.parseExpression((Element) target);
}
protected Predicate parseError(Node target) {
return ExpressionParser.parseError((Element) target);
}
protected Predicate parseScoping(Node target) {
Node child = target.getFirstChild();
Predicate condition = SimplePredicate.TRUE;
while (child != null) {
Node grandchild = child.getFirstChild();
- Predicate childcondition = SimplePredicate.TRUE;
+ Predicate childcondition = null;
while (grandchild != null) {
if (grandchild.getNodeName().equals("AnySubject")
|| grandchild.getNodeName().equals("AnyResource")
|| grandchild.getNodeName().equals("AnyAction"))
break;
// else we go in another level...
Predicate grandchildcondition = null;
Node grandgrandchild = grandchild.getFirstChild();
while (grandgrandchild != null) {
if (grandgrandchild.getNodeName().equals("ResourceMatch")
|| grandgrandchild.getNodeName().equals(
"SubjectMatch")
|| grandgrandchild.getNodeName().equals(
"ActionMatch")) {
if (grandchildcondition == null)
grandchildcondition = ExpressionParser
.parseExpression((Element) grandgrandchild);
else
grandchildcondition = grandchildcondition
- .orWith(ExpressionParser
- .parseExpression((Element) grandgrandchild));
+ .andWith(ExpressionParser
+ .parseExpression((Element) grandgrandchild));
}
grandgrandchild = grandgrandchild.getNextSibling();
}
- if (grandchildcondition != null)
- childcondition = childcondition
- .andWith(grandchildcondition);
+ if (grandchildcondition != null) {
+ if (childcondition == null)
+ childcondition = grandchildcondition;
+ else
+ childcondition = childcondition
+ .orWith(grandchildcondition);
+ }
grandchild = grandchild.getNextSibling();
}
- condition = condition.andWith(childcondition);
+ if (childcondition != null)
+ condition = condition.andWith(childcondition);
child = child.getNextSibling();
}
return condition;
}
protected Tree ruleToTree(String text, Tree first, Tree second) {
return ruleLookup.get(text).go(first, second);
}
static public Tree parse(Element e) {
String ns = e.getNamespaceURI();
if (ns == null)
ns = xacmlns;
String name = e.getNodeName();
AbstractParser parser = nodeLookup.get(ns).get(name);
return parser.parseElement(e);
}
}
/*
* arch-tag: 13F35F83-0439-11D8-9466-000A95A2610A
*/
| false | true | protected Predicate parseScoping(Node target) {
Node child = target.getFirstChild();
Predicate condition = SimplePredicate.TRUE;
while (child != null) {
Node grandchild = child.getFirstChild();
Predicate childcondition = SimplePredicate.TRUE;
while (grandchild != null) {
if (grandchild.getNodeName().equals("AnySubject")
|| grandchild.getNodeName().equals("AnyResource")
|| grandchild.getNodeName().equals("AnyAction"))
break;
// else we go in another level...
Predicate grandchildcondition = null;
Node grandgrandchild = grandchild.getFirstChild();
while (grandgrandchild != null) {
if (grandgrandchild.getNodeName().equals("ResourceMatch")
|| grandgrandchild.getNodeName().equals(
"SubjectMatch")
|| grandgrandchild.getNodeName().equals(
"ActionMatch")) {
if (grandchildcondition == null)
grandchildcondition = ExpressionParser
.parseExpression((Element) grandgrandchild);
else
grandchildcondition = grandchildcondition
.orWith(ExpressionParser
.parseExpression((Element) grandgrandchild));
}
grandgrandchild = grandgrandchild.getNextSibling();
}
if (grandchildcondition != null)
childcondition = childcondition
.andWith(grandchildcondition);
grandchild = grandchild.getNextSibling();
}
condition = condition.andWith(childcondition);
child = child.getNextSibling();
}
return condition;
}
| protected Predicate parseScoping(Node target) {
Node child = target.getFirstChild();
Predicate condition = SimplePredicate.TRUE;
while (child != null) {
Node grandchild = child.getFirstChild();
Predicate childcondition = null;
while (grandchild != null) {
if (grandchild.getNodeName().equals("AnySubject")
|| grandchild.getNodeName().equals("AnyResource")
|| grandchild.getNodeName().equals("AnyAction"))
break;
// else we go in another level...
Predicate grandchildcondition = null;
Node grandgrandchild = grandchild.getFirstChild();
while (grandgrandchild != null) {
if (grandgrandchild.getNodeName().equals("ResourceMatch")
|| grandgrandchild.getNodeName().equals(
"SubjectMatch")
|| grandgrandchild.getNodeName().equals(
"ActionMatch")) {
if (grandchildcondition == null)
grandchildcondition = ExpressionParser
.parseExpression((Element) grandgrandchild);
else
grandchildcondition = grandchildcondition
.andWith(ExpressionParser
.parseExpression((Element) grandgrandchild));
}
grandgrandchild = grandgrandchild.getNextSibling();
}
if (grandchildcondition != null) {
if (childcondition == null)
childcondition = grandchildcondition;
else
childcondition = childcondition
.orWith(grandchildcondition);
}
grandchild = grandchild.getNextSibling();
}
if (childcondition != null)
condition = condition.andWith(childcondition);
child = child.getNextSibling();
}
return condition;
}
|
diff --git a/examples/src/main/scala/spark/streaming/examples/JavaFlumeEventCount.java b/examples/src/main/scala/spark/streaming/examples/JavaFlumeEventCount.java
index 6592d9bc..151b71eb 100644
--- a/examples/src/main/scala/spark/streaming/examples/JavaFlumeEventCount.java
+++ b/examples/src/main/scala/spark/streaming/examples/JavaFlumeEventCount.java
@@ -1,50 +1,50 @@
package spark.streaming.examples;
import spark.api.java.function.Function;
import spark.streaming.*;
import spark.streaming.api.java.*;
import spark.streaming.dstream.SparkFlumeEvent;
/**
* Produces a count of events received from Flume.
*
* This should be used in conjunction with an AvroSink in Flume. It will start
* an Avro server on at the request host:port address and listen for requests.
* Your Flume AvroSink should be pointed to this address.
*
* Usage: FlumeEventCount <master> <host> <port>
*
* <master> is a Spark master URL
* <host> is the host the Flume receiver will be started on - a receiver
* creates a server and listens for flume events.
* <port> is the port the Flume receiver will listen on.
*/
public class JavaFlumeEventCount {
public static void main(String[] args) {
if (args.length != 3) {
System.err.println("Usage: JavaFlumeEventCount <master> <host> <port>");
System.exit(1);
}
String master = args[0];
String host = args[1];
int port = Integer.parseInt(args[2]);
Duration batchInterval = new Duration(2000);
JavaStreamingContext sc = new JavaStreamingContext(master, "FlumeEventCount", batchInterval);
JavaDStream<SparkFlumeEvent> flumeStream = sc.flumeStream("localhost", port);
flumeStream.count();
- flumeStream.count().map(new Function<Integer, String>() {
+ flumeStream.count().map(new Function<Long, String>() {
@Override
- public String call(Integer in) {
+ public String call(Long in) {
return "Received " + in + " flume events.";
}
}).print();
sc.start();
}
}
| false | true | public static void main(String[] args) {
if (args.length != 3) {
System.err.println("Usage: JavaFlumeEventCount <master> <host> <port>");
System.exit(1);
}
String master = args[0];
String host = args[1];
int port = Integer.parseInt(args[2]);
Duration batchInterval = new Duration(2000);
JavaStreamingContext sc = new JavaStreamingContext(master, "FlumeEventCount", batchInterval);
JavaDStream<SparkFlumeEvent> flumeStream = sc.flumeStream("localhost", port);
flumeStream.count();
flumeStream.count().map(new Function<Integer, String>() {
@Override
public String call(Integer in) {
return "Received " + in + " flume events.";
}
}).print();
sc.start();
}
| public static void main(String[] args) {
if (args.length != 3) {
System.err.println("Usage: JavaFlumeEventCount <master> <host> <port>");
System.exit(1);
}
String master = args[0];
String host = args[1];
int port = Integer.parseInt(args[2]);
Duration batchInterval = new Duration(2000);
JavaStreamingContext sc = new JavaStreamingContext(master, "FlumeEventCount", batchInterval);
JavaDStream<SparkFlumeEvent> flumeStream = sc.flumeStream("localhost", port);
flumeStream.count();
flumeStream.count().map(new Function<Long, String>() {
@Override
public String call(Long in) {
return "Received " + in + " flume events.";
}
}).print();
sc.start();
}
|
diff --git a/netcracker/src/main/java/netcracker/dao/InterviewDAOImpl.java b/netcracker/src/main/java/netcracker/dao/InterviewDAOImpl.java
index 32258b8..d721a34 100644
--- a/netcracker/src/main/java/netcracker/dao/InterviewDAOImpl.java
+++ b/netcracker/src/main/java/netcracker/dao/InterviewDAOImpl.java
@@ -1,186 +1,186 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package netcracker.dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author lastride
*/
public class InterviewDAOImpl implements InterviewDAO {
private static final Logger log =
Logger.getLogger(InterviewDAOImpl.class.getName());
@Override
public boolean createInterview(Interview interview) {
PreparedStatement stmtInsert = null;
Connection conn = DAOFactory.createConnection();
try {
StringBuilder sbInsert = new StringBuilder();
sbInsert.append("INSERT INTO ");
sbInsert.append(DAOConstants.ResultsTableName);
sbInsert.append(" (id_student, id_employee, comment)");
sbInsert.append(" VALUES (");
sbInsert.append("?, ?, ?)");
stmtInsert = conn.prepareStatement(sbInsert.toString());
stmtInsert.setInt(1, interview.getIdStudent());
stmtInsert.setInt(2, interview.getIdEmployee());
stmtInsert.setString(3, interview.getComment());
int rows = stmtInsert.executeUpdate();
if (rows != 1) {
log.info("Error in createInterview");
}
} catch (SQLException ex) {
log.log(Level.SEVERE, null, ex);
} finally {
DAOFactory.closeConnection(conn);
DAOFactory.closePreparedStatement(stmtInsert);
}
return true;
}
@Override
public boolean deleteInterviewByIdStudent(int idStudent) {
Connection conn = DAOFactory.createConnection();
PreparedStatement stmtDelete = null;
try {
StringBuilder sbDelete = new StringBuilder();
sbDelete.append("DELETE FROM ");
sbDelete.append(DAOConstants.ResultsTableName);
sbDelete.append(" WHERE id_student = ?");
stmtDelete = conn.prepareStatement(sbDelete.toString());
stmtDelete.setInt(1, idStudent);
stmtDelete.executeUpdate();
} catch (SQLException ex) {
log.log(Level.SEVERE, null, ex);
} finally {
DAOFactory.closeConnection(conn);
DAOFactory.closePreparedStatement(stmtDelete);
}
return true;
}
@Override
public List<String> getInterviewsResultByStudentId(int idStudent) {
List<String> comments = new ArrayList<String>();
Connection conn = DAOFactory.createConnection();
Statement stmtSelect = null;
ResultSet res = null;
String comment = null;
try {
StringBuilder sbSelect = new StringBuilder();
sbSelect.append(
"SELECT " + DAOConstants.ResultsTableName + ".comment "
+ "FROM " + DAOConstants.ResultsTableName
+ " WHERE " + DAOConstants.ResultsTableName
+ ".id_student = ").append(idStudent);
stmtSelect = conn.createStatement();
res = stmtSelect.executeQuery(sbSelect.toString());
int rowsCount = 0;
while (res.next()) {
comment = res.getString(1);
comments.add(comment);
rowsCount++;
}
if (rowsCount <= 0) {
log.info("No comments found");
}
if (rowsCount > 2) {
log.info("Student have more than 2 comments");
}
} catch (SQLException ex) {
log.log(Level.SEVERE, null, ex);
} finally {
DAOFactory.closeConnection(conn);
DAOFactory.closeStatement(stmtSelect);
}
return comments;
}
@Override
public List<String> getInterviewsResultByEmployeeId(int idEmployee) {
List<String> comments = new ArrayList<String>();
Connection conn = DAOFactory.createConnection();
Statement stmtSelect = null;
ResultSet res = null;
String comment = null;
try {
StringBuilder sbSelect = new StringBuilder();
sbSelect.append(
"SELECT " + DAOConstants.ResultsTableName + ".id_comment "
+ "FROM " + DAOConstants.ResultsTableName
+ " WHERE " + DAOConstants.ResultsTableName
+ ".id_employee = ").append(idEmployee);
stmtSelect = conn.createStatement();
System.out.print(sbSelect.toString());
res = stmtSelect.executeQuery(sbSelect.toString());
int rowsCount = 0;
while (res.next()) {
comment = res.getString(1);
comments.add(comment);
rowsCount++;
}
if (rowsCount <= 0) {
log.info("This employee did no comment");
}
} catch (SQLException ex) {
log.log(Level.SEVERE, null, ex);
} finally {
DAOFactory.closeConnection(conn);
DAOFactory.closeStatement(stmtSelect);
}
return comments;
}
@Override
public boolean updateInterviewsResultByIdStudent(int idStudent, int idFirstEmployee, int idSecondEmployee, String firstComment, String secondComment) {
PreparedStatement stmtFirstUpdate = null;
PreparedStatement stmtSecondUpdate = null;
Connection conn = DAOFactory.createConnection();
try {
StringBuilder sbFirstUpdate = new StringBuilder();
sbFirstUpdate.append("UPDATE ");
sbFirstUpdate.append(DAOConstants.ResultsTableName);
sbFirstUpdate.append(" SET comment = ?");
- sbFirstUpdate.append(" WHERE id_student = ?").append(" AND id_employee = ?");
+ sbFirstUpdate.append(" WHERE id_student = ? AND id_employee = ?");
stmtFirstUpdate = conn.prepareStatement(sbFirstUpdate.toString());
stmtFirstUpdate.setString(1, firstComment);
stmtFirstUpdate.setInt(2, idStudent);
stmtFirstUpdate.setInt(3, idFirstEmployee);
int rowsFirst = stmtFirstUpdate.executeUpdate();
if (rowsFirst != 1) {
log.info("Error in updateInterviewsResultByIdStudent");
}
StringBuilder sbSecondUpdate = new StringBuilder();
sbSecondUpdate.append("UPDATE ");
sbSecondUpdate.append(DAOConstants.ResultsTableName);
sbSecondUpdate.append(" SET comment = ?");
- sbSecondUpdate.append(" WHERE id_student = ?").append(" AND id_employee = ?");
+ sbSecondUpdate.append(" WHERE id_student = ? AND id_employee = ?");
stmtSecondUpdate = conn.prepareStatement(sbSecondUpdate.toString());
stmtSecondUpdate.setString(1, secondComment);
stmtSecondUpdate.setInt(2, idStudent);
stmtSecondUpdate.setInt(3, idSecondEmployee);
int rowsSecond = stmtSecondUpdate.executeUpdate();
if (rowsSecond != 1) {
log.info("Error in updateInterviewsResultByIdStudent");
}
} catch (SQLException ex) {
log.log(Level.SEVERE, null, ex);
} finally {
DAOFactory.closeConnection(conn);
DAOFactory.closePreparedStatement(stmtFirstUpdate);
DAOFactory.closePreparedStatement(stmtSecondUpdate);
}
return true;
}
}
| false | true | public boolean updateInterviewsResultByIdStudent(int idStudent, int idFirstEmployee, int idSecondEmployee, String firstComment, String secondComment) {
PreparedStatement stmtFirstUpdate = null;
PreparedStatement stmtSecondUpdate = null;
Connection conn = DAOFactory.createConnection();
try {
StringBuilder sbFirstUpdate = new StringBuilder();
sbFirstUpdate.append("UPDATE ");
sbFirstUpdate.append(DAOConstants.ResultsTableName);
sbFirstUpdate.append(" SET comment = ?");
sbFirstUpdate.append(" WHERE id_student = ?").append(" AND id_employee = ?");
stmtFirstUpdate = conn.prepareStatement(sbFirstUpdate.toString());
stmtFirstUpdate.setString(1, firstComment);
stmtFirstUpdate.setInt(2, idStudent);
stmtFirstUpdate.setInt(3, idFirstEmployee);
int rowsFirst = stmtFirstUpdate.executeUpdate();
if (rowsFirst != 1) {
log.info("Error in updateInterviewsResultByIdStudent");
}
StringBuilder sbSecondUpdate = new StringBuilder();
sbSecondUpdate.append("UPDATE ");
sbSecondUpdate.append(DAOConstants.ResultsTableName);
sbSecondUpdate.append(" SET comment = ?");
sbSecondUpdate.append(" WHERE id_student = ?").append(" AND id_employee = ?");
stmtSecondUpdate = conn.prepareStatement(sbSecondUpdate.toString());
stmtSecondUpdate.setString(1, secondComment);
stmtSecondUpdate.setInt(2, idStudent);
stmtSecondUpdate.setInt(3, idSecondEmployee);
int rowsSecond = stmtSecondUpdate.executeUpdate();
if (rowsSecond != 1) {
log.info("Error in updateInterviewsResultByIdStudent");
}
} catch (SQLException ex) {
log.log(Level.SEVERE, null, ex);
} finally {
DAOFactory.closeConnection(conn);
DAOFactory.closePreparedStatement(stmtFirstUpdate);
DAOFactory.closePreparedStatement(stmtSecondUpdate);
}
return true;
}
| public boolean updateInterviewsResultByIdStudent(int idStudent, int idFirstEmployee, int idSecondEmployee, String firstComment, String secondComment) {
PreparedStatement stmtFirstUpdate = null;
PreparedStatement stmtSecondUpdate = null;
Connection conn = DAOFactory.createConnection();
try {
StringBuilder sbFirstUpdate = new StringBuilder();
sbFirstUpdate.append("UPDATE ");
sbFirstUpdate.append(DAOConstants.ResultsTableName);
sbFirstUpdate.append(" SET comment = ?");
sbFirstUpdate.append(" WHERE id_student = ? AND id_employee = ?");
stmtFirstUpdate = conn.prepareStatement(sbFirstUpdate.toString());
stmtFirstUpdate.setString(1, firstComment);
stmtFirstUpdate.setInt(2, idStudent);
stmtFirstUpdate.setInt(3, idFirstEmployee);
int rowsFirst = stmtFirstUpdate.executeUpdate();
if (rowsFirst != 1) {
log.info("Error in updateInterviewsResultByIdStudent");
}
StringBuilder sbSecondUpdate = new StringBuilder();
sbSecondUpdate.append("UPDATE ");
sbSecondUpdate.append(DAOConstants.ResultsTableName);
sbSecondUpdate.append(" SET comment = ?");
sbSecondUpdate.append(" WHERE id_student = ? AND id_employee = ?");
stmtSecondUpdate = conn.prepareStatement(sbSecondUpdate.toString());
stmtSecondUpdate.setString(1, secondComment);
stmtSecondUpdate.setInt(2, idStudent);
stmtSecondUpdate.setInt(3, idSecondEmployee);
int rowsSecond = stmtSecondUpdate.executeUpdate();
if (rowsSecond != 1) {
log.info("Error in updateInterviewsResultByIdStudent");
}
} catch (SQLException ex) {
log.log(Level.SEVERE, null, ex);
} finally {
DAOFactory.closeConnection(conn);
DAOFactory.closePreparedStatement(stmtFirstUpdate);
DAOFactory.closePreparedStatement(stmtSecondUpdate);
}
return true;
}
|
diff --git a/MODSRC/vazkii/tinkerer/research/ModInfusionRecipes.java b/MODSRC/vazkii/tinkerer/research/ModInfusionRecipes.java
index 3ce13bf2..7760915f 100644
--- a/MODSRC/vazkii/tinkerer/research/ModInfusionRecipes.java
+++ b/MODSRC/vazkii/tinkerer/research/ModInfusionRecipes.java
@@ -1,156 +1,156 @@
package vazkii.tinkerer.research;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import thaumcraft.api.EnumTag;
import thaumcraft.api.ObjectTags;
import thaumcraft.api.ThaumcraftApi;
import thaumcraft.common.Config;
import vazkii.tinkerer.block.ModBlocks;
import vazkii.tinkerer.item.ModItems;
import vazkii.tinkerer.lib.LibBlockNames;
import vazkii.tinkerer.lib.LibItemNames;
import vazkii.tinkerer.lib.LibMisc;
public final class ModInfusionRecipes {
public static void initInfusionRecipes() {
ObjectTags tags = new ObjectTags().add(EnumTag.MAGIC, 16).add(EnumTag.VOID, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.WAND_TINKERER_R, LibItemNames.WAND_TINKERER_R, 85, tags, new ItemStack(ModItems.wandTinkerer),
"SSS", "SWS", "SSS",
'S', new ItemStack(Config.itemShard, 1, 4),
'W', new ItemStack(Config.itemWandCastingAdept, 1, LibMisc.CRAFTING_META_WILDCARD));
tags = new ObjectTags().add(EnumTag.WIND, 8);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.GLOWSTONE_GAS_R, LibItemNames.GLOWSTONE_GAS_R, 5, tags, new ItemStack(ModItems.glowstoneGas),
"GPG", " N ",
'G', new ItemStack(Block.glowStone),
'P', new ItemStack(Config.itemEssence, 1, 0),
'N', new ItemStack(Config.itemResource, 1, 1));
tags = new ObjectTags().add(EnumTag.CLOTH, 4).add(EnumTag.MAGIC, 6).add(EnumTag.EXCHANGE, 8);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.SPELL_CLOTH_R, LibItemNames.SPELL_CLOTH_R, 55, tags, new ItemStack(ModItems.spellCloth),
" C ", "CEC", " C ",
'C', new ItemStack(Config.itemResource, 1, 7),
'E', new ItemStack(Item.expBottle));
tags = new ObjectTags().add(EnumTag.TIME, 12).add(EnumTag.MECHANISM, 20);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.STOPWATCH_R, LibItemNames.STOPWATCH_R, 85, tags, new ItemStack(ModItems.stopwatch),
" Q ", "QCQ", " Q ",
'Q', new ItemStack(Item.netherQuartz),
'C', new ItemStack(Item.pocketSundial));
tags = new ObjectTags().add(EnumTag.TRAP, 12).add(EnumTag.EXCHANGE, 14);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.WAND_DISLOCATION_R, LibItemNames.WAND_DISLOCATION_R, 90, tags, new ItemStack(ModItems.wandDislocation),
" H", "W ",
'H', new ItemStack(Config.itemPortableHole),
'W', new ItemStack(Config.itemWandTrade));
tags = new ObjectTags().add(EnumTag.FLUX, 24).add(EnumTag.EXCHANGE, 48);
ThaumcraftApi.addInfusionCraftingRecipe(LibBlockNames.TRANSMUTATOR_R, LibBlockNames.TRANSMUTATOR_R, 320, tags, new ItemStack(ModBlocks.transmutator),
"ITI", "WFW", "WCW",
'W', new ItemStack(Config.blockWooden),
'T', new ItemStack(Config.itemWandTrade),
'I', new ItemStack(Config.itemResource, 1, 2),
'F', new ItemStack(Config.itemResource, 1, 8),
'C', new ItemStack(Config.blockCrucible));
tags = new ObjectTags().add(EnumTag.EVIL, 6).add(EnumTag.TRAP, 18).add(EnumTag.KNOWLEDGE, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.XP_TALISMAN_R, LibItemNames.XP_TALISMAN_R, 140, tags, new ItemStack(ModItems.xpTalisman),
"OGO", "GBG", "OGO",
'O', new ItemStack(Block.obsidian),
'G', new ItemStack(Item.ingotGold),
'B', new ItemStack(Config.itemResource, 1, 5));
tags = new ObjectTags().add(EnumTag.FIRE, 8).add(EnumTag.ROCK, 6).add(EnumTag.METAL, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.FIRE_BRACELET_R, LibItemNames.FIRE_BRACELET_R, 85, tags, new ItemStack(ModItems.fireBracelet),
"O O", "ILI",
'O', new ItemStack(Block.obsidian),
'I', new ItemStack(Item.ingotIron),
'L', new ItemStack(Item.bucketLava));
tags = new ObjectTags().add(EnumTag.VOID, 12).add(EnumTag.MAGIC, 16);
ThaumcraftApi.addInfusionCraftingRecipe(LibBlockNames.WARD_CHEST_R, LibBlockNames.WARD_CHEST_R, 25, tags, new ItemStack(ModBlocks.wardChest),
"GGG", "IBI", "WCW",
'G', new ItemStack(Config.blockCosmeticOpaque, 1, 2),
'I', new ItemStack(Config.itemResource, 1, 2),
'B', new ItemStack(Config.itemResource, 1, 5),
'W', new ItemStack(Config.blockWooden),
'C', new ItemStack(Block.chest));
tags = new ObjectTags().add(EnumTag.MOTION, 16).add(EnumTag.ELDRITCH, 4).add(EnumTag.MECHANISM, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.TELEPORTATION_SIGIL_R, LibItemNames.TELEPORTATION_SIGIL_R, 50, tags, new ItemStack(ModItems.teleportSigil),
" O ", "OEO", " O ",
'O', new ItemStack(Block.obsidian),
'E', new ItemStack(Item.enderPearl));
tags = new ObjectTags().add(EnumTag.FLIGHT, 12).add(EnumTag.WIND, 6);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.WAND_UPRISING_R, LibItemNames.WAND_UPRISING_R, 25, tags, new ItemStack(ModItems.wandUprising),
" Q ", "QWQ", " Q ",
- 'Q', new ItemStack(Config.itemResource, 1, 10),
+ 'Q', new ItemStack(Config.itemResource, 1, 3),
'W', new ItemStack(Config.itemWandLightning));
tags = new ObjectTags().add(EnumTag.POWER, 14).add(EnumTag.FLIGHT, 6);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.SWORD_CONDOR_R, LibItemNames.SWORD_CONDOR_R, 25, tags, new ItemStack(ModItems.swordCondor),
"I W", " S ", " I",
'I', new ItemStack(Config.itemResource, 1, 2),
'S', new ItemStack(Config.itemSwordElemental),
'W', new ItemStack(ModItems.wandUprising));
tags = new ObjectTags().add(EnumTag.DEATH, 16).add(EnumTag.POWER, 12).add(EnumTag.MAGIC, 20);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.DEATH_RUNE_R, LibItemNames.DEATH_RUNE_R, 60, tags, new ItemStack(ModItems.deathRune),
"TOT", "OBO", "TOT",
'T', new ItemStack(Config.itemResource, 1, 2),
'O', new ItemStack(Block.obsidian),
'B', new ItemStack(Config.itemResource, 1, 5));
tags = new ObjectTags().add(EnumTag.CONTROL, 16).add(EnumTag.MOTION, 8).add(EnumTag.MECHANISM, 16).add(EnumTag.MAGIC, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibBlockNames.ANIMATION_TABLET_R, LibBlockNames.ANIMATION_TABLET_R, 25, tags, new ItemStack(ModBlocks.animationTablet),
"GIG", "ICI",
'G', new ItemStack(Item.ingotGold),
'I', new ItemStack(Item.ingotIron),
'C', new ItemStack(Config.itemGolemCore, 1, 0));
tags = new ObjectTags().add(EnumTag.TOOL, 25).add(EnumTag.DARK, 4).add(EnumTag.MAGIC, 12).add(EnumTag.CLOTH, 100);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.SILK_SWORD_R, LibItemNames.SILK_SWORD_R, 100, tags, new ItemStack(ModItems.silkSword),
"O1O", "2D3", "O4O",
'1', new ItemStack(Config.itemSwordThaumium),
'2', new ItemStack(Config.itemAxeThaumium),
'3', new ItemStack(Config.itemPickThaumium),
'4', new ItemStack(Config.itemShovelThaumium),
'O', new ItemStack(Block.obsidian),
'D', new ItemStack(Item.diamond));
tags = new ObjectTags().add(EnumTag.TOOL, 25).add(EnumTag.DARK, 4).add(EnumTag.MAGIC, 12).add(EnumTag.VALUABLE, 25);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.FORTUNE_MAUL_R, LibItemNames.FORTUNE_MAUL_R, 100, tags, new ItemStack(ModItems.fortuneMaul),
"O1O", "2D3", "O4O",
'1', new ItemStack(Config.itemHoeThaumium),
'2', new ItemStack(Config.itemAxeThaumium),
'3', new ItemStack(Config.itemPickThaumium),
'4', new ItemStack(Config.itemShovelThaumium),
'O', new ItemStack(Block.obsidian),
'D', new ItemStack(Item.diamond));
tags = new ObjectTags().add(EnumTag.TOOL, 8).add(EnumTag.VISION, 6).add(EnumTag.ELDRITCH, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.ENDER_MIRROR_R, LibItemNames.ENDER_MIRROR_R, 25, tags, new ItemStack(ModItems.enderMirror),
"E C", " M ", "O E",
'O', new ItemStack(Block.obsidian),
'C', new ItemStack(Block.enderChest),
'M', new ItemStack(Config.itemHandMirror),
'E', new ItemStack(Item.enderPearl));
tags = new ObjectTags().add(EnumTag.BEAST, 16).add(EnumTag.ARMOR, 16);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.GOLIATH_LEGS_R, LibItemNames.GOLIATH_LEGS_R, 80, tags, new ItemStack(ModItems.goliathLegs),
"LLL", "LRL", "L L",
'L', new ItemStack(Item.leather),
'R', new ItemStack(Config.itemLegsRobe));
tags = new ObjectTags().add(EnumTag.WIND, 6).add(EnumTag.DARK, 2);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.DARK_GAS_R, LibItemNames.DARK_GAS_R, 5, tags, new ItemStack(ModItems.darkGas),
"QPQ", " A ",
'Q', new ItemStack(ModItems.darkQuartz),
'P', new ItemStack(Config.itemEssence, 1, 0),
'A', new ItemStack(Config.itemResource, 1, 0));
}
}
| true | true | public static void initInfusionRecipes() {
ObjectTags tags = new ObjectTags().add(EnumTag.MAGIC, 16).add(EnumTag.VOID, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.WAND_TINKERER_R, LibItemNames.WAND_TINKERER_R, 85, tags, new ItemStack(ModItems.wandTinkerer),
"SSS", "SWS", "SSS",
'S', new ItemStack(Config.itemShard, 1, 4),
'W', new ItemStack(Config.itemWandCastingAdept, 1, LibMisc.CRAFTING_META_WILDCARD));
tags = new ObjectTags().add(EnumTag.WIND, 8);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.GLOWSTONE_GAS_R, LibItemNames.GLOWSTONE_GAS_R, 5, tags, new ItemStack(ModItems.glowstoneGas),
"GPG", " N ",
'G', new ItemStack(Block.glowStone),
'P', new ItemStack(Config.itemEssence, 1, 0),
'N', new ItemStack(Config.itemResource, 1, 1));
tags = new ObjectTags().add(EnumTag.CLOTH, 4).add(EnumTag.MAGIC, 6).add(EnumTag.EXCHANGE, 8);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.SPELL_CLOTH_R, LibItemNames.SPELL_CLOTH_R, 55, tags, new ItemStack(ModItems.spellCloth),
" C ", "CEC", " C ",
'C', new ItemStack(Config.itemResource, 1, 7),
'E', new ItemStack(Item.expBottle));
tags = new ObjectTags().add(EnumTag.TIME, 12).add(EnumTag.MECHANISM, 20);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.STOPWATCH_R, LibItemNames.STOPWATCH_R, 85, tags, new ItemStack(ModItems.stopwatch),
" Q ", "QCQ", " Q ",
'Q', new ItemStack(Item.netherQuartz),
'C', new ItemStack(Item.pocketSundial));
tags = new ObjectTags().add(EnumTag.TRAP, 12).add(EnumTag.EXCHANGE, 14);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.WAND_DISLOCATION_R, LibItemNames.WAND_DISLOCATION_R, 90, tags, new ItemStack(ModItems.wandDislocation),
" H", "W ",
'H', new ItemStack(Config.itemPortableHole),
'W', new ItemStack(Config.itemWandTrade));
tags = new ObjectTags().add(EnumTag.FLUX, 24).add(EnumTag.EXCHANGE, 48);
ThaumcraftApi.addInfusionCraftingRecipe(LibBlockNames.TRANSMUTATOR_R, LibBlockNames.TRANSMUTATOR_R, 320, tags, new ItemStack(ModBlocks.transmutator),
"ITI", "WFW", "WCW",
'W', new ItemStack(Config.blockWooden),
'T', new ItemStack(Config.itemWandTrade),
'I', new ItemStack(Config.itemResource, 1, 2),
'F', new ItemStack(Config.itemResource, 1, 8),
'C', new ItemStack(Config.blockCrucible));
tags = new ObjectTags().add(EnumTag.EVIL, 6).add(EnumTag.TRAP, 18).add(EnumTag.KNOWLEDGE, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.XP_TALISMAN_R, LibItemNames.XP_TALISMAN_R, 140, tags, new ItemStack(ModItems.xpTalisman),
"OGO", "GBG", "OGO",
'O', new ItemStack(Block.obsidian),
'G', new ItemStack(Item.ingotGold),
'B', new ItemStack(Config.itemResource, 1, 5));
tags = new ObjectTags().add(EnumTag.FIRE, 8).add(EnumTag.ROCK, 6).add(EnumTag.METAL, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.FIRE_BRACELET_R, LibItemNames.FIRE_BRACELET_R, 85, tags, new ItemStack(ModItems.fireBracelet),
"O O", "ILI",
'O', new ItemStack(Block.obsidian),
'I', new ItemStack(Item.ingotIron),
'L', new ItemStack(Item.bucketLava));
tags = new ObjectTags().add(EnumTag.VOID, 12).add(EnumTag.MAGIC, 16);
ThaumcraftApi.addInfusionCraftingRecipe(LibBlockNames.WARD_CHEST_R, LibBlockNames.WARD_CHEST_R, 25, tags, new ItemStack(ModBlocks.wardChest),
"GGG", "IBI", "WCW",
'G', new ItemStack(Config.blockCosmeticOpaque, 1, 2),
'I', new ItemStack(Config.itemResource, 1, 2),
'B', new ItemStack(Config.itemResource, 1, 5),
'W', new ItemStack(Config.blockWooden),
'C', new ItemStack(Block.chest));
tags = new ObjectTags().add(EnumTag.MOTION, 16).add(EnumTag.ELDRITCH, 4).add(EnumTag.MECHANISM, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.TELEPORTATION_SIGIL_R, LibItemNames.TELEPORTATION_SIGIL_R, 50, tags, new ItemStack(ModItems.teleportSigil),
" O ", "OEO", " O ",
'O', new ItemStack(Block.obsidian),
'E', new ItemStack(Item.enderPearl));
tags = new ObjectTags().add(EnumTag.FLIGHT, 12).add(EnumTag.WIND, 6);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.WAND_UPRISING_R, LibItemNames.WAND_UPRISING_R, 25, tags, new ItemStack(ModItems.wandUprising),
" Q ", "QWQ", " Q ",
'Q', new ItemStack(Config.itemResource, 1, 10),
'W', new ItemStack(Config.itemWandLightning));
tags = new ObjectTags().add(EnumTag.POWER, 14).add(EnumTag.FLIGHT, 6);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.SWORD_CONDOR_R, LibItemNames.SWORD_CONDOR_R, 25, tags, new ItemStack(ModItems.swordCondor),
"I W", " S ", " I",
'I', new ItemStack(Config.itemResource, 1, 2),
'S', new ItemStack(Config.itemSwordElemental),
'W', new ItemStack(ModItems.wandUprising));
tags = new ObjectTags().add(EnumTag.DEATH, 16).add(EnumTag.POWER, 12).add(EnumTag.MAGIC, 20);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.DEATH_RUNE_R, LibItemNames.DEATH_RUNE_R, 60, tags, new ItemStack(ModItems.deathRune),
"TOT", "OBO", "TOT",
'T', new ItemStack(Config.itemResource, 1, 2),
'O', new ItemStack(Block.obsidian),
'B', new ItemStack(Config.itemResource, 1, 5));
tags = new ObjectTags().add(EnumTag.CONTROL, 16).add(EnumTag.MOTION, 8).add(EnumTag.MECHANISM, 16).add(EnumTag.MAGIC, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibBlockNames.ANIMATION_TABLET_R, LibBlockNames.ANIMATION_TABLET_R, 25, tags, new ItemStack(ModBlocks.animationTablet),
"GIG", "ICI",
'G', new ItemStack(Item.ingotGold),
'I', new ItemStack(Item.ingotIron),
'C', new ItemStack(Config.itemGolemCore, 1, 0));
tags = new ObjectTags().add(EnumTag.TOOL, 25).add(EnumTag.DARK, 4).add(EnumTag.MAGIC, 12).add(EnumTag.CLOTH, 100);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.SILK_SWORD_R, LibItemNames.SILK_SWORD_R, 100, tags, new ItemStack(ModItems.silkSword),
"O1O", "2D3", "O4O",
'1', new ItemStack(Config.itemSwordThaumium),
'2', new ItemStack(Config.itemAxeThaumium),
'3', new ItemStack(Config.itemPickThaumium),
'4', new ItemStack(Config.itemShovelThaumium),
'O', new ItemStack(Block.obsidian),
'D', new ItemStack(Item.diamond));
tags = new ObjectTags().add(EnumTag.TOOL, 25).add(EnumTag.DARK, 4).add(EnumTag.MAGIC, 12).add(EnumTag.VALUABLE, 25);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.FORTUNE_MAUL_R, LibItemNames.FORTUNE_MAUL_R, 100, tags, new ItemStack(ModItems.fortuneMaul),
"O1O", "2D3", "O4O",
'1', new ItemStack(Config.itemHoeThaumium),
'2', new ItemStack(Config.itemAxeThaumium),
'3', new ItemStack(Config.itemPickThaumium),
'4', new ItemStack(Config.itemShovelThaumium),
'O', new ItemStack(Block.obsidian),
'D', new ItemStack(Item.diamond));
tags = new ObjectTags().add(EnumTag.TOOL, 8).add(EnumTag.VISION, 6).add(EnumTag.ELDRITCH, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.ENDER_MIRROR_R, LibItemNames.ENDER_MIRROR_R, 25, tags, new ItemStack(ModItems.enderMirror),
"E C", " M ", "O E",
'O', new ItemStack(Block.obsidian),
'C', new ItemStack(Block.enderChest),
'M', new ItemStack(Config.itemHandMirror),
'E', new ItemStack(Item.enderPearl));
tags = new ObjectTags().add(EnumTag.BEAST, 16).add(EnumTag.ARMOR, 16);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.GOLIATH_LEGS_R, LibItemNames.GOLIATH_LEGS_R, 80, tags, new ItemStack(ModItems.goliathLegs),
"LLL", "LRL", "L L",
'L', new ItemStack(Item.leather),
'R', new ItemStack(Config.itemLegsRobe));
tags = new ObjectTags().add(EnumTag.WIND, 6).add(EnumTag.DARK, 2);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.DARK_GAS_R, LibItemNames.DARK_GAS_R, 5, tags, new ItemStack(ModItems.darkGas),
"QPQ", " A ",
'Q', new ItemStack(ModItems.darkQuartz),
'P', new ItemStack(Config.itemEssence, 1, 0),
'A', new ItemStack(Config.itemResource, 1, 0));
}
| public static void initInfusionRecipes() {
ObjectTags tags = new ObjectTags().add(EnumTag.MAGIC, 16).add(EnumTag.VOID, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.WAND_TINKERER_R, LibItemNames.WAND_TINKERER_R, 85, tags, new ItemStack(ModItems.wandTinkerer),
"SSS", "SWS", "SSS",
'S', new ItemStack(Config.itemShard, 1, 4),
'W', new ItemStack(Config.itemWandCastingAdept, 1, LibMisc.CRAFTING_META_WILDCARD));
tags = new ObjectTags().add(EnumTag.WIND, 8);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.GLOWSTONE_GAS_R, LibItemNames.GLOWSTONE_GAS_R, 5, tags, new ItemStack(ModItems.glowstoneGas),
"GPG", " N ",
'G', new ItemStack(Block.glowStone),
'P', new ItemStack(Config.itemEssence, 1, 0),
'N', new ItemStack(Config.itemResource, 1, 1));
tags = new ObjectTags().add(EnumTag.CLOTH, 4).add(EnumTag.MAGIC, 6).add(EnumTag.EXCHANGE, 8);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.SPELL_CLOTH_R, LibItemNames.SPELL_CLOTH_R, 55, tags, new ItemStack(ModItems.spellCloth),
" C ", "CEC", " C ",
'C', new ItemStack(Config.itemResource, 1, 7),
'E', new ItemStack(Item.expBottle));
tags = new ObjectTags().add(EnumTag.TIME, 12).add(EnumTag.MECHANISM, 20);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.STOPWATCH_R, LibItemNames.STOPWATCH_R, 85, tags, new ItemStack(ModItems.stopwatch),
" Q ", "QCQ", " Q ",
'Q', new ItemStack(Item.netherQuartz),
'C', new ItemStack(Item.pocketSundial));
tags = new ObjectTags().add(EnumTag.TRAP, 12).add(EnumTag.EXCHANGE, 14);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.WAND_DISLOCATION_R, LibItemNames.WAND_DISLOCATION_R, 90, tags, new ItemStack(ModItems.wandDislocation),
" H", "W ",
'H', new ItemStack(Config.itemPortableHole),
'W', new ItemStack(Config.itemWandTrade));
tags = new ObjectTags().add(EnumTag.FLUX, 24).add(EnumTag.EXCHANGE, 48);
ThaumcraftApi.addInfusionCraftingRecipe(LibBlockNames.TRANSMUTATOR_R, LibBlockNames.TRANSMUTATOR_R, 320, tags, new ItemStack(ModBlocks.transmutator),
"ITI", "WFW", "WCW",
'W', new ItemStack(Config.blockWooden),
'T', new ItemStack(Config.itemWandTrade),
'I', new ItemStack(Config.itemResource, 1, 2),
'F', new ItemStack(Config.itemResource, 1, 8),
'C', new ItemStack(Config.blockCrucible));
tags = new ObjectTags().add(EnumTag.EVIL, 6).add(EnumTag.TRAP, 18).add(EnumTag.KNOWLEDGE, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.XP_TALISMAN_R, LibItemNames.XP_TALISMAN_R, 140, tags, new ItemStack(ModItems.xpTalisman),
"OGO", "GBG", "OGO",
'O', new ItemStack(Block.obsidian),
'G', new ItemStack(Item.ingotGold),
'B', new ItemStack(Config.itemResource, 1, 5));
tags = new ObjectTags().add(EnumTag.FIRE, 8).add(EnumTag.ROCK, 6).add(EnumTag.METAL, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.FIRE_BRACELET_R, LibItemNames.FIRE_BRACELET_R, 85, tags, new ItemStack(ModItems.fireBracelet),
"O O", "ILI",
'O', new ItemStack(Block.obsidian),
'I', new ItemStack(Item.ingotIron),
'L', new ItemStack(Item.bucketLava));
tags = new ObjectTags().add(EnumTag.VOID, 12).add(EnumTag.MAGIC, 16);
ThaumcraftApi.addInfusionCraftingRecipe(LibBlockNames.WARD_CHEST_R, LibBlockNames.WARD_CHEST_R, 25, tags, new ItemStack(ModBlocks.wardChest),
"GGG", "IBI", "WCW",
'G', new ItemStack(Config.blockCosmeticOpaque, 1, 2),
'I', new ItemStack(Config.itemResource, 1, 2),
'B', new ItemStack(Config.itemResource, 1, 5),
'W', new ItemStack(Config.blockWooden),
'C', new ItemStack(Block.chest));
tags = new ObjectTags().add(EnumTag.MOTION, 16).add(EnumTag.ELDRITCH, 4).add(EnumTag.MECHANISM, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.TELEPORTATION_SIGIL_R, LibItemNames.TELEPORTATION_SIGIL_R, 50, tags, new ItemStack(ModItems.teleportSigil),
" O ", "OEO", " O ",
'O', new ItemStack(Block.obsidian),
'E', new ItemStack(Item.enderPearl));
tags = new ObjectTags().add(EnumTag.FLIGHT, 12).add(EnumTag.WIND, 6);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.WAND_UPRISING_R, LibItemNames.WAND_UPRISING_R, 25, tags, new ItemStack(ModItems.wandUprising),
" Q ", "QWQ", " Q ",
'Q', new ItemStack(Config.itemResource, 1, 3),
'W', new ItemStack(Config.itemWandLightning));
tags = new ObjectTags().add(EnumTag.POWER, 14).add(EnumTag.FLIGHT, 6);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.SWORD_CONDOR_R, LibItemNames.SWORD_CONDOR_R, 25, tags, new ItemStack(ModItems.swordCondor),
"I W", " S ", " I",
'I', new ItemStack(Config.itemResource, 1, 2),
'S', new ItemStack(Config.itemSwordElemental),
'W', new ItemStack(ModItems.wandUprising));
tags = new ObjectTags().add(EnumTag.DEATH, 16).add(EnumTag.POWER, 12).add(EnumTag.MAGIC, 20);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.DEATH_RUNE_R, LibItemNames.DEATH_RUNE_R, 60, tags, new ItemStack(ModItems.deathRune),
"TOT", "OBO", "TOT",
'T', new ItemStack(Config.itemResource, 1, 2),
'O', new ItemStack(Block.obsidian),
'B', new ItemStack(Config.itemResource, 1, 5));
tags = new ObjectTags().add(EnumTag.CONTROL, 16).add(EnumTag.MOTION, 8).add(EnumTag.MECHANISM, 16).add(EnumTag.MAGIC, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibBlockNames.ANIMATION_TABLET_R, LibBlockNames.ANIMATION_TABLET_R, 25, tags, new ItemStack(ModBlocks.animationTablet),
"GIG", "ICI",
'G', new ItemStack(Item.ingotGold),
'I', new ItemStack(Item.ingotIron),
'C', new ItemStack(Config.itemGolemCore, 1, 0));
tags = new ObjectTags().add(EnumTag.TOOL, 25).add(EnumTag.DARK, 4).add(EnumTag.MAGIC, 12).add(EnumTag.CLOTH, 100);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.SILK_SWORD_R, LibItemNames.SILK_SWORD_R, 100, tags, new ItemStack(ModItems.silkSword),
"O1O", "2D3", "O4O",
'1', new ItemStack(Config.itemSwordThaumium),
'2', new ItemStack(Config.itemAxeThaumium),
'3', new ItemStack(Config.itemPickThaumium),
'4', new ItemStack(Config.itemShovelThaumium),
'O', new ItemStack(Block.obsidian),
'D', new ItemStack(Item.diamond));
tags = new ObjectTags().add(EnumTag.TOOL, 25).add(EnumTag.DARK, 4).add(EnumTag.MAGIC, 12).add(EnumTag.VALUABLE, 25);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.FORTUNE_MAUL_R, LibItemNames.FORTUNE_MAUL_R, 100, tags, new ItemStack(ModItems.fortuneMaul),
"O1O", "2D3", "O4O",
'1', new ItemStack(Config.itemHoeThaumium),
'2', new ItemStack(Config.itemAxeThaumium),
'3', new ItemStack(Config.itemPickThaumium),
'4', new ItemStack(Config.itemShovelThaumium),
'O', new ItemStack(Block.obsidian),
'D', new ItemStack(Item.diamond));
tags = new ObjectTags().add(EnumTag.TOOL, 8).add(EnumTag.VISION, 6).add(EnumTag.ELDRITCH, 12);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.ENDER_MIRROR_R, LibItemNames.ENDER_MIRROR_R, 25, tags, new ItemStack(ModItems.enderMirror),
"E C", " M ", "O E",
'O', new ItemStack(Block.obsidian),
'C', new ItemStack(Block.enderChest),
'M', new ItemStack(Config.itemHandMirror),
'E', new ItemStack(Item.enderPearl));
tags = new ObjectTags().add(EnumTag.BEAST, 16).add(EnumTag.ARMOR, 16);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.GOLIATH_LEGS_R, LibItemNames.GOLIATH_LEGS_R, 80, tags, new ItemStack(ModItems.goliathLegs),
"LLL", "LRL", "L L",
'L', new ItemStack(Item.leather),
'R', new ItemStack(Config.itemLegsRobe));
tags = new ObjectTags().add(EnumTag.WIND, 6).add(EnumTag.DARK, 2);
ThaumcraftApi.addInfusionCraftingRecipe(LibItemNames.DARK_GAS_R, LibItemNames.DARK_GAS_R, 5, tags, new ItemStack(ModItems.darkGas),
"QPQ", " A ",
'Q', new ItemStack(ModItems.darkQuartz),
'P', new ItemStack(Config.itemEssence, 1, 0),
'A', new ItemStack(Config.itemResource, 1, 0));
}
|
diff --git a/web/src/main/java/org/openmrs/web/dwr/ObsListItem.java b/web/src/main/java/org/openmrs/web/dwr/ObsListItem.java
index 1fbcaf62..55c90e1e 100644
--- a/web/src/main/java/org/openmrs/web/dwr/ObsListItem.java
+++ b/web/src/main/java/org/openmrs/web/dwr/ObsListItem.java
@@ -1,208 +1,209 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.dwr;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Obs;
import org.openmrs.util.Format;
import org.openmrs.util.Format.FORMAT_TYPE;
public class ObsListItem {
protected final Log log = LogFactory.getLog(getClass());
private Integer obsId;
private String encounter = "";
private String encounterName = "";
private String personName = "";
private String conceptName = "";
private String order = "";
private String location = "";
private Date encounterDatetime;
private Date datetime;
private String encounterDate = "";
private String obsDate = "";
private Boolean voided = false;
private String value = "";
public ObsListItem() {
}
public ObsListItem(Obs obs, Locale locale) {
if (obs != null) {
obsId = obs.getObsId();
if (obs.getEncounter() != null) {
encounter = obs.getEncounter().getEncounterId().toString();
encounterDatetime = obs.getEncounter().getEncounterDatetime();
encounterDate = encounterDatetime == null ? "" : Format.format(encounterDatetime, locale, FORMAT_TYPE.DATE);
encounterName = obs.getEncounter().getForm() == null ? "" : obs.getEncounter().getForm().getName();
}
personName = obs.getPerson().getPersonName().toString();
conceptName = obs.getConcept().getName(locale).getName();
if (obs.getOrder() != null)
order = obs.getOrder().getOrderId().toString();
- location = obs.getLocation().getName();
+ if (obs.getLocation() != null)
+ location = obs.getLocation().getName();
datetime = obs.getObsDatetime();
obsDate = datetime == null ? "" : Format.format(datetime, locale, FORMAT_TYPE.DATE);
voided = obs.isVoided();
value = obs.getValueAsString(locale);
}
}
public Integer getObsId() {
return obsId;
}
public void setObsId(Integer obsId) {
this.obsId = obsId;
}
public String getConceptName() {
return conceptName;
}
public void setConceptName(String conceptName) {
this.conceptName = conceptName;
}
public Date getDatetime() {
return datetime;
}
public void setDatetime(Date datetime) {
this.datetime = datetime;
}
public String getEncounter() {
return encounter;
}
public void setEncounter(String encounter) {
this.encounter = encounter;
}
public Date getEncounterDatetime() {
return encounterDatetime;
}
public void setEcounterDatetime(Date encounterDatetime) {
this.encounterDatetime = encounterDatetime;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public Boolean getVoided() {
return voided;
}
public void setVoided(Boolean voided) {
this.voided = voided;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
/**
* @return Returns the encounterDate.
*/
public String getEncounterDate() {
return encounterDate;
}
/**
* @param encounterDate The encounterDate to set.
*/
public void setEncounterDate(String encounterDate) {
this.encounterDate = encounterDate;
}
/**
* @return Returns the encounterName.
*/
public String getEncounterName() {
return encounterName;
}
/**
* @param encounterName The encounterName to set.
*/
public void setEncounterName(String encounterName) {
this.encounterName = encounterName;
}
/**
* @return Returns the obsDate.
*/
public String getObsDate() {
return obsDate;
}
/**
* @param obsDate The obsDate to set.
*/
public void setObsDate(String obsDate) {
this.obsDate = obsDate;
}
/**
* @param encounterDatetime The encounterDatetime to set.
*/
public void setEncounterDatetime(Date encounterDatetime) {
this.encounterDatetime = encounterDatetime;
}
}
| true | true | public ObsListItem(Obs obs, Locale locale) {
if (obs != null) {
obsId = obs.getObsId();
if (obs.getEncounter() != null) {
encounter = obs.getEncounter().getEncounterId().toString();
encounterDatetime = obs.getEncounter().getEncounterDatetime();
encounterDate = encounterDatetime == null ? "" : Format.format(encounterDatetime, locale, FORMAT_TYPE.DATE);
encounterName = obs.getEncounter().getForm() == null ? "" : obs.getEncounter().getForm().getName();
}
personName = obs.getPerson().getPersonName().toString();
conceptName = obs.getConcept().getName(locale).getName();
if (obs.getOrder() != null)
order = obs.getOrder().getOrderId().toString();
location = obs.getLocation().getName();
datetime = obs.getObsDatetime();
obsDate = datetime == null ? "" : Format.format(datetime, locale, FORMAT_TYPE.DATE);
voided = obs.isVoided();
value = obs.getValueAsString(locale);
}
}
| public ObsListItem(Obs obs, Locale locale) {
if (obs != null) {
obsId = obs.getObsId();
if (obs.getEncounter() != null) {
encounter = obs.getEncounter().getEncounterId().toString();
encounterDatetime = obs.getEncounter().getEncounterDatetime();
encounterDate = encounterDatetime == null ? "" : Format.format(encounterDatetime, locale, FORMAT_TYPE.DATE);
encounterName = obs.getEncounter().getForm() == null ? "" : obs.getEncounter().getForm().getName();
}
personName = obs.getPerson().getPersonName().toString();
conceptName = obs.getConcept().getName(locale).getName();
if (obs.getOrder() != null)
order = obs.getOrder().getOrderId().toString();
if (obs.getLocation() != null)
location = obs.getLocation().getName();
datetime = obs.getObsDatetime();
obsDate = datetime == null ? "" : Format.format(datetime, locale, FORMAT_TYPE.DATE);
voided = obs.isVoided();
value = obs.getValueAsString(locale);
}
}
|
diff --git a/cruisecontrol/main/test/net/sourceforge/cruisecontrol/util/ProcessesTest.java b/cruisecontrol/main/test/net/sourceforge/cruisecontrol/util/ProcessesTest.java
index 2d545aba..c6284713 100644
--- a/cruisecontrol/main/test/net/sourceforge/cruisecontrol/util/ProcessesTest.java
+++ b/cruisecontrol/main/test/net/sourceforge/cruisecontrol/util/ProcessesTest.java
@@ -1,157 +1,157 @@
/********************************************************************************
* CruiseControl, a Continuous Integration Toolkit
* Copyright (c) 2006, ThoughtWorks, Inc.
* 200 E. Randolph, 25th Floor
* Chicago, IL 60601 USA
* 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 ThoughtWorks, Inc., CruiseControl, 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 REGENTS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************/
package net.sourceforge.cruisecontrol.util;
import junit.framework.TestCase;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ProcessesTest extends TestCase {
public void testShouldReturnProcessWhenCommandProvided() throws IOException {
Processes.setRuntime(new MockExecutor());
Commandline c = new Commandline() {
};
assertNotNull(Processes.execute(c));
}
- public void testShouldStartStreamPumperForErrorStream() throws IOException {
+ public void testShouldStartStreamPumperForErrorStream() throws Exception {
Processes.setRuntime(new MockExecutor());
Commandline c = new Commandline();
c.setExecutable("UnitTestDummyExcectuable");
int preCount = Thread.activeCount();
assertNotNull(Processes.execute(c));
// allow some time for thread to spin up. can be longer in java 5
int waitCount = 0;
int postCount = Thread.activeCount();
while ((preCount <= postCount) && (waitCount < 40)) {
waitCount++;
- Thread.yield();
+ Thread.sleep(10);
postCount = Thread.activeCount();
}
assertTrue("A StreamPumper Thread wasn't started. postCount: " + postCount
+ "; preCount: " + preCount + "; waitCount: " + waitCount,
postCount > preCount);
}
public void testShouldCloseStreamsWhenExecutingFully() throws IOException, InterruptedException {
MockExecutor executor = new MockExecutor();
Processes.setRuntime(executor);
Commandline c = new Commandline() {
};
Processes.executeFully(c);
assertTrue(executor.streamsClosed());
}
private static class CloseableProcess extends MockProcess {
private CloseAwareInputStream error = new CloseAwareInputStream(4 * 1000);
private CloseAwareInputStream input = new CloseAwareInputStream(4 * 1000);
private CloseAwareOutputStream output = new CloseAwareOutputStream();
public CloseableProcess() {
super();
setErrorStream(error);
setInputStream(input);
setOutputStream(output);
}
public boolean streamsClosed() {
return error.isClosed() && input.isClosed() && output.isClosed();
}
}
private static final class CloseAwareInputStream extends InputStream {
private final int millisTillEndOfStream;
private long starttime;
private boolean closed;
private CloseAwareInputStream(final int millisTillEndOfStream) {
this.millisTillEndOfStream = millisTillEndOfStream;
}
public void close() throws IOException {
closed = true;
}
public boolean isClosed() {
return closed;
}
public int read() throws IOException {
if (starttime == 0) {
starttime = System.currentTimeMillis();
}
if ((System.currentTimeMillis() - starttime) < millisTillEndOfStream) {
Thread.yield();
return 0;
}
return -1;
}
}
static class CloseAwareOutputStream extends OutputStream {
private boolean closed;
public void close() throws IOException {
closed = true;
}
public boolean isClosed() {
return closed;
}
public void write(int i) throws IOException {
}
}
private static class MockExecutor implements Executor {
private CloseableProcess mockProcess;
public Process exec(Commandline c) throws IOException {
mockProcess = new CloseableProcess();
return mockProcess;
}
public boolean streamsClosed() {
return mockProcess.streamsClosed();
}
}
}
| false | true | public void testShouldStartStreamPumperForErrorStream() throws IOException {
Processes.setRuntime(new MockExecutor());
Commandline c = new Commandline();
c.setExecutable("UnitTestDummyExcectuable");
int preCount = Thread.activeCount();
assertNotNull(Processes.execute(c));
// allow some time for thread to spin up. can be longer in java 5
int waitCount = 0;
int postCount = Thread.activeCount();
while ((preCount <= postCount) && (waitCount < 40)) {
waitCount++;
Thread.yield();
postCount = Thread.activeCount();
}
assertTrue("A StreamPumper Thread wasn't started. postCount: " + postCount
+ "; preCount: " + preCount + "; waitCount: " + waitCount,
postCount > preCount);
}
| public void testShouldStartStreamPumperForErrorStream() throws Exception {
Processes.setRuntime(new MockExecutor());
Commandline c = new Commandline();
c.setExecutable("UnitTestDummyExcectuable");
int preCount = Thread.activeCount();
assertNotNull(Processes.execute(c));
// allow some time for thread to spin up. can be longer in java 5
int waitCount = 0;
int postCount = Thread.activeCount();
while ((preCount <= postCount) && (waitCount < 40)) {
waitCount++;
Thread.sleep(10);
postCount = Thread.activeCount();
}
assertTrue("A StreamPumper Thread wasn't started. postCount: " + postCount
+ "; preCount: " + preCount + "; waitCount: " + waitCount,
postCount > preCount);
}
|
diff --git a/parser/src/de/skuzzle/polly/parsing/InputParser.java b/parser/src/de/skuzzle/polly/parsing/InputParser.java
index ccf21da7..b2c17803 100644
--- a/parser/src/de/skuzzle/polly/parsing/InputParser.java
+++ b/parser/src/de/skuzzle/polly/parsing/InputParser.java
@@ -1,717 +1,711 @@
package de.skuzzle.polly.parsing;
import java.io.UnsupportedEncodingException;
import java.util.List;
import de.skuzzle.polly.parsing.PrecedenceTable.PrecedenceLevel;
import de.skuzzle.polly.parsing.declarations.Declaration;
import de.skuzzle.polly.parsing.declarations.FunctionDeclaration;
import de.skuzzle.polly.parsing.declarations.VarDeclaration;
import de.skuzzle.polly.parsing.tree.AssignmentExpression;
import de.skuzzle.polly.parsing.tree.BinaryExpression;
import de.skuzzle.polly.parsing.tree.CastExpression;
import de.skuzzle.polly.parsing.tree.Expression;
import de.skuzzle.polly.parsing.tree.NamespaceAccessExpression;
import de.skuzzle.polly.parsing.tree.Root;
import de.skuzzle.polly.parsing.tree.TernaryExpression;
import de.skuzzle.polly.parsing.tree.TreeElement;
import de.skuzzle.polly.parsing.tree.TypeParameterExpression;
import de.skuzzle.polly.parsing.tree.UnaryExpression;
import de.skuzzle.polly.parsing.tree.VarOrCallExpression;
import de.skuzzle.polly.parsing.tree.literals.BooleanLiteral;
import de.skuzzle.polly.parsing.tree.literals.ChannelLiteral;
import de.skuzzle.polly.parsing.tree.literals.CommandLiteral;
import de.skuzzle.polly.parsing.tree.literals.DateLiteral;
import de.skuzzle.polly.parsing.tree.literals.HelpLiteral;
import de.skuzzle.polly.parsing.tree.literals.IdentifierLiteral;
import de.skuzzle.polly.parsing.tree.literals.ListLiteral;
import de.skuzzle.polly.parsing.tree.literals.Literal;
import de.skuzzle.polly.parsing.tree.literals.NumberLiteral;
import de.skuzzle.polly.parsing.tree.literals.StringLiteral;
import de.skuzzle.polly.parsing.tree.literals.TimespanLiteral;
import de.skuzzle.polly.parsing.tree.literals.UserLiteral;
/**
*
* <pre>
* input -> command (\t signature)? EOS
* signature -> assignment (\t assignment)*
*
* assignment -> relation ('->' modifier definition)?
* modifier -> 'public'? 'temp'?
* definition -> identifier ( '(' func_definition ')' )
* func_def -> ( type_def \t identifier (',' type_def \t identifier)* ) | e
* type_def -> identifier ('<' identifier '>')?
*
* relation -> conjunction (relational_op conjunction)?
* conjunction -> disjunction (conjunction_op disjunction)*
* disjunction -> expression (disjunction_op expression)*
* expression -> term (expression_op term)*
* term -> factor (term_op factor)*
* factor -> postfix (factor_op factor)?
* postfix -> autlist (postfix_op)*
* autolist -> dotdot (';' dotdot)*
* dotdot -> literal ('..' literal ('?' literal)?)?
* access -> literal ['.' literal]
* literal -> identifier ( '(' parameters ')' )?
* | boolean_literal
* | number_literal
* | channel_literal
* | string_literal
* | date_literal
* | '{' list_literal '}'
* | '(' relation ')'
* | '-' literal
* | '!' literal
* list_literal -> e // for empty lists!
* | expression (',' expression)
*
* command -> ':' identifier
* identifier ->
* boolean_literal -> 'true' | 'false' | 'ja' | 'nein'
* number_literal -> \d+(\.\d+)?([+-]?[eE]\d+)?
* channel_literal -> '#' identifier
* user_literal -> identifier ':'
* string_literal -> '"' any_char '"'
* date_literal ->
* conjunction_op -> '||' | '|'
* disjunction_op -> '&&' | '&'
* relational_op -> '>' | '<' | '<=' | '>=' | '==' | '!='
* expression_op -> '+' | '-'
* term_op -> '*' | '/' | '\' | '%'
* factor_op -> '^'
* </pre>
*
* This leads to the following list of operator precedence (with descending precedence
* level):
*
* <pre>
* !,- Unary operators
* .. Dotdot list generator operator
* [] Index access for lists and strings
* ^ Exponential operator
* /,*,\,% Arithmetic operators
* +,- Arithmetic operators
* &,&& Boolean/Integer 'And'
* |,|| Boolean/Integer 'Or'
* <,>,==,!= Relational operators
* <=,>=
* -> Assignment operator
* </pre>
*
*/
public class InputParser extends AbstractParser<InputScanner> {
private PrecedenceTable operators;
private int openExpressions;
public Root parse(String input) throws ParseException {
try {
return this.parse(input, "ISO-8859-1");
} catch (UnsupportedEncodingException ignore) {
ignore.printStackTrace();
}
// better not happen
return null;
}
public Root parse(String input, String encoding)
throws ParseException, UnsupportedEncodingException {
InputScanner inp = new InputScanner(input, encoding);
this.operators = new PrecedenceTable();
return (Root) this.parse(inp);
}
public Root tryParse(String input) {
try {
return this.tryParse(input, "ISO-8859-1");
} catch (UnsupportedEncodingException ignore) {
return null;
}
}
public Root tryParse(String input, String encoding)
throws UnsupportedEncodingException {
return (Root) this.tryParse(new InputScanner(input, encoding));
}
protected void allowWhiteSpace() throws ParseException {
this.scanner.match(TokenType.SEPERATOR);
}
protected void enterExpression() {
++this.openExpressions;
this.scanner.setSkipWhiteSpaces(true);
}
protected void leaveExpression() {
--this.openExpressions;
if (this.openExpressions == 0) {
this.scanner.setSkipWhiteSpaces(false);
}
}
@Override
protected TreeElement parse_input() throws ParseException {
/*
* Ignore any ParseException when reading the first character to ignore
* inputs that are not meant to be parsed.
*/
Root root = null;
try {
Token la = this.scanner.lookAhead();
if (!this.scanner.match(TokenType.COMMAND)) {
return null;
}
root = new Root(new CommandLiteral(la));
// Commandnames must be at least 3 characters
if (root.getName().getCommandName().length() < 3) {
return null;
}
} catch (Exception e) {
return null;
}
if (this.scanner.lookAhead().matches(TokenType.SEPERATOR)) {
this.expect(TokenType.SEPERATOR);
this.parse_signature(root.getParameters());
}
// fixing ISSUE 0000015 with expecting an EOS here. This prevents unexpected chars
// to be ignored.
this.expect(TokenType.EOS);
return root;
}
protected void parse_signature(List<Expression> expressions) throws ParseException {
expressions.add(this.parse_assignment());
while (this.scanner.lookAhead().matches(TokenType.SEPERATOR)) {
this.scanner.consume();
expressions.add(this.parse_assignment());
}
}
protected Expression parse_assignment() throws ParseException {
Expression expression = this.parse_relational();
Token la = this.scanner.lookAhead();
if (la.matches(TokenType.ASSIGNMENT)) {
this.scanner.consume();
expression = new AssignmentExpression(expression, la.getPosition(),
this.parse_definition());
}
return expression;
}
protected Declaration parse_definition() throws ParseException {
boolean isPublic = false;
if (this.scanner.match(TokenType.PUBLIC)) {
this.expect(TokenType.SEPERATOR);
isPublic = true;
}
boolean isTemp = false;
if (this.scanner.match(TokenType.TEMP)) {
this.expect(TokenType.SEPERATOR);
isTemp = true;
}
Token id = this.expect(TokenType.IDENTIFIER);
if (this.scanner.match(TokenType.OPENBR)) {
FunctionDeclaration decl = new FunctionDeclaration(new IdentifierLiteral(id),
isPublic, isTemp);
this.parse_func_definition(decl.getFormalParameters());
this.expect(TokenType.CLOSEDBR);
return decl;
}
return new VarDeclaration(new IdentifierLiteral(id), isPublic, isTemp);
}
protected void parse_func_definition(List<VarDeclaration> parameters)
throws ParseException {
/*
* If the next token is a closing brace, return. So we have functions with no
* parameters
*/
if (this.scanner.lookAhead().getType() == TokenType.CLOSEDBR) {
return;
}
int i = 0;
do {
if (i++ != 0) {
// HACK: in second iteration, a whitespace is allowed here
this.allowWhiteSpace();
}
Expression type = this.parse_type_definition();
this.expect(TokenType.SEPERATOR);
Token paramName = this.expect(TokenType.IDENTIFIER);
VarDeclaration decl = new VarDeclaration(
new IdentifierLiteral(paramName.getStringValue()), false, false);
decl.setExpression(type);
parameters.add(decl);
} while (this.scanner.match(TokenType.COMMA));
}
protected Expression parse_type_definition() throws ParseException {
Token typeId = this.expect(TokenType.IDENTIFIER);
Token la = this.scanner.lookAhead();
if (la.matches(TokenType.LT)) {
this.scanner.consume();
Token subId = this.expect(TokenType.IDENTIFIER);
this.expect(TokenType.GT);
return new TypeParameterExpression(new IdentifierLiteral(typeId),
new IdentifierLiteral(subId),
this.scanner.spanFrom(typeId));
}
return new TypeParameterExpression(new IdentifierLiteral(typeId),
this.scanner.spanFrom(typeId));
}
protected Expression parse_relational() throws ParseException {
Expression expression = this.parse_conjunction();
Token la = this.scanner.lookAhead();
if (this.operators.match(la, PrecedenceLevel.RELATION)) {
this.scanner.consume();
expression = new BinaryExpression(expression, la, this.parse_conjunction());
}
return expression;
}
protected Expression parse_conjunction() throws ParseException {
Expression expression = parse_disjunction();
Token la = this.scanner.lookAhead();
while (this.operators.match(la, PrecedenceLevel.CONJUNCTION)) {
this.scanner.consume();
expression = new BinaryExpression(expression, la, this.parse_disjunction());
la = this.scanner.lookAhead();
}
return expression;
}
protected Expression parse_disjunction() throws ParseException {
Expression expression = parse_expression();
Token la = this.scanner.lookAhead();
while (this.operators.match(la, PrecedenceLevel.DISJUNCTION)) {
this.scanner.consume();
expression = new BinaryExpression(expression, la, this.parse_expression());
la = this.scanner.lookAhead();
}
return expression;
}
protected Expression parse_expression() throws ParseException {
Expression expression = this.parse_term();
Token la = this.scanner.lookAhead();
while (this.operators.match(la, PrecedenceLevel.EXPRESSION)) {
this.scanner.consume();
expression = new BinaryExpression(expression, la, this.parse_term());
la = this.scanner.lookAhead();
}
return expression;
}
protected Expression parse_term() throws ParseException {
Expression expression = this.parse_factor();
Token la = this.scanner.lookAhead();
while (this.operators.match(la, PrecedenceLevel.TERM)) {
// ISSUE 0000099: If Identifier or open brace, do not consume the token but
// pretend it was a multiplication
if (la.matches(TokenType.IDENTIFIER) || la.matches(TokenType.OPENBR)) {
la = new Token(TokenType.MUL, la.getPosition());
} else {
this.scanner.consume();
}
expression = new BinaryExpression(expression, la, this.parse_factor());
la = this.scanner.lookAhead();
}
return expression;
}
protected Expression parse_factor() throws ParseException {
Expression expression = this.parse_postfix();
Token la = this.scanner.lookAhead();
while (this.operators.match(la, PrecedenceLevel.FACTOR)) {
this.scanner.consume();
expression = new BinaryExpression(expression, la, this.parse_factor());
la = this.scanner.lookAhead();
}
return expression;
}
protected Expression parse_postfix() throws ParseException {
// Expression expression = this.parse_dotdot();
Expression expression = this.parse_autolist();
Token la = this.scanner.lookAhead();
while (this.operators.match(la, PrecedenceLevel.POSTFIX)) {
this.scanner.consume();
if (la.matches(TokenType.OPENSQBR)) {
Token t = new Token(TokenType.INDEX, this.scanner.spanFrom(la));
expression = new BinaryExpression(expression, t, this.parse_expression());
this.expect(TokenType.CLOSEDSQBR);
/*
* Correct position so that it spans the whole operator including
* the closing braces.
*/
expression.setPosition(this.scanner.spanFrom(la));
} else if (la.matches(TokenType.QUESTION)) {
return new UnaryExpression(la, expression);
}
la = this.scanner.lookAhead();
}
return expression;
}
protected Expression parse_autolist() throws ParseException {
Expression e = this.parse_dotdot();
Token la = this.scanner.lookAhead();
if (la.matches(TokenType.SEMICOLON)) {
ListLiteral result = new ListLiteral(la);
result.getElements().add(e);
while (this.scanner.match(TokenType.SEMICOLON)) {
result.getElements().add(this.parse_dotdot());
}
return result;
} else {
return e;
}
}
protected Expression parse_dotdot() throws ParseException {
Expression expression = this.parse_access();
Token la = this.scanner.lookAhead();
if (this.operators.match(la, PrecedenceLevel.DOTDOT)) {
this.scanner.consume();
// Default step value
Literal tmp = new NumberLiteral(1.0, this.scanner.spanFrom(la));
TernaryExpression tmpExpression = new TernaryExpression(expression,
this.parse_access(), tmp, la);
la = scanner.lookAhead();
if (la.matches(TokenType.DOLLAR)) {
this.scanner.consume();
tmpExpression.setThirdOperand(this.parse_access());
}
expression = tmpExpression;
}
return expression;
}
protected Expression parse_access() throws ParseException {
Expression e = this.parse_literal();
Token la = this.scanner.lookAhead();
if (la.matches(TokenType.DOT)) {
this.scanner.consume();
e = new NamespaceAccessExpression(e, this.parse_literal(),
new Position(e.getPosition(), this.scanner.spanFrom(la)));
}
return e;
}
protected Expression parse_literal() throws ParseException {
Token la = this.scanner.lookAhead();
Expression expression = null;
switch (la.getType()) {
case IDENTIFIER:
this.scanner.consume();
IdentifierLiteral id = new IdentifierLiteral(la);
la = this.scanner.lookAhead();
if (la.getType() == TokenType.OPENBR) {
this.scanner.consume();
VarOrCallExpression call = new VarOrCallExpression(id);
this.parse_expression_list(call.getActualParameters(),
TokenType.CLOSEDBR);
this.expect(TokenType.CLOSEDBR);
/*
* CONSIDER: make the function calls position span the whole
* statement including parameter and braces?
*
* call.setPosition(this.scanner.spanFrom(id.getToken()));
*/
return call;
} else {
/* fixed ISSUE: 0000003 with VarAccessExpression */
return new VarOrCallExpression(id);
}
case RADIX:
this.scanner.consume();
return new BinaryExpression(
new NumberLiteral(la.getLongValue(), la.getPosition()),
la,
this.parse_literal());
case CHANNEL:
this.scanner.consume();
return new ChannelLiteral(la);
case USER:
this.scanner.consume();
return new UserLiteral(la);
case STRING:
this.scanner.consume();
return new StringLiteral(la);
case NUMBER:
this.scanner.consume();
return new NumberLiteral(la);
case TRUE:
case FALSE:
this.scanner.consume();
return new BooleanLiteral(la);
case OPENBR:
this.scanner.consume();
/*
* Now we can ignore whitespaces until the matching closing brace is
* read.
*/
this.enterExpression();
/*
* Check if this is a type cast. If it is not, but a normal
* identifier in braces, context check will resolve this issue.
*
* gettin' little messy now
*/
Token tmp = this.scanner.lookAhead();
- if (tmp.getType() == TokenType.IDENTIFIER) {
+ if (tmp.matches(TokenType.IDENTIFIER)) {
this.scanner.consume();
// check for subtype
Token subType = null;
if (this.scanner.match(TokenType.LT)) {
subType = this.scanner.lookAhead();
this.expect(TokenType.IDENTIFIER);
this.expect(TokenType.GT);
}
if (this.scanner.lookAhead().getType() == TokenType.CLOSEDBR) {
this.scanner.consume();
this.leaveExpression();
Expression castOp;
if (this.scanner.lookAhead().getType() == TokenType.EOS) {
// just an identifier in braces?
return new VarOrCallExpression(
new IdentifierLiteral(tmp));
} else if (subType == null) {
castOp = new TypeParameterExpression(
new IdentifierLiteral(tmp.getStringValue()),
tmp.getPosition());
} else {
castOp = new TypeParameterExpression(
new IdentifierLiteral(tmp.getStringValue()),
new IdentifierLiteral(subType.getStringValue()),
this.scanner.spanFrom(tmp.getPosition().getStart()));
}
return new CastExpression(
castOp,
this.parse_literal(),
this.scanner.spanFrom(la));
} else if (subType != null) {
throw new ParseException("Invalid sub type definition",
subType.getPosition());
} else {
/*
* this was no typecast, so pushback the identifier and go on
* the normal way.
*/
this.scanner.pushback(tmp);
}
- } else {
- /*
- * this was no typecast, so pushback the identifier and go on
- * the normal way.
- */
- this.scanner.pushback(tmp);
}
expression = this.parse_relational();
/*
* HACK: EXPERIMENTAL
*/
la = this.scanner.lookAhead();
- if (la.getType() == TokenType.COMMA) {
+ if (la.matches(TokenType.COMMA)) {
this.scanner.consume();
Expression e2 = this.parse_relational();
this.expect(TokenType.CLOSEDBR);
this.leaveExpression();
return new BinaryExpression(expression, new Token(TokenType.CHOOSE,
la.getPosition()), e2);
}
this.expect(TokenType.CLOSEDBR);
this.leaveExpression();
/*
* To include braces within the position
*/
expression.setPosition(this.scanner.spanFrom(la));
return expression;
case OPENCURLBR:
this.scanner.consume();
ListLiteral result = new ListLiteral(la);
this.parse_expression_list(result.getElements(), TokenType.CLOSEDCURLBR);
this.expect(TokenType.CLOSEDCURLBR);
/*
* Correct position so it contains the closing brace
*/
result.setPosition(this.scanner.spanFrom(la));
return result;
case DATETIME:
this.scanner.consume();
return new DateLiteral(la);
case TIMESPAN:
this.scanner.consume();
return new TimespanLiteral(la);
case SUB:
case EXCLAMATION:
this.scanner.consume();
return new UnaryExpression(la, this.parse_literal());
case COMMAND:
this.scanner.consume();
return new CommandLiteral(la);
case QUESTION:
this.scanner.consume();
return new HelpLiteral(la);
default:
/*
* This will cause a ParseException to be thrown, indicating a missing
* literal.
*/
this.expect(TokenType.LITERAL);
}
return null;
}
protected void parse_expression_list(List<Expression> result,
TokenType listEnd) throws ParseException {
Token la = this.scanner.lookAhead();
/*
* Empty list
*/
if (la.matches(listEnd)) {
return;
}
result.add(this.parse_relational());
/*
* Whitespaces are allowed after comma
*/
la = this.scanner.lookAhead();
while (la.matches(TokenType.COMMA)) {
this.scanner.consume();
this.allowWhiteSpace();
result.add(this.parse_relational());
la = this.scanner.lookAhead();
}
}
}
| false | true | protected Expression parse_literal() throws ParseException {
Token la = this.scanner.lookAhead();
Expression expression = null;
switch (la.getType()) {
case IDENTIFIER:
this.scanner.consume();
IdentifierLiteral id = new IdentifierLiteral(la);
la = this.scanner.lookAhead();
if (la.getType() == TokenType.OPENBR) {
this.scanner.consume();
VarOrCallExpression call = new VarOrCallExpression(id);
this.parse_expression_list(call.getActualParameters(),
TokenType.CLOSEDBR);
this.expect(TokenType.CLOSEDBR);
/*
* CONSIDER: make the function calls position span the whole
* statement including parameter and braces?
*
* call.setPosition(this.scanner.spanFrom(id.getToken()));
*/
return call;
} else {
/* fixed ISSUE: 0000003 with VarAccessExpression */
return new VarOrCallExpression(id);
}
case RADIX:
this.scanner.consume();
return new BinaryExpression(
new NumberLiteral(la.getLongValue(), la.getPosition()),
la,
this.parse_literal());
case CHANNEL:
this.scanner.consume();
return new ChannelLiteral(la);
case USER:
this.scanner.consume();
return new UserLiteral(la);
case STRING:
this.scanner.consume();
return new StringLiteral(la);
case NUMBER:
this.scanner.consume();
return new NumberLiteral(la);
case TRUE:
case FALSE:
this.scanner.consume();
return new BooleanLiteral(la);
case OPENBR:
this.scanner.consume();
/*
* Now we can ignore whitespaces until the matching closing brace is
* read.
*/
this.enterExpression();
/*
* Check if this is a type cast. If it is not, but a normal
* identifier in braces, context check will resolve this issue.
*
* gettin' little messy now
*/
Token tmp = this.scanner.lookAhead();
if (tmp.getType() == TokenType.IDENTIFIER) {
this.scanner.consume();
// check for subtype
Token subType = null;
if (this.scanner.match(TokenType.LT)) {
subType = this.scanner.lookAhead();
this.expect(TokenType.IDENTIFIER);
this.expect(TokenType.GT);
}
if (this.scanner.lookAhead().getType() == TokenType.CLOSEDBR) {
this.scanner.consume();
this.leaveExpression();
Expression castOp;
if (this.scanner.lookAhead().getType() == TokenType.EOS) {
// just an identifier in braces?
return new VarOrCallExpression(
new IdentifierLiteral(tmp));
} else if (subType == null) {
castOp = new TypeParameterExpression(
new IdentifierLiteral(tmp.getStringValue()),
tmp.getPosition());
} else {
castOp = new TypeParameterExpression(
new IdentifierLiteral(tmp.getStringValue()),
new IdentifierLiteral(subType.getStringValue()),
this.scanner.spanFrom(tmp.getPosition().getStart()));
}
return new CastExpression(
castOp,
this.parse_literal(),
this.scanner.spanFrom(la));
} else if (subType != null) {
throw new ParseException("Invalid sub type definition",
subType.getPosition());
} else {
/*
* this was no typecast, so pushback the identifier and go on
* the normal way.
*/
this.scanner.pushback(tmp);
}
} else {
/*
* this was no typecast, so pushback the identifier and go on
* the normal way.
*/
this.scanner.pushback(tmp);
}
expression = this.parse_relational();
/*
* HACK: EXPERIMENTAL
*/
la = this.scanner.lookAhead();
if (la.getType() == TokenType.COMMA) {
this.scanner.consume();
Expression e2 = this.parse_relational();
this.expect(TokenType.CLOSEDBR);
this.leaveExpression();
return new BinaryExpression(expression, new Token(TokenType.CHOOSE,
la.getPosition()), e2);
}
this.expect(TokenType.CLOSEDBR);
this.leaveExpression();
/*
* To include braces within the position
*/
expression.setPosition(this.scanner.spanFrom(la));
return expression;
case OPENCURLBR:
this.scanner.consume();
ListLiteral result = new ListLiteral(la);
this.parse_expression_list(result.getElements(), TokenType.CLOSEDCURLBR);
this.expect(TokenType.CLOSEDCURLBR);
/*
* Correct position so it contains the closing brace
*/
result.setPosition(this.scanner.spanFrom(la));
return result;
case DATETIME:
this.scanner.consume();
return new DateLiteral(la);
case TIMESPAN:
this.scanner.consume();
return new TimespanLiteral(la);
case SUB:
case EXCLAMATION:
this.scanner.consume();
return new UnaryExpression(la, this.parse_literal());
case COMMAND:
this.scanner.consume();
return new CommandLiteral(la);
case QUESTION:
this.scanner.consume();
return new HelpLiteral(la);
default:
/*
* This will cause a ParseException to be thrown, indicating a missing
* literal.
*/
this.expect(TokenType.LITERAL);
}
return null;
}
| protected Expression parse_literal() throws ParseException {
Token la = this.scanner.lookAhead();
Expression expression = null;
switch (la.getType()) {
case IDENTIFIER:
this.scanner.consume();
IdentifierLiteral id = new IdentifierLiteral(la);
la = this.scanner.lookAhead();
if (la.getType() == TokenType.OPENBR) {
this.scanner.consume();
VarOrCallExpression call = new VarOrCallExpression(id);
this.parse_expression_list(call.getActualParameters(),
TokenType.CLOSEDBR);
this.expect(TokenType.CLOSEDBR);
/*
* CONSIDER: make the function calls position span the whole
* statement including parameter and braces?
*
* call.setPosition(this.scanner.spanFrom(id.getToken()));
*/
return call;
} else {
/* fixed ISSUE: 0000003 with VarAccessExpression */
return new VarOrCallExpression(id);
}
case RADIX:
this.scanner.consume();
return new BinaryExpression(
new NumberLiteral(la.getLongValue(), la.getPosition()),
la,
this.parse_literal());
case CHANNEL:
this.scanner.consume();
return new ChannelLiteral(la);
case USER:
this.scanner.consume();
return new UserLiteral(la);
case STRING:
this.scanner.consume();
return new StringLiteral(la);
case NUMBER:
this.scanner.consume();
return new NumberLiteral(la);
case TRUE:
case FALSE:
this.scanner.consume();
return new BooleanLiteral(la);
case OPENBR:
this.scanner.consume();
/*
* Now we can ignore whitespaces until the matching closing brace is
* read.
*/
this.enterExpression();
/*
* Check if this is a type cast. If it is not, but a normal
* identifier in braces, context check will resolve this issue.
*
* gettin' little messy now
*/
Token tmp = this.scanner.lookAhead();
if (tmp.matches(TokenType.IDENTIFIER)) {
this.scanner.consume();
// check for subtype
Token subType = null;
if (this.scanner.match(TokenType.LT)) {
subType = this.scanner.lookAhead();
this.expect(TokenType.IDENTIFIER);
this.expect(TokenType.GT);
}
if (this.scanner.lookAhead().getType() == TokenType.CLOSEDBR) {
this.scanner.consume();
this.leaveExpression();
Expression castOp;
if (this.scanner.lookAhead().getType() == TokenType.EOS) {
// just an identifier in braces?
return new VarOrCallExpression(
new IdentifierLiteral(tmp));
} else if (subType == null) {
castOp = new TypeParameterExpression(
new IdentifierLiteral(tmp.getStringValue()),
tmp.getPosition());
} else {
castOp = new TypeParameterExpression(
new IdentifierLiteral(tmp.getStringValue()),
new IdentifierLiteral(subType.getStringValue()),
this.scanner.spanFrom(tmp.getPosition().getStart()));
}
return new CastExpression(
castOp,
this.parse_literal(),
this.scanner.spanFrom(la));
} else if (subType != null) {
throw new ParseException("Invalid sub type definition",
subType.getPosition());
} else {
/*
* this was no typecast, so pushback the identifier and go on
* the normal way.
*/
this.scanner.pushback(tmp);
}
}
expression = this.parse_relational();
/*
* HACK: EXPERIMENTAL
*/
la = this.scanner.lookAhead();
if (la.matches(TokenType.COMMA)) {
this.scanner.consume();
Expression e2 = this.parse_relational();
this.expect(TokenType.CLOSEDBR);
this.leaveExpression();
return new BinaryExpression(expression, new Token(TokenType.CHOOSE,
la.getPosition()), e2);
}
this.expect(TokenType.CLOSEDBR);
this.leaveExpression();
/*
* To include braces within the position
*/
expression.setPosition(this.scanner.spanFrom(la));
return expression;
case OPENCURLBR:
this.scanner.consume();
ListLiteral result = new ListLiteral(la);
this.parse_expression_list(result.getElements(), TokenType.CLOSEDCURLBR);
this.expect(TokenType.CLOSEDCURLBR);
/*
* Correct position so it contains the closing brace
*/
result.setPosition(this.scanner.spanFrom(la));
return result;
case DATETIME:
this.scanner.consume();
return new DateLiteral(la);
case TIMESPAN:
this.scanner.consume();
return new TimespanLiteral(la);
case SUB:
case EXCLAMATION:
this.scanner.consume();
return new UnaryExpression(la, this.parse_literal());
case COMMAND:
this.scanner.consume();
return new CommandLiteral(la);
case QUESTION:
this.scanner.consume();
return new HelpLiteral(la);
default:
/*
* This will cause a ParseException to be thrown, indicating a missing
* literal.
*/
this.expect(TokenType.LITERAL);
}
return null;
}
|
diff --git a/library/src/jp/co/cyberagent/android/gpuimage/GPUImage.java b/library/src/jp/co/cyberagent/android/gpuimage/GPUImage.java
index 85812fc..b445732 100644
--- a/library/src/jp/co/cyberagent/android/gpuimage/GPUImage.java
+++ b/library/src/jp/co/cyberagent/android/gpuimage/GPUImage.java
@@ -1,694 +1,694 @@
/*
* Copyright (C) 2012 CyberAgent
*
* 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 jp.co.cyberagent.android.gpuimage;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Display;
import android.view.WindowManager;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.concurrent.Semaphore;
/**
* The main accessor for GPUImage functionality. This class helps to do common
* tasks through a simple interface.
*/
public class GPUImage {
private final Context mContext;
private final GPUImageRenderer mRenderer;
private GLSurfaceView mGlSurfaceView;
private GPUImageFilter mFilter;
private Bitmap mCurrentBitmap;
private ScaleType mScaleType = ScaleType.CENTER_CROP;
/**
* Instantiates a new GPUImage object.
*
* @param context the context
*/
public GPUImage(final Context context) {
if (!supportsOpenGLES2(context)) {
throw new IllegalStateException("OpenGL ES 2.0 is not supported on this phone.");
}
mContext = context;
mFilter = new GPUImageFilter();
mRenderer = new GPUImageRenderer(mFilter);
}
/**
* Checks if OpenGL ES 2.0 is supported on the current device.
*
* @param context the context
* @return true, if successful
*/
private boolean supportsOpenGLES2(final Context context) {
final ActivityManager activityManager = (ActivityManager)
context.getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo =
activityManager.getDeviceConfigurationInfo();
return configurationInfo.reqGlEsVersion >= 0x20000;
}
/**
* Sets the GLSurfaceView which will display the preview.
*
* @param view the GLSurfaceView
*/
public void setGLSurfaceView(final GLSurfaceView view) {
mGlSurfaceView = view;
mGlSurfaceView.setEGLContextClientVersion(2);
mGlSurfaceView.setRenderer(mRenderer);
mGlSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
mGlSurfaceView.requestRender();
}
/**
* Request the preview to be rendered again.
*/
public void requestRender() {
if (mGlSurfaceView != null) {
mGlSurfaceView.requestRender();
}
}
/**
* Sets the up camera to be connected to GPUImage to get a filtered preview.
*
* @param camera the camera
*/
public void setUpCamera(final Camera camera) {
setUpCamera(camera, 0, false, false);
}
/**
* Sets the up camera to be connected to GPUImage to get a filtered preview.
*
* @param camera the camera
* @param degrees by how many degrees the image should be rotated
* @param flipHorizontal if the image should be flipped horizontally
* @param flipVertical if the image should be flipped vertically
*/
public void setUpCamera(final Camera camera, final int degrees, final boolean flipHorizontal,
final boolean flipVertical) {
mGlSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
setUpCameraGingerbread(camera);
} else {
camera.setPreviewCallback(mRenderer);
camera.startPreview();
}
Rotation rotation = Rotation.NORMAL;
switch (degrees) {
case 90:
rotation = Rotation.ROTATION_90;
break;
case 180:
rotation = Rotation.ROTATION_180;
break;
case 270:
rotation = Rotation.ROTATION_270;
break;
}
mRenderer.setRotationCamera(rotation, flipHorizontal, flipVertical);
}
@TargetApi(11)
private void setUpCameraGingerbread(final Camera camera) {
mRenderer.setUpSurfaceTexture(camera);
}
/**
* Sets the filter which should be applied to the image which was (or will
* be) set by setImage(...).
*
* @param filter the new filter
*/
public void setFilter(final GPUImageFilter filter) {
mFilter = filter;
mRenderer.setFilter(mFilter);
requestRender();
}
/**
* Sets the image on which the filter should be applied.
*
* @param bitmap the new image
*/
public void setImage(final Bitmap bitmap) {
mCurrentBitmap = bitmap;
mRenderer.setImageBitmap(bitmap, false);
requestRender();
}
/**
* This sets the scale type of GPUImage. This has to be run before setting the image.
* If image is set and scale type changed, image needs to be reset.
*
* @param scaleType The new ScaleType
*/
public void setScaleType(ScaleType scaleType) {
mScaleType = scaleType;
mRenderer.setScaleType(scaleType);
mRenderer.deleteImage();
mCurrentBitmap = null;
requestRender();
}
/**
* Sets the rotation of the displayed image.
*
* @param rotation new rotation
*/
public void setRotation(Rotation rotation) {
mRenderer.setRotation(rotation);
}
/**
* Deletes the current image.
*/
public void deleteImage() {
mRenderer.deleteImage();
mCurrentBitmap = null;
requestRender();
}
/**
* Sets the image on which the filter should be applied from a Uri.
*
* @param uri the uri of the new image
*/
public void setImage(final Uri uri) {
new LoadImageUriTask(this, uri).execute();
}
/**
* Sets the image on which the filter should be applied from a File.
*
* @param file the file of the new image
*/
public void setImage(final File file) {
new LoadImageFileTask(this, file).execute();
}
private String getPath(final Uri uri) {
String[] projection = {
MediaStore.Images.Media.DATA,
};
Cursor cursor = mContext.getContentResolver()
.query(uri, projection, null, null, null);
int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String path = null;
if (cursor.moveToFirst()) {
path = cursor.getString(pathIndex);
}
cursor.close();
return path;
}
/**
* Gets the current displayed image with applied filter as a Bitmap.
*
* @return the current image with filter applied
*/
public Bitmap getBitmapWithFilterApplied() {
return getBitmapWithFilterApplied(mCurrentBitmap);
}
/**
* Gets the given bitmap with current filter applied as a Bitmap.
*
* @param bitmap the bitmap on which the current filter should be applied
* @return the bitmap with filter applied
*/
public Bitmap getBitmapWithFilterApplied(final Bitmap bitmap) {
if (mGlSurfaceView != null) {
mRenderer.deleteImage();
mRenderer.runOnDraw(new Runnable() {
@Override
public void run() {
synchronized(mFilter) {
mFilter.destroy();
mFilter.notify();
}
}
});
- requestRender();
synchronized(mFilter) {
+ requestRender();
try {
mFilter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
GPUImageRenderer renderer = new GPUImageRenderer(mFilter);
renderer.setRotation(Rotation.NORMAL,
mRenderer.isFlippedHorizontally(), mRenderer.isFlippedVertically());
renderer.setScaleType(mScaleType);
PixelBuffer buffer = new PixelBuffer(bitmap.getWidth(), bitmap.getHeight());
buffer.setRenderer(renderer);
renderer.setImageBitmap(bitmap, false);
Bitmap result = buffer.getBitmap();
mFilter.destroy();
renderer.deleteImage();
buffer.destroy();
mRenderer.setFilter(mFilter);
if (mCurrentBitmap != null) {
mRenderer.setImageBitmap(mCurrentBitmap, false);
}
requestRender();
return result;
}
/**
* Gets the images for multiple filters on a image. This can be used to
* quickly get thumbnail images for filters. <br />
* Whenever a new Bitmap is ready, the listener will be called with the
* bitmap. The order of the calls to the listener will be the same as the
* filter order.
*
* @param bitmap the bitmap on which the filters will be applied
* @param filters the filters which will be applied on the bitmap
* @param listener the listener on which the results will be notified
*/
public static void getBitmapForMultipleFilters(final Bitmap bitmap,
final List<GPUImageFilter> filters, final ResponseListener<Bitmap> listener) {
if (filters.isEmpty()) {
return;
}
GPUImageRenderer renderer = new GPUImageRenderer(filters.get(0));
renderer.setImageBitmap(bitmap, false);
PixelBuffer buffer = new PixelBuffer(bitmap.getWidth(), bitmap.getHeight());
buffer.setRenderer(renderer);
for (GPUImageFilter filter : filters) {
renderer.setFilter(filter);
listener.response(buffer.getBitmap());
filter.destroy();
}
renderer.deleteImage();
buffer.destroy();
}
/**
* Deprecated: Please use
* {@link GPUImageView#saveToPictures(String, String, jp.co.cyberagent.android.gpuimage.GPUImageView.OnPictureSavedListener)}
*
* Save current image with applied filter to Pictures. It will be stored on
* the default Picture folder on the phone below the given folerName and
* fileName. <br />
* This method is async and will notify when the image was saved through the
* listener.
*
* @param folderName the folder name
* @param fileName the file name
* @param listener the listener
*/
@Deprecated
public void saveToPictures(final String folderName, final String fileName,
final OnPictureSavedListener listener) {
saveToPictures(mCurrentBitmap, folderName, fileName, listener);
}
/**
* Deprecated: Please use
* {@link GPUImageView#saveToPictures(String, String, jp.co.cyberagent.android.gpuimage.GPUImageView.OnPictureSavedListener)}
*
* Apply and save the given bitmap with applied filter to Pictures. It will
* be stored on the default Picture folder on the phone below the given
* folerName and fileName. <br />
* This method is async and will notify when the image was saved through the
* listener.
*
* @param bitmap the bitmap
* @param folderName the folder name
* @param fileName the file name
* @param listener the listener
*/
@Deprecated
public void saveToPictures(final Bitmap bitmap, final String folderName, final String fileName,
final OnPictureSavedListener listener) {
new SaveTask(bitmap, folderName, fileName, listener).execute();
}
/**
* Runs the given Runnable on the OpenGL thread.
*
* @param runnable The runnable to be run on the OpenGL thread.
*/
void runOnGLThread(Runnable runnable) {
mRenderer.runOnDrawEnd(runnable);
}
private int getOutputWidth() {
if (mRenderer != null && mRenderer.getFrameWidth() != 0) {
return mRenderer.getFrameWidth();
} else if (mCurrentBitmap != null) {
return mCurrentBitmap.getWidth();
} else {
WindowManager windowManager =
(WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
return display.getWidth();
}
}
private int getOutputHeight() {
if (mRenderer != null && mRenderer.getFrameHeight() != 0) {
return mRenderer.getFrameHeight();
} else if (mCurrentBitmap != null) {
return mCurrentBitmap.getHeight();
} else {
WindowManager windowManager =
(WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
return display.getHeight();
}
}
@Deprecated
private class SaveTask extends AsyncTask<Void, Void, Void> {
private final Bitmap mBitmap;
private final String mFolderName;
private final String mFileName;
private final OnPictureSavedListener mListener;
private final Handler mHandler;
public SaveTask(final Bitmap bitmap, final String folderName, final String fileName,
final OnPictureSavedListener listener) {
mBitmap = bitmap;
mFolderName = folderName;
mFileName = fileName;
mListener = listener;
mHandler = new Handler();
}
@Override
protected Void doInBackground(final Void... params) {
Bitmap result = getBitmapWithFilterApplied(mBitmap);
saveImage(mFolderName, mFileName, result);
return null;
}
private void saveImage(final String folderName, final String fileName, final Bitmap image) {
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path, folderName + "/" + fileName);
try {
file.getParentFile().mkdirs();
image.compress(CompressFormat.JPEG, 80, new FileOutputStream(file));
MediaScannerConnection.scanFile(mContext,
new String[] {
file.toString()
}, null,
new MediaScannerConnection.OnScanCompletedListener() {
@Override
public void onScanCompleted(final String path, final Uri uri) {
if (mListener != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
mListener.onPictureSaved(uri);
}
});
}
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public interface OnPictureSavedListener {
void onPictureSaved(Uri uri);
}
private class LoadImageUriTask extends LoadImageTask {
private final Uri mUri;
public LoadImageUriTask(GPUImage gpuImage, Uri uri) {
super(gpuImage);
mUri = uri;
}
@Override
protected Bitmap decode(BitmapFactory.Options options) {
try {
InputStream inputStream;
if (mUri.getScheme().startsWith("http") || mUri.getScheme().startsWith("https")) {
inputStream = new URL(mUri.toString()).openStream();
} else {
inputStream = mContext.getContentResolver().openInputStream(mUri);
}
return BitmapFactory.decodeStream(inputStream, null, options);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected int getImageOrientation() throws IOException {
Cursor cursor = mContext.getContentResolver().query(mUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor == null || cursor.getCount() != 1) {
return 0;
}
cursor.moveToFirst();
int orientation = cursor.getInt(0);
cursor.close();
return orientation;
}
}
private class LoadImageFileTask extends LoadImageTask {
private final File mImageFile;
public LoadImageFileTask(GPUImage gpuImage, File file) {
super(gpuImage);
mImageFile = file;
}
@Override
protected Bitmap decode(BitmapFactory.Options options) {
return BitmapFactory.decodeFile(mImageFile.getAbsolutePath(), options);
}
@Override
protected int getImageOrientation() throws IOException {
ExifInterface exif = new ExifInterface(mImageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return 0;
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
default:
return 0;
}
}
}
private abstract class LoadImageTask extends AsyncTask<Void, Void, Bitmap> {
private final GPUImage mGPUImage;
private int mOutputWidth;
private int mOutputHeight;
@SuppressWarnings("deprecation")
public LoadImageTask(final GPUImage gpuImage) {
mGPUImage = gpuImage;
}
@Override
protected Bitmap doInBackground(Void... params) {
if (mRenderer != null && mRenderer.getFrameWidth() == 0) {
try {
synchronized (mRenderer.mSurfaceChangedWaiter) {
mRenderer.mSurfaceChangedWaiter.wait(3000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mOutputWidth = getOutputWidth();
mOutputHeight = getOutputHeight();
return loadResizedImage();
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
mGPUImage.deleteImage();
mGPUImage.setImage(bitmap);
}
protected abstract Bitmap decode(BitmapFactory.Options options);
private Bitmap loadResizedImage() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
decode(options);
int scale = 1;
while (checkSize(options.outWidth / scale > mOutputWidth, options.outHeight / scale > mOutputHeight)) {
scale++;
}
scale--;
if (scale < 1) {
scale = 1;
}
options = new BitmapFactory.Options();
options.inSampleSize = scale;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inPurgeable = true;
options.inTempStorage = new byte[32 * 1024];
Bitmap bitmap = decode(options);
if (bitmap == null) {
return null;
}
bitmap = rotateImage(bitmap);
bitmap = scaleBitmap(bitmap);
return bitmap;
}
private Bitmap scaleBitmap(Bitmap bitmap) {
// resize to desired dimensions
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] newSize = getScaleSize(width, height);
Bitmap workBitmap = Bitmap.createScaledBitmap(bitmap, newSize[0], newSize[1], true);
if (workBitmap != bitmap) {
bitmap.recycle();
bitmap = workBitmap;
System.gc();
}
if (mScaleType == ScaleType.CENTER_CROP) {
// Crop it
int diffWidth = newSize[0] - mOutputWidth;
int diffHeight = newSize[1] - mOutputHeight;
workBitmap = Bitmap.createBitmap(bitmap, diffWidth / 2, diffHeight / 2,
newSize[0] - diffWidth, newSize[1] - diffHeight);
if (workBitmap != bitmap) {
bitmap.recycle();
bitmap = workBitmap;
}
}
return bitmap;
}
/**
* Retrieve the scaling size for the image dependent on the ScaleType.<br />
* <br/>
* If CROP: sides are same size or bigger than output's sides<br />
* Else : sides are same size or smaller than output's sides
*/
private int[] getScaleSize(int width, int height) {
float newWidth;
float newHeight;
float withRatio = (float) width / mOutputWidth;
float heightRatio = (float) height / mOutputHeight;
boolean adjustWidth = mScaleType == ScaleType.CENTER_CROP
? withRatio > heightRatio : withRatio < heightRatio;
if (adjustWidth) {
newHeight = mOutputHeight;
newWidth = (newHeight / height) * width;
} else {
newWidth = mOutputWidth;
newHeight = (newWidth / width) * height;
}
return new int[]{Math.round(newWidth), Math.round(newHeight)};
}
private boolean checkSize(boolean widthBigger, boolean heightBigger) {
if (mScaleType == ScaleType.CENTER_CROP) {
return widthBigger && heightBigger;
} else {
return widthBigger || heightBigger;
}
}
private Bitmap rotateImage(final Bitmap bitmap) {
if (bitmap == null) {
return null;
}
Bitmap rotatedBitmap = bitmap;
try {
int orientation = getImageOrientation();
if (orientation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
bitmap.recycle();
}
} catch (IOException e) {
e.printStackTrace();
}
return rotatedBitmap;
}
protected abstract int getImageOrientation() throws IOException;
}
public interface ResponseListener<T> {
void response(T item);
}
public enum ScaleType { CENTER_INSIDE, CENTER_CROP }
}
| false | true | public Bitmap getBitmapWithFilterApplied(final Bitmap bitmap) {
if (mGlSurfaceView != null) {
mRenderer.deleteImage();
mRenderer.runOnDraw(new Runnable() {
@Override
public void run() {
synchronized(mFilter) {
mFilter.destroy();
mFilter.notify();
}
}
});
requestRender();
synchronized(mFilter) {
try {
mFilter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
GPUImageRenderer renderer = new GPUImageRenderer(mFilter);
renderer.setRotation(Rotation.NORMAL,
mRenderer.isFlippedHorizontally(), mRenderer.isFlippedVertically());
renderer.setScaleType(mScaleType);
PixelBuffer buffer = new PixelBuffer(bitmap.getWidth(), bitmap.getHeight());
buffer.setRenderer(renderer);
renderer.setImageBitmap(bitmap, false);
Bitmap result = buffer.getBitmap();
mFilter.destroy();
renderer.deleteImage();
buffer.destroy();
mRenderer.setFilter(mFilter);
if (mCurrentBitmap != null) {
mRenderer.setImageBitmap(mCurrentBitmap, false);
}
requestRender();
return result;
}
| public Bitmap getBitmapWithFilterApplied(final Bitmap bitmap) {
if (mGlSurfaceView != null) {
mRenderer.deleteImage();
mRenderer.runOnDraw(new Runnable() {
@Override
public void run() {
synchronized(mFilter) {
mFilter.destroy();
mFilter.notify();
}
}
});
synchronized(mFilter) {
requestRender();
try {
mFilter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
GPUImageRenderer renderer = new GPUImageRenderer(mFilter);
renderer.setRotation(Rotation.NORMAL,
mRenderer.isFlippedHorizontally(), mRenderer.isFlippedVertically());
renderer.setScaleType(mScaleType);
PixelBuffer buffer = new PixelBuffer(bitmap.getWidth(), bitmap.getHeight());
buffer.setRenderer(renderer);
renderer.setImageBitmap(bitmap, false);
Bitmap result = buffer.getBitmap();
mFilter.destroy();
renderer.deleteImage();
buffer.destroy();
mRenderer.setFilter(mFilter);
if (mCurrentBitmap != null) {
mRenderer.setImageBitmap(mCurrentBitmap, false);
}
requestRender();
return result;
}
|
diff --git a/kundera-core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfiguration.java b/kundera-core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfiguration.java
index 336123c03..7ff6842f3 100644
--- a/kundera-core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfiguration.java
+++ b/kundera-core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfiguration.java
@@ -1,169 +1,172 @@
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * 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.impetus.kundera.configure;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.KunderaPersistence;
import com.impetus.kundera.loader.PersistenceLoaderException;
import com.impetus.kundera.loader.PersistenceXMLLoader;
import com.impetus.kundera.metadata.model.ApplicationMetadata;
import com.impetus.kundera.metadata.model.KunderaMetadata;
import com.impetus.kundera.metadata.model.PersistenceUnitMetadata;
import com.impetus.kundera.utils.InvalidConfigurationException;
/**
* The Class PersistenceUnitConfiguration: 1) Find and load/configure
* persistence unit meta data. Earlier it was PersistenceUnitLoader.
*
* @author vivek.mishra
*/
public class PersistenceUnitConfiguration implements Configuration
{
/** The log instance. */
private static Logger log = LoggerFactory.getLogger(PersistenceUnitConfiguration.class);
/** The Constant PROVIDER_IMPLEMENTATION_NAME. */
private static final String PROVIDER_IMPLEMENTATION_NAME = KunderaPersistence.class.getName();
/** Holding instance for persistence units. */
protected String[] persistenceUnits;
/**
* Constructor parameterised with persistence units.
*
* @param persistenceUnits
* persistence units.
*/
public PersistenceUnitConfiguration(String... persistenceUnits)
{
this.persistenceUnits = persistenceUnits;
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.configure.Configuration#configure()
*/
@Override
public void configure()
{
log.info("Loading Metadata from persistence.xml ...");
KunderaMetadata kunderaMetadata = KunderaMetadata.INSTANCE;
ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
Map<String, PersistenceUnitMetadata> metadatas;
try
{
metadatas = findPersistenceMetadatas();
for (String persistenceUnit : persistenceUnits)
{
if (!metadatas.containsKey(persistenceUnit))
{
log.error("Unconfigured persistence unit: " + persistenceUnit
+ " please validate with persistence.xml");
throw new PersistenceUnitConfigurationException("Invalid persistence unit: " + persistenceUnit
+ " provided");
}
// metadatas.get(persistenceUnit);
}
log.info("Finishing persistence unit metadata configuration ...");
appMetadata.addPersistenceUnitMetadata(metadatas);
}
catch (InvalidConfigurationException icex)
{
log.error("Error occurred during persistence unit configuration, Caused by:" + icex.getMessage());
throw new PersistenceLoaderException(icex);
}
}
/**
* Find persistence meta data. Loads configured persistence.xml and load all
* provided configurations within persistence meta data as per @see JPA 2.0
* specifications.
*
* @return the list configure persistence unit meta data.
*/
private Map<String, PersistenceUnitMetadata> findPersistenceMetadatas() throws InvalidConfigurationException
{
Enumeration<URL> xmls = null;
try
{
xmls = Thread.currentThread().getContextClassLoader().getResources("META-INF/persistence.xml");
}
catch (IOException ioex)
{
log.warn("Error while loading persistence.xml Caused by:" + ioex.getMessage());
}
if (xmls == null || !xmls.hasMoreElements())
{
log.info("Could not find any META-INF/persistence.xml " + " file in the classpath");
throw new InvalidConfigurationException("Could not find any META-INF/persistence.xml "
+ " file in the classpath");
}
Set<String> persistenceUnitNames = new HashSet<String>();
Map<String, PersistenceUnitMetadata> persistenceUnitMap = new HashMap<String, PersistenceUnitMetadata>();
while (xmls.hasMoreElements())
{
URL url = xmls.nextElement();
log.trace("Analysing persistence.xml: " + url);
List<PersistenceUnitMetadata> metadataFiles = PersistenceXMLLoader.findPersistenceUnits(url,
PersistenceUnitTransactionType.RESOURCE_LOCAL);
// Pick only those that have Kundera Provider
for (PersistenceUnitMetadata metadata : metadataFiles)
{
// check for unique names
if (persistenceUnitNames.contains(metadata.getPersistenceUnitName()))
{
- throw new InvalidConfigurationException("Duplicate persistence-units for name: "
- + metadata.getPersistenceUnitName() + ". verify your persistence.xml file");
+ if (log.isWarnEnabled())
+ {
+ log.warn("Duplicate persistence-units for name: " + metadata.getPersistenceUnitName()
+ + ". verify your persistence.xml file");
+ }
}
// check for provider
if (metadata.getPersistenceProviderClassName() == null
|| PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getPersistenceProviderClassName()))
{
persistenceUnitMap.put(metadata.getPersistenceUnitName(), metadata);
}
// add to check for duplicate persistence unit.
persistenceUnitNames.add(metadata.getPersistenceUnitName());
}
}
return persistenceUnitMap;
}
}
| true | true | private Map<String, PersistenceUnitMetadata> findPersistenceMetadatas() throws InvalidConfigurationException
{
Enumeration<URL> xmls = null;
try
{
xmls = Thread.currentThread().getContextClassLoader().getResources("META-INF/persistence.xml");
}
catch (IOException ioex)
{
log.warn("Error while loading persistence.xml Caused by:" + ioex.getMessage());
}
if (xmls == null || !xmls.hasMoreElements())
{
log.info("Could not find any META-INF/persistence.xml " + " file in the classpath");
throw new InvalidConfigurationException("Could not find any META-INF/persistence.xml "
+ " file in the classpath");
}
Set<String> persistenceUnitNames = new HashSet<String>();
Map<String, PersistenceUnitMetadata> persistenceUnitMap = new HashMap<String, PersistenceUnitMetadata>();
while (xmls.hasMoreElements())
{
URL url = xmls.nextElement();
log.trace("Analysing persistence.xml: " + url);
List<PersistenceUnitMetadata> metadataFiles = PersistenceXMLLoader.findPersistenceUnits(url,
PersistenceUnitTransactionType.RESOURCE_LOCAL);
// Pick only those that have Kundera Provider
for (PersistenceUnitMetadata metadata : metadataFiles)
{
// check for unique names
if (persistenceUnitNames.contains(metadata.getPersistenceUnitName()))
{
throw new InvalidConfigurationException("Duplicate persistence-units for name: "
+ metadata.getPersistenceUnitName() + ". verify your persistence.xml file");
}
// check for provider
if (metadata.getPersistenceProviderClassName() == null
|| PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getPersistenceProviderClassName()))
{
persistenceUnitMap.put(metadata.getPersistenceUnitName(), metadata);
}
// add to check for duplicate persistence unit.
persistenceUnitNames.add(metadata.getPersistenceUnitName());
}
}
return persistenceUnitMap;
}
| private Map<String, PersistenceUnitMetadata> findPersistenceMetadatas() throws InvalidConfigurationException
{
Enumeration<URL> xmls = null;
try
{
xmls = Thread.currentThread().getContextClassLoader().getResources("META-INF/persistence.xml");
}
catch (IOException ioex)
{
log.warn("Error while loading persistence.xml Caused by:" + ioex.getMessage());
}
if (xmls == null || !xmls.hasMoreElements())
{
log.info("Could not find any META-INF/persistence.xml " + " file in the classpath");
throw new InvalidConfigurationException("Could not find any META-INF/persistence.xml "
+ " file in the classpath");
}
Set<String> persistenceUnitNames = new HashSet<String>();
Map<String, PersistenceUnitMetadata> persistenceUnitMap = new HashMap<String, PersistenceUnitMetadata>();
while (xmls.hasMoreElements())
{
URL url = xmls.nextElement();
log.trace("Analysing persistence.xml: " + url);
List<PersistenceUnitMetadata> metadataFiles = PersistenceXMLLoader.findPersistenceUnits(url,
PersistenceUnitTransactionType.RESOURCE_LOCAL);
// Pick only those that have Kundera Provider
for (PersistenceUnitMetadata metadata : metadataFiles)
{
// check for unique names
if (persistenceUnitNames.contains(metadata.getPersistenceUnitName()))
{
if (log.isWarnEnabled())
{
log.warn("Duplicate persistence-units for name: " + metadata.getPersistenceUnitName()
+ ". verify your persistence.xml file");
}
}
// check for provider
if (metadata.getPersistenceProviderClassName() == null
|| PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getPersistenceProviderClassName()))
{
persistenceUnitMap.put(metadata.getPersistenceUnitName(), metadata);
}
// add to check for duplicate persistence unit.
persistenceUnitNames.add(metadata.getPersistenceUnitName());
}
}
return persistenceUnitMap;
}
|
diff --git a/test/com/eteks/sweethome3d/junit/PackageDependenciesTest.java b/test/com/eteks/sweethome3d/junit/PackageDependenciesTest.java
index a3f1a572..2c1f5b37 100644
--- a/test/com/eteks/sweethome3d/junit/PackageDependenciesTest.java
+++ b/test/com/eteks/sweethome3d/junit/PackageDependenciesTest.java
@@ -1,175 +1,179 @@
/**
* PackageDependenciesTest.java
*/
package com.eteks.sweethome3d.junit;
import java.io.IOException;
import jdepend.framework.DependencyConstraint;
import jdepend.framework.JDepend;
import jdepend.framework.JavaPackage;
import jdepend.framework.PackageFilter;
import junit.framework.TestCase;
/**
* Tests if dependencies between Sweet Home 3D packages are met.
* @author Emmanuel Puybaret
*/
public class PackageDependenciesTest extends TestCase {
/**
* Tests that the package dependencies constraint is met for the analyzed packages.
*/
public void testPackageDependencies() throws IOException {
PackageFilter packageFilter = new PackageFilter();
// Ignore Java packages and Swing sub packages
packageFilter.addPackage("java.*");
packageFilter.addPackage("javax.swing.*");
// Ignore JUnit tests
packageFilter.addPackage("com.eteks.sweethome3d.junit");
JDepend jdepend = new JDepend(packageFilter);
jdepend.addDirectory("classes");
DependencyConstraint constraint = new DependencyConstraint();
// Sweet Home 3D packages
JavaPackage sweetHome3DModel = constraint.addPackage("com.eteks.sweethome3d.model");
JavaPackage sweetHome3DTools = constraint.addPackage("com.eteks.sweethome3d.tools");
JavaPackage sweetHome3DPlugin = constraint.addPackage("com.eteks.sweethome3d.plugin");
JavaPackage sweetHome3DViewController = constraint.addPackage("com.eteks.sweethome3d.viewcontroller");
JavaPackage sweetHome3DSwing = constraint.addPackage("com.eteks.sweethome3d.swing");
JavaPackage sweetHome3DJava3D = constraint.addPackage("com.eteks.sweethome3d.j3d");
JavaPackage sweetHome3DIO = constraint.addPackage("com.eteks.sweethome3d.io");
JavaPackage sweetHome3DApplication = constraint.addPackage("com.eteks.sweethome3d");
JavaPackage sweetHome3DApplet = constraint.addPackage("com.eteks.sweethome3d.applet");
// Swing components packages
JavaPackage swing = constraint.addPackage("javax.swing");
JavaPackage imageio = constraint.addPackage("javax.imageio");
// Java 3D
JavaPackage java3d = constraint.addPackage("javax.media.j3d");
JavaPackage vecmath = constraint.addPackage("javax.vecmath");
JavaPackage sun3dLoaders = constraint.addPackage("com.sun.j3d.loaders");
JavaPackage sun3dLoadersLw3d = constraint.addPackage("com.sun.j3d.loaders.lw3d");
JavaPackage sun3dUtilsGeometry = constraint.addPackage("com.sun.j3d.utils.geometry");
JavaPackage sun3dUtilsImage = constraint.addPackage("com.sun.j3d.utils.image");
JavaPackage sun3dUtilsUniverse = constraint.addPackage("com.sun.j3d.utils.universe");
JavaPackage loader3ds = constraint.addPackage("com.microcrowd.loader.java3d.max3ds");
// XML
JavaPackage xmlParsers = constraint.addPackage("javax.xml.parsers");
JavaPackage xmlSax = constraint.addPackage("org.xml.sax");
JavaPackage xmlSaxHelpers = constraint.addPackage("org.xml.sax.helpers");
// JMF
JavaPackage jmf = constraint.addPackage("javax.media");
JavaPackage jmfControl = constraint.addPackage("javax.media.control");
JavaPackage jmfDataSink = constraint.addPackage("javax.media.datasink");
JavaPackage jmfFormat = constraint.addPackage("javax.media.format");
JavaPackage jmfProtocol = constraint.addPackage("javax.media.protocol");
// SunFlow
JavaPackage sunflow = constraint.addPackage("org.sunflow");
JavaPackage sunflowCore = constraint.addPackage("org.sunflow.core");
JavaPackage sunflowCoreLight = constraint.addPackage("org.sunflow.core.light");
+ JavaPackage sunflowCorePrimitive = constraint.addPackage("org.sunflow.core.primitive");
JavaPackage sunflowImage = constraint.addPackage("org.sunflow.image");
JavaPackage sunflowMath = constraint.addPackage("org.sunflow.math");
JavaPackage sunflowSystem = constraint.addPackage("org.sunflow.system");
JavaPackage sunflowSystemUI = constraint.addPackage("org.sunflow.system.ui");
// iText for PDF
JavaPackage iText = constraint.addPackage("com.lowagie.text");
JavaPackage iTextPdf = constraint.addPackage("com.lowagie.text.pdf");
// FreeHEP Vector Graphics for SVG
JavaPackage vectorGraphicsUtil = constraint.addPackage("org.freehep.util");
JavaPackage vectorGraphicsSvg = constraint.addPackage("org.freehep.graphicsio.svg");
// Java JNLP
JavaPackage jnlp = constraint.addPackage("javax.jnlp");
// Mac OS X specific interfaces
JavaPackage eawt = constraint.addPackage("com.applet.eawt");
JavaPackage eio = constraint.addPackage("com.applet.eio");
// Describe dependencies : model don't have any dependency on
// other packages, IO and View/Controller packages ignore each other
// and Swing components and Java 3D use is isolated in sweetHome3DSwing
sweetHome3DTools.dependsUpon(sweetHome3DModel);
+ sweetHome3DTools.dependsUpon(eio);
sweetHome3DPlugin.dependsUpon(sweetHome3DModel);
sweetHome3DPlugin.dependsUpon(sweetHome3DTools);
sweetHome3DViewController.dependsUpon(sweetHome3DModel);
sweetHome3DViewController.dependsUpon(sweetHome3DTools);
sweetHome3DViewController.dependsUpon(sweetHome3DPlugin);
sweetHome3DJava3D.dependsUpon(sweetHome3DModel);
sweetHome3DJava3D.dependsUpon(sweetHome3DTools);
+ sweetHome3DJava3D.dependsUpon(sweetHome3DViewController);
sweetHome3DJava3D.dependsUpon(java3d);
sweetHome3DJava3D.dependsUpon(vecmath);
sweetHome3DJava3D.dependsUpon(sun3dLoaders);
sweetHome3DJava3D.dependsUpon(sun3dLoadersLw3d);
sweetHome3DJava3D.dependsUpon(sun3dUtilsGeometry);
sweetHome3DJava3D.dependsUpon(sun3dUtilsImage);
sweetHome3DJava3D.dependsUpon(sun3dUtilsUniverse);
sweetHome3DJava3D.dependsUpon(loader3ds);
sweetHome3DJava3D.dependsUpon(imageio);
sweetHome3DJava3D.dependsUpon(sunflow);
sweetHome3DJava3D.dependsUpon(sunflowCore);
sweetHome3DJava3D.dependsUpon(sunflowCoreLight);
+ sweetHome3DJava3D.dependsUpon(sunflowCorePrimitive);
sweetHome3DJava3D.dependsUpon(sunflowImage);
sweetHome3DJava3D.dependsUpon(sunflowMath);
sweetHome3DJava3D.dependsUpon(sunflowSystem);
sweetHome3DJava3D.dependsUpon(sunflowSystemUI);
sweetHome3DJava3D.dependsUpon(xmlParsers);
sweetHome3DJava3D.dependsUpon(xmlSax);
sweetHome3DJava3D.dependsUpon(xmlSaxHelpers);
sweetHome3DSwing.dependsUpon(sweetHome3DModel);
sweetHome3DSwing.dependsUpon(sweetHome3DTools);
sweetHome3DSwing.dependsUpon(sweetHome3DPlugin);
sweetHome3DSwing.dependsUpon(sweetHome3DViewController);
sweetHome3DSwing.dependsUpon(sweetHome3DJava3D);
sweetHome3DSwing.dependsUpon(swing);
sweetHome3DSwing.dependsUpon(imageio);
sweetHome3DSwing.dependsUpon(java3d);
sweetHome3DSwing.dependsUpon(vecmath);
sweetHome3DSwing.dependsUpon(sun3dUtilsGeometry);
sweetHome3DSwing.dependsUpon(sun3dUtilsUniverse);
sweetHome3DSwing.dependsUpon(jmf);
sweetHome3DSwing.dependsUpon(jmfControl);
sweetHome3DSwing.dependsUpon(jmfDataSink);
sweetHome3DSwing.dependsUpon(jmfFormat);
sweetHome3DSwing.dependsUpon(jmfProtocol);
sweetHome3DSwing.dependsUpon(iText);
sweetHome3DSwing.dependsUpon(iTextPdf);
sweetHome3DSwing.dependsUpon(vectorGraphicsUtil);
sweetHome3DSwing.dependsUpon(vectorGraphicsSvg);
sweetHome3DSwing.dependsUpon(jnlp);
sweetHome3DIO.dependsUpon(sweetHome3DModel);
sweetHome3DIO.dependsUpon(sweetHome3DTools);
sweetHome3DIO.dependsUpon(eio);
// Describe application and applet assembly packages
sweetHome3DApplication.dependsUpon(sweetHome3DModel);
sweetHome3DApplication.dependsUpon(sweetHome3DTools);
sweetHome3DApplication.dependsUpon(sweetHome3DPlugin);
sweetHome3DApplication.dependsUpon(sweetHome3DViewController);
sweetHome3DApplication.dependsUpon(sweetHome3DJava3D);
sweetHome3DApplication.dependsUpon(sweetHome3DSwing);
sweetHome3DApplication.dependsUpon(sweetHome3DIO);
sweetHome3DApplication.dependsUpon(swing);
sweetHome3DApplication.dependsUpon(imageio);
sweetHome3DApplication.dependsUpon(java3d);
sweetHome3DApplication.dependsUpon(eawt);
sweetHome3DApplication.dependsUpon(jnlp);
sweetHome3DApplet.dependsUpon(sweetHome3DModel);
sweetHome3DApplet.dependsUpon(sweetHome3DTools);
sweetHome3DApplet.dependsUpon(sweetHome3DPlugin);
sweetHome3DApplet.dependsUpon(sweetHome3DViewController);
sweetHome3DApplet.dependsUpon(sweetHome3DJava3D);
sweetHome3DApplet.dependsUpon(sweetHome3DSwing);
sweetHome3DApplet.dependsUpon(sweetHome3DIO);
sweetHome3DApplet.dependsUpon(swing);
sweetHome3DApplet.dependsUpon(java3d);
sweetHome3DApplet.dependsUpon(jnlp);
jdepend.analyze();
assertTrue("Dependency mismatch", jdepend.dependencyMatch(constraint));
}
}
| false | true | public void testPackageDependencies() throws IOException {
PackageFilter packageFilter = new PackageFilter();
// Ignore Java packages and Swing sub packages
packageFilter.addPackage("java.*");
packageFilter.addPackage("javax.swing.*");
// Ignore JUnit tests
packageFilter.addPackage("com.eteks.sweethome3d.junit");
JDepend jdepend = new JDepend(packageFilter);
jdepend.addDirectory("classes");
DependencyConstraint constraint = new DependencyConstraint();
// Sweet Home 3D packages
JavaPackage sweetHome3DModel = constraint.addPackage("com.eteks.sweethome3d.model");
JavaPackage sweetHome3DTools = constraint.addPackage("com.eteks.sweethome3d.tools");
JavaPackage sweetHome3DPlugin = constraint.addPackage("com.eteks.sweethome3d.plugin");
JavaPackage sweetHome3DViewController = constraint.addPackage("com.eteks.sweethome3d.viewcontroller");
JavaPackage sweetHome3DSwing = constraint.addPackage("com.eteks.sweethome3d.swing");
JavaPackage sweetHome3DJava3D = constraint.addPackage("com.eteks.sweethome3d.j3d");
JavaPackage sweetHome3DIO = constraint.addPackage("com.eteks.sweethome3d.io");
JavaPackage sweetHome3DApplication = constraint.addPackage("com.eteks.sweethome3d");
JavaPackage sweetHome3DApplet = constraint.addPackage("com.eteks.sweethome3d.applet");
// Swing components packages
JavaPackage swing = constraint.addPackage("javax.swing");
JavaPackage imageio = constraint.addPackage("javax.imageio");
// Java 3D
JavaPackage java3d = constraint.addPackage("javax.media.j3d");
JavaPackage vecmath = constraint.addPackage("javax.vecmath");
JavaPackage sun3dLoaders = constraint.addPackage("com.sun.j3d.loaders");
JavaPackage sun3dLoadersLw3d = constraint.addPackage("com.sun.j3d.loaders.lw3d");
JavaPackage sun3dUtilsGeometry = constraint.addPackage("com.sun.j3d.utils.geometry");
JavaPackage sun3dUtilsImage = constraint.addPackage("com.sun.j3d.utils.image");
JavaPackage sun3dUtilsUniverse = constraint.addPackage("com.sun.j3d.utils.universe");
JavaPackage loader3ds = constraint.addPackage("com.microcrowd.loader.java3d.max3ds");
// XML
JavaPackage xmlParsers = constraint.addPackage("javax.xml.parsers");
JavaPackage xmlSax = constraint.addPackage("org.xml.sax");
JavaPackage xmlSaxHelpers = constraint.addPackage("org.xml.sax.helpers");
// JMF
JavaPackage jmf = constraint.addPackage("javax.media");
JavaPackage jmfControl = constraint.addPackage("javax.media.control");
JavaPackage jmfDataSink = constraint.addPackage("javax.media.datasink");
JavaPackage jmfFormat = constraint.addPackage("javax.media.format");
JavaPackage jmfProtocol = constraint.addPackage("javax.media.protocol");
// SunFlow
JavaPackage sunflow = constraint.addPackage("org.sunflow");
JavaPackage sunflowCore = constraint.addPackage("org.sunflow.core");
JavaPackage sunflowCoreLight = constraint.addPackage("org.sunflow.core.light");
JavaPackage sunflowImage = constraint.addPackage("org.sunflow.image");
JavaPackage sunflowMath = constraint.addPackage("org.sunflow.math");
JavaPackage sunflowSystem = constraint.addPackage("org.sunflow.system");
JavaPackage sunflowSystemUI = constraint.addPackage("org.sunflow.system.ui");
// iText for PDF
JavaPackage iText = constraint.addPackage("com.lowagie.text");
JavaPackage iTextPdf = constraint.addPackage("com.lowagie.text.pdf");
// FreeHEP Vector Graphics for SVG
JavaPackage vectorGraphicsUtil = constraint.addPackage("org.freehep.util");
JavaPackage vectorGraphicsSvg = constraint.addPackage("org.freehep.graphicsio.svg");
// Java JNLP
JavaPackage jnlp = constraint.addPackage("javax.jnlp");
// Mac OS X specific interfaces
JavaPackage eawt = constraint.addPackage("com.applet.eawt");
JavaPackage eio = constraint.addPackage("com.applet.eio");
// Describe dependencies : model don't have any dependency on
// other packages, IO and View/Controller packages ignore each other
// and Swing components and Java 3D use is isolated in sweetHome3DSwing
sweetHome3DTools.dependsUpon(sweetHome3DModel);
sweetHome3DPlugin.dependsUpon(sweetHome3DModel);
sweetHome3DPlugin.dependsUpon(sweetHome3DTools);
sweetHome3DViewController.dependsUpon(sweetHome3DModel);
sweetHome3DViewController.dependsUpon(sweetHome3DTools);
sweetHome3DViewController.dependsUpon(sweetHome3DPlugin);
sweetHome3DJava3D.dependsUpon(sweetHome3DModel);
sweetHome3DJava3D.dependsUpon(sweetHome3DTools);
sweetHome3DJava3D.dependsUpon(java3d);
sweetHome3DJava3D.dependsUpon(vecmath);
sweetHome3DJava3D.dependsUpon(sun3dLoaders);
sweetHome3DJava3D.dependsUpon(sun3dLoadersLw3d);
sweetHome3DJava3D.dependsUpon(sun3dUtilsGeometry);
sweetHome3DJava3D.dependsUpon(sun3dUtilsImage);
sweetHome3DJava3D.dependsUpon(sun3dUtilsUniverse);
sweetHome3DJava3D.dependsUpon(loader3ds);
sweetHome3DJava3D.dependsUpon(imageio);
sweetHome3DJava3D.dependsUpon(sunflow);
sweetHome3DJava3D.dependsUpon(sunflowCore);
sweetHome3DJava3D.dependsUpon(sunflowCoreLight);
sweetHome3DJava3D.dependsUpon(sunflowImage);
sweetHome3DJava3D.dependsUpon(sunflowMath);
sweetHome3DJava3D.dependsUpon(sunflowSystem);
sweetHome3DJava3D.dependsUpon(sunflowSystemUI);
sweetHome3DJava3D.dependsUpon(xmlParsers);
sweetHome3DJava3D.dependsUpon(xmlSax);
sweetHome3DJava3D.dependsUpon(xmlSaxHelpers);
sweetHome3DSwing.dependsUpon(sweetHome3DModel);
sweetHome3DSwing.dependsUpon(sweetHome3DTools);
sweetHome3DSwing.dependsUpon(sweetHome3DPlugin);
sweetHome3DSwing.dependsUpon(sweetHome3DViewController);
sweetHome3DSwing.dependsUpon(sweetHome3DJava3D);
sweetHome3DSwing.dependsUpon(swing);
sweetHome3DSwing.dependsUpon(imageio);
sweetHome3DSwing.dependsUpon(java3d);
sweetHome3DSwing.dependsUpon(vecmath);
sweetHome3DSwing.dependsUpon(sun3dUtilsGeometry);
sweetHome3DSwing.dependsUpon(sun3dUtilsUniverse);
sweetHome3DSwing.dependsUpon(jmf);
sweetHome3DSwing.dependsUpon(jmfControl);
sweetHome3DSwing.dependsUpon(jmfDataSink);
sweetHome3DSwing.dependsUpon(jmfFormat);
sweetHome3DSwing.dependsUpon(jmfProtocol);
sweetHome3DSwing.dependsUpon(iText);
sweetHome3DSwing.dependsUpon(iTextPdf);
sweetHome3DSwing.dependsUpon(vectorGraphicsUtil);
sweetHome3DSwing.dependsUpon(vectorGraphicsSvg);
sweetHome3DSwing.dependsUpon(jnlp);
sweetHome3DIO.dependsUpon(sweetHome3DModel);
sweetHome3DIO.dependsUpon(sweetHome3DTools);
sweetHome3DIO.dependsUpon(eio);
// Describe application and applet assembly packages
sweetHome3DApplication.dependsUpon(sweetHome3DModel);
sweetHome3DApplication.dependsUpon(sweetHome3DTools);
sweetHome3DApplication.dependsUpon(sweetHome3DPlugin);
sweetHome3DApplication.dependsUpon(sweetHome3DViewController);
sweetHome3DApplication.dependsUpon(sweetHome3DJava3D);
sweetHome3DApplication.dependsUpon(sweetHome3DSwing);
sweetHome3DApplication.dependsUpon(sweetHome3DIO);
sweetHome3DApplication.dependsUpon(swing);
sweetHome3DApplication.dependsUpon(imageio);
sweetHome3DApplication.dependsUpon(java3d);
sweetHome3DApplication.dependsUpon(eawt);
sweetHome3DApplication.dependsUpon(jnlp);
sweetHome3DApplet.dependsUpon(sweetHome3DModel);
sweetHome3DApplet.dependsUpon(sweetHome3DTools);
sweetHome3DApplet.dependsUpon(sweetHome3DPlugin);
sweetHome3DApplet.dependsUpon(sweetHome3DViewController);
sweetHome3DApplet.dependsUpon(sweetHome3DJava3D);
sweetHome3DApplet.dependsUpon(sweetHome3DSwing);
sweetHome3DApplet.dependsUpon(sweetHome3DIO);
sweetHome3DApplet.dependsUpon(swing);
sweetHome3DApplet.dependsUpon(java3d);
sweetHome3DApplet.dependsUpon(jnlp);
jdepend.analyze();
assertTrue("Dependency mismatch", jdepend.dependencyMatch(constraint));
}
| public void testPackageDependencies() throws IOException {
PackageFilter packageFilter = new PackageFilter();
// Ignore Java packages and Swing sub packages
packageFilter.addPackage("java.*");
packageFilter.addPackage("javax.swing.*");
// Ignore JUnit tests
packageFilter.addPackage("com.eteks.sweethome3d.junit");
JDepend jdepend = new JDepend(packageFilter);
jdepend.addDirectory("classes");
DependencyConstraint constraint = new DependencyConstraint();
// Sweet Home 3D packages
JavaPackage sweetHome3DModel = constraint.addPackage("com.eteks.sweethome3d.model");
JavaPackage sweetHome3DTools = constraint.addPackage("com.eteks.sweethome3d.tools");
JavaPackage sweetHome3DPlugin = constraint.addPackage("com.eteks.sweethome3d.plugin");
JavaPackage sweetHome3DViewController = constraint.addPackage("com.eteks.sweethome3d.viewcontroller");
JavaPackage sweetHome3DSwing = constraint.addPackage("com.eteks.sweethome3d.swing");
JavaPackage sweetHome3DJava3D = constraint.addPackage("com.eteks.sweethome3d.j3d");
JavaPackage sweetHome3DIO = constraint.addPackage("com.eteks.sweethome3d.io");
JavaPackage sweetHome3DApplication = constraint.addPackage("com.eteks.sweethome3d");
JavaPackage sweetHome3DApplet = constraint.addPackage("com.eteks.sweethome3d.applet");
// Swing components packages
JavaPackage swing = constraint.addPackage("javax.swing");
JavaPackage imageio = constraint.addPackage("javax.imageio");
// Java 3D
JavaPackage java3d = constraint.addPackage("javax.media.j3d");
JavaPackage vecmath = constraint.addPackage("javax.vecmath");
JavaPackage sun3dLoaders = constraint.addPackage("com.sun.j3d.loaders");
JavaPackage sun3dLoadersLw3d = constraint.addPackage("com.sun.j3d.loaders.lw3d");
JavaPackage sun3dUtilsGeometry = constraint.addPackage("com.sun.j3d.utils.geometry");
JavaPackage sun3dUtilsImage = constraint.addPackage("com.sun.j3d.utils.image");
JavaPackage sun3dUtilsUniverse = constraint.addPackage("com.sun.j3d.utils.universe");
JavaPackage loader3ds = constraint.addPackage("com.microcrowd.loader.java3d.max3ds");
// XML
JavaPackage xmlParsers = constraint.addPackage("javax.xml.parsers");
JavaPackage xmlSax = constraint.addPackage("org.xml.sax");
JavaPackage xmlSaxHelpers = constraint.addPackage("org.xml.sax.helpers");
// JMF
JavaPackage jmf = constraint.addPackage("javax.media");
JavaPackage jmfControl = constraint.addPackage("javax.media.control");
JavaPackage jmfDataSink = constraint.addPackage("javax.media.datasink");
JavaPackage jmfFormat = constraint.addPackage("javax.media.format");
JavaPackage jmfProtocol = constraint.addPackage("javax.media.protocol");
// SunFlow
JavaPackage sunflow = constraint.addPackage("org.sunflow");
JavaPackage sunflowCore = constraint.addPackage("org.sunflow.core");
JavaPackage sunflowCoreLight = constraint.addPackage("org.sunflow.core.light");
JavaPackage sunflowCorePrimitive = constraint.addPackage("org.sunflow.core.primitive");
JavaPackage sunflowImage = constraint.addPackage("org.sunflow.image");
JavaPackage sunflowMath = constraint.addPackage("org.sunflow.math");
JavaPackage sunflowSystem = constraint.addPackage("org.sunflow.system");
JavaPackage sunflowSystemUI = constraint.addPackage("org.sunflow.system.ui");
// iText for PDF
JavaPackage iText = constraint.addPackage("com.lowagie.text");
JavaPackage iTextPdf = constraint.addPackage("com.lowagie.text.pdf");
// FreeHEP Vector Graphics for SVG
JavaPackage vectorGraphicsUtil = constraint.addPackage("org.freehep.util");
JavaPackage vectorGraphicsSvg = constraint.addPackage("org.freehep.graphicsio.svg");
// Java JNLP
JavaPackage jnlp = constraint.addPackage("javax.jnlp");
// Mac OS X specific interfaces
JavaPackage eawt = constraint.addPackage("com.applet.eawt");
JavaPackage eio = constraint.addPackage("com.applet.eio");
// Describe dependencies : model don't have any dependency on
// other packages, IO and View/Controller packages ignore each other
// and Swing components and Java 3D use is isolated in sweetHome3DSwing
sweetHome3DTools.dependsUpon(sweetHome3DModel);
sweetHome3DTools.dependsUpon(eio);
sweetHome3DPlugin.dependsUpon(sweetHome3DModel);
sweetHome3DPlugin.dependsUpon(sweetHome3DTools);
sweetHome3DViewController.dependsUpon(sweetHome3DModel);
sweetHome3DViewController.dependsUpon(sweetHome3DTools);
sweetHome3DViewController.dependsUpon(sweetHome3DPlugin);
sweetHome3DJava3D.dependsUpon(sweetHome3DModel);
sweetHome3DJava3D.dependsUpon(sweetHome3DTools);
sweetHome3DJava3D.dependsUpon(sweetHome3DViewController);
sweetHome3DJava3D.dependsUpon(java3d);
sweetHome3DJava3D.dependsUpon(vecmath);
sweetHome3DJava3D.dependsUpon(sun3dLoaders);
sweetHome3DJava3D.dependsUpon(sun3dLoadersLw3d);
sweetHome3DJava3D.dependsUpon(sun3dUtilsGeometry);
sweetHome3DJava3D.dependsUpon(sun3dUtilsImage);
sweetHome3DJava3D.dependsUpon(sun3dUtilsUniverse);
sweetHome3DJava3D.dependsUpon(loader3ds);
sweetHome3DJava3D.dependsUpon(imageio);
sweetHome3DJava3D.dependsUpon(sunflow);
sweetHome3DJava3D.dependsUpon(sunflowCore);
sweetHome3DJava3D.dependsUpon(sunflowCoreLight);
sweetHome3DJava3D.dependsUpon(sunflowCorePrimitive);
sweetHome3DJava3D.dependsUpon(sunflowImage);
sweetHome3DJava3D.dependsUpon(sunflowMath);
sweetHome3DJava3D.dependsUpon(sunflowSystem);
sweetHome3DJava3D.dependsUpon(sunflowSystemUI);
sweetHome3DJava3D.dependsUpon(xmlParsers);
sweetHome3DJava3D.dependsUpon(xmlSax);
sweetHome3DJava3D.dependsUpon(xmlSaxHelpers);
sweetHome3DSwing.dependsUpon(sweetHome3DModel);
sweetHome3DSwing.dependsUpon(sweetHome3DTools);
sweetHome3DSwing.dependsUpon(sweetHome3DPlugin);
sweetHome3DSwing.dependsUpon(sweetHome3DViewController);
sweetHome3DSwing.dependsUpon(sweetHome3DJava3D);
sweetHome3DSwing.dependsUpon(swing);
sweetHome3DSwing.dependsUpon(imageio);
sweetHome3DSwing.dependsUpon(java3d);
sweetHome3DSwing.dependsUpon(vecmath);
sweetHome3DSwing.dependsUpon(sun3dUtilsGeometry);
sweetHome3DSwing.dependsUpon(sun3dUtilsUniverse);
sweetHome3DSwing.dependsUpon(jmf);
sweetHome3DSwing.dependsUpon(jmfControl);
sweetHome3DSwing.dependsUpon(jmfDataSink);
sweetHome3DSwing.dependsUpon(jmfFormat);
sweetHome3DSwing.dependsUpon(jmfProtocol);
sweetHome3DSwing.dependsUpon(iText);
sweetHome3DSwing.dependsUpon(iTextPdf);
sweetHome3DSwing.dependsUpon(vectorGraphicsUtil);
sweetHome3DSwing.dependsUpon(vectorGraphicsSvg);
sweetHome3DSwing.dependsUpon(jnlp);
sweetHome3DIO.dependsUpon(sweetHome3DModel);
sweetHome3DIO.dependsUpon(sweetHome3DTools);
sweetHome3DIO.dependsUpon(eio);
// Describe application and applet assembly packages
sweetHome3DApplication.dependsUpon(sweetHome3DModel);
sweetHome3DApplication.dependsUpon(sweetHome3DTools);
sweetHome3DApplication.dependsUpon(sweetHome3DPlugin);
sweetHome3DApplication.dependsUpon(sweetHome3DViewController);
sweetHome3DApplication.dependsUpon(sweetHome3DJava3D);
sweetHome3DApplication.dependsUpon(sweetHome3DSwing);
sweetHome3DApplication.dependsUpon(sweetHome3DIO);
sweetHome3DApplication.dependsUpon(swing);
sweetHome3DApplication.dependsUpon(imageio);
sweetHome3DApplication.dependsUpon(java3d);
sweetHome3DApplication.dependsUpon(eawt);
sweetHome3DApplication.dependsUpon(jnlp);
sweetHome3DApplet.dependsUpon(sweetHome3DModel);
sweetHome3DApplet.dependsUpon(sweetHome3DTools);
sweetHome3DApplet.dependsUpon(sweetHome3DPlugin);
sweetHome3DApplet.dependsUpon(sweetHome3DViewController);
sweetHome3DApplet.dependsUpon(sweetHome3DJava3D);
sweetHome3DApplet.dependsUpon(sweetHome3DSwing);
sweetHome3DApplet.dependsUpon(sweetHome3DIO);
sweetHome3DApplet.dependsUpon(swing);
sweetHome3DApplet.dependsUpon(java3d);
sweetHome3DApplet.dependsUpon(jnlp);
jdepend.analyze();
assertTrue("Dependency mismatch", jdepend.dependencyMatch(constraint));
}
|
diff --git a/src/plugins/Library/index/TermEntryReaderWriter.java b/src/plugins/Library/index/TermEntryReaderWriter.java
index 2fd2149..2c8347a 100644
--- a/src/plugins/Library/index/TermEntryReaderWriter.java
+++ b/src/plugins/Library/index/TermEntryReaderWriter.java
@@ -1,113 +1,114 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.Library.index;
import plugins.Library.io.DataFormatException;
import plugins.Library.io.ObjectStreamReader;
import plugins.Library.io.ObjectStreamWriter;
import freenet.keys.FreenetURI;
import java.util.Map;
import java.util.HashMap;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
** Reads and writes {@link TermEntry}s in binary form, for performance.
**
** @author infinity0
*/
public class TermEntryReaderWriter implements ObjectStreamReader<TermEntry>, ObjectStreamWriter<TermEntry> {
final private static TermEntryReaderWriter instance = new TermEntryReaderWriter();
protected TermEntryReaderWriter() {}
public static TermEntryReaderWriter getInstance() {
return instance;
}
/*@Override**/ public TermEntry readObject(InputStream is) throws IOException {
return readObject(new DataInputStream(is));
}
public TermEntry readObject(DataInputStream dis) throws IOException {
long svuid = dis.readLong();
if (svuid != TermEntry.serialVersionUID) {
throw new DataFormatException("Incorrect serialVersionUID", null, svuid);
}
int type = dis.readInt();
String subj = dis.readUTF();
float rel = dis.readFloat();
TermEntry.EntryType[] types = TermEntry.EntryType.values();
if (type < 0 || type >= types.length) {
throw new DataFormatException("Unrecognised entry type", null, type);
}
switch (types[type]) {
case TERM:
return new TermTermEntry(subj, rel, dis.readUTF());
case INDEX:
return new TermIndexEntry(subj, rel, FreenetURI.readFullBinaryKeyWithLength(dis));
case PAGE:
FreenetURI page = FreenetURI.readFullBinaryKeyWithLength(dis);
int size = dis.readInt();
String title = null;
if (size < 0) {
title = dis.readUTF();
size = ~size;
}
Map<Integer, String> pos = new HashMap<Integer, String>(size<<1);
for (int i=0; i<size; ++i) {
+ int index = dis.readInt();
String val = dis.readUTF();
- pos.put(dis.readInt(), "".equals(val) ? null : val);
+ pos.put(index, "".equals(val) ? null : val);
}
return new TermPageEntry(subj, rel, page, title, pos);
default:
throw new AssertionError();
}
}
/*@Override**/ public void writeObject(TermEntry en, OutputStream os) throws IOException {
writeObject(en, new DataOutputStream(os));
}
public void writeObject(TermEntry en, DataOutputStream dos) throws IOException {
dos.writeLong(TermEntry.serialVersionUID);
TermEntry.EntryType type = en.entryType();
dos.writeInt(type.ordinal());
dos.writeUTF(en.subj);
dos.writeFloat(en.rel);
switch (type) {
case TERM:
dos.writeUTF(((TermTermEntry)en).term);
return;
case INDEX:
((TermIndexEntry)en).index.writeFullBinaryKeyWithLength(dos);
return;
case PAGE:
TermPageEntry enn = (TermPageEntry)en;
enn.page.writeFullBinaryKeyWithLength(dos);
if (enn.title == null) {
dos.writeInt(enn.pos.size());
} else {
dos.writeInt(~enn.pos.size()); // invert bits to signify title is set
dos.writeUTF(enn.title);
}
for (Map.Entry<Integer, String> p: enn.pos.entrySet()) {
dos.writeInt(p.getKey());
if(p.getValue() == null)
dos.writeUTF("");
else
dos.writeUTF(p.getValue());
}
return;
}
}
}
| false | true | public TermEntry readObject(DataInputStream dis) throws IOException {
long svuid = dis.readLong();
if (svuid != TermEntry.serialVersionUID) {
throw new DataFormatException("Incorrect serialVersionUID", null, svuid);
}
int type = dis.readInt();
String subj = dis.readUTF();
float rel = dis.readFloat();
TermEntry.EntryType[] types = TermEntry.EntryType.values();
if (type < 0 || type >= types.length) {
throw new DataFormatException("Unrecognised entry type", null, type);
}
switch (types[type]) {
case TERM:
return new TermTermEntry(subj, rel, dis.readUTF());
case INDEX:
return new TermIndexEntry(subj, rel, FreenetURI.readFullBinaryKeyWithLength(dis));
case PAGE:
FreenetURI page = FreenetURI.readFullBinaryKeyWithLength(dis);
int size = dis.readInt();
String title = null;
if (size < 0) {
title = dis.readUTF();
size = ~size;
}
Map<Integer, String> pos = new HashMap<Integer, String>(size<<1);
for (int i=0; i<size; ++i) {
String val = dis.readUTF();
pos.put(dis.readInt(), "".equals(val) ? null : val);
}
return new TermPageEntry(subj, rel, page, title, pos);
default:
throw new AssertionError();
}
}
| public TermEntry readObject(DataInputStream dis) throws IOException {
long svuid = dis.readLong();
if (svuid != TermEntry.serialVersionUID) {
throw new DataFormatException("Incorrect serialVersionUID", null, svuid);
}
int type = dis.readInt();
String subj = dis.readUTF();
float rel = dis.readFloat();
TermEntry.EntryType[] types = TermEntry.EntryType.values();
if (type < 0 || type >= types.length) {
throw new DataFormatException("Unrecognised entry type", null, type);
}
switch (types[type]) {
case TERM:
return new TermTermEntry(subj, rel, dis.readUTF());
case INDEX:
return new TermIndexEntry(subj, rel, FreenetURI.readFullBinaryKeyWithLength(dis));
case PAGE:
FreenetURI page = FreenetURI.readFullBinaryKeyWithLength(dis);
int size = dis.readInt();
String title = null;
if (size < 0) {
title = dis.readUTF();
size = ~size;
}
Map<Integer, String> pos = new HashMap<Integer, String>(size<<1);
for (int i=0; i<size; ++i) {
int index = dis.readInt();
String val = dis.readUTF();
pos.put(index, "".equals(val) ? null : val);
}
return new TermPageEntry(subj, rel, page, title, pos);
default:
throw new AssertionError();
}
}
|
diff --git a/src/simpleserver/bot/Bot.java b/src/simpleserver/bot/Bot.java
index e4b0ff7..1f93c5e 100644
--- a/src/simpleserver/bot/Bot.java
+++ b/src/simpleserver/bot/Bot.java
@@ -1,658 +1,660 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* 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 simpleserver.bot;
import static simpleserver.stream.StreamTunnel.ENCHANTABLE;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.locks.ReentrantLock;
import simpleserver.Coordinate.Dimension;
import simpleserver.Position;
import simpleserver.Server;
public class Bot {
private static final int VERSION = 23;
protected String name;
protected Server server;
private boolean connected;
private boolean expectDisconnect;
protected boolean ready;
protected boolean dead;
private Socket socket;
protected DataInputStream in;
protected DataOutputStream out;
ReentrantLock writeLock;
protected Position position;
protected BotController controller;
protected boolean gotFirstPacket = false;
private byte lastPacket;
private short health;
public Bot(Server server, String name) {
this.name = name;
this.server = server;
position = new Position();
}
void connect() throws UnknownHostException, IOException {
try {
InetAddress localAddress = InetAddress.getByName(Server.addressFactory.getNextAddress());
socket = new Socket(InetAddress.getByName(null), server.options.getInt("internalPort"), localAddress, 0);
} catch (Exception e) {
socket = new Socket(InetAddress.getByName(null), server.options.getInt("internalPort"));
}
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
writeLock = new ReentrantLock();
connected = true;
new Tunneler().start();
handshake();
}
boolean ninja() {
return false;
}
protected void positionUpdate() throws IOException {
}
private void keepAlive(int keepAliveId) throws IOException {
writeLock.lock();
out.writeByte(0x0);
out.writeInt(keepAliveId);
writeLock.unlock();
}
private void handshake() throws IOException {
writeLock.lock();
out.writeByte(2);
write(name);
out.flush();
writeLock.unlock();
}
public void logout() throws IOException {
die();
expectDisconnect = true;
out.writeByte(0xff);
write("quitting");
out.flush();
}
protected void login() throws IOException {
writeLock.lock();
out.writeByte(1);
out.writeInt(VERSION);
write(name);
out.writeLong(0);
write(readUTF16()); // Added in 1.1 (level type)
out.writeInt(0);
out.writeByte(0);
out.writeByte(0);
out.writeByte(0);
out.writeByte(0);
writeLock.unlock();
}
private void respawn() throws IOException {
writeLock.lock();
out.writeByte(9);
out.writeByte(position.dimension.index());
out.writeByte(0);
out.writeShort(128);
out.writeLong(0);
write(readUTF16()); // Added in 1.1 (level type)
writeLock.unlock();
}
protected void ready() throws IOException {
ready = true;
}
protected void walk(double d) {
double heading = position.yaw * Math.PI / 180;
position.x -= Math.sin(heading) * d;
position.z += Math.cos(heading) * d;
}
protected void ascend(double d) {
position.y += d;
position.stance += d;
if (position.stance - position.y > 1.6 || position.stance - position.y < 0.15) {
position.stance = position.y + 0.5;
}
}
protected void sendPosition() throws IOException {
writeLock.lock();
position.send(out);
writeLock.unlock();
}
protected boolean trashdat() {
return true;
}
protected void handlePacket(byte packetId) throws IOException {
// System.out.println("Packet: 0x" + Integer.toHexString(packetId));
switch (packetId) {
case 0x2:
readUTF16();
login();
break;
case 0x1:
in.readInt();
readUTF16();
in.readLong();
+ readUTF16(); // Added in 1.1, level type
in.readInt();
position.dimension = Dimension.get(in.readByte());
in.readByte();
in.readByte();
in.readByte();
break;
case 0x0d: // Player Position & Look
double x = in.readDouble();
double stance = in.readDouble();
double y = in.readDouble();
double z = in.readDouble();
float yaw = in.readFloat();
float pitch = in.readFloat();
boolean onGround = in.readBoolean();
position.updatePosition(x, y, z, stance);
position.updateLook(yaw, pitch);
position.updateGround(onGround);
if (!ready) {
sendPosition();
ready();
} else if (dead) {
sendPosition();
dead = false;
}
positionUpdate();
break;
case 0x0b: // Player Position
double x2 = in.readDouble();
double stance2 = in.readDouble();
double y2 = in.readDouble();
double z2 = in.readDouble();
boolean onGround2 = in.readBoolean();
position.updatePosition(x2, y2, z2, stance2);
position.updateGround(onGround2);
positionUpdate();
break;
case (byte) 0xff: // Disconnect/Kick
String reason = readUTF16();
error(reason);
break;
case 0x00: // Keep Alive
keepAlive(in.readInt());
break;
case 0x03: // Chat Message
readUTF16();
break;
case 0x04: // Time Update
in.readLong();
break;
case 0x05: // Player Inventory
in.readInt();
in.readShort();
in.readShort();
in.readShort();
break;
case 0x06: // Spawn Position
readNBytes(12);
break;
case 0x07: // Use Entity?
in.readInt();
in.readInt();
in.readBoolean();
in.readBoolean();
break;
case 0x08: // Update Health
health = in.readShort();
in.readShort();
in.readFloat();
if (health <= 0) {
dead = true;
respawn();
}
break;
case 0x09: // Respawn
position.dimension = Dimension.get(in.readByte());
in.readByte();
in.readByte();
in.readShort();
in.readLong();
+ readUTF16(); // Added in 1.1, level type
break;
case 0x0a: // Player
in.readByte();
break;
case 0x0c: // Player Look
readNBytes(9);
break;
case 0x0e: // Player Digging
in.readByte();
in.readInt();
in.readByte();
in.readInt();
in.readByte();
break;
case 0x0f: // Player Block Placement
in.readInt();
in.readByte();
in.readInt();
in.readByte();
readItem();
break;
case 0x10: // Holding Change
readNBytes(2);
break;
case 0x11: // Use Bed
readNBytes(14);
break;
case 0x12: // Animation
readNBytes(5);
break;
case 0x13: // ???
in.readInt();
in.readByte();
break;
case 0x14: // Named Entity Spawn
in.readInt();
readUTF16();
readNBytes(16);
break;
case 0x15: // Pickup spawn
readNBytes(24);
break;
case 0x16: // Collect Item
readNBytes(8);
break;
case 0x17: // Add Object/Vehicle
in.readInt();
in.readByte();
in.readInt();
in.readInt();
in.readInt();
int flag = in.readInt();
if (flag > 0) {
in.readShort();
in.readShort();
in.readShort();
}
break;
case 0x18: // Mob Spawn
in.readInt();
in.readByte();
in.readInt();
in.readInt();
in.readInt();
in.readByte();
in.readByte();
readUnknownBlob();
break;
case 0x19: // Painting
in.readInt();
readUTF16();
in.readInt();
in.readInt();
in.readInt();
in.readInt();
break;
case 0x1a:
in.readInt();
in.readInt();
in.readInt();
in.readInt();
in.readShort();
break;
case 0x1c: // Entity Velocity?
readNBytes(10);
break;
case 0x1d: // Destroy Entity
readNBytes(4);
break;
case 0x1e: // Entity
readNBytes(4);
break;
case 0x1f: // Entity Relative Move
readNBytes(7);
break;
case 0x20: // Entity Look
readNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
readNBytes(9);
break;
case 0x22: // Entity Teleport
readNBytes(18);
break;
case 0x26: // Entity status?
readNBytes(5);
break;
case 0x27: // Attach Entity?
readNBytes(8);
break;
case 0x28: // Entity Metadata
in.readInt();
readUnknownBlob();
break;
case 0x29: // new in 1.8, add status effect (41)
in.readInt();
in.readByte();
in.readByte();
in.readShort();
break;
case 0x2a: // new in 1.8, remove status effect (42)
in.readInt();
in.readByte();
break;
case 0x2b: // experience
in.readFloat();
in.readShort();
in.readShort();
break;
case 0x32: // Pre-Chunk
readNBytes(9);
break;
case 0x33: // Map Chunk
readNBytes(13);
int chunkSize = in.readInt();
readNBytes(chunkSize);
break;
case 0x34: // Multi Block Change
readNBytes(8);
short arraySize = in.readShort();
readNBytes(arraySize * 4);
break;
case 0x35: // Block Change
in.readInt();
in.readByte();
in.readInt();
in.readByte();
in.readByte();
break;
case 0x36: // ???
readNBytes(12);
break;
case 0x3c: // Explosion
readNBytes(28);
int recordCount = in.readInt();
readNBytes(recordCount * 3);
break;
case 0x3d: // Unknown
in.readInt();
in.readInt();
in.readByte();
in.readInt();
in.readInt();
break;
case 0x46: // Invalid Bed
readNBytes(2);
break;
case 0x47: // Thunder
readNBytes(17);
break;
case 0x64: // Open window
in.readByte();
in.readByte();
readUTF16();
in.readByte();
break;
case 0x65:
in.readByte();
break;
case 0x66: // Inventory Item Move
in.readByte();
in.readShort();
in.readByte();
in.readShort();
in.readBoolean();
readItem();
break;
case 0x67: // Inventory Item Update
in.readByte();
in.readShort();
readItem();
break;
case 0x68: // Inventory
in.readByte();
short count = in.readShort();
for (int c = 0; c < count; ++c) {
readItem();
}
break;
case 0x69:
in.readByte();
in.readShort();
in.readShort();
break;
case 0x6a: // item transaction
in.readByte();
in.readShort();
in.readByte();
break;
case 0x6b: // creative item get
in.readShort();
readItem();
break;
case (byte) 0x6c:
readNBytes(2);
break;
case (byte) 0x82: // Update Sign
in.readInt();
in.readShort();
in.readInt();
readUTF16();
readUTF16();
readUTF16();
readUTF16();
break;
case (byte) 0x83: // Map data
in.readShort();
in.readShort();
byte length = in.readByte();
readNBytes(0xff & length);
break;
case (byte) 0xc8: // Statistic
readNBytes(5);
break;
case (byte) 0xc9: // User list
readUTF16();
in.readBoolean();
in.readShort();
break;
case (byte) 0xe6: // ModLoaderMP by SDK
in.readInt(); // mod
in.readInt(); // packet id
readNBytes(in.readInt() * 4); // ints
readNBytes(in.readInt() * 4); // floats
int sizeString = in.readInt(); // strings
for (int i = 0; i < sizeString; i++) {
readNBytes(in.readInt());
}
break;
case (byte) 0xfa: // Unknown, added in 1.1
readUTF16();
short arrayLength = in.readShort();
readNBytes(0xff & arrayLength);
break;
case (byte) 0xfe:
break;
default:
error("Unable to handle packet 0x" + Integer.toHexString(packetId)
+ " after 0x" + Integer.toHexString(lastPacket));
}
lastPacket = packetId;
}
private void readItem() throws IOException {
short id;
if ((id = in.readShort()) > 0) {
in.readByte();
in.readShort();
if (ENCHANTABLE.contains(id)) {
short length;
if ((length = in.readShort()) > 0) {
readNBytes(length);
}
}
}
}
private void readUnknownBlob() throws IOException {
byte unknown = in.readByte();
while (unknown != 0x7f) {
int type = (unknown & 0xE0) >> 5;
switch (type) {
case 0:
in.readByte();
break;
case 1:
in.readShort();
break;
case 2:
in.readInt();
break;
case 3:
in.readFloat();
break;
case 4:
readUTF16();
break;
case 5:
in.readShort();
in.readByte();
in.readShort();
break;
case 6:
in.readInt();
in.readInt();
in.readInt();
}
unknown = in.readByte();
}
}
protected String write(String s) throws IOException {
byte[] bytes = s.getBytes("UTF-16");
if (s.length() == 0) {
out.write((byte) 0x00);
out.write((byte) 0x00);
return s;
}
bytes[0] = (byte) ((s.length() >> 8) & 0xFF);
bytes[1] = (byte) ((s.length() & 0xFF));
for (byte b : bytes) {
out.write(b);
}
return s;
}
protected String readUTF16() throws IOException {
short length = in.readShort();
byte[] bytes = new byte[length * 2 + 2];
for (short i = 0; i < length * 2; i++) {
bytes[i + 2] = in.readByte();
}
bytes[0] = (byte) 0xfffffffe;
bytes[1] = (byte) 0xffffffff;
return new String(bytes, "UTF-16");
}
private void readNBytes(int bytes) throws IOException {
for (int c = 0; c < bytes; ++c) {
in.readByte();
}
}
protected void die() {
connected = false;
if (controller != null) {
controller.remove(this);
}
if (trashdat()) {
File dat = new File(server.options.get("levelName") + File.separator + "players" + File.separator + name + ".dat");
if (controller != null) {
controller.trash(dat);
} else {
dat.delete();
}
}
}
protected void error(String reason) {
die();
if (!expectDisconnect) {
System.out.print("[SimpleServer] Bot " + name + " died (" + reason + ")");
}
}
public void setController(BotController controller) {
this.controller = controller;
}
private final class Tunneler extends Thread {
@Override
public void run() {
while (connected) {
try {
handlePacket(in.readByte());
out.flush();
if (!gotFirstPacket) {
gotFirstPacket = true;
}
} catch (IOException e) {
if (!gotFirstPacket) {
try {
connect();
} catch (Exception e2) {
error("Soket closed on reconnect");
}
break;
} else {
error("Soket closed");
}
}
}
}
}
}
| false | true | protected void handlePacket(byte packetId) throws IOException {
// System.out.println("Packet: 0x" + Integer.toHexString(packetId));
switch (packetId) {
case 0x2:
readUTF16();
login();
break;
case 0x1:
in.readInt();
readUTF16();
in.readLong();
in.readInt();
position.dimension = Dimension.get(in.readByte());
in.readByte();
in.readByte();
in.readByte();
break;
case 0x0d: // Player Position & Look
double x = in.readDouble();
double stance = in.readDouble();
double y = in.readDouble();
double z = in.readDouble();
float yaw = in.readFloat();
float pitch = in.readFloat();
boolean onGround = in.readBoolean();
position.updatePosition(x, y, z, stance);
position.updateLook(yaw, pitch);
position.updateGround(onGround);
if (!ready) {
sendPosition();
ready();
} else if (dead) {
sendPosition();
dead = false;
}
positionUpdate();
break;
case 0x0b: // Player Position
double x2 = in.readDouble();
double stance2 = in.readDouble();
double y2 = in.readDouble();
double z2 = in.readDouble();
boolean onGround2 = in.readBoolean();
position.updatePosition(x2, y2, z2, stance2);
position.updateGround(onGround2);
positionUpdate();
break;
case (byte) 0xff: // Disconnect/Kick
String reason = readUTF16();
error(reason);
break;
case 0x00: // Keep Alive
keepAlive(in.readInt());
break;
case 0x03: // Chat Message
readUTF16();
break;
case 0x04: // Time Update
in.readLong();
break;
case 0x05: // Player Inventory
in.readInt();
in.readShort();
in.readShort();
in.readShort();
break;
case 0x06: // Spawn Position
readNBytes(12);
break;
case 0x07: // Use Entity?
in.readInt();
in.readInt();
in.readBoolean();
in.readBoolean();
break;
case 0x08: // Update Health
health = in.readShort();
in.readShort();
in.readFloat();
if (health <= 0) {
dead = true;
respawn();
}
break;
case 0x09: // Respawn
position.dimension = Dimension.get(in.readByte());
in.readByte();
in.readByte();
in.readShort();
in.readLong();
break;
case 0x0a: // Player
in.readByte();
break;
case 0x0c: // Player Look
readNBytes(9);
break;
case 0x0e: // Player Digging
in.readByte();
in.readInt();
in.readByte();
in.readInt();
in.readByte();
break;
case 0x0f: // Player Block Placement
in.readInt();
in.readByte();
in.readInt();
in.readByte();
readItem();
break;
case 0x10: // Holding Change
readNBytes(2);
break;
case 0x11: // Use Bed
readNBytes(14);
break;
case 0x12: // Animation
readNBytes(5);
break;
case 0x13: // ???
in.readInt();
in.readByte();
break;
case 0x14: // Named Entity Spawn
in.readInt();
readUTF16();
readNBytes(16);
break;
case 0x15: // Pickup spawn
readNBytes(24);
break;
case 0x16: // Collect Item
readNBytes(8);
break;
case 0x17: // Add Object/Vehicle
in.readInt();
in.readByte();
in.readInt();
in.readInt();
in.readInt();
int flag = in.readInt();
if (flag > 0) {
in.readShort();
in.readShort();
in.readShort();
}
break;
case 0x18: // Mob Spawn
in.readInt();
in.readByte();
in.readInt();
in.readInt();
in.readInt();
in.readByte();
in.readByte();
readUnknownBlob();
break;
case 0x19: // Painting
in.readInt();
readUTF16();
in.readInt();
in.readInt();
in.readInt();
in.readInt();
break;
case 0x1a:
in.readInt();
in.readInt();
in.readInt();
in.readInt();
in.readShort();
break;
case 0x1c: // Entity Velocity?
readNBytes(10);
break;
case 0x1d: // Destroy Entity
readNBytes(4);
break;
case 0x1e: // Entity
readNBytes(4);
break;
case 0x1f: // Entity Relative Move
readNBytes(7);
break;
case 0x20: // Entity Look
readNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
readNBytes(9);
break;
case 0x22: // Entity Teleport
readNBytes(18);
break;
case 0x26: // Entity status?
readNBytes(5);
break;
case 0x27: // Attach Entity?
readNBytes(8);
break;
case 0x28: // Entity Metadata
in.readInt();
readUnknownBlob();
break;
case 0x29: // new in 1.8, add status effect (41)
in.readInt();
in.readByte();
in.readByte();
in.readShort();
break;
case 0x2a: // new in 1.8, remove status effect (42)
in.readInt();
in.readByte();
break;
case 0x2b: // experience
in.readFloat();
in.readShort();
in.readShort();
break;
case 0x32: // Pre-Chunk
readNBytes(9);
break;
case 0x33: // Map Chunk
readNBytes(13);
int chunkSize = in.readInt();
readNBytes(chunkSize);
break;
case 0x34: // Multi Block Change
readNBytes(8);
short arraySize = in.readShort();
readNBytes(arraySize * 4);
break;
case 0x35: // Block Change
in.readInt();
in.readByte();
in.readInt();
in.readByte();
in.readByte();
break;
case 0x36: // ???
readNBytes(12);
break;
case 0x3c: // Explosion
readNBytes(28);
int recordCount = in.readInt();
readNBytes(recordCount * 3);
break;
case 0x3d: // Unknown
in.readInt();
in.readInt();
in.readByte();
in.readInt();
in.readInt();
break;
case 0x46: // Invalid Bed
readNBytes(2);
break;
case 0x47: // Thunder
readNBytes(17);
break;
case 0x64: // Open window
in.readByte();
in.readByte();
readUTF16();
in.readByte();
break;
case 0x65:
in.readByte();
break;
case 0x66: // Inventory Item Move
in.readByte();
in.readShort();
in.readByte();
in.readShort();
in.readBoolean();
readItem();
break;
case 0x67: // Inventory Item Update
in.readByte();
in.readShort();
readItem();
break;
case 0x68: // Inventory
in.readByte();
short count = in.readShort();
for (int c = 0; c < count; ++c) {
readItem();
}
break;
case 0x69:
in.readByte();
in.readShort();
in.readShort();
break;
case 0x6a: // item transaction
in.readByte();
in.readShort();
in.readByte();
break;
case 0x6b: // creative item get
in.readShort();
readItem();
break;
case (byte) 0x6c:
readNBytes(2);
break;
case (byte) 0x82: // Update Sign
in.readInt();
in.readShort();
in.readInt();
readUTF16();
readUTF16();
readUTF16();
readUTF16();
break;
case (byte) 0x83: // Map data
in.readShort();
in.readShort();
byte length = in.readByte();
readNBytes(0xff & length);
break;
case (byte) 0xc8: // Statistic
readNBytes(5);
break;
case (byte) 0xc9: // User list
readUTF16();
in.readBoolean();
in.readShort();
break;
case (byte) 0xe6: // ModLoaderMP by SDK
in.readInt(); // mod
in.readInt(); // packet id
readNBytes(in.readInt() * 4); // ints
readNBytes(in.readInt() * 4); // floats
int sizeString = in.readInt(); // strings
for (int i = 0; i < sizeString; i++) {
readNBytes(in.readInt());
}
break;
case (byte) 0xfa: // Unknown, added in 1.1
readUTF16();
short arrayLength = in.readShort();
readNBytes(0xff & arrayLength);
break;
case (byte) 0xfe:
break;
default:
error("Unable to handle packet 0x" + Integer.toHexString(packetId)
+ " after 0x" + Integer.toHexString(lastPacket));
}
lastPacket = packetId;
}
| protected void handlePacket(byte packetId) throws IOException {
// System.out.println("Packet: 0x" + Integer.toHexString(packetId));
switch (packetId) {
case 0x2:
readUTF16();
login();
break;
case 0x1:
in.readInt();
readUTF16();
in.readLong();
readUTF16(); // Added in 1.1, level type
in.readInt();
position.dimension = Dimension.get(in.readByte());
in.readByte();
in.readByte();
in.readByte();
break;
case 0x0d: // Player Position & Look
double x = in.readDouble();
double stance = in.readDouble();
double y = in.readDouble();
double z = in.readDouble();
float yaw = in.readFloat();
float pitch = in.readFloat();
boolean onGround = in.readBoolean();
position.updatePosition(x, y, z, stance);
position.updateLook(yaw, pitch);
position.updateGround(onGround);
if (!ready) {
sendPosition();
ready();
} else if (dead) {
sendPosition();
dead = false;
}
positionUpdate();
break;
case 0x0b: // Player Position
double x2 = in.readDouble();
double stance2 = in.readDouble();
double y2 = in.readDouble();
double z2 = in.readDouble();
boolean onGround2 = in.readBoolean();
position.updatePosition(x2, y2, z2, stance2);
position.updateGround(onGround2);
positionUpdate();
break;
case (byte) 0xff: // Disconnect/Kick
String reason = readUTF16();
error(reason);
break;
case 0x00: // Keep Alive
keepAlive(in.readInt());
break;
case 0x03: // Chat Message
readUTF16();
break;
case 0x04: // Time Update
in.readLong();
break;
case 0x05: // Player Inventory
in.readInt();
in.readShort();
in.readShort();
in.readShort();
break;
case 0x06: // Spawn Position
readNBytes(12);
break;
case 0x07: // Use Entity?
in.readInt();
in.readInt();
in.readBoolean();
in.readBoolean();
break;
case 0x08: // Update Health
health = in.readShort();
in.readShort();
in.readFloat();
if (health <= 0) {
dead = true;
respawn();
}
break;
case 0x09: // Respawn
position.dimension = Dimension.get(in.readByte());
in.readByte();
in.readByte();
in.readShort();
in.readLong();
readUTF16(); // Added in 1.1, level type
break;
case 0x0a: // Player
in.readByte();
break;
case 0x0c: // Player Look
readNBytes(9);
break;
case 0x0e: // Player Digging
in.readByte();
in.readInt();
in.readByte();
in.readInt();
in.readByte();
break;
case 0x0f: // Player Block Placement
in.readInt();
in.readByte();
in.readInt();
in.readByte();
readItem();
break;
case 0x10: // Holding Change
readNBytes(2);
break;
case 0x11: // Use Bed
readNBytes(14);
break;
case 0x12: // Animation
readNBytes(5);
break;
case 0x13: // ???
in.readInt();
in.readByte();
break;
case 0x14: // Named Entity Spawn
in.readInt();
readUTF16();
readNBytes(16);
break;
case 0x15: // Pickup spawn
readNBytes(24);
break;
case 0x16: // Collect Item
readNBytes(8);
break;
case 0x17: // Add Object/Vehicle
in.readInt();
in.readByte();
in.readInt();
in.readInt();
in.readInt();
int flag = in.readInt();
if (flag > 0) {
in.readShort();
in.readShort();
in.readShort();
}
break;
case 0x18: // Mob Spawn
in.readInt();
in.readByte();
in.readInt();
in.readInt();
in.readInt();
in.readByte();
in.readByte();
readUnknownBlob();
break;
case 0x19: // Painting
in.readInt();
readUTF16();
in.readInt();
in.readInt();
in.readInt();
in.readInt();
break;
case 0x1a:
in.readInt();
in.readInt();
in.readInt();
in.readInt();
in.readShort();
break;
case 0x1c: // Entity Velocity?
readNBytes(10);
break;
case 0x1d: // Destroy Entity
readNBytes(4);
break;
case 0x1e: // Entity
readNBytes(4);
break;
case 0x1f: // Entity Relative Move
readNBytes(7);
break;
case 0x20: // Entity Look
readNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
readNBytes(9);
break;
case 0x22: // Entity Teleport
readNBytes(18);
break;
case 0x26: // Entity status?
readNBytes(5);
break;
case 0x27: // Attach Entity?
readNBytes(8);
break;
case 0x28: // Entity Metadata
in.readInt();
readUnknownBlob();
break;
case 0x29: // new in 1.8, add status effect (41)
in.readInt();
in.readByte();
in.readByte();
in.readShort();
break;
case 0x2a: // new in 1.8, remove status effect (42)
in.readInt();
in.readByte();
break;
case 0x2b: // experience
in.readFloat();
in.readShort();
in.readShort();
break;
case 0x32: // Pre-Chunk
readNBytes(9);
break;
case 0x33: // Map Chunk
readNBytes(13);
int chunkSize = in.readInt();
readNBytes(chunkSize);
break;
case 0x34: // Multi Block Change
readNBytes(8);
short arraySize = in.readShort();
readNBytes(arraySize * 4);
break;
case 0x35: // Block Change
in.readInt();
in.readByte();
in.readInt();
in.readByte();
in.readByte();
break;
case 0x36: // ???
readNBytes(12);
break;
case 0x3c: // Explosion
readNBytes(28);
int recordCount = in.readInt();
readNBytes(recordCount * 3);
break;
case 0x3d: // Unknown
in.readInt();
in.readInt();
in.readByte();
in.readInt();
in.readInt();
break;
case 0x46: // Invalid Bed
readNBytes(2);
break;
case 0x47: // Thunder
readNBytes(17);
break;
case 0x64: // Open window
in.readByte();
in.readByte();
readUTF16();
in.readByte();
break;
case 0x65:
in.readByte();
break;
case 0x66: // Inventory Item Move
in.readByte();
in.readShort();
in.readByte();
in.readShort();
in.readBoolean();
readItem();
break;
case 0x67: // Inventory Item Update
in.readByte();
in.readShort();
readItem();
break;
case 0x68: // Inventory
in.readByte();
short count = in.readShort();
for (int c = 0; c < count; ++c) {
readItem();
}
break;
case 0x69:
in.readByte();
in.readShort();
in.readShort();
break;
case 0x6a: // item transaction
in.readByte();
in.readShort();
in.readByte();
break;
case 0x6b: // creative item get
in.readShort();
readItem();
break;
case (byte) 0x6c:
readNBytes(2);
break;
case (byte) 0x82: // Update Sign
in.readInt();
in.readShort();
in.readInt();
readUTF16();
readUTF16();
readUTF16();
readUTF16();
break;
case (byte) 0x83: // Map data
in.readShort();
in.readShort();
byte length = in.readByte();
readNBytes(0xff & length);
break;
case (byte) 0xc8: // Statistic
readNBytes(5);
break;
case (byte) 0xc9: // User list
readUTF16();
in.readBoolean();
in.readShort();
break;
case (byte) 0xe6: // ModLoaderMP by SDK
in.readInt(); // mod
in.readInt(); // packet id
readNBytes(in.readInt() * 4); // ints
readNBytes(in.readInt() * 4); // floats
int sizeString = in.readInt(); // strings
for (int i = 0; i < sizeString; i++) {
readNBytes(in.readInt());
}
break;
case (byte) 0xfa: // Unknown, added in 1.1
readUTF16();
short arrayLength = in.readShort();
readNBytes(0xff & arrayLength);
break;
case (byte) 0xfe:
break;
default:
error("Unable to handle packet 0x" + Integer.toHexString(packetId)
+ " after 0x" + Integer.toHexString(lastPacket));
}
lastPacket = packetId;
}
|
diff --git a/src/test/junit/fedora/test/integration/TestCommandLineUtilities.java b/src/test/junit/fedora/test/integration/TestCommandLineUtilities.java
index b7e00f8c3..768cf5138 100644
--- a/src/test/junit/fedora/test/integration/TestCommandLineUtilities.java
+++ b/src/test/junit/fedora/test/integration/TestCommandLineUtilities.java
@@ -1,308 +1,310 @@
package fedora.test.integration;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.custommonkey.xmlunit.SimpleXpathEngine;
import fedora.client.FedoraClient;
import fedora.server.management.FedoraAPIM;
import fedora.test.DemoObjectTestSetup;
import fedora.test.FedoraServerTestCase;
import fedora.utilities.ExecUtility;
/**
* @author Edwin Shin
*
*/
public class TestCommandLineUtilities extends FedoraServerTestCase
{
static ByteArrayOutputStream sbOut = null;
static ByteArrayOutputStream sbErr = null;
static TestCommandLineUtilities curTest = null;
public static Test suite()
{
TestSuite suite = new TestSuite("Command Line Utilities TestSuite");
suite.addTestSuite(TestCommandLineUtilities.class);
return new DemoObjectTestSetup(suite);
}
public void testFedoraPurgeAndIngest()
{
System.out.println("Purging object demo:5");
System.out.println("FEDORA-HOME = " + FEDORA_HOME);
purgeUsingScript("demo:5");
assertEquals(0, sbErr.size());
System.out.println("Re-ingesting object demo:5");
ingestFoxmlFile(new File(FEDORA_HOME + "/client/demo/foxml/local-server-demos/simple-image-demo/obj_demo_5.xml"));
String out = sbOut.toString();
String err = sbErr.toString();
assertEquals(out.indexOf("Ingested PID: demo:5")!= -1, true );
System.out.println("Purge and ingest test succeeded");
}
public void testBatchBuildAndBatchIngestAndPurge() throws Exception
{
System.out.println("Building batch objects");
batchBuild(new File(FEDORA_HOME + "/client/demo/batch-demo/foxml-template.xml"),
new File(FEDORA_HOME + "/client/demo/batch-demo/object-specifics"),
new File(FEDORA_HOME + "/client/demo/batch-demo/objects"),
new File(FEDORA_HOME + "/client/logs/build.log"));
String out = sbOut.toString();
String err = sbErr.toString();
assertEquals(err, true, err.indexOf("10 Fedora FOXML XML documents successfully created")!= -1);
System.out.println("Ingesting batch objects");
batchIngest(new File(FEDORA_HOME + "/client/demo/batch-demo/objects"),
new File(FEDORA_HOME + "/server/logs/junit_ingest.log"));
out = sbOut.toString();
err = sbErr.toString();
if (err.indexOf("10 objects successfully ingested into Fedora") == -1) {
System.out.println("Didn't find expected string in output:\n" + err);
assertEquals(true, false);
}
assertEquals(err.indexOf("10 objects successfully ingested into Fedora")!= -1, true );
String batchObjs[] = { "demo:3010", "demo:3011", "demo:3012", "demo:3013", "demo:3014",
"demo:3015", "demo:3016", "demo:3017", "demo:3018", "demo:3019"};
System.out.println("Purging batch objects");
purgeFast(batchObjs);
System.out.println("Build and ingest test succeeded");
}
public void testBatchBuildIngestAndPurge() throws Exception
{
System.out.println("Building and Ingesting batch objects");
batchBuildIngest(new File(FEDORA_HOME + "/client/demo/batch-demo/foxml-template.xml"),
new File(FEDORA_HOME + "/client/demo/batch-demo/object-specifics"),
new File(FEDORA_HOME + "/client/demo/batch-demo/objects"),
new File(FEDORA_HOME + "/server/logs/junit_buildingest.log"));
String out = sbOut.toString();
String err = sbErr.toString();
assertEquals("Response did not contain expected string re: FOXML XML documents: <reponse>" + err + "</response>", err.indexOf("10 Fedora FOXML XML documents successfully created")!= -1, true );
assertEquals("Response did not contain expected string re: objects successfully ingested: <reponse>" + err + "</reponse", err.indexOf("10 objects successfully ingested into Fedora")!= -1, true );
String batchObjs[] = { "demo:3010", "demo:3011", "demo:3012", "demo:3013", "demo:3014",
"demo:3015", "demo:3016", "demo:3017", "demo:3018", "demo:3019"};
System.out.println("Purging batch objects");
purgeFast(batchObjs);
System.out.println("Build/ingest test succeeded");
}
public void testBatchModify() throws Exception
{
System.out.println("Running batch modify of objects");
batchModify(new File(FEDORA_HOME + "/client/demo/batch-demo/modify-batch-directives.xml"),
new File(FEDORA_HOME + "/server/logs/junit_modify.log"));
String out = sbOut.toString();
String err = sbErr.toString();
if (out.indexOf("23 modify directives successfully processed.")== -1)
{
System.out.println(" out = " + out);
System.out.println(" err = " + err);
}
assertEquals(false, out.indexOf("23 modify directives successfully processed.")== -1);
assertEquals(false, out.indexOf("0 modify directives failed.")== -1);
System.out.println("Purging batch modify object");
purgeFast("demo:32");
System.out.println("Batch modify test succeeded");
}
public void testExport()
{
System.out.println("Testing fedora-export");
File outFile = new File(FEDORA_HOME + "/client/demo/batch-demo/demo_5.xml");
String absPath = outFile.getAbsolutePath();
if (outFile.exists())
{
outFile.delete();
}
System.out.println("Exporting object demo:5");
exportObj("demo:5", new File(FEDORA_HOME + "/client/demo/batch-demo"));
String out = sbOut.toString();
String err = sbErr.toString();
assertEquals(out.indexOf("Exported demo:5")!= -1, true );
File outFile2 = new File(FEDORA_HOME + "/client/demo/batch-demo/demo_5.xml");
String absPath2 = outFile2.getAbsolutePath();
assertEquals(outFile2.exists(), true );
System.out.println("Deleting exported file");
if (outFile2.exists())
{
outFile2.delete();
}
System.out.println("Export test succeeded");
}
public void testValidatePolicy()
{
System.out.println("Testing Validate Policies");
File validDir = new File("src/test/junit/XACMLTestPolicies/valid-policies");
traverseAndValidate(validDir, true);
File invalidDir = new File("src/test/junit/XACMLTestPolicies/invalid-policies");
traverseAndValidate(invalidDir, false);
System.out.println("Validate Policies test succeeded");
}
private void traverseAndValidate(File testDir, boolean expectValid)
{
// assertEquals(testDir.isDirectory(), true);
File testFiles[] = testDir.listFiles(new java.io.FilenameFilter()
{
public boolean accept(File dir, String name)
{
if ((name.toLowerCase().startsWith("permit") ||
name.toLowerCase().startsWith("deny")) &&
name.endsWith(".xml"))
{
return(true);
}
return(false);
}
}
);
for ( int i = 0; i < testFiles.length; i++)
{
System.out.println("Checking "+(expectValid ? "valid" : "invalid") +" policy: "+
testFiles[i].getName());
execute(FEDORA_HOME+ "/server/bin/validate-policy", testFiles[i].getAbsolutePath());
String out = sbOut.toString();
String err = sbErr.toString();
if (expectValid)
{
- assertTrue(out.indexOf("Validation successful") != -1);
+ assertTrue("Expected \"Validation successful\", but received \"" + out + "\"",
+ out.indexOf("Validation successful") != -1);
}
else
{
- assertTrue(out.indexOf("Validation failed")!= -1);
+ assertTrue("Expected \"Validation failed\", but received \"" + out + "\"",
+ out.indexOf("Validation failed")!= -1);
}
}
}
private void ingestFoxmlDirectory(File dir)
{
//fedora-ingest f obj1.xml foxml1.0 myrepo.com:8443 jane jpw https
execute(FEDORA_HOME + "/client/bin/fedora-ingest", "d " + dir.getAbsolutePath() +
" foxml1.0 DMO " + getHost() + ":" + getPort() + " " + getUsername() +
" " + getPassword() + " " + getProtocol() + " \"junit ingest\"");
}
private void ingestFoxmlFile(File f)
{
//fedora-ingest f obj1.xml foxml1.0 myrepo.com:8443 jane jpw https
// File exe = new File("client/bin/fedora-ingest");
execute(FEDORA_HOME + "/client/bin/fedora-ingest", "f " + f.getAbsolutePath() +
" foxml1.0 " + getHost() + ":" + getPort() + " " + getUsername() +
" " + getPassword() + " " + getProtocol() + " junit-ingest");
}
private static void purgeUsingScript(String pid)
{
// File exe = new File("client/bin/fedora-purge");
execute(FEDORA_HOME + "/client/bin/fedora-purge", getHost() + ":" + getPort() +
" " + getUsername() + " " + getPassword() + " " + pid + " " +
getProtocol() + " junit-purge");
}
private static void purgeFast(String pid) throws Exception {
getAPIM().purgeObject(pid, "because", false);
}
private static void purgeFast(String[] pids) throws Exception {
FedoraAPIM apim = getAPIM();
for (int i = 0; i < pids.length; i++) {
apim.purgeObject(pids[i], "because", false);
}
}
private static FedoraAPIM getAPIM() throws Exception {
String baseURL = getProtocol() + "://"
+ getHost() + ":"
+ getPort() + "/fedora";
FedoraClient client = new FedoraClient(baseURL,
getUsername(),
getPassword());
return client.getAPIM();
}
private void batchBuild(File objectTemplateFile, File objectSpecificDir, File objectDir, File logFile)
{
execute(FEDORA_HOME + "/client/bin/fedora-batch-build", objectTemplateFile.getAbsolutePath() + " " +
objectSpecificDir.getAbsolutePath() + " " + objectDir.getAbsolutePath() + " " +
logFile.getAbsolutePath() + " text");
}
private void batchIngest(File objectDir, File logFile)
{
execute(FEDORA_HOME + "/client/bin/fedora-batch-ingest", objectDir.getAbsolutePath() + " " +
logFile.getAbsolutePath() + " text foxml1.0 " + getHost() + ":" + getPort() +
" " + getUsername() + " " + getPassword() + " " + getProtocol() );
}
private void batchBuildIngest(File objectTemplateFile, File objectSpecificDir, File objectDir, File logFile)
{
execute(FEDORA_HOME + "/client/bin/fedora-batch-buildingest", objectTemplateFile.getAbsolutePath() + " " +
objectSpecificDir.getAbsolutePath() + " " + objectDir.getAbsolutePath() + " " +
logFile.getAbsolutePath() + " text " + getHost() + ":" + getPort() +
" " + getUsername() + " " + getPassword() + " " + getProtocol() );
}
private void batchModify(File batchDirectives, File logFile)
{
execute(FEDORA_HOME + "/client/bin/fedora-modify", getHost() + ":" + getPort() + " " +
getUsername() + " " + getPassword() + " " + batchDirectives.getAbsolutePath() + " " +
logFile.getAbsolutePath() + " " + getProtocol() );
}
private void exportObj(String pid, File dir)
{
execute(FEDORA_HOME + "/client/bin/fedora-export", getHost() + ":" + getPort() + " " +
getUsername() + " " + getPassword() + " " + pid + " foxml1.0 public " +
dir.getAbsolutePath() + " " + getProtocol() );
}
public static void execute(String cmd, String args)
{
String osName = System.getProperty("os.name");
if (!osName.startsWith("Windows")) {
// needed for the Fedora shell scripts
cmd = cmd + ".sh";
}
// System.out.println("Executing cmd:" + cmd + " " + args);
if (sbOut != null && sbErr != null)
{
sbOut.reset();
sbErr.reset();
ExecUtility.execCommandLineUtility(cmd + " " + args, sbOut, sbErr);
}
else
{
ExecUtility.execCommandLineUtility(cmd + " " + args);
}
// System.out.println("Executed cmd:" + cmd );
}
public void setUp() throws Exception {
SimpleXpathEngine.registerNamespace("oai_dc", "http://www.openarchives.org/OAI/2.0/oai_dc/");
SimpleXpathEngine.registerNamespace("uvalibadmin", "http://dl.lib.virginia.edu/bin/admin/admin.dtd/");
sbOut = new ByteArrayOutputStream();
sbErr = new ByteArrayOutputStream();
}
public void tearDown()
{
SimpleXpathEngine.clearNamespaces();
}
public static void main(String[] args)
{
junit.textui.TestRunner.run(TestCommandLineUtilities.class);
}
}
| false | true | private void traverseAndValidate(File testDir, boolean expectValid)
{
// assertEquals(testDir.isDirectory(), true);
File testFiles[] = testDir.listFiles(new java.io.FilenameFilter()
{
public boolean accept(File dir, String name)
{
if ((name.toLowerCase().startsWith("permit") ||
name.toLowerCase().startsWith("deny")) &&
name.endsWith(".xml"))
{
return(true);
}
return(false);
}
}
);
for ( int i = 0; i < testFiles.length; i++)
{
System.out.println("Checking "+(expectValid ? "valid" : "invalid") +" policy: "+
testFiles[i].getName());
execute(FEDORA_HOME+ "/server/bin/validate-policy", testFiles[i].getAbsolutePath());
String out = sbOut.toString();
String err = sbErr.toString();
if (expectValid)
{
assertTrue(out.indexOf("Validation successful") != -1);
}
else
{
assertTrue(out.indexOf("Validation failed")!= -1);
}
}
}
| private void traverseAndValidate(File testDir, boolean expectValid)
{
// assertEquals(testDir.isDirectory(), true);
File testFiles[] = testDir.listFiles(new java.io.FilenameFilter()
{
public boolean accept(File dir, String name)
{
if ((name.toLowerCase().startsWith("permit") ||
name.toLowerCase().startsWith("deny")) &&
name.endsWith(".xml"))
{
return(true);
}
return(false);
}
}
);
for ( int i = 0; i < testFiles.length; i++)
{
System.out.println("Checking "+(expectValid ? "valid" : "invalid") +" policy: "+
testFiles[i].getName());
execute(FEDORA_HOME+ "/server/bin/validate-policy", testFiles[i].getAbsolutePath());
String out = sbOut.toString();
String err = sbErr.toString();
if (expectValid)
{
assertTrue("Expected \"Validation successful\", but received \"" + out + "\"",
out.indexOf("Validation successful") != -1);
}
else
{
assertTrue("Expected \"Validation failed\", but received \"" + out + "\"",
out.indexOf("Validation failed")!= -1);
}
}
}
|
diff --git a/src/net/slipcor/pvparena/loadables/ArenaGoalManager.java b/src/net/slipcor/pvparena/loadables/ArenaGoalManager.java
index aae4a633..72bb9ecd 100644
--- a/src/net/slipcor/pvparena/loadables/ArenaGoalManager.java
+++ b/src/net/slipcor/pvparena/loadables/ArenaGoalManager.java
@@ -1,403 +1,403 @@
package net.slipcor.pvparena.loadables;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import net.slipcor.pvparena.PVPArena;
import net.slipcor.pvparena.arena.Arena;
import net.slipcor.pvparena.arena.ArenaPlayer;
import net.slipcor.pvparena.arena.ArenaTeam;
import net.slipcor.pvparena.arena.ArenaPlayer.Status;
import net.slipcor.pvparena.core.Config.CFG;
import net.slipcor.pvparena.core.Debug;
import net.slipcor.pvparena.core.Language;
import net.slipcor.pvparena.core.Language.MSG;
import net.slipcor.pvparena.goals.GoalBlockDestroy;
import net.slipcor.pvparena.goals.GoalDomination;
import net.slipcor.pvparena.goals.GoalFlags;
import net.slipcor.pvparena.goals.GoalPhysicalFlags;
import net.slipcor.pvparena.goals.GoalPlayerDeathMatch;
import net.slipcor.pvparena.goals.GoalPlayerKillReward;
import net.slipcor.pvparena.goals.GoalPlayerLives;
import net.slipcor.pvparena.goals.GoalSabotage;
import net.slipcor.pvparena.goals.GoalTank;
import net.slipcor.pvparena.goals.GoalTeamDeathMatch;
import net.slipcor.pvparena.goals.GoalTeamLives;
import net.slipcor.pvparena.goals.GoalTime;
import net.slipcor.pvparena.ncloader.NCBLoader;
import net.slipcor.pvparena.runnables.EndRunnable;
/**
* <pre>Arena Goal Manager class</pre>
*
* Loads and manages arena goals
*
* @author slipcor
*
* @version v0.10.2
*/
public class ArenaGoalManager {
private List<ArenaGoal> types;
private final NCBLoader<ArenaGoal> loader;
protected static final Debug DEBUG = new Debug(31);
/**
* create an arena type instance
*
* @param plugin
* the plugin instance
*/
public ArenaGoalManager(final PVPArena plugin) {
final File path = new File(plugin.getDataFolder().toString() + "/goals");
if (!path.exists()) {
path.mkdir();
}
loader = new NCBLoader<ArenaGoal>(plugin, path, new Object[] {});
types = loader.load();
fill();
}
private void fill() {
types.add(new GoalBlockDestroy());
types.add(new GoalDomination());
types.add(new GoalFlags());
types.add(new GoalPhysicalFlags());
types.add(new GoalPlayerDeathMatch());
types.add(new GoalPlayerKillReward());
types.add(new GoalPlayerLives());
types.add(new GoalSabotage());
types.add(new GoalTank());
types.add(new GoalTeamDeathMatch());
types.add(new GoalTeamLives());
types.add(new GoalTime());
for (ArenaGoal type : types) {
type.onThisLoad();
DEBUG.i("module ArenaType loaded: " + type.getName() + " (version "
+ type.version() + ")");
}
}
public boolean allowsJoinInBattle(final Arena arena) {
for (ArenaGoal type : arena.getGoals()) {
if (!type.allowsJoinInBattle()) {
return false;
}
}
return true;
}
public String checkForMissingSpawns(final Arena arena, final Set<String> list) {
for (ArenaGoal type : arena.getGoals()) {
final String error = type.checkForMissingSpawns(list);
if (error != null) {
return error;
}
}
return null;
}
public void configParse(final Arena arena, final YamlConfiguration config) {
for (ArenaGoal type : arena.getGoals()) {
type.configParse(config);
}
}
public Set<String> getAllGoalNames() {
final Set<String> result = new HashSet<String>();
for (ArenaGoal goal : types) {
result.add(goal.getName());
}
return result;
}
public List<ArenaGoal> getAllGoals() {
return types;
}
/**
* find an arena type by arena type name
*
* @param tName
* the type name to find
* @return the arena type if found, null otherwise
*/
public ArenaGoal getGoalByName(final String tName) {
for (ArenaGoal type : types) {
if (type.getName().equalsIgnoreCase(tName)) {
return type;
}
}
return null;
}
public String guessSpawn(final Arena arena, final String place) {
for (ArenaGoal type : arena.getGoals()) {
final String result = type.guessSpawn(place);
if (result != null) {
return result;
}
}
return null;
}
public void initiate(final Arena arena, final Player player) {
DEBUG.i("initiating " + player.getName(), player);
for (ArenaGoal type : arena.getGoals()) {
type.initate(player);
}
}
public String ready(final Arena arena) {
DEBUG.i("AGM ready!?!");
String error = null;
for (ArenaGoal type : arena.getGoals()) {
error = type.ready();
if (error != null) {
DEBUG.i("type error:" + type.getName());
return error;
}
}
return null;
}
public void reload() {
types = loader.reload();
fill();
}
public void reset(final Arena arena, final boolean force) {
for (ArenaGoal type : arena.getGoals()) {
type.reset(force);
}
}
public void setDefaults(final Arena arena, final YamlConfiguration config) {
for (ArenaGoal type : arena.getGoals()) {
type.setDefaults(config);
}
}
public void setPlayerLives(final Arena arena, final int value) {
for (ArenaGoal type : arena.getGoals()) {
type.setPlayerLives(value);
}
}
public void setPlayerLives(final Arena arena, final ArenaPlayer player, final int value) {
for (ArenaGoal type : arena.getGoals()) {
type.setPlayerLives(player, value);
}
}
public void timedEnd(final Arena arena) {
/**
* name/team => score points
*
* handed over to each module
*/
DEBUG.i("timed end!");
Map<String, Double> scores = new HashMap<String, Double>();
for (ArenaGoal type : arena.getGoals()) {
DEBUG.i("scores: " + type.getName());
scores = type.timedEnd(scores);
}
final Set<String> winners = new HashSet<String>();
if (arena.isFreeForAll()) {
winners.add("free");
DEBUG.i("adding FREE");
} else if (arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER).equals("none")) {
// check all teams
double maxScore = 0;
for (String team : arena.getTeamNames()) {
if (scores.containsKey(team)) {
final double teamScore = scores.get(team);
if (teamScore > maxScore) {
maxScore = teamScore;
winners.clear();
winners.add(team);
DEBUG.i("clear and add team " + team);
} else if (teamScore == maxScore) {
winners.add(team);
DEBUG.i("add team "+team);
}
}
}
} else {
winners.add(arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER));
DEBUG.i("added winner!");
}
if (winners.size() > 1) {
DEBUG.i("more than 1");
final Set<String> preciseWinners = new HashSet<String>();
// several teams have max score!!
double maxSum = 0;
double sum = 0;
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
sum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
if (scores.containsKey(ap.getName())) {
sum += scores.get(ap.getName());
}
}
if (sum == maxSum) {
preciseWinners.add(team.getName());
DEBUG.i("adddding " + team.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(team.getName());
DEBUG.i("clearing and adddding + " + team.getName());
}
}
if (!preciseWinners.isEmpty()) {
winners.clear();
winners.addAll(preciseWinners);
}
}
if (arena.isFreeForAll()) {
DEBUG.i("FFAAA");
final Set<String> preciseWinners = new HashSet<String>();
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
double maxSum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
double sum = 0;
if (scores.containsKey(ap.getName())) {
sum = scores.get(ap.getName());
}
if (sum == maxSum) {
preciseWinners.add(ap.getName());
DEBUG.i("ffa adding " + ap.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(ap.getName());
DEBUG.i("ffa clr & adding " + ap.getName());
}
}
}
winners.clear();
if (preciseWinners.size() != arena.getPlayedPlayers().size()) {
winners.addAll(preciseWinners);
}
}
ArenaModuleManager.timedEnd(arena, winners);
if (arena.isFreeForAll()) {
for (ArenaTeam team : arena.getTeams()) {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (winners.isEmpty()) {
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
} else {
if (winners.contains(p.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.PLAYER_HAS_WON, p.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.PLAYER_HAS_WON, p.getName()));
} else {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (winners.isEmpty()) {
ArenaModuleManager.announce(arena, Language.parse(MSG.FIGHT_DRAW), "WINNER");
arena.broadcast(Language.parse(MSG.FIGHT_DRAW));
}
} else {
boolean hasBroadcasted = false;
for (ArenaTeam team : arena.getTeams()) {
if (winners.contains(team.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.TEAM_HAS_WON, "Team " + team.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
hasBroadcasted = true;
} else {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
if (!hasBroadcasted) {
arena.msg(p.get(), Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
}
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
- if (arena.endRunner == null) {
- arena.endRunner = new EndRunnable(arena, arena.getArenaConfig().getInt(
+ if (arena.realEndRunner == null) {
+ new EndRunnable(arena, arena.getArenaConfig().getInt(
CFG.TIME_ENDCOUNTDOWN));
}
}
public void unload(final Arena arena, final Player player) {
for (ArenaGoal type : arena.getGoals()) {
type.unload(player);
}
}
public void disconnect(final Arena arena, final ArenaPlayer player) {
if (arena == null) {
return;
}
for (ArenaGoal type : arena.getGoals()) {
type.disconnect(player);
}
}
}
| true | true | public void timedEnd(final Arena arena) {
/**
* name/team => score points
*
* handed over to each module
*/
DEBUG.i("timed end!");
Map<String, Double> scores = new HashMap<String, Double>();
for (ArenaGoal type : arena.getGoals()) {
DEBUG.i("scores: " + type.getName());
scores = type.timedEnd(scores);
}
final Set<String> winners = new HashSet<String>();
if (arena.isFreeForAll()) {
winners.add("free");
DEBUG.i("adding FREE");
} else if (arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER).equals("none")) {
// check all teams
double maxScore = 0;
for (String team : arena.getTeamNames()) {
if (scores.containsKey(team)) {
final double teamScore = scores.get(team);
if (teamScore > maxScore) {
maxScore = teamScore;
winners.clear();
winners.add(team);
DEBUG.i("clear and add team " + team);
} else if (teamScore == maxScore) {
winners.add(team);
DEBUG.i("add team "+team);
}
}
}
} else {
winners.add(arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER));
DEBUG.i("added winner!");
}
if (winners.size() > 1) {
DEBUG.i("more than 1");
final Set<String> preciseWinners = new HashSet<String>();
// several teams have max score!!
double maxSum = 0;
double sum = 0;
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
sum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
if (scores.containsKey(ap.getName())) {
sum += scores.get(ap.getName());
}
}
if (sum == maxSum) {
preciseWinners.add(team.getName());
DEBUG.i("adddding " + team.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(team.getName());
DEBUG.i("clearing and adddding + " + team.getName());
}
}
if (!preciseWinners.isEmpty()) {
winners.clear();
winners.addAll(preciseWinners);
}
}
if (arena.isFreeForAll()) {
DEBUG.i("FFAAA");
final Set<String> preciseWinners = new HashSet<String>();
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
double maxSum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
double sum = 0;
if (scores.containsKey(ap.getName())) {
sum = scores.get(ap.getName());
}
if (sum == maxSum) {
preciseWinners.add(ap.getName());
DEBUG.i("ffa adding " + ap.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(ap.getName());
DEBUG.i("ffa clr & adding " + ap.getName());
}
}
}
winners.clear();
if (preciseWinners.size() != arena.getPlayedPlayers().size()) {
winners.addAll(preciseWinners);
}
}
ArenaModuleManager.timedEnd(arena, winners);
if (arena.isFreeForAll()) {
for (ArenaTeam team : arena.getTeams()) {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (winners.isEmpty()) {
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
} else {
if (winners.contains(p.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.PLAYER_HAS_WON, p.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.PLAYER_HAS_WON, p.getName()));
} else {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (winners.isEmpty()) {
ArenaModuleManager.announce(arena, Language.parse(MSG.FIGHT_DRAW), "WINNER");
arena.broadcast(Language.parse(MSG.FIGHT_DRAW));
}
} else {
boolean hasBroadcasted = false;
for (ArenaTeam team : arena.getTeams()) {
if (winners.contains(team.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.TEAM_HAS_WON, "Team " + team.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
hasBroadcasted = true;
} else {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
if (!hasBroadcasted) {
arena.msg(p.get(), Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
}
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (arena.endRunner == null) {
arena.endRunner = new EndRunnable(arena, arena.getArenaConfig().getInt(
CFG.TIME_ENDCOUNTDOWN));
}
}
| public void timedEnd(final Arena arena) {
/**
* name/team => score points
*
* handed over to each module
*/
DEBUG.i("timed end!");
Map<String, Double> scores = new HashMap<String, Double>();
for (ArenaGoal type : arena.getGoals()) {
DEBUG.i("scores: " + type.getName());
scores = type.timedEnd(scores);
}
final Set<String> winners = new HashSet<String>();
if (arena.isFreeForAll()) {
winners.add("free");
DEBUG.i("adding FREE");
} else if (arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER).equals("none")) {
// check all teams
double maxScore = 0;
for (String team : arena.getTeamNames()) {
if (scores.containsKey(team)) {
final double teamScore = scores.get(team);
if (teamScore > maxScore) {
maxScore = teamScore;
winners.clear();
winners.add(team);
DEBUG.i("clear and add team " + team);
} else if (teamScore == maxScore) {
winners.add(team);
DEBUG.i("add team "+team);
}
}
}
} else {
winners.add(arena.getArenaConfig().getString(CFG.GOAL_TIME_WINNER));
DEBUG.i("added winner!");
}
if (winners.size() > 1) {
DEBUG.i("more than 1");
final Set<String> preciseWinners = new HashSet<String>();
// several teams have max score!!
double maxSum = 0;
double sum = 0;
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
sum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
if (scores.containsKey(ap.getName())) {
sum += scores.get(ap.getName());
}
}
if (sum == maxSum) {
preciseWinners.add(team.getName());
DEBUG.i("adddding " + team.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(team.getName());
DEBUG.i("clearing and adddding + " + team.getName());
}
}
if (!preciseWinners.isEmpty()) {
winners.clear();
winners.addAll(preciseWinners);
}
}
if (arena.isFreeForAll()) {
DEBUG.i("FFAAA");
final Set<String> preciseWinners = new HashSet<String>();
for (ArenaTeam team : arena.getTeams()) {
if (!winners.contains(team.getName())) {
continue;
}
double maxSum = 0;
for (ArenaPlayer ap : team.getTeamMembers()) {
double sum = 0;
if (scores.containsKey(ap.getName())) {
sum = scores.get(ap.getName());
}
if (sum == maxSum) {
preciseWinners.add(ap.getName());
DEBUG.i("ffa adding " + ap.getName());
} else if (sum > maxSum) {
maxSum = sum;
preciseWinners.clear();
preciseWinners.add(ap.getName());
DEBUG.i("ffa clr & adding " + ap.getName());
}
}
}
winners.clear();
if (preciseWinners.size() != arena.getPlayedPlayers().size()) {
winners.addAll(preciseWinners);
}
}
ArenaModuleManager.timedEnd(arena, winners);
if (arena.isFreeForAll()) {
for (ArenaTeam team : arena.getTeams()) {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (winners.isEmpty()) {
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
} else {
if (winners.contains(p.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.PLAYER_HAS_WON, p.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.PLAYER_HAS_WON, p.getName()));
} else {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (winners.isEmpty()) {
ArenaModuleManager.announce(arena, Language.parse(MSG.FIGHT_DRAW), "WINNER");
arena.broadcast(Language.parse(MSG.FIGHT_DRAW));
}
} else {
boolean hasBroadcasted = false;
for (ArenaTeam team : arena.getTeams()) {
if (winners.contains(team.getName())) {
ArenaModuleManager.announce(arena, Language.parse(MSG.TEAM_HAS_WON, "Team " + team.getName()), "WINNER");
arena.broadcast(Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
hasBroadcasted = true;
} else {
final Set<ArenaPlayer> apSet = new HashSet<ArenaPlayer>();
for (ArenaPlayer p : team.getTeamMembers()) {
apSet.add(p);
}
for (ArenaPlayer p : apSet) {
if (!p.getStatus().equals(Status.FIGHT)) {
continue;
}
p.addLosses();
if (!hasBroadcasted) {
arena.msg(p.get(), Language.parse(MSG.TEAM_HAS_WON, team.getColor()
+ "Team " + team.getName()));
}
arena.removePlayer(p.get(), arena.getArenaConfig().getString(CFG.TP_LOSE), false, false);
}
}
}
}
if (arena.realEndRunner == null) {
new EndRunnable(arena, arena.getArenaConfig().getInt(
CFG.TIME_ENDCOUNTDOWN));
}
}
|
diff --git a/uk.ac.gda.common.rcp/src/uk/ac/gda/ui/utils/ProjectUtils.java b/uk.ac.gda.common.rcp/src/uk/ac/gda/ui/utils/ProjectUtils.java
index 34b9c57..018d81f 100644
--- a/uk.ac.gda.common.rcp/src/uk/ac/gda/ui/utils/ProjectUtils.java
+++ b/uk.ac.gda.common.rcp/src/uk/ac/gda/ui/utils/ProjectUtils.java
@@ -1,129 +1,136 @@
/*-
* Copyright © 2011 Diamond Light Source Ltd.
*
* This file is part of GDA.
*
* GDA is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 as published by the Free
* Software Foundation.
*
* GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.gda.ui.utils;
import java.io.File;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import uk.ac.gda.common.rcp.CommonRCPActivator;
public class ProjectUtils {
/**
*
* @param projectName
* @param folderName
* @param importFolder
* @param natureId
* @param resourceFilterWrappers
* @param monitor
* @return IProject created
* @throws CoreException
*/
public static IProject createImportProjectAndFolder(final String projectName, final String folderName,
final String importFolder, final String natureId, final List<ResourceFilterWrapper> resourceFilterWrappers,
IProgressMonitor monitor) throws CoreException {
File file = new File(importFolder);
- if(!file.exists())
- throw new CoreException(new Status(IStatus.ERROR, CommonRCPActivator.PLUGIN_ID,
- "Unable to create project folder " + projectName + "." + folderName + " as folder " + importFolder + " does not exist "));
+ final String finalFolder;
+ if (!file.exists()) {
+ finalFolder = importFolder.trim();
+ file = new File(finalFolder);
+ if (!file.exists())
+ throw new CoreException(new Status(IStatus.ERROR, CommonRCPActivator.PLUGIN_ID,
+ "Unable to create project folder " + projectName + "." + folderName + " as folder " + finalFolder + " does not exist "));
+ } else {
+ finalFolder = importFolder;
+ }
IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
@Override
public void run(IProgressMonitor monitor) throws CoreException {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject project = root.getProject(projectName);
if (!project.exists()) {
monitor.subTask("Creating project :" + projectName);
project.create(monitor);
if (natureId != null) {
project.open(monitor);
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { natureId });
project.setDescription(description, monitor);
}
}
project.open(monitor);
if (project.findMember(folderName) == null) {
final IFolder src = project.getFolder(folderName);
- src.createLink(new Path(importFolder), IResource.BACKGROUND_REFRESH,
+ src.createLink(new Path(finalFolder), IResource.BACKGROUND_REFRESH,
monitor);
if (resourceFilterWrappers != null) {
for (ResourceFilterWrapper wrapper : resourceFilterWrappers) {
src.createFilter(wrapper.type, wrapper.fileInfoMatcherDescription,
IResource.BACKGROUND_REFRESH, monitor);
}
}
}
}
};
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
workspace.run(runnable, workspace.getRuleFactory().modifyRule(root), IResource.NONE, monitor);
return root.getProject(projectName);
}
public static void addRemoveNature(IProject project, IProgressMonitor monitor, boolean add, String natureId) throws CoreException{
IProjectDescription description = project.getDescription();
boolean hasNature = project.hasNature(natureId);
String [] newNatures=null;
if( add ){
if( !hasNature){
String[] natures = description.getNatureIds();
newNatures = new String[natures.length + 1];
System.arraycopy(natures, 0, newNatures, 0, natures.length);
newNatures[natures.length] = natureId;
}
} else {
if( hasNature){
String[] natures = description.getNatureIds();
Vector<String> v_newNatures= new Vector<String>();
for(int i=0; i< natures.length; i++){
if( !natures[i].equals(natureId))
v_newNatures.add(natures[i]);
}
newNatures = v_newNatures.toArray(new String[0]);
}
}
if( newNatures != null){
description.setNatureIds(newNatures);
project.setDescription(description, monitor);
}
}
}
| false | true | public static IProject createImportProjectAndFolder(final String projectName, final String folderName,
final String importFolder, final String natureId, final List<ResourceFilterWrapper> resourceFilterWrappers,
IProgressMonitor monitor) throws CoreException {
File file = new File(importFolder);
if(!file.exists())
throw new CoreException(new Status(IStatus.ERROR, CommonRCPActivator.PLUGIN_ID,
"Unable to create project folder " + projectName + "." + folderName + " as folder " + importFolder + " does not exist "));
IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
@Override
public void run(IProgressMonitor monitor) throws CoreException {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject project = root.getProject(projectName);
if (!project.exists()) {
monitor.subTask("Creating project :" + projectName);
project.create(monitor);
if (natureId != null) {
project.open(monitor);
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { natureId });
project.setDescription(description, monitor);
}
}
project.open(monitor);
if (project.findMember(folderName) == null) {
final IFolder src = project.getFolder(folderName);
src.createLink(new Path(importFolder), IResource.BACKGROUND_REFRESH,
monitor);
if (resourceFilterWrappers != null) {
for (ResourceFilterWrapper wrapper : resourceFilterWrappers) {
src.createFilter(wrapper.type, wrapper.fileInfoMatcherDescription,
IResource.BACKGROUND_REFRESH, monitor);
}
}
}
}
};
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
workspace.run(runnable, workspace.getRuleFactory().modifyRule(root), IResource.NONE, monitor);
return root.getProject(projectName);
}
| public static IProject createImportProjectAndFolder(final String projectName, final String folderName,
final String importFolder, final String natureId, final List<ResourceFilterWrapper> resourceFilterWrappers,
IProgressMonitor monitor) throws CoreException {
File file = new File(importFolder);
final String finalFolder;
if (!file.exists()) {
finalFolder = importFolder.trim();
file = new File(finalFolder);
if (!file.exists())
throw new CoreException(new Status(IStatus.ERROR, CommonRCPActivator.PLUGIN_ID,
"Unable to create project folder " + projectName + "." + folderName + " as folder " + finalFolder + " does not exist "));
} else {
finalFolder = importFolder;
}
IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
@Override
public void run(IProgressMonitor monitor) throws CoreException {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject project = root.getProject(projectName);
if (!project.exists()) {
monitor.subTask("Creating project :" + projectName);
project.create(monitor);
if (natureId != null) {
project.open(monitor);
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { natureId });
project.setDescription(description, monitor);
}
}
project.open(monitor);
if (project.findMember(folderName) == null) {
final IFolder src = project.getFolder(folderName);
src.createLink(new Path(finalFolder), IResource.BACKGROUND_REFRESH,
monitor);
if (resourceFilterWrappers != null) {
for (ResourceFilterWrapper wrapper : resourceFilterWrappers) {
src.createFilter(wrapper.type, wrapper.fileInfoMatcherDescription,
IResource.BACKGROUND_REFRESH, monitor);
}
}
}
}
};
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
workspace.run(runnable, workspace.getRuleFactory().modifyRule(root), IResource.NONE, monitor);
return root.getProject(projectName);
}
|
diff --git a/output/ui/src/main/java/org/richfaces/component/AbstractTabPanel.java b/output/ui/src/main/java/org/richfaces/component/AbstractTabPanel.java
index 1d361dde9..130bebd4e 100644
--- a/output/ui/src/main/java/org/richfaces/component/AbstractTabPanel.java
+++ b/output/ui/src/main/java/org/richfaces/component/AbstractTabPanel.java
@@ -1,110 +1,110 @@
/*
* JBoss, Home of Professional Open Source
* Copyright ${year}, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt 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.richfaces.component;
import org.richfaces.HeaderAlignment;
import org.richfaces.HeaderPosition;
import org.richfaces.cdk.annotations.Attribute;
import org.richfaces.cdk.annotations.JsfComponent;
import org.richfaces.cdk.annotations.JsfRenderer;
import org.richfaces.cdk.annotations.Tag;
import org.richfaces.cdk.annotations.TagType;
/**
* @author akolonitsky
* @since 2010-08-24
*/
@JsfComponent(tag = @Tag(type = TagType.Facelets, handler = "org.richfaces.view.facelets.html.TogglePanelTagHandler"), renderer = @JsfRenderer(type = "org.richfaces.TabPanelRenderer"))
public abstract class AbstractTabPanel extends AbstractTogglePanel {
public static final String COMPONENT_TYPE = "org.richfaces.TabPanel";
public static final String COMPONENT_FAMILY = "org.richfaces.TabPanel";
protected AbstractTabPanel() {
setRendererType("org.richfaces.TabPanelRenderer");
}
@Override
public String getFamily() {
return COMPONENT_FAMILY;
}
@Override
@Attribute(generate = false)
public String getActiveItem() {
String res = super.getActiveItem();
- if (res == null) {
+ if ((res == null)||(res.equals(""))) {
res = getFirstItem().getName();
} else {
AbstractTogglePanelTitledItem item = (AbstractTogglePanelTitledItem) super.getItemByIndex(super.getChildIndex(res));
- if (item.isDisabled()) {
+ if ((item == null)||(item.isDisabled())) {
res = getFirstItem().getName();
}
}
return res;
}
// ------------------------------------------------ Html Attributes
@Attribute
public abstract HeaderPosition getHeaderPosition();
@Attribute
public abstract HeaderAlignment getHeaderAlignment();
@Attribute
public abstract String getTabActiveHeaderClass();
@Attribute
public abstract String getTabDisabledHeaderClass();
@Attribute
public abstract String getTabInactiveHeaderClass();
@Attribute
public abstract String getTabContentClass();
@Attribute
public abstract String getTabHeaderClass();
@Attribute(hidden = true)
public abstract boolean isLimitRender();
@Attribute(hidden = true)
public abstract Object getData();
@Attribute(hidden = true)
public abstract String getStatus();
@Attribute(hidden = true)
public abstract Object getExecute();
@Attribute(hidden = true)
public abstract Object getRender();
public boolean isHeaderPositionedTop() {
return (null == this.getHeaderPosition()) || (this.getHeaderPosition().equals(HeaderPosition.top));
}
public boolean isHeaderAlignedLeft() {
return (null == this.getHeaderAlignment()) || (this.getHeaderAlignment().equals(HeaderAlignment.left));
}
}
| false | true | public String getActiveItem() {
String res = super.getActiveItem();
if (res == null) {
res = getFirstItem().getName();
} else {
AbstractTogglePanelTitledItem item = (AbstractTogglePanelTitledItem) super.getItemByIndex(super.getChildIndex(res));
if (item.isDisabled()) {
res = getFirstItem().getName();
}
}
return res;
}
| public String getActiveItem() {
String res = super.getActiveItem();
if ((res == null)||(res.equals(""))) {
res = getFirstItem().getName();
} else {
AbstractTogglePanelTitledItem item = (AbstractTogglePanelTitledItem) super.getItemByIndex(super.getChildIndex(res));
if ((item == null)||(item.isDisabled())) {
res = getFirstItem().getName();
}
}
return res;
}
|
diff --git a/test/dao/org/appfuse/dao/RoleDAOTest.java b/test/dao/org/appfuse/dao/RoleDAOTest.java
index 077a1b59..edaae1cd 100644
--- a/test/dao/org/appfuse/dao/RoleDAOTest.java
+++ b/test/dao/org/appfuse/dao/RoleDAOTest.java
@@ -1,52 +1,51 @@
package org.appfuse.dao;
import org.appfuse.Constants;
import org.appfuse.model.Role;
public class RoleDAOTest extends BaseDAOTestCase {
private Role role = null;
private RoleDAO dao = null;
protected void setUp() throws Exception {
super.setUp();
dao = (RoleDAO) ctx.getBean("roleDAO");
}
protected void tearDown() throws Exception {
super.tearDown();
dao = null;
}
public void testGetRoleInvalid() throws Exception {
role = dao.getRole("badrolename");
assertNull(role);
}
public void testGetRole() throws Exception {
role = dao.getRole(Constants.USER_ROLE);
assertNotNull(role);
}
public void testUpdateRole() throws Exception {
role = dao.getRole("tomcat");
log.info(role);
role.setDescription("test descr");
dao.saveRole(role);
assertEquals(role.getDescription(), "test descr");
}
public void testAddAndRemoveRole() throws Exception {
- role = new Role();
- role.setName("testrole");
+ role = new Role("testrole");
role.setDescription("new role descr");
dao.saveRole(role);
assertNotNull(role.getName());
dao.removeRole("testrole");
role = dao.getRole("testrole");
assertNull(role);
}
}
| true | true | public void testAddAndRemoveRole() throws Exception {
role = new Role();
role.setName("testrole");
role.setDescription("new role descr");
dao.saveRole(role);
assertNotNull(role.getName());
dao.removeRole("testrole");
role = dao.getRole("testrole");
assertNull(role);
}
| public void testAddAndRemoveRole() throws Exception {
role = new Role("testrole");
role.setDescription("new role descr");
dao.saveRole(role);
assertNotNull(role.getName());
dao.removeRole("testrole");
role = dao.getRole("testrole");
assertNull(role);
}
|
diff --git a/rmt/src/main/java/de/flower/rmt/ui/markup/html/form/renderer/EventRenderer.java b/rmt/src/main/java/de/flower/rmt/ui/markup/html/form/renderer/EventRenderer.java
index 6ce79ba7..bb008d1e 100644
--- a/rmt/src/main/java/de/flower/rmt/ui/markup/html/form/renderer/EventRenderer.java
+++ b/rmt/src/main/java/de/flower/rmt/ui/markup/html/form/renderer/EventRenderer.java
@@ -1,55 +1,57 @@
package de.flower.rmt.ui.markup.html.form.renderer;
import de.flower.rmt.model.db.entity.event.Event;
import de.flower.rmt.model.db.entity.event.Match;
import de.flower.rmt.model.db.type.EventType;
import de.flower.rmt.util.Dates;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.ResourceModel;
/**
* @author flowerrrr
*/
public class EventRenderer implements IChoiceRenderer<Event> {
private boolean dateLong;
public EventRenderer() {
this(false);
}
public EventRenderer(final boolean dateLong) {
this.dateLong = dateLong;
}
@Override
public Object getDisplayValue(final Event event) {
return getDateTeamTypeSummary(event, dateLong);
}
@Override
public String getIdValue(final Event object, final int index) {
if (object.getId() != null) {
return "" + object.getId();
} else {
return "index-" + index;
}
}
public static String getDateTeamTypeSummary(final Event event, boolean dateLong) {
String team = event.getTeam().getName();
String opponent = "";
String eventType = new ResourceModel(EventType.from(event).getResourceKey()).getObject();
if (EventType.from(event).isMatch()) {
Match match = (Match) event;
- opponent = " : " + match.getOpponent().getName();
+ if (match.getOpponent() != null) {
+ opponent = " : " + match.getOpponent().getName();
+ }
}
String date;
if (dateLong) {
date = Dates.formatDateLongTimeShortWithWeekday(event.getDateTimeAsDate());
} else {
date = Dates.formatDateTimeShortWithWeekday(event.getDateTimeAsDate());
}
return date + " - " + eventType + " - " + team + opponent + " - " + event.getSummary();
}
}
| true | true | public static String getDateTeamTypeSummary(final Event event, boolean dateLong) {
String team = event.getTeam().getName();
String opponent = "";
String eventType = new ResourceModel(EventType.from(event).getResourceKey()).getObject();
if (EventType.from(event).isMatch()) {
Match match = (Match) event;
opponent = " : " + match.getOpponent().getName();
}
String date;
if (dateLong) {
date = Dates.formatDateLongTimeShortWithWeekday(event.getDateTimeAsDate());
} else {
date = Dates.formatDateTimeShortWithWeekday(event.getDateTimeAsDate());
}
return date + " - " + eventType + " - " + team + opponent + " - " + event.getSummary();
}
| public static String getDateTeamTypeSummary(final Event event, boolean dateLong) {
String team = event.getTeam().getName();
String opponent = "";
String eventType = new ResourceModel(EventType.from(event).getResourceKey()).getObject();
if (EventType.from(event).isMatch()) {
Match match = (Match) event;
if (match.getOpponent() != null) {
opponent = " : " + match.getOpponent().getName();
}
}
String date;
if (dateLong) {
date = Dates.formatDateLongTimeShortWithWeekday(event.getDateTimeAsDate());
} else {
date = Dates.formatDateTimeShortWithWeekday(event.getDateTimeAsDate());
}
return date + " - " + eventType + " - " + team + opponent + " - " + event.getSummary();
}
|
diff --git a/main/src/cgeo/geocaching/network/HtmlImage.java b/main/src/cgeo/geocaching/network/HtmlImage.java
index fbcbaaf9b..37c748635 100644
--- a/main/src/cgeo/geocaching/network/HtmlImage.java
+++ b/main/src/cgeo/geocaching/network/HtmlImage.java
@@ -1,235 +1,235 @@
package cgeo.geocaching.network;
import cgeo.geocaching.R;
import cgeo.geocaching.StoredList;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.utils.Log;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.text.Html;
import android.view.Display;
import android.view.WindowManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
public class HtmlImage implements Html.ImageGetter {
private static final String[] BLOCKED = new String[] {
"gccounter.de",
"gccounter.com",
"cachercounter/?",
"gccounter/imgcount.php",
"flagcounter.com",
"compteur-blog.net",
"counter.digits.com",
"andyhoppe"
};
final private Context context;
final private String geocode;
/**
* on error: return large error image, if <code>true</code>, otherwise empty 1x1 image
*/
final private boolean returnErrorImage;
final private int listId;
final private boolean onlySave;
final private BitmapFactory.Options bfOptions;
final private int maxWidth;
final private int maxHeight;
public HtmlImage(final Context contextIn, final String geocode, final boolean returnErrorImage, final int listId, final boolean onlySave) {
this.context = contextIn;
this.geocode = geocode;
this.returnErrorImage = returnErrorImage;
this.listId = listId;
this.onlySave = onlySave;
bfOptions = new BitmapFactory.Options();
bfOptions.inTempStorage = new byte[16 * 1024];
final Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
this.maxWidth = display.getWidth() - 25;
this.maxHeight = display.getHeight() - 25;
}
@Override
public BitmapDrawable getDrawable(final String url) {
// Reject empty and counter images URL
if (StringUtils.isBlank(url) || isCounter(url)) {
return new BitmapDrawable(getTransparent1x1Image());
}
- Bitmap imagePre = onlySave ? null : loadImageFromStorage(url);
+ Bitmap imagePre = loadImageFromStorage(url);
// Download image and save it to the cache
- if (imagePre == null || onlySave) {
+ if (imagePre == null) {
final String absoluteURL = makeAbsoluteURL(url);
if (absoluteURL != null) {
try {
final File file = LocalStorage.getStorageFile(geocode, url, true, true);
final HttpResponse httpResponse = Network.request(absoluteURL, null, file);
if (httpResponse != null) {
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
LocalStorage.saveEntityToFile(httpResponse, file);
} else if (statusCode == 304) {
file.setLastModified(System.currentTimeMillis());
}
}
} catch (Exception e) {
Log.e("HtmlImage.getDrawable (downloading from web)", e);
}
}
}
if (onlySave) {
return null;
}
// now load the newly downloaded image
if (imagePre == null) {
imagePre = loadImageFromStorage(url);
}
// get image and return
if (imagePre == null) {
Log.d("HtmlImage.getDrawable: Failed to obtain image");
if (returnErrorImage) {
imagePre = BitmapFactory.decodeResource(context.getResources(), R.drawable.image_not_loaded);
} else {
imagePre = getTransparent1x1Image();
}
}
final int imgWidth = imagePre.getWidth();
final int imgHeight = imagePre.getHeight();
int width;
int height;
if (imgWidth > maxWidth || imgHeight > maxHeight) {
final double ratio = Math.min((double) maxHeight / (double) imgHeight, (double) maxWidth / (double) imgWidth);
width = (int) Math.ceil(imgWidth * ratio);
height = (int) Math.ceil(imgHeight * ratio);
try {
imagePre = Bitmap.createScaledBitmap(imagePre, width, height, true);
} catch (Exception e) {
Log.d("HtmlImage.getDrawable: Failed to scale image");
return null;
}
} else {
width = imgWidth;
height = imgHeight;
}
final BitmapDrawable image = new BitmapDrawable(imagePre);
image.setBounds(new Rect(0, 0, width, height));
return image;
}
private Bitmap getTransparent1x1Image() {
return BitmapFactory.decodeResource(context.getResources(), R.drawable.image_no_placement);
}
private Bitmap loadImageFromStorage(final String url) {
try {
final File file = LocalStorage.getStorageFile(geocode, url, true, false);
final Bitmap image = loadCachedImage(file);
if (image != null) {
return image;
}
final File fileSec = LocalStorage.getStorageSecFile(geocode, url, true);
return loadCachedImage(fileSec);
} catch (Exception e) {
Log.w("HtmlImage.getDrawable (reading cache): " + e.toString());
}
return null;
}
private final String makeAbsoluteURL(final String url) {
try {
// Check if uri is absolute or not, if not attach the connector hostname
// FIXME: that should also include the scheme
if (Uri.parse(url).isAbsolute()) {
return url;
} else {
final String host = ConnectorFactory.getConnector(geocode).getHost();
if (StringUtils.isNotEmpty(host)) {
StringBuilder builder = new StringBuilder("http://");
builder.append(host);
if (!StringUtils.startsWith(url, "/")) {
builder.append('/');
}
builder.append(url);
return builder.toString();
}
}
} catch (Exception e) {
Log.e("HtmlImage.makeAbsoluteURL (parse URL)", e);
}
return null;
}
private Bitmap loadCachedImage(final File file) {
if (file.exists()) {
if (listId >= StoredList.STANDARD_LIST_ID || file.lastModified() > (new Date().getTime() - (24 * 60 * 60 * 1000))) {
setSampleSize(file);
return BitmapFactory.decodeFile(file.getPath(), bfOptions);
}
}
return null;
}
private void setSampleSize(final File file) {
//Decode image size only
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
BitmapFactory.decodeStream(fis, null, options);
} catch (FileNotFoundException e) {
Log.e("HtmlImage.setSampleSize", e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// ignore
}
}
}
int scale = 1;
if (options.outHeight > maxHeight || options.outWidth > maxWidth) {
scale = Math.max(options.outHeight / maxHeight, options.outWidth / maxWidth);
}
bfOptions.inSampleSize = scale;
}
private static boolean isCounter(final String url) {
for (String entry : BLOCKED) {
if (StringUtils.containsIgnoreCase(url, entry)) {
return true;
}
}
return false;
}
}
| false | true | public BitmapDrawable getDrawable(final String url) {
// Reject empty and counter images URL
if (StringUtils.isBlank(url) || isCounter(url)) {
return new BitmapDrawable(getTransparent1x1Image());
}
Bitmap imagePre = onlySave ? null : loadImageFromStorage(url);
// Download image and save it to the cache
if (imagePre == null || onlySave) {
final String absoluteURL = makeAbsoluteURL(url);
if (absoluteURL != null) {
try {
final File file = LocalStorage.getStorageFile(geocode, url, true, true);
final HttpResponse httpResponse = Network.request(absoluteURL, null, file);
if (httpResponse != null) {
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
LocalStorage.saveEntityToFile(httpResponse, file);
} else if (statusCode == 304) {
file.setLastModified(System.currentTimeMillis());
}
}
} catch (Exception e) {
Log.e("HtmlImage.getDrawable (downloading from web)", e);
}
}
}
if (onlySave) {
return null;
}
// now load the newly downloaded image
if (imagePre == null) {
imagePre = loadImageFromStorage(url);
}
// get image and return
if (imagePre == null) {
Log.d("HtmlImage.getDrawable: Failed to obtain image");
if (returnErrorImage) {
imagePre = BitmapFactory.decodeResource(context.getResources(), R.drawable.image_not_loaded);
} else {
imagePre = getTransparent1x1Image();
}
}
final int imgWidth = imagePre.getWidth();
final int imgHeight = imagePre.getHeight();
int width;
int height;
if (imgWidth > maxWidth || imgHeight > maxHeight) {
final double ratio = Math.min((double) maxHeight / (double) imgHeight, (double) maxWidth / (double) imgWidth);
width = (int) Math.ceil(imgWidth * ratio);
height = (int) Math.ceil(imgHeight * ratio);
try {
imagePre = Bitmap.createScaledBitmap(imagePre, width, height, true);
} catch (Exception e) {
Log.d("HtmlImage.getDrawable: Failed to scale image");
return null;
}
} else {
width = imgWidth;
height = imgHeight;
}
final BitmapDrawable image = new BitmapDrawable(imagePre);
image.setBounds(new Rect(0, 0, width, height));
return image;
}
| public BitmapDrawable getDrawable(final String url) {
// Reject empty and counter images URL
if (StringUtils.isBlank(url) || isCounter(url)) {
return new BitmapDrawable(getTransparent1x1Image());
}
Bitmap imagePre = loadImageFromStorage(url);
// Download image and save it to the cache
if (imagePre == null) {
final String absoluteURL = makeAbsoluteURL(url);
if (absoluteURL != null) {
try {
final File file = LocalStorage.getStorageFile(geocode, url, true, true);
final HttpResponse httpResponse = Network.request(absoluteURL, null, file);
if (httpResponse != null) {
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
LocalStorage.saveEntityToFile(httpResponse, file);
} else if (statusCode == 304) {
file.setLastModified(System.currentTimeMillis());
}
}
} catch (Exception e) {
Log.e("HtmlImage.getDrawable (downloading from web)", e);
}
}
}
if (onlySave) {
return null;
}
// now load the newly downloaded image
if (imagePre == null) {
imagePre = loadImageFromStorage(url);
}
// get image and return
if (imagePre == null) {
Log.d("HtmlImage.getDrawable: Failed to obtain image");
if (returnErrorImage) {
imagePre = BitmapFactory.decodeResource(context.getResources(), R.drawable.image_not_loaded);
} else {
imagePre = getTransparent1x1Image();
}
}
final int imgWidth = imagePre.getWidth();
final int imgHeight = imagePre.getHeight();
int width;
int height;
if (imgWidth > maxWidth || imgHeight > maxHeight) {
final double ratio = Math.min((double) maxHeight / (double) imgHeight, (double) maxWidth / (double) imgWidth);
width = (int) Math.ceil(imgWidth * ratio);
height = (int) Math.ceil(imgHeight * ratio);
try {
imagePre = Bitmap.createScaledBitmap(imagePre, width, height, true);
} catch (Exception e) {
Log.d("HtmlImage.getDrawable: Failed to scale image");
return null;
}
} else {
width = imgWidth;
height = imgHeight;
}
final BitmapDrawable image = new BitmapDrawable(imagePre);
image.setBounds(new Rect(0, 0, width, height));
return image;
}
|
diff --git a/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/CalculatedQuestionExtractListener.java b/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/CalculatedQuestionExtractListener.java
index 1f2a70ed0..4de03a9fe 100644
--- a/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/CalculatedQuestionExtractListener.java
+++ b/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/CalculatedQuestionExtractListener.java
@@ -1,546 +1,547 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2004, 2005, 2006, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.assessment.ui.listener.author;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import org.apache.commons.lang.StringUtils;
import org.sakaiproject.tool.assessment.services.GradingService;
import org.sakaiproject.tool.assessment.ui.bean.author.CalculatedQuestionCalculationBean;
import org.sakaiproject.tool.assessment.ui.bean.author.CalculatedQuestionFormulaBean;
import org.sakaiproject.tool.assessment.ui.bean.author.CalculatedQuestionVariableBean;
import org.sakaiproject.tool.assessment.ui.bean.author.ItemAuthorBean;
import org.sakaiproject.tool.assessment.ui.bean.author.ItemBean;
import org.sakaiproject.tool.assessment.ui.bean.author.CalculatedQuestionBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
import org.sakaiproject.tool.assessment.util.SamigoExpressionError;
public class CalculatedQuestionExtractListener implements ActionListener{
private static final String ERROR_MESSAGE_BUNDLE = "org.sakaiproject.tool.assessment.bundle.AuthorMessages";
/**
* This listener will read in the instructions, parse any variables and
* formula names it finds, and then check to see if there are any errors
* in the configuration for the question.
*
* <p>Errors include <ul><li>no variables or formulas named in the instructions</li>
* <li>variables and formulas sharing a name</li>
* <li>variables with invalid ranges of values</li>
* <li>formulas that are syntactically wrong</li></ul>
* Any errors are written to the context messager
* <p>The validate formula is also called directly from the ItemAddListner, before
* saving a calculated question, to ensure any last minute changes are caught.
*/
public void processAction(ActionEvent arg0) throws AbortProcessingException {
ItemAuthorBean itemauthorbean = (ItemAuthorBean) ContextUtil.lookupBean("itemauthor");
ItemBean item = itemauthorbean.getCurrentItem();
List<String> errors = this.validate(item);
if (errors.size() > 0) {
item.setOutcome("calculatedQuestion");
item.setPoolOutcome("calculatedQuestion");
FacesContext context=FacesContext.getCurrentInstance();
for (String error : errors) {
context.addMessage(null, new FacesMessage(error));
}
context.renderResponse();
}
}
/**
* validate() returns a list of error strings to display to the context.
* <p>Errors include <ul><li>no variables or formulas named in the instructions</li>
* <li>variables and formulas sharing a name</li>
* <li>variables with invalid ranges of values</li>
* <li>formulas that are syntactically wrong</li></ul>
* Any errors are written to the context messager
* <p>The validate formula is also called directly from the ItemAddListner, before
* saving a calculated question, to ensure any last minute changes are caught.
* @param item - an ItemBean, which contains all of the needed information
* about the CalculatedQuestion
* @returns a List<String> of error messages to be displayed in the context messager.
*/
public List<String> validate(ItemBean item) {
List<String> errors = new ArrayList<String>();
// prepare any already existing variables and formula for new extracts
this.initializeVariables(item);
this.initializeFormulas(item);
GradingService service = new GradingService();
String instructions = item.getInstruction();
List<String> formulaNames = service.extractFormulas(instructions);
List<String> variableNames = service.extractVariables(instructions);
errors.addAll(validateExtractedNames(variableNames, formulaNames));
// add new variables and formulas
// verify that at least one variable and formula are defined
if (errors.size() == 0) {
errors.addAll(createFormulasFromInstructions(item, formulaNames));
errors.addAll(createVariablesFromInstructions(item, variableNames));
errors.addAll(createCalculationsFromInstructions(item.getCalculatedQuestion(), item.getItemText(), service));
}
// validate variable min and max and formula tolerance
if (errors.size() == 0) {
errors.addAll(validateMinMax(item));
errors.addAll(validateTolerance(item));
}
// don't bother looking at formulas if any data validations have failed
if (errors.size() == 0) {
errors.addAll(validateFormulas(item, service));
errors.addAll(validateCalculations(item.getCalculatedQuestion(), service));
} else {
errors.add(getErrorMessage("formulas_not_validated"));
}
return errors;
}
/**
* initializeVariables() prepares any previously defined variables for updates
* that occur when extracting new variables from instructions
* @param item
*/
private void initializeVariables(ItemBean item) {
Map<String, CalculatedQuestionVariableBean> variables = item.getCalculatedQuestion().getVariables();
for (CalculatedQuestionVariableBean bean : variables.values()) {
bean.setActive(false);
bean.setValidMax(true);
bean.setValidMin(true);
}
}
/**
* initializeFormulas() prepares any previously defined formulas for updates
* that occur when extracting new formulas from instructions
* @param item
*/
private void initializeFormulas(ItemBean item) {
Map<String, CalculatedQuestionFormulaBean> formulas = item.getCalculatedQuestion().getFormulas();
for (CalculatedQuestionFormulaBean bean : formulas.values()) {
bean.setActive(false);
bean.setValidFormula(true);
bean.setValidTolerance(true);
}
}
/**
* createFormulasFromInstructions adds any formulas that exist in the list of formulaNames
* but do not already exist in the question
* @param item
* @param formulaNames
*/
private List<String> createFormulasFromInstructions(ItemBean item, List<String> formulaNames) {
List<String> errors = new ArrayList<String>();
Map<String, CalculatedQuestionFormulaBean> formulas = item.getCalculatedQuestion().getFormulas();
Map<String, CalculatedQuestionVariableBean> variables = item.getCalculatedQuestion().getVariables();
// add any missing formulas
for (String formulaName : formulaNames) {
if (!formulas.containsKey(formulaName)) {
CalculatedQuestionFormulaBean bean = new CalculatedQuestionFormulaBean();
bean.setName(formulaName);
bean.setSequence(Long.valueOf(variables.size() + formulas.size() + 1));
item.getCalculatedQuestion().addFormula(bean);
} else {
CalculatedQuestionFormulaBean bean = formulas.get(formulaName);
bean.setActive(true);
}
}
if (item.getCalculatedQuestion().getActiveFormulas().size() == 0) {
errors.add(getErrorMessage("no_formulas_defined"));
}
return errors;
}
/**
* createVariablesFromInstructions adds any variables that exist in the list
* of variableNames but do not already exist in the question
* @param item
* @param variableNames
*/
private List<String> createVariablesFromInstructions(ItemBean item, List<String> variableNames) {
List<String> errors = new ArrayList<String>();
Map<String, CalculatedQuestionFormulaBean> formulas = item.getCalculatedQuestion().getFormulas();
Map<String, CalculatedQuestionVariableBean> variables = item.getCalculatedQuestion().getVariables();
// add any missing variables
for (String variableName : variableNames) {
if (!variables.containsKey(variableName)) {
CalculatedQuestionVariableBean bean = new CalculatedQuestionVariableBean();
bean.setName(variableName);
bean.setSequence(Long.valueOf(variables.size() + formulas.size() + 1));
item.getCalculatedQuestion().addVariable(bean);
} else {
CalculatedQuestionVariableBean bean = variables.get(variableName);
bean.setActive(true);
}
}
if (item.getCalculatedQuestion().getActiveVariables().size() == 0) {
errors.add(getErrorMessage("no_variables_defined"));
}
return errors;
}
/**
* Finds the calculations in the instructions and places them in the CalculatedQuestionBean
*
* @param calculatedQuestionBean
* @param instructions
* @param service
* @return list of error messages (empty if there are none)
*/
static List<String> createCalculationsFromInstructions(CalculatedQuestionBean calculatedQuestionBean, String instructions, GradingService service) {
List<String> errors = new ArrayList<String>();
List<String> calculations = service.extractCalculations(instructions);
if (!calculations.isEmpty()) {
for (String calculation : calculations) {
CalculatedQuestionCalculationBean calc = new CalculatedQuestionCalculationBean(calculation);
calculatedQuestionBean.addCalculation(calc);
}
}
return errors;
}
/**
* validateExtractedNames looks through all of the variable and formula names defined
* in the instructions and determines if the names are valid, and if the formula and
* variable names overlap.
* @param item
* @return a list of validation errors to display
*/
private List<String> validateExtractedNames(List<String> variableNames, List<String> formulaNames) {
List<String> errors = new ArrayList<String>();
// formula validations
for (String formula : formulaNames) {
if (formula == null || formula.length() == 0) {
errors.add(getErrorMessage("formula_name_empty"));
} else {
if (!formula.matches("[a-zA-Z]\\w*")) {
errors.add(getErrorMessage("formula_name_invalid"));
}
}
}
// variable validations
for (String variable : variableNames) {
if (variable == null || variable.length() == 0) {
errors.add(getErrorMessage("variable_name_empty"));
} else {
if (!variable.matches("[a-zA-Z]\\w*")) {
errors.add(getErrorMessage("variable_name_invalid"));
}
}
}
// throw an error if variables and formulas share any names
// don't continue processing if there are problems with the extract
if (!Collections.disjoint(formulaNames, variableNames)) {
errors.add(getErrorMessage("unique_names"));
}
return errors;
}
/**
* validateTolerance() verifies that formula tolerances are positive numbers
* @param item
* @return a list of validation errors to display
*/
private List<String> validateTolerance(ItemBean item) {
List<String> errors = new ArrayList<String>();
CalculatedQuestionBean question = item.getCalculatedQuestion();
// formula tolerances must be numbers or percentages
for (CalculatedQuestionFormulaBean formula : question.getActiveFormulas().values()) {
String toleranceStr = formula.getTolerance().trim();
// cannot be blank
if (toleranceStr == null || toleranceStr.length() == 0) {
errors.add(getErrorMessage("empty_field"));
formula.setValidTolerance(false);
}
// no non-number characters (although percentage is allowed
// allow a negative here, we'll catch negative tolerances in another place
if (formula.getValidTolerance()) {
if (!toleranceStr.matches("[0-9\\.\\-\\%]+")) {
errors.add(getErrorMessage("invalid_tolerance"));
formula.setValidTolerance(false);
}
}
// if not a percentage, try to convert to a double to validate
// format
if (formula.getValidTolerance()) {
if (!toleranceStr.matches("[0-9]+\\.?[0-9]*\\%")) {
try {
double tolerance = Double.parseDouble(toleranceStr);
// this strips out any leading spaces or zeroes
formula.setTolerance(Double.toString(tolerance));
if (tolerance < 0) {
errors.add(getErrorMessage("tolerance_negative"));
formula.setValidTolerance(false);
}
} catch (NumberFormatException n) {
errors.add(getErrorMessage("invalid_tolerance"));
formula.setValidTolerance(false);
}
}
}
}
return errors;
}
/**
* validateMinMax() looks at each variable and ensures that the
* min and max are valid numbers. It also verifies that the min is less
* than the max.
* @param item
* @return a list of validation errors to display
*/
private List<String> validateMinMax(ItemBean item) {
List<String> errors = new ArrayList<String>();
CalculatedQuestionBean question = item.getCalculatedQuestion();
for (CalculatedQuestionVariableBean variable : question.getActiveVariables().values()) {
// min
String minStr = variable.getMin().trim();
double min = 0d;
if (minStr == null || minStr.length() == 0) {
errors.add(getErrorMessage("empty_field"));
variable.setValidMin(false);
}
if (variable.getValidMin()) {
try {
min = Double.parseDouble(minStr);
// this strips out any leading spaces or zeroes
variable.setMin(Double.toString(min));
} catch (NumberFormatException n) {
errors.add(getErrorMessage("invalid_min"));
variable.setValidMin(false);
}
}
// max
String maxStr = variable.getMax().trim();
double max = 0d;
if (maxStr == null || maxStr.length() == 0) {
errors.add(getErrorMessage("empty_field"));
variable.setValidMax(false);
}
if (variable.getValidMax()) {
try {
max = Double.parseDouble(maxStr);
// this strips out any leading spaces or zeroes
variable.setMax(Double.toString(max));
} catch (NumberFormatException n) {
errors.add(getErrorMessage("invalid_max"));
variable.setValidMax(false);
}
}
// max < min
if (variable.getValidMax() && variable.getValidMin()) {
if (max < min) {
errors.add(getErrorMessage("max_less_than_min"));
variable.setValidMin(false);
variable.setValidMax(false);
}
}
}
return errors;
}
/**
* Takes a populated calculatedQuestionBean and validates the calculations and populates the
* calculation values and sample data (and status)
*
* @param calculatedQuestionBean
* @param service
* @return a list of validation errors to display
*/
static List<String> validateCalculations(CalculatedQuestionBean calculatedQuestionBean, GradingService service) {
List<String> errors = new ArrayList<String>();
if (service == null) {
service = new GradingService();
}
// list of variables to substitute
Map<String, String> variableRangeMap = new HashMap<String, String>();
for (CalculatedQuestionVariableBean variable : calculatedQuestionBean.getActiveVariables().values()) {
String match = variable.getMin() + "|" + variable.getMax() + "," + variable.getDecimalPlaces();
variableRangeMap.put(variable.getName(), match);
}
int attemptCnt = 0;
while (attemptCnt < 100 && errors.size() == 0) {
// create random values for the variables to substitute into the formulas (using dummy values)
Map<String, String> answersMap = service.determineRandomValuesForRanges(variableRangeMap, 1, 1, "dummy", attemptCnt);
// evaluate each calculation
for (CalculatedQuestionCalculationBean cqcb : calculatedQuestionBean.getCalculationsList()) {
String formulaStr = GradingService.cleanFormula(cqcb.getText());
if (formulaStr == null || formulaStr.length() == 0) {
String msg = getErrorMessage("empty_field");
cqcb.setStatus(msg);
errors.add(msg);
} else {
String substitutedFormulaStr = service.replaceMappedVariablesWithNumbers(formulaStr, answersMap);
cqcb.setFormula(substitutedFormulaStr);
// look for wrapped variables that haven't been replaced (undefined variable)
List<String> unwrappedVariables = service.extractVariables(substitutedFormulaStr);
if (unwrappedVariables.size() > 0) {
String msg = getErrorMessage("samigo_formula_error_9");
cqcb.setStatus(msg);
errors.add(msg);
} else {
try {
if (service.isNegativeSqrt(substitutedFormulaStr)) {
String msg = getErrorMessage("samigo_formula_error_8");
cqcb.setStatus(msg);
errors.add(msg);
} else {
String formulaValue = service.processFormulaIntoValue(substitutedFormulaStr, 5); // throws exceptions if formula is invalid
cqcb.setValue(formulaValue);
cqcb.setText(formulaStr);
}
} catch (SamigoExpressionError e) {
String msg = getErrorMessage("samigo_formula_error_" + Integer.valueOf(e.get_id()));
cqcb.setStatus(msg);
errors.add(msg);
} catch (Exception e) {
String msg = getErrorMessage("samigo_formula_error_500");
cqcb.setStatus(msg);
errors.add(msg);
}
}
}
}
attemptCnt++;
}
return errors;
}
/**
* validateFormulas() iterates through all of the formula definitions. It
* creates valid dummy values for all of the defined variables, substitutes those
* variables into the formula, then executes the formula to determine if a value
* is returned. This is a syntax checker; a syntactically valid formula can
* definitely return the wrong value if the author enters a wrong formula.
* @param item
* @return a map of errors. The Key is an integer value, set by the SamigoExpressionParser, the
* value is the string result of that error message.
*/
private List<String> validateFormulas(ItemBean item, GradingService service) {
List<String> errors = new ArrayList<String>();
if (service == null) {
service = new GradingService();
}
// list of variables to substitute
Map<String, String> variableRangeMap = new HashMap<String, String>();
for (CalculatedQuestionVariableBean variable : item.getCalculatedQuestion().getActiveVariables().values()) {
String match = variable.getMin() + "|" + variable.getMax() + "," + variable.getDecimalPlaces();
variableRangeMap.put(variable.getName(), match);
}
// dummy variables needed to generate random values within ranges for the variables
long dummyItemId = 1;
long dummyGradingId = 1;
String dummyAgentId = "dummy";
int attemptCnt = 0;
while (attemptCnt < 100 && errors.size() == 0) {
// create random values for the variables to substitute into the formulas
Map<String, String> answersMap = service.determineRandomValuesForRanges(variableRangeMap, dummyItemId,
dummyGradingId, dummyAgentId, attemptCnt);
// evaluate each formula
for (CalculatedQuestionFormulaBean formulaBean : item.getCalculatedQuestion().getActiveFormulas().values()) {
String formulaStr = formulaBean.getText();
if (formulaStr == null || formulaStr.length() == 0) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("empty_field"));
} else {
String substitutedFormulaStr = service.replaceMappedVariablesWithNumbers(formulaStr, answersMap);
// look for wrapped variables that haven't been replaced (undefined variable)
List<String> unwrappedVariables = service.extractVariables(substitutedFormulaStr);
if (unwrappedVariables.size() > 0) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("samigo_formula_error_9"));
} else {
try {
if (service.isNegativeSqrt(substitutedFormulaStr)) {
formulaBean.setValidFormula(false);
- errors.add(getErrorMessage("samigo_formula_error_8"));
+ errors.add(getErrorMessage("samigo_formula_error_8") + " :"+substitutedFormulaStr);
} else {
service.processFormulaIntoValue(substitutedFormulaStr, 5); // throws exceptions on failure
}
} catch (SamigoExpressionError e) {
formulaBean.setValidFormula(false);
- errors.add(getErrorMessage("samigo_formula_error_" + Integer.valueOf(e.get_id())));
+ String msg = getErrorMessage("samigo_formula_error_" + Integer.valueOf(e.get_id()));
+ errors.add(msg + " :"+substitutedFormulaStr);
} catch (Exception e) {
formulaBean.setValidFormula(false);
- errors.add(getErrorMessage("samigo_formula_error_500"));
+ errors.add(getErrorMessage("samigo_formula_error_500") + " :"+substitutedFormulaStr);
}
}
}
}
attemptCnt++;
}
return errors;
}
/**
* getErrorMessage() retrieves the localized error message associated with
* the errorCode
* @param errorCode
* @return
*/
private static String getErrorMessage(String errorCode) {
String err = ContextUtil.getLocalizedString(ERROR_MESSAGE_BUNDLE,
errorCode);
return err;
}
}
| false | true | private List<String> validateFormulas(ItemBean item, GradingService service) {
List<String> errors = new ArrayList<String>();
if (service == null) {
service = new GradingService();
}
// list of variables to substitute
Map<String, String> variableRangeMap = new HashMap<String, String>();
for (CalculatedQuestionVariableBean variable : item.getCalculatedQuestion().getActiveVariables().values()) {
String match = variable.getMin() + "|" + variable.getMax() + "," + variable.getDecimalPlaces();
variableRangeMap.put(variable.getName(), match);
}
// dummy variables needed to generate random values within ranges for the variables
long dummyItemId = 1;
long dummyGradingId = 1;
String dummyAgentId = "dummy";
int attemptCnt = 0;
while (attemptCnt < 100 && errors.size() == 0) {
// create random values for the variables to substitute into the formulas
Map<String, String> answersMap = service.determineRandomValuesForRanges(variableRangeMap, dummyItemId,
dummyGradingId, dummyAgentId, attemptCnt);
// evaluate each formula
for (CalculatedQuestionFormulaBean formulaBean : item.getCalculatedQuestion().getActiveFormulas().values()) {
String formulaStr = formulaBean.getText();
if (formulaStr == null || formulaStr.length() == 0) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("empty_field"));
} else {
String substitutedFormulaStr = service.replaceMappedVariablesWithNumbers(formulaStr, answersMap);
// look for wrapped variables that haven't been replaced (undefined variable)
List<String> unwrappedVariables = service.extractVariables(substitutedFormulaStr);
if (unwrappedVariables.size() > 0) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("samigo_formula_error_9"));
} else {
try {
if (service.isNegativeSqrt(substitutedFormulaStr)) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("samigo_formula_error_8"));
} else {
service.processFormulaIntoValue(substitutedFormulaStr, 5); // throws exceptions on failure
}
} catch (SamigoExpressionError e) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("samigo_formula_error_" + Integer.valueOf(e.get_id())));
} catch (Exception e) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("samigo_formula_error_500"));
}
}
}
}
attemptCnt++;
}
return errors;
}
| private List<String> validateFormulas(ItemBean item, GradingService service) {
List<String> errors = new ArrayList<String>();
if (service == null) {
service = new GradingService();
}
// list of variables to substitute
Map<String, String> variableRangeMap = new HashMap<String, String>();
for (CalculatedQuestionVariableBean variable : item.getCalculatedQuestion().getActiveVariables().values()) {
String match = variable.getMin() + "|" + variable.getMax() + "," + variable.getDecimalPlaces();
variableRangeMap.put(variable.getName(), match);
}
// dummy variables needed to generate random values within ranges for the variables
long dummyItemId = 1;
long dummyGradingId = 1;
String dummyAgentId = "dummy";
int attemptCnt = 0;
while (attemptCnt < 100 && errors.size() == 0) {
// create random values for the variables to substitute into the formulas
Map<String, String> answersMap = service.determineRandomValuesForRanges(variableRangeMap, dummyItemId,
dummyGradingId, dummyAgentId, attemptCnt);
// evaluate each formula
for (CalculatedQuestionFormulaBean formulaBean : item.getCalculatedQuestion().getActiveFormulas().values()) {
String formulaStr = formulaBean.getText();
if (formulaStr == null || formulaStr.length() == 0) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("empty_field"));
} else {
String substitutedFormulaStr = service.replaceMappedVariablesWithNumbers(formulaStr, answersMap);
// look for wrapped variables that haven't been replaced (undefined variable)
List<String> unwrappedVariables = service.extractVariables(substitutedFormulaStr);
if (unwrappedVariables.size() > 0) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("samigo_formula_error_9"));
} else {
try {
if (service.isNegativeSqrt(substitutedFormulaStr)) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("samigo_formula_error_8") + " :"+substitutedFormulaStr);
} else {
service.processFormulaIntoValue(substitutedFormulaStr, 5); // throws exceptions on failure
}
} catch (SamigoExpressionError e) {
formulaBean.setValidFormula(false);
String msg = getErrorMessage("samigo_formula_error_" + Integer.valueOf(e.get_id()));
errors.add(msg + " :"+substitutedFormulaStr);
} catch (Exception e) {
formulaBean.setValidFormula(false);
errors.add(getErrorMessage("samigo_formula_error_500") + " :"+substitutedFormulaStr);
}
}
}
}
attemptCnt++;
}
return errors;
}
|
diff --git a/kraken-generic/src/main/java/org/wikimedia/analytics/kraken/pageview/ProjectInfo.java b/kraken-generic/src/main/java/org/wikimedia/analytics/kraken/pageview/ProjectInfo.java
index 04b5aed..1a3d8b4 100644
--- a/kraken-generic/src/main/java/org/wikimedia/analytics/kraken/pageview/ProjectInfo.java
+++ b/kraken-generic/src/main/java/org/wikimedia/analytics/kraken/pageview/ProjectInfo.java
@@ -1,364 +1,369 @@
package org.wikimedia.analytics.kraken.pageview;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import java.nio.charset.Charset;
import java.util.*;
/**
* Processes a hostname to extract WMF Project info.
*/
public class ProjectInfo {
private static Map<String, String> SITE_VERSIONS = new HashMap<String, String>();
private static Set<String> LANGUAGES = new HashSet<String>();
static {
SITE_VERSIONS.put("zero", "Z");
SITE_VERSIONS.put("m", "M");
SITE_VERSIONS.put("mobile", "M");
// List<String> langs = Resources.readLines(Resources.getResource("languages.txt"), Charset.defaultCharset());
LANGUAGES.add("en");
LANGUAGES.add("de");
LANGUAGES.add("fr");
LANGUAGES.add("nl");
LANGUAGES.add("it");
LANGUAGES.add("es");
LANGUAGES.add("pl");
LANGUAGES.add("ru");
LANGUAGES.add("ja");
LANGUAGES.add("pt");
LANGUAGES.add("zh");
LANGUAGES.add("sv");
LANGUAGES.add("vi");
LANGUAGES.add("uk");
LANGUAGES.add("ca");
LANGUAGES.add("no");
LANGUAGES.add("fi");
LANGUAGES.add("cs");
LANGUAGES.add("fa");
LANGUAGES.add("hu");
LANGUAGES.add("ro");
LANGUAGES.add("ko");
LANGUAGES.add("ar");
LANGUAGES.add("tr");
LANGUAGES.add("id");
LANGUAGES.add("sk");
LANGUAGES.add("eo");
LANGUAGES.add("da");
LANGUAGES.add("sr");
LANGUAGES.add("kk");
LANGUAGES.add("lt");
LANGUAGES.add("eu");
LANGUAGES.add("ms");
LANGUAGES.add("he");
LANGUAGES.add("bg");
LANGUAGES.add("sl");
LANGUAGES.add("vo");
LANGUAGES.add("hr");
LANGUAGES.add("war");
LANGUAGES.add("hi");
LANGUAGES.add("et");
LANGUAGES.add("gl");
LANGUAGES.add("az");
LANGUAGES.add("nn");
LANGUAGES.add("simple");
LANGUAGES.add("la");
LANGUAGES.add("el");
LANGUAGES.add("th");
LANGUAGES.add("sh");
LANGUAGES.add("oc");
LANGUAGES.add("new");
LANGUAGES.add("mk");
LANGUAGES.add("roa-rup");
LANGUAGES.add("ka");
LANGUAGES.add("tl");
LANGUAGES.add("pms");
LANGUAGES.add("ht");
LANGUAGES.add("be");
LANGUAGES.add("te");
LANGUAGES.add("ta");
LANGUAGES.add("be-x-old");
LANGUAGES.add("uz");
LANGUAGES.add("lv");
LANGUAGES.add("br");
LANGUAGES.add("ceb");
LANGUAGES.add("sq");
LANGUAGES.add("jv");
LANGUAGES.add("mg");
LANGUAGES.add("mr");
LANGUAGES.add("cy");
LANGUAGES.add("lb");
LANGUAGES.add("is");
LANGUAGES.add("bs");
LANGUAGES.add("hy");
LANGUAGES.add("my");
LANGUAGES.add("yo");
LANGUAGES.add("an");
LANGUAGES.add("lmo");
LANGUAGES.add("ml");
LANGUAGES.add("pnb");
LANGUAGES.add("fy");
LANGUAGES.add("bpy");
LANGUAGES.add("af");
LANGUAGES.add("bn");
LANGUAGES.add("sw");
LANGUAGES.add("io");
LANGUAGES.add("ne");
LANGUAGES.add("gu");
LANGUAGES.add("zh-yue");
LANGUAGES.add("nds");
LANGUAGES.add("ur");
LANGUAGES.add("ba");
LANGUAGES.add("scn");
LANGUAGES.add("ku");
LANGUAGES.add("ast");
LANGUAGES.add("qu");
LANGUAGES.add("su");
LANGUAGES.add("diq");
LANGUAGES.add("tt");
LANGUAGES.add("ga");
LANGUAGES.add("ky");
LANGUAGES.add("cv");
LANGUAGES.add("ia");
LANGUAGES.add("nap");
LANGUAGES.add("bat-smg");
LANGUAGES.add("map-bms");
LANGUAGES.add("als");
LANGUAGES.add("wa");
LANGUAGES.add("kn");
LANGUAGES.add("am");
LANGUAGES.add("gd");
LANGUAGES.add("ckb");
LANGUAGES.add("sco");
LANGUAGES.add("bug");
LANGUAGES.add("tg");
LANGUAGES.add("mzn");
LANGUAGES.add("zh-min-nan");
LANGUAGES.add("yi");
LANGUAGES.add("vec");
LANGUAGES.add("arz");
LANGUAGES.add("hif");
LANGUAGES.add("roa-tara");
LANGUAGES.add("nah");
LANGUAGES.add("os");
LANGUAGES.add("sah");
LANGUAGES.add("mn");
LANGUAGES.add("sa");
LANGUAGES.add("pam");
LANGUAGES.add("hsb");
LANGUAGES.add("li");
LANGUAGES.add("mi");
LANGUAGES.add("si");
LANGUAGES.add("se");
LANGUAGES.add("co");
LANGUAGES.add("gan");
LANGUAGES.add("glk");
LANGUAGES.add("bar");
LANGUAGES.add("fo");
LANGUAGES.add("ilo");
LANGUAGES.add("bo");
LANGUAGES.add("bcl");
LANGUAGES.add("mrj");
LANGUAGES.add("fiu-vro");
LANGUAGES.add("nds-nl");
LANGUAGES.add("ps");
LANGUAGES.add("tk");
LANGUAGES.add("vls");
LANGUAGES.add("gv");
LANGUAGES.add("rue");
LANGUAGES.add("pa");
LANGUAGES.add("dv");
LANGUAGES.add("xmf");
LANGUAGES.add("pag");
LANGUAGES.add("nrm");
LANGUAGES.add("kv");
LANGUAGES.add("zea");
LANGUAGES.add("koi");
LANGUAGES.add("km");
LANGUAGES.add("rm");
LANGUAGES.add("csb");
LANGUAGES.add("lad");
LANGUAGES.add("udm");
LANGUAGES.add("or");
LANGUAGES.add("mhr");
LANGUAGES.add("mt");
LANGUAGES.add("fur");
LANGUAGES.add("lij");
LANGUAGES.add("wuu");
LANGUAGES.add("ug");
LANGUAGES.add("pi");
LANGUAGES.add("sc");
LANGUAGES.add("zh-classical");
LANGUAGES.add("frr");
LANGUAGES.add("bh");
LANGUAGES.add("nov");
LANGUAGES.add("ksh");
LANGUAGES.add("ang");
LANGUAGES.add("so");
LANGUAGES.add("stq");
LANGUAGES.add("kw");
LANGUAGES.add("nv");
LANGUAGES.add("hak");
LANGUAGES.add("ay");
LANGUAGES.add("frp");
LANGUAGES.add("vep");
LANGUAGES.add("ext");
LANGUAGES.add("pcd");
LANGUAGES.add("szl");
LANGUAGES.add("gag");
LANGUAGES.add("gn");
LANGUAGES.add("ie");
LANGUAGES.add("ln");
LANGUAGES.add("haw");
LANGUAGES.add("xal");
LANGUAGES.add("eml");
LANGUAGES.add("pfl");
LANGUAGES.add("pdc");
LANGUAGES.add("rw");
LANGUAGES.add("krc");
LANGUAGES.add("crh");
LANGUAGES.add("ace");
LANGUAGES.add("to");
LANGUAGES.add("as");
LANGUAGES.add("ce");
LANGUAGES.add("kl");
LANGUAGES.add("arc");
LANGUAGES.add("dsb");
LANGUAGES.add("myv");
LANGUAGES.add("bjn");
LANGUAGES.add("pap");
LANGUAGES.add("sn");
LANGUAGES.add("tpi");
LANGUAGES.add("lbe");
LANGUAGES.add("mdf");
LANGUAGES.add("wo");
LANGUAGES.add("kab");
LANGUAGES.add("jbo");
LANGUAGES.add("av");
LANGUAGES.add("lez");
LANGUAGES.add("srn");
LANGUAGES.add("cbk-zam");
LANGUAGES.add("ty");
LANGUAGES.add("bxr");
LANGUAGES.add("lo");
LANGUAGES.add("kbd");
LANGUAGES.add("ab");
LANGUAGES.add("tet");
LANGUAGES.add("mwl");
LANGUAGES.add("ltg");
LANGUAGES.add("na");
LANGUAGES.add("ig");
LANGUAGES.add("kg");
LANGUAGES.add("nso");
LANGUAGES.add("za");
LANGUAGES.add("kaa");
LANGUAGES.add("zu");
LANGUAGES.add("rmy");
LANGUAGES.add("chy");
LANGUAGES.add("cu");
LANGUAGES.add("tn");
LANGUAGES.add("chr");
LANGUAGES.add("got");
LANGUAGES.add("cdo");
LANGUAGES.add("sm");
LANGUAGES.add("bi");
LANGUAGES.add("mo");
LANGUAGES.add("bm");
LANGUAGES.add("iu");
LANGUAGES.add("pih");
LANGUAGES.add("ss");
LANGUAGES.add("sd");
LANGUAGES.add("pnt");
LANGUAGES.add("ee");
LANGUAGES.add("om");
LANGUAGES.add("ha");
LANGUAGES.add("ki");
LANGUAGES.add("ti");
LANGUAGES.add("ts");
LANGUAGES.add("ks");
LANGUAGES.add("sg");
LANGUAGES.add("ve");
LANGUAGES.add("rn");
LANGUAGES.add("cr");
LANGUAGES.add("ak");
LANGUAGES.add("lg");
LANGUAGES.add("tum");
LANGUAGES.add("dz");
LANGUAGES.add("ny");
LANGUAGES.add("ik");
LANGUAGES.add("ff");
LANGUAGES.add("ch");
LANGUAGES.add("st");
LANGUAGES.add("fj");
LANGUAGES.add("tw");
LANGUAGES.add("xh");
LANGUAGES.add("ng");
LANGUAGES.add("ii");
LANGUAGES.add("cho");
LANGUAGES.add("mh");
LANGUAGES.add("aa");
LANGUAGES.add("kj");
LANGUAGES.add("ho");
LANGUAGES.add("mus");
LANGUAGES.add("kr");
LANGUAGES.add("hz");
}
private String hostname; // Provided hostname
private String language = null;
private String siteVersion = "X";
private String projectDomain;
// TODO: work out the actual space of project names and assign them canonical IDs.
// private String project; // Canonical ID for this project
// private String projectName; // Human-readable name of this project
public ProjectInfo(String hostname) {
this.hostname = hostname;
String[] domainParts = hostname.split("\\.");
List<String> projectParts = Lists.newArrayListWithExpectedSize(domainParts.length);
// Ignore SLD+TLD, as language/version are always before (andalso country TLDs look like languages)
for (int i = 0; i < domainParts.length - 2; i++) {
String part = domainParts[i];
if (part.equalsIgnoreCase("www")) {
continue;
} else if (language == null && LANGUAGES.contains(part)) {
language = part;
} else if (SITE_VERSIONS.containsKey(part)) {
siteVersion = SITE_VERSIONS.get(part);
} else {
projectParts.add(part);
}
}
// Add SLD+TLD which we skipped above
- projectParts.add(domainParts[domainParts.length - 2]);
- projectParts.add(domainParts[domainParts.length - 1]);
- projectDomain = Joiner.on('.').skipNulls().join(projectParts);
+ if (domainParts.length > 1) {
+ projectParts.add(domainParts[domainParts.length - 2]);
+ projectParts.add(domainParts[domainParts.length - 1]);
+ projectDomain = Joiner.on('.').skipNulls().join(projectParts);
+ }
+ else {
+ projectDomain = Joiner.on('.').skipNulls().join(domainParts);
+ }
}
public String getHostname() {
return hostname;
}
public String getLanguage() {
return language;
}
public String getSiteVersion() {
return siteVersion;
}
public String getProjectDomain() {
return projectDomain;
}
}
| true | true | public ProjectInfo(String hostname) {
this.hostname = hostname;
String[] domainParts = hostname.split("\\.");
List<String> projectParts = Lists.newArrayListWithExpectedSize(domainParts.length);
// Ignore SLD+TLD, as language/version are always before (andalso country TLDs look like languages)
for (int i = 0; i < domainParts.length - 2; i++) {
String part = domainParts[i];
if (part.equalsIgnoreCase("www")) {
continue;
} else if (language == null && LANGUAGES.contains(part)) {
language = part;
} else if (SITE_VERSIONS.containsKey(part)) {
siteVersion = SITE_VERSIONS.get(part);
} else {
projectParts.add(part);
}
}
// Add SLD+TLD which we skipped above
projectParts.add(domainParts[domainParts.length - 2]);
projectParts.add(domainParts[domainParts.length - 1]);
projectDomain = Joiner.on('.').skipNulls().join(projectParts);
}
| public ProjectInfo(String hostname) {
this.hostname = hostname;
String[] domainParts = hostname.split("\\.");
List<String> projectParts = Lists.newArrayListWithExpectedSize(domainParts.length);
// Ignore SLD+TLD, as language/version are always before (andalso country TLDs look like languages)
for (int i = 0; i < domainParts.length - 2; i++) {
String part = domainParts[i];
if (part.equalsIgnoreCase("www")) {
continue;
} else if (language == null && LANGUAGES.contains(part)) {
language = part;
} else if (SITE_VERSIONS.containsKey(part)) {
siteVersion = SITE_VERSIONS.get(part);
} else {
projectParts.add(part);
}
}
// Add SLD+TLD which we skipped above
if (domainParts.length > 1) {
projectParts.add(domainParts[domainParts.length - 2]);
projectParts.add(domainParts[domainParts.length - 1]);
projectDomain = Joiner.on('.').skipNulls().join(projectParts);
}
else {
projectDomain = Joiner.on('.').skipNulls().join(domainParts);
}
}
|
diff --git a/src/com/android/contacts/editor/PhotoActionPopup.java b/src/com/android/contacts/editor/PhotoActionPopup.java
index ac2d64fd3..cca6f9d08 100644
--- a/src/com/android/contacts/editor/PhotoActionPopup.java
+++ b/src/com/android/contacts/editor/PhotoActionPopup.java
@@ -1,138 +1,138 @@
/*
* 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.contacts.editor;
import com.android.contacts.R;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListPopupWindow;
import java.util.ArrayList;
/**
* Shows a popup asking the user what to do for a photo. The result is pased back to the Listener
*/
public class PhotoActionPopup {
public static final String TAG = "PhotoActionPopup";
public static final int MODE_NO_PHOTO = 0;
public static final int MODE_READ_ONLY_ALLOW_PRIMARY = 1;
public static final int MODE_PHOTO_DISALLOW_PRIMARY = 2;
public static final int MODE_PHOTO_ALLOW_PRIMARY = 3;
public static ListPopupWindow createPopupMenu(Context context, View anchorView,
final Listener listener, int mode) {
// Build choices, depending on the current mode. We assume this Dialog is never called
// if there are NO choices (e.g. a read-only picture is already super-primary)
final ArrayList<ChoiceListItem> choices = new ArrayList<ChoiceListItem>(4);
// Use as Primary
if (mode == MODE_PHOTO_ALLOW_PRIMARY || mode == MODE_READ_ONLY_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_USE_AS_PRIMARY,
context.getString(R.string.use_photo_as_primary)));
}
// Remove
if (mode == MODE_PHOTO_DISALLOW_PRIMARY || mode == MODE_PHOTO_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_REMOVE,
context.getString(R.string.removePhoto)));
}
// Take photo (if there is already a photo, it says "Take new photo")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.take_photo :R.string.take_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_TAKE_PHOTO,
context.getString(resId)));
}
// Select from Gallery (or "Select new from Gallery")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.pick_photo :R.string.pick_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_PICK_PHOTO,
context.getString(resId)));
}
final ListAdapter adapter = new ArrayAdapter<ChoiceListItem>(context,
- android.R.layout.select_dialog_item, choices);
+ R.layout.select_dialog_item, choices);
final ListPopupWindow listPopupWindow = new ListPopupWindow(context);
final OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ChoiceListItem choice = choices.get(position);
listPopupWindow.dismiss();
switch (choice.getId()) {
case ChoiceListItem.ID_USE_AS_PRIMARY:
listener.onUseAsPrimaryChosen();
break;
case ChoiceListItem.ID_REMOVE:
listener.onRemovePictureChosen();
break;
case ChoiceListItem.ID_TAKE_PHOTO:
listener.onTakePhotoChosen();
break;
case ChoiceListItem.ID_PICK_PHOTO:
listener.onPickFromGalleryChosen();
break;
}
}
};
listPopupWindow.setAnchorView(anchorView);
listPopupWindow.setAdapter(adapter);
listPopupWindow.setOnItemClickListener(clickListener);
listPopupWindow.setWidth(context.getResources().getDimensionPixelSize(
R.dimen.photo_action_popup_width));
listPopupWindow.setModal(true);
listPopupWindow.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
return listPopupWindow;
}
private static final class ChoiceListItem {
private final int mId;
private final String mCaption;
public static final int ID_USE_AS_PRIMARY = 0;
public static final int ID_TAKE_PHOTO = 1;
public static final int ID_PICK_PHOTO = 2;
public static final int ID_REMOVE = 3;
public ChoiceListItem(int id, String caption) {
mId = id;
mCaption = caption;
}
@Override
public String toString() {
return mCaption;
}
public int getId() {
return mId;
}
}
public interface Listener {
void onUseAsPrimaryChosen();
void onRemovePictureChosen();
void onTakePhotoChosen();
void onPickFromGalleryChosen();
}
}
| true | true | public static ListPopupWindow createPopupMenu(Context context, View anchorView,
final Listener listener, int mode) {
// Build choices, depending on the current mode. We assume this Dialog is never called
// if there are NO choices (e.g. a read-only picture is already super-primary)
final ArrayList<ChoiceListItem> choices = new ArrayList<ChoiceListItem>(4);
// Use as Primary
if (mode == MODE_PHOTO_ALLOW_PRIMARY || mode == MODE_READ_ONLY_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_USE_AS_PRIMARY,
context.getString(R.string.use_photo_as_primary)));
}
// Remove
if (mode == MODE_PHOTO_DISALLOW_PRIMARY || mode == MODE_PHOTO_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_REMOVE,
context.getString(R.string.removePhoto)));
}
// Take photo (if there is already a photo, it says "Take new photo")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.take_photo :R.string.take_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_TAKE_PHOTO,
context.getString(resId)));
}
// Select from Gallery (or "Select new from Gallery")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.pick_photo :R.string.pick_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_PICK_PHOTO,
context.getString(resId)));
}
final ListAdapter adapter = new ArrayAdapter<ChoiceListItem>(context,
android.R.layout.select_dialog_item, choices);
final ListPopupWindow listPopupWindow = new ListPopupWindow(context);
final OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ChoiceListItem choice = choices.get(position);
listPopupWindow.dismiss();
switch (choice.getId()) {
case ChoiceListItem.ID_USE_AS_PRIMARY:
listener.onUseAsPrimaryChosen();
break;
case ChoiceListItem.ID_REMOVE:
listener.onRemovePictureChosen();
break;
case ChoiceListItem.ID_TAKE_PHOTO:
listener.onTakePhotoChosen();
break;
case ChoiceListItem.ID_PICK_PHOTO:
listener.onPickFromGalleryChosen();
break;
}
}
};
listPopupWindow.setAnchorView(anchorView);
listPopupWindow.setAdapter(adapter);
listPopupWindow.setOnItemClickListener(clickListener);
listPopupWindow.setWidth(context.getResources().getDimensionPixelSize(
R.dimen.photo_action_popup_width));
listPopupWindow.setModal(true);
listPopupWindow.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
return listPopupWindow;
}
| public static ListPopupWindow createPopupMenu(Context context, View anchorView,
final Listener listener, int mode) {
// Build choices, depending on the current mode. We assume this Dialog is never called
// if there are NO choices (e.g. a read-only picture is already super-primary)
final ArrayList<ChoiceListItem> choices = new ArrayList<ChoiceListItem>(4);
// Use as Primary
if (mode == MODE_PHOTO_ALLOW_PRIMARY || mode == MODE_READ_ONLY_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_USE_AS_PRIMARY,
context.getString(R.string.use_photo_as_primary)));
}
// Remove
if (mode == MODE_PHOTO_DISALLOW_PRIMARY || mode == MODE_PHOTO_ALLOW_PRIMARY) {
choices.add(new ChoiceListItem(ChoiceListItem.ID_REMOVE,
context.getString(R.string.removePhoto)));
}
// Take photo (if there is already a photo, it says "Take new photo")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.take_photo :R.string.take_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_TAKE_PHOTO,
context.getString(resId)));
}
// Select from Gallery (or "Select new from Gallery")
if (mode == MODE_NO_PHOTO || mode == MODE_PHOTO_ALLOW_PRIMARY
|| mode == MODE_PHOTO_DISALLOW_PRIMARY) {
final int resId = mode == MODE_NO_PHOTO ? R.string.pick_photo :R.string.pick_new_photo;
choices.add(new ChoiceListItem(ChoiceListItem.ID_PICK_PHOTO,
context.getString(resId)));
}
final ListAdapter adapter = new ArrayAdapter<ChoiceListItem>(context,
R.layout.select_dialog_item, choices);
final ListPopupWindow listPopupWindow = new ListPopupWindow(context);
final OnItemClickListener clickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ChoiceListItem choice = choices.get(position);
listPopupWindow.dismiss();
switch (choice.getId()) {
case ChoiceListItem.ID_USE_AS_PRIMARY:
listener.onUseAsPrimaryChosen();
break;
case ChoiceListItem.ID_REMOVE:
listener.onRemovePictureChosen();
break;
case ChoiceListItem.ID_TAKE_PHOTO:
listener.onTakePhotoChosen();
break;
case ChoiceListItem.ID_PICK_PHOTO:
listener.onPickFromGalleryChosen();
break;
}
}
};
listPopupWindow.setAnchorView(anchorView);
listPopupWindow.setAdapter(adapter);
listPopupWindow.setOnItemClickListener(clickListener);
listPopupWindow.setWidth(context.getResources().getDimensionPixelSize(
R.dimen.photo_action_popup_width));
listPopupWindow.setModal(true);
listPopupWindow.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
return listPopupWindow;
}
|
diff --git a/bundles/binding/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/KNXCoreTypeMapper.java b/bundles/binding/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/KNXCoreTypeMapper.java
index 82e20653..edc99630 100644
--- a/bundles/binding/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/KNXCoreTypeMapper.java
+++ b/bundles/binding/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/dpt/KNXCoreTypeMapper.java
@@ -1,274 +1,280 @@
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2012, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.binding.knx.internal.dpt;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.knx.config.KNXTypeMapper;
import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.IncreaseDecreaseType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
import org.openhab.core.library.types.PercentType;
import org.openhab.core.library.types.StopMoveType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.types.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tuwien.auto.calimero.datapoint.Datapoint;
import tuwien.auto.calimero.dptxlator.DPTXlator;
import tuwien.auto.calimero.dptxlator.DPTXlator2ByteUnsigned;
import tuwien.auto.calimero.dptxlator.DPTXlator3BitControlled;
import tuwien.auto.calimero.dptxlator.DPTXlator8BitUnsigned;
import tuwien.auto.calimero.dptxlator.DPTXlatorBoolean;
import tuwien.auto.calimero.dptxlator.DPTXlatorDate;
import tuwien.auto.calimero.dptxlator.DPTXlatorScene;
import tuwien.auto.calimero.dptxlator.DPTXlatorString;
import tuwien.auto.calimero.dptxlator.DPTXlatorTime;
import tuwien.auto.calimero.dptxlator.TranslatorTypes;
import tuwien.auto.calimero.exception.KNXException;
/**
* This class provides type mapping between all openHAB core types and KNX data point types.
*
* @author Kai Kreuzer
* @since 0.3.0
*
*/
public class KNXCoreTypeMapper implements KNXTypeMapper {
static private final Logger logger = LoggerFactory.getLogger(KNXCoreTypeMapper.class);
private final static SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("EEE, HH:mm:ss", Locale.US);
private final static SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
/** stores the openHAB type class for all (supported) KNX datapoint types */
static private Map<String, Class<? extends Type>> dptTypeMap;
/** stores the default KNX DPT to use for each openHAB type */
static private Map<Class<? extends Type>, String> defaultDptMap;
static {
dptTypeMap = new HashMap<String, Class<? extends Type>>();
dptTypeMap.put(DPTXlatorBoolean.DPT_UPDOWN.getID(), UpDownType.class);
dptTypeMap.put(DPTXlator3BitControlled.DPT_CONTROL_DIMMING.getID(), IncreaseDecreaseType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_STEP.getID(), IncreaseDecreaseType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_SWITCH.getID(), OnOffType.class);
dptTypeMap.put(DPTXlator8BitUnsigned.DPT_PERCENT_U8.getID(), PercentType.class);
dptTypeMap.put(DPTXlator8BitUnsigned.DPT_SCALING.getID(), PercentType.class);
dptTypeMap.put(DPTXlator8BitUnsigned.DPT_DECIMALFACTOR.getID(), DecimalType.class);
dptTypeMap.put(DPTXlator2ByteUnsigned.DPT_ELECTRICAL_CURRENT.getID(), DecimalType.class);
dptTypeMap.put(DPTXlator2ByteUnsigned.DPT_BRIGHTNESS.getID(), DecimalType.class);
dptTypeMap.put("9.001", DecimalType.class); // Temperature
dptTypeMap.put(DPTXlatorString.DPT_STRING_8859_1.getID(), StringType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_WINDOW_DOOR.getID(), OpenClosedType.class);
dptTypeMap.put(DPTXlatorBoolean.DPT_START.getID(), StopMoveType.class);
dptTypeMap.put(DPTXlatorDate.DPT_DATE.getID(), DateTimeType.class);
dptTypeMap.put(DPTXlatorTime.DPT_TIMEOFDAY.getID(), DateTimeType.class);
defaultDptMap = new HashMap<Class<? extends Type>, String>();
defaultDptMap.put(UpDownType.class, DPTXlatorBoolean.DPT_UPDOWN.getID());
defaultDptMap.put(IncreaseDecreaseType.class, DPTXlator3BitControlled.DPT_CONTROL_DIMMING.getID());
defaultDptMap.put(OnOffType.class, DPTXlatorBoolean.DPT_SWITCH.getID());
defaultDptMap.put(PercentType.class, DPTXlator8BitUnsigned.DPT_PERCENT_U8.getID());
defaultDptMap.put(DecimalType.class, "9.001");
defaultDptMap.put(StringType.class, DPTXlatorString.DPT_STRING_8859_1.getID());
defaultDptMap.put(OpenClosedType.class, DPTXlatorBoolean.DPT_WINDOW_DOOR.getID());
defaultDptMap.put(StopMoveType.class, DPTXlatorBoolean.DPT_START.getID());
defaultDptMap.put(DateTimeType.class, DPTXlatorTime.DPT_TIMEOFDAY.getID());
}
public String toDPTValue(Type type, String dpt) {
if(type instanceof OnOffType) return type.toString().toLowerCase();
if(type instanceof UpDownType) return type.toString().toLowerCase();
if(type instanceof IncreaseDecreaseType) return type.toString().toLowerCase() + " 5";
if(type instanceof PercentType) {
if(dpt.equals(DPTXlator8BitUnsigned.DPT_PERCENT_U8.getID())) {
return mapTo8bit((PercentType) type);
} else {
return type.toString();
}
}
if(type instanceof DecimalType) return type.toString();
if(type instanceof StringType) return type.toString();
if(type instanceof OpenClosedType) return type.toString().toLowerCase();
if(type==StopMoveType.MOVE) return "start";
if(type==StopMoveType.STOP) return "stop";
if(type instanceof DateTimeType) return formatDateTime((DateTimeType) type, dpt);
return null;
}
public Type toType(Datapoint datapoint, byte[] data) {
try {
DPTXlator translator = TranslatorTypes.createTranslator(datapoint.getMainNumber(), datapoint.getDPT());
translator.setData(data);
String value = translator.getValue();
String id = translator.getType().getID();
if(datapoint.getMainNumber()==9) id = "9.001"; // we do not care about the unit of a value, so map everything to 9.001
Class<? extends Type> typeClass = toTypeClass(id);
if(typeClass.equals(UpDownType.class)) return UpDownType.valueOf(value.toUpperCase());
if(typeClass.equals(IncreaseDecreaseType.class)) return IncreaseDecreaseType.valueOf(StringUtils.substringBefore(value.toUpperCase(), " "));
if(typeClass.equals(OnOffType.class)) return OnOffType.valueOf(value.toUpperCase());
- if(typeClass.equals(PercentType.class)) return PercentType.valueOf(value.split(" ")[0]);
+ if(typeClass.equals(PercentType.class)) {
+ if(id.equals(DPTXlator8BitUnsigned.DPT_PERCENT_U8.getID())) {
+ return PercentType.valueOf(mapToPercent(value));
+ } else {
+ return PercentType.valueOf(value.split(" ")[0]);
+ }
+ }
if(typeClass.equals(DecimalType.class)) return DecimalType.valueOf(value.split(" ")[0]);
if(typeClass.equals(StringType.class)) return StringType.valueOf(value);
if(typeClass.equals(OpenClosedType.class)) return OpenClosedType.valueOf(value.toUpperCase());
if(typeClass.equals(StopMoveType.class)) return value.equals("start")?StopMoveType.MOVE:StopMoveType.STOP;
if(typeClass.equals(DateTimeType.class)) return DateTimeType.valueOf(formatDateTime(value, datapoint.getDPT()));
}
catch (KNXException e) {
logger.warn("Failed creating a translator for datapoint type ‘{}‘.", datapoint.getDPT(), e);
}
return null;
}
/**
* Converts a datapoint type id into an openHAB type class
*
* @param dptId the datapoint type id
* @return the openHAB type (command or state) class
*/
static public Class<? extends Type> toTypeClass(String dptId) {
/*
* DecimalType is by default associated to 9.001, so for 12.001
* or 17.001, we need to do exceptional handling
*/
if ("12.001".equals(dptId)) {
return DecimalType.class;
}
else if (DPTXlatorScene.DPT_SCENE_NUMBER.getID().equals(dptId)) {
return DecimalType.class;
} else {
return dptTypeMap.get(dptId);
}
}
/**
* Converts an openHAB type class into a datapoint type id.
*
* @param typeClass the openHAB type class
* @return the datapoint type id
*/
static public String toDPTid(Class<? extends Type> typeClass) {
return defaultDptMap.get(typeClass);
}
/**
* Maps an 8-bit KNX percent value (range 0-255) to a "real" percent value as a string.
*
* @param value the 8-bit KNX percent value
* @return the real value as a string (e.g. "99.5")
*/
static private String mapToPercent(String value) {
int percent = Integer.parseInt(StringUtils.substringBefore(value.toString(), " "));
return Integer.toString(percent * 100 / 255);
}
/**
* Maps an openHAB percent value to an 8-bit KNX percent value (0-255) as a string.
* The mapping is linear and starts with 0->0 and ends with 100->255.
*
* @param type the openHAB percent value
* @return the 8-bit KNX percent value
*/
static private String mapTo8bit(PercentType type) {
int value = Integer.parseInt(type.toString());
return Integer.toString(value * 255 / 100);
}
/**
* Formats the given <code>value</code> according to the datapoint type
* <code>dpt</code> to a String which can be processed by {@link DateTimeType}.
*
* @param value
* @param dpt
*
* @return a formatted String like </code>yyyy-MM-dd'T'HH:mm:ss</code> which
* is target format of the {@link DateTimeType}
*/
private String formatDateTime(String value, String dpt) {
Date date = null;
try {
if (DPTXlatorDate.DPT_DATE.getID().equals(dpt)) {
date = DATE_FORMATTER.parse(value);
}
else if (DPTXlatorTime.DPT_TIMEOFDAY.getID().equals(dpt)) {
date = TIME_FORMATTER.parse(value);
}
}
catch (ParseException pe) {
// do nothing but logging
logger.warn("Could not parse '{}' to a valid date", value);
}
return date != null ? DateTimeType.DATE_FORMATTER.format(date) : "";
}
/**
* Formats the given internal <code>dateType</code> to a knx readable String
* according to the target datapoint type <code>dpt</code>.
*
* @param dateType
* @param dpt the target datapoint type
*
* @return a String which contains either an ISO8601 formatted date (yyyy-mm-dd) or
* a formatted 24-hour clock with the day of week prepended (Mon, 12:00:00)
*
* @throws IllegalArgumentException if none of the datapoint types DPT_DATE or
* DPT_TIMEOFDAY has been used.
*/
static private String formatDateTime(DateTimeType dateType, String dpt) {
if (DPTXlatorDate.DPT_DATE.getID().equals(dpt)) {
return dateType.format("%tF");
}
else if (DPTXlatorTime.DPT_TIMEOFDAY.getID().equals(dpt)) {
return dateType.format(Locale.US, "%1$ta, %1$tT");
}
else {
throw new IllegalArgumentException("Could not format date to datapoint type '" + dpt + "'");
}
}
}
| true | true | public Type toType(Datapoint datapoint, byte[] data) {
try {
DPTXlator translator = TranslatorTypes.createTranslator(datapoint.getMainNumber(), datapoint.getDPT());
translator.setData(data);
String value = translator.getValue();
String id = translator.getType().getID();
if(datapoint.getMainNumber()==9) id = "9.001"; // we do not care about the unit of a value, so map everything to 9.001
Class<? extends Type> typeClass = toTypeClass(id);
if(typeClass.equals(UpDownType.class)) return UpDownType.valueOf(value.toUpperCase());
if(typeClass.equals(IncreaseDecreaseType.class)) return IncreaseDecreaseType.valueOf(StringUtils.substringBefore(value.toUpperCase(), " "));
if(typeClass.equals(OnOffType.class)) return OnOffType.valueOf(value.toUpperCase());
if(typeClass.equals(PercentType.class)) return PercentType.valueOf(value.split(" ")[0]);
if(typeClass.equals(DecimalType.class)) return DecimalType.valueOf(value.split(" ")[0]);
if(typeClass.equals(StringType.class)) return StringType.valueOf(value);
if(typeClass.equals(OpenClosedType.class)) return OpenClosedType.valueOf(value.toUpperCase());
if(typeClass.equals(StopMoveType.class)) return value.equals("start")?StopMoveType.MOVE:StopMoveType.STOP;
if(typeClass.equals(DateTimeType.class)) return DateTimeType.valueOf(formatDateTime(value, datapoint.getDPT()));
}
catch (KNXException e) {
logger.warn("Failed creating a translator for datapoint type ‘{}‘.", datapoint.getDPT(), e);
}
return null;
}
| public Type toType(Datapoint datapoint, byte[] data) {
try {
DPTXlator translator = TranslatorTypes.createTranslator(datapoint.getMainNumber(), datapoint.getDPT());
translator.setData(data);
String value = translator.getValue();
String id = translator.getType().getID();
if(datapoint.getMainNumber()==9) id = "9.001"; // we do not care about the unit of a value, so map everything to 9.001
Class<? extends Type> typeClass = toTypeClass(id);
if(typeClass.equals(UpDownType.class)) return UpDownType.valueOf(value.toUpperCase());
if(typeClass.equals(IncreaseDecreaseType.class)) return IncreaseDecreaseType.valueOf(StringUtils.substringBefore(value.toUpperCase(), " "));
if(typeClass.equals(OnOffType.class)) return OnOffType.valueOf(value.toUpperCase());
if(typeClass.equals(PercentType.class)) {
if(id.equals(DPTXlator8BitUnsigned.DPT_PERCENT_U8.getID())) {
return PercentType.valueOf(mapToPercent(value));
} else {
return PercentType.valueOf(value.split(" ")[0]);
}
}
if(typeClass.equals(DecimalType.class)) return DecimalType.valueOf(value.split(" ")[0]);
if(typeClass.equals(StringType.class)) return StringType.valueOf(value);
if(typeClass.equals(OpenClosedType.class)) return OpenClosedType.valueOf(value.toUpperCase());
if(typeClass.equals(StopMoveType.class)) return value.equals("start")?StopMoveType.MOVE:StopMoveType.STOP;
if(typeClass.equals(DateTimeType.class)) return DateTimeType.valueOf(formatDateTime(value, datapoint.getDPT()));
}
catch (KNXException e) {
logger.warn("Failed creating a translator for datapoint type ‘{}‘.", datapoint.getDPT(), e);
}
return null;
}
|
diff --git a/Client/src/se/lth/student/eda040/a1/data/Input.java b/Client/src/se/lth/student/eda040/a1/data/Input.java
index 1e5617b..7ddebf5 100644
--- a/Client/src/se/lth/student/eda040/a1/data/Input.java
+++ b/Client/src/se/lth/student/eda040/a1/data/Input.java
@@ -1,36 +1,36 @@
package se.lth.student.eda040.a1.data;
import java.io.IOException;
import android.util.Log;
import se.lth.student.eda040.a1.network.*;
public class Input extends Thread {
private ClientMonitor monitor;
private ClientProtocol protocol;
public Input(ClientMonitor monitor, ClientProtocol protocol) {
this.monitor = monitor;
this.protocol = protocol;
}
public void run() {
Image image;
while (!interrupted()) {
try {
Log.d("Input", "Checking for connection in monitor");
monitor.connectionCheck(protocol.getCameraId());
Log.d("Input", "In started to fetch images");
image = protocol.awaitImage();
monitor.putImage(image, protocol.getCameraId());
} catch (IOException e) {
try {
protocol.disconnect();
} catch (IOException ioe) {
System.err.println("Could not disconnect some how.");
+ interrupt();
}
- interrupt();
}
}
}
}
| false | true | public void run() {
Image image;
while (!interrupted()) {
try {
Log.d("Input", "Checking for connection in monitor");
monitor.connectionCheck(protocol.getCameraId());
Log.d("Input", "In started to fetch images");
image = protocol.awaitImage();
monitor.putImage(image, protocol.getCameraId());
} catch (IOException e) {
try {
protocol.disconnect();
} catch (IOException ioe) {
System.err.println("Could not disconnect some how.");
}
interrupt();
}
}
}
| public void run() {
Image image;
while (!interrupted()) {
try {
Log.d("Input", "Checking for connection in monitor");
monitor.connectionCheck(protocol.getCameraId());
Log.d("Input", "In started to fetch images");
image = protocol.awaitImage();
monitor.putImage(image, protocol.getCameraId());
} catch (IOException e) {
try {
protocol.disconnect();
} catch (IOException ioe) {
System.err.println("Could not disconnect some how.");
interrupt();
}
}
}
}
|
diff --git a/android/AvalancheRisk/src/woodsie/avalanche/reduction/ReductionCalculator.java b/android/AvalancheRisk/src/woodsie/avalanche/reduction/ReductionCalculator.java
index 33dff97..ce6ad13 100644
--- a/android/AvalancheRisk/src/woodsie/avalanche/reduction/ReductionCalculator.java
+++ b/android/AvalancheRisk/src/woodsie/avalanche/reduction/ReductionCalculator.java
@@ -1,43 +1,43 @@
package woodsie.avalanche.reduction;
import java.math.BigDecimal;
import java.math.MathContext;
import woodsie.avalanche.reduction.data.Hazard;
import woodsie.avalanche.reduction.data.ReductionParams;
import woodsie.avalanche.reduction.data.Steepness;
import woodsie.avalanche.reduction.data.Where;
public class ReductionCalculator {
public static final BigDecimal EXTREME = BigDecimal.valueOf(100);
public BigDecimal process(ReductionParams params) {
if (params.hazardLevel == Hazard.VERY_HIGH) {
return EXTREME;
}
BigDecimal dangerPotential = new BigDecimal(params.hazardLevel.getDangerPotential(params.higherHazard), MathContext.DECIMAL32);
int reductionFactor = 1;
if ((params.hazardLevel.getDangerPotential(params.higherHazard) < Hazard.CONSIDERABLE.getDangerPotential(false))
|| (params.hazardLevel == Hazard.HIGH && params.steepness == Steepness.NOT_STEEP)
- || (params.hazardLevel == Hazard.CONSIDERABLE && params.steepness.getReductionFactor() >= 1)) {
+ || (params.hazardLevel == Hazard.CONSIDERABLE && params.steepness.getReductionFactor() > 1)) {
reductionFactor *= params.steepness.getReductionFactor();
if (!params.allAspects) {
if (!params.inverse
|| (params.inverse && params.where == Where.AVOID_CRITICAL)) {
reductionFactor *= params.where.getReductionFactor();
}
reductionFactor *= params.terrain.getReductionFactor();
}
reductionFactor *= params.groupSize.getReductionFactor();
}
return dangerPotential.divide(new BigDecimal(reductionFactor), MathContext.DECIMAL32);
}
}
| true | true | public BigDecimal process(ReductionParams params) {
if (params.hazardLevel == Hazard.VERY_HIGH) {
return EXTREME;
}
BigDecimal dangerPotential = new BigDecimal(params.hazardLevel.getDangerPotential(params.higherHazard), MathContext.DECIMAL32);
int reductionFactor = 1;
if ((params.hazardLevel.getDangerPotential(params.higherHazard) < Hazard.CONSIDERABLE.getDangerPotential(false))
|| (params.hazardLevel == Hazard.HIGH && params.steepness == Steepness.NOT_STEEP)
|| (params.hazardLevel == Hazard.CONSIDERABLE && params.steepness.getReductionFactor() >= 1)) {
reductionFactor *= params.steepness.getReductionFactor();
if (!params.allAspects) {
if (!params.inverse
|| (params.inverse && params.where == Where.AVOID_CRITICAL)) {
reductionFactor *= params.where.getReductionFactor();
}
reductionFactor *= params.terrain.getReductionFactor();
}
reductionFactor *= params.groupSize.getReductionFactor();
}
return dangerPotential.divide(new BigDecimal(reductionFactor), MathContext.DECIMAL32);
}
| public BigDecimal process(ReductionParams params) {
if (params.hazardLevel == Hazard.VERY_HIGH) {
return EXTREME;
}
BigDecimal dangerPotential = new BigDecimal(params.hazardLevel.getDangerPotential(params.higherHazard), MathContext.DECIMAL32);
int reductionFactor = 1;
if ((params.hazardLevel.getDangerPotential(params.higherHazard) < Hazard.CONSIDERABLE.getDangerPotential(false))
|| (params.hazardLevel == Hazard.HIGH && params.steepness == Steepness.NOT_STEEP)
|| (params.hazardLevel == Hazard.CONSIDERABLE && params.steepness.getReductionFactor() > 1)) {
reductionFactor *= params.steepness.getReductionFactor();
if (!params.allAspects) {
if (!params.inverse
|| (params.inverse && params.where == Where.AVOID_CRITICAL)) {
reductionFactor *= params.where.getReductionFactor();
}
reductionFactor *= params.terrain.getReductionFactor();
}
reductionFactor *= params.groupSize.getReductionFactor();
}
return dangerPotential.divide(new BigDecimal(reductionFactor), MathContext.DECIMAL32);
}
|
diff --git a/GAE/src/services/TranslationGenerator.java b/GAE/src/services/TranslationGenerator.java
index 400772664..365e3c5ca 100644
--- a/GAE/src/services/TranslationGenerator.java
+++ b/GAE/src/services/TranslationGenerator.java
@@ -1,133 +1,133 @@
/*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package services;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
public class TranslationGenerator {
private static final String HPREFIX = "{{t ";
private static final String HSUFFX = "}}";
private static final String JSCALLPREFIX = "String.loc('";
private static final String JSCALLSUFXX = "'";
private static final String[] EXTS = { "handlebars", "js" };
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.err.println("<Dashboard> directory is required");
return;
}
final File sources = new File(args[0]);
final Properties ui_strings = new Properties();
ui_strings.load(new FileInputStream(new File(sources,
"/translations/locale/ui-strings.properties")));
final Map<String, String> trlKeys = new HashMap<String, String>();
final List<String> enValues = new ArrayList<String>();
for (File f : (List<File>) FileUtils.listFiles(sources, EXTS, true)) {
if (f.getAbsolutePath().contains("vendor")) {
continue; // skipping
}
final List<String> lines = FileUtils.readLines(f, "UTF-8");
for (String line : lines) {
if (line.contains(HPREFIX) || line.contains(JSCALLPREFIX)) {
final String key = getKey(line);
if (key != null && !trlKeys.containsKey(key)) {
final String en = ui_strings.getProperty(key);
if (en == null) {
System.err.println("Translation key `" + key
+ "` not found in ui-strings.properties");
ui_strings.put(key, "");
}
- trlKeys.put(key, en);
+ trlKeys.put(key, (en == null ? "" : en));
- if (!"".equals(en) && !enValues.contains(en)) {
+ if (en != null && !"".equals(en) && !enValues.contains(en)) {
enValues.add(en);
}
}
}
}
}
Collections.sort(enValues);
StringBuffer sb = new StringBuffer();
for (String val : enValues) {
sb.append(val).append(" = ").append(val).append("\n");
}
FileUtils.writeStringToFile(new File(sources,
"/translations/locale/en.properties"), sb.toString(), "UTF-8");
final List<String> tmp = new ArrayList<String>(trlKeys.keySet());
Collections.sort(tmp);
final StringBuffer uisource = new StringBuffer();
for (String ui : tmp) {
uisource.append(ui).append(" = ").append(trlKeys.get(ui))
.append("\n");
}
FileUtils.writeStringToFile(new File(sources,
"/translations/locale/ui-strings.properties"), uisource
.toString(), "UTF-8");
}
private static String getKey(String line) {
if (line.contains(HPREFIX)) {
return getKeyFromTemplate(line);
} else if (line.contains(JSCALLPREFIX)) {
return getKeyFromJSCall(line);
}
return null;
}
private static String getKeyFromTemplate(String line) {
return extractKeyFromLine(line, HPREFIX, HSUFFX);
}
private static String getKeyFromJSCall(String line) {
return extractKeyFromLine(line, JSCALLPREFIX, JSCALLSUFXX);
}
private static String extractKeyFromLine(String line, String prefix,
String suffix) {
int start = line.indexOf(prefix) + prefix.length();
int end = line.indexOf(suffix, start);
if (start < 0 || end < 0) {
return null;
}
return line.substring(start, end);
}
}
| false | true | public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.err.println("<Dashboard> directory is required");
return;
}
final File sources = new File(args[0]);
final Properties ui_strings = new Properties();
ui_strings.load(new FileInputStream(new File(sources,
"/translations/locale/ui-strings.properties")));
final Map<String, String> trlKeys = new HashMap<String, String>();
final List<String> enValues = new ArrayList<String>();
for (File f : (List<File>) FileUtils.listFiles(sources, EXTS, true)) {
if (f.getAbsolutePath().contains("vendor")) {
continue; // skipping
}
final List<String> lines = FileUtils.readLines(f, "UTF-8");
for (String line : lines) {
if (line.contains(HPREFIX) || line.contains(JSCALLPREFIX)) {
final String key = getKey(line);
if (key != null && !trlKeys.containsKey(key)) {
final String en = ui_strings.getProperty(key);
if (en == null) {
System.err.println("Translation key `" + key
+ "` not found in ui-strings.properties");
ui_strings.put(key, "");
}
trlKeys.put(key, en);
if (!"".equals(en) && !enValues.contains(en)) {
enValues.add(en);
}
}
}
}
}
Collections.sort(enValues);
StringBuffer sb = new StringBuffer();
for (String val : enValues) {
sb.append(val).append(" = ").append(val).append("\n");
}
FileUtils.writeStringToFile(new File(sources,
"/translations/locale/en.properties"), sb.toString(), "UTF-8");
final List<String> tmp = new ArrayList<String>(trlKeys.keySet());
Collections.sort(tmp);
final StringBuffer uisource = new StringBuffer();
for (String ui : tmp) {
uisource.append(ui).append(" = ").append(trlKeys.get(ui))
.append("\n");
}
FileUtils.writeStringToFile(new File(sources,
"/translations/locale/ui-strings.properties"), uisource
.toString(), "UTF-8");
}
| public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.err.println("<Dashboard> directory is required");
return;
}
final File sources = new File(args[0]);
final Properties ui_strings = new Properties();
ui_strings.load(new FileInputStream(new File(sources,
"/translations/locale/ui-strings.properties")));
final Map<String, String> trlKeys = new HashMap<String, String>();
final List<String> enValues = new ArrayList<String>();
for (File f : (List<File>) FileUtils.listFiles(sources, EXTS, true)) {
if (f.getAbsolutePath().contains("vendor")) {
continue; // skipping
}
final List<String> lines = FileUtils.readLines(f, "UTF-8");
for (String line : lines) {
if (line.contains(HPREFIX) || line.contains(JSCALLPREFIX)) {
final String key = getKey(line);
if (key != null && !trlKeys.containsKey(key)) {
final String en = ui_strings.getProperty(key);
if (en == null) {
System.err.println("Translation key `" + key
+ "` not found in ui-strings.properties");
ui_strings.put(key, "");
}
trlKeys.put(key, (en == null ? "" : en));
if (en != null && !"".equals(en) && !enValues.contains(en)) {
enValues.add(en);
}
}
}
}
}
Collections.sort(enValues);
StringBuffer sb = new StringBuffer();
for (String val : enValues) {
sb.append(val).append(" = ").append(val).append("\n");
}
FileUtils.writeStringToFile(new File(sources,
"/translations/locale/en.properties"), sb.toString(), "UTF-8");
final List<String> tmp = new ArrayList<String>(trlKeys.keySet());
Collections.sort(tmp);
final StringBuffer uisource = new StringBuffer();
for (String ui : tmp) {
uisource.append(ui).append(" = ").append(trlKeys.get(ui))
.append("\n");
}
FileUtils.writeStringToFile(new File(sources,
"/translations/locale/ui-strings.properties"), uisource
.toString(), "UTF-8");
}
|
diff --git a/src/org/apache/xerces/impl/XMLNamespaceBinder.java b/src/org/apache/xerces/impl/XMLNamespaceBinder.java
index 49d2ae8da..ddcf03575 100644
--- a/src/org/apache/xerces/impl/XMLNamespaceBinder.java
+++ b/src/org/apache/xerces/impl/XMLNamespaceBinder.java
@@ -1,871 +1,875 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.impl;
import java.util.Enumeration;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.msg.XMLMessageFormatter;
import org.apache.xerces.util.NamespaceSupport;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
/**
* This class performs namespace binding on the startElement and endElement
* method calls and passes all other methods through to the registered
* document handler. This class can be configured to only pass the
* start and end prefix mappings (start/endPrefixMapping).
* <p>
* This component requires the following features and properties from the
* component manager that uses it:
* <ul>
* <li>http://xml.org/sax/features/namespaces</li>
* <li>http://apache.org/xml/properties/internal/symbol-table</li>
* <li>http://apache.org/xml/properties/internal/error-reporter</li>
* </ul>
*
* @author Andy Clark, IBM
*
* @version $Id$
*/
public class XMLNamespaceBinder
implements XMLComponent, XMLDocumentFilter {
//
// Constants
//
// feature identifiers
/** Feature identifier: namespaces. */
protected static final String NAMESPACES =
Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE;
// property identifiers
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
// recognized features and properties
/** Recognized features. */
protected static final String[] RECOGNIZED_FEATURES = {
NAMESPACES,
};
/** Recognized properties. */
protected static final String[] RECOGNIZED_PROPERTIES = {
SYMBOL_TABLE,
ERROR_REPORTER,
};
//
// Data
//
// features
/** Namespaces. */
protected boolean fNamespaces;
// properties
/** Symbol table. */
protected SymbolTable fSymbolTable;
/** Error reporter. */
protected XMLErrorReporter fErrorReporter;
// handlers
/** Document handler. */
protected XMLDocumentHandler fDocumentHandler;
// namespaces
/** Namespace support. */
protected NamespaceSupport fNamespaceSupport = new NamespaceSupport();
// settings
/** Only pass start and end prefix mapping events. */
protected boolean fOnlyPassPrefixMappingEvents;
// shared context
/** Namespace context. */
private NamespaceContext fNamespaceContext;
// temp vars
/** Attribute QName. */
private QName fAttributeQName = new QName();
// symbols
/** Symbol: "". */
private String fEmptySymbol;
/** Symbol: "xml". */
private String fXmlSymbol;
/** Symbol: "xmlns". */
private String fXmlnsSymbol;
//
// Constructors
//
/** Default constructor. */
public XMLNamespaceBinder() {
this(null);
} // <init>()
/**
* Constructs a namespace binder that shares the specified namespace
* context during each parse.
*
* @param namespaceContext The shared context.
*/
public XMLNamespaceBinder(NamespaceContext namespaceContext) {
fNamespaceContext = namespaceContext;
} // <init>(NamespaceContext)
//
// Public methods
//
/** Returns the current namespace context. */
public NamespaceContext getNamespaceContext() {
return fNamespaceSupport;
} // getNamespaceContext():NamespaceContext
// settings
/**
* Sets whether the namespace binder only passes the prefix mapping
* events to the registered document handler or passes all document
* events.
*
* @param onlyPassPrefixMappingEvents True to pass only the prefix
* mapping events; false to pass
* all events.
*/
public void setOnlyPassPrefixMappingEvents(boolean onlyPassPrefixMappingEvents) {
fOnlyPassPrefixMappingEvents = onlyPassPrefixMappingEvents;
} // setOnlyPassPrefixMappingEvents(boolean)
/**
* Returns true if the namespace binder only passes the prefix mapping
* events to the registered document handler; false if the namespace
* binder passes all document events.
*/
public boolean getOnlyPassPrefixMappingEvents() {
return fOnlyPassPrefixMappingEvents;
} // getOnlyPassPrefixMappingEvents():boolean
//
// XMLComponent methods
//
/**
* Resets the component. The component can query the component manager
* about any features and properties that affect the operation of the
* component.
*
* @param componentManager The component manager.
*
* @throws SAXException Thrown by component on initialization error.
* For example, if a feature or property is
* required for the operation of the component, the
* component manager may throw a
* SAXNotRecognizedException or a
* SAXNotSupportedException.
*/
public void reset(XMLComponentManager componentManager)
throws XNIException {
// features
try {
fNamespaces = componentManager.getFeature(NAMESPACES);
}
catch (XMLConfigurationException e) {
fNamespaces = true;
}
// Xerces properties
fSymbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE);
fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
// initialize vars
fNamespaceSupport.reset(fSymbolTable);
// save built-in entity names
fEmptySymbol = fSymbolTable.addSymbol("");
fXmlSymbol = fSymbolTable.addSymbol("xml");
fXmlnsSymbol = fSymbolTable.addSymbol("xmlns");
// use shared context
NamespaceContext context = fNamespaceContext;
while (context != null) {
int count = context.getDeclaredPrefixCount();
for (int i = 0; i < count; i++) {
String prefix = context.getDeclaredPrefixAt(i);
if (fNamespaceSupport.getURI(prefix) == null) {
String uri = context.getURI(prefix);
fNamespaceSupport.declarePrefix(prefix, uri);
}
}
context = context.getParentContext();
}
} // reset(XMLComponentManager)
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return RECOGNIZED_FEATURES;
} // getRecognizedFeatures():String[]
/**
* Sets the state of a feature. This method is called by the component
* manager any time after reset when a feature changes state.
* <p>
* <strong>Note:</strong> Components should silently ignore features
* that do not affect the operation of the component.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
} // setFeature(String,boolean)
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return RECOGNIZED_PROPERTIES;
} // getRecognizedProperties():String[]
/**
* Sets the value of a property during parsing.
*
* @param propertyId
* @param value
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
// Xerces properties
if (propertyId.startsWith(Constants.XERCES_PROPERTY_PREFIX)) {
String property =
propertyId.substring(Constants.XERCES_PROPERTY_PREFIX.length());
if (property.equals(Constants.SYMBOL_TABLE_PROPERTY)) {
fSymbolTable = (SymbolTable)value;
}
else if (property.equals(Constants.ERROR_REPORTER_PROPERTY)) {
fErrorReporter = (XMLErrorReporter)value;
}
return;
}
} // setProperty(String,Object)
//
// XMLDocumentSource methods
//
/**
* Sets the document handler to receive information about the document.
*
* @param documentHandler The document handler.
*/
public void setDocumentHandler(XMLDocumentHandler documentHandler) {
fDocumentHandler = documentHandler;
} // setDocumentHandler(XMLDocumentHandler)
//
// XMLDocumentHandler methods
//
/**
* This method notifies the start of a general entity.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the general entity.
* @param identifier The resource identifier.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal entities or a document entity that is
* parsed from a java.io.Reader).
* @param augs Additional information that may include infoset augmentations
*
* @exception XNIException Thrown by handler to signal an error.
*/
public void startGeneralEntity(String name,
XMLResourceIdentifier identifier,
String encoding, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.startGeneralEntity(name, identifier, encoding, augs);
}
} // startEntity(String,String,String,String,String)
/**
* Notifies of the presence of a TextDecl line in an entity. If present,
* this method will be called immediately following the startEntity call.
* <p>
* <strong>Note:</strong> This method will never be called for the
* document entity; it is only called for external general entities
* referenced in document content.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param version The XML version, or null if not specified.
* @param encoding The IANA encoding name of the entity.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void textDecl(String version, String encoding, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.textDecl(version, encoding, augs);
}
} // textDecl(String,String)
/**
* The start of the document.
*
* @param locator The system identifier of the entity if the entity
* is external, null otherwise.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal entities or a document entity that is
* parsed from a java.io.Reader).
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startDocument(XMLLocator locator, String encoding, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.startDocument(locator, encoding, augs);
}
} // startDocument(XMLLocator,String)
/**
* Notifies of the presence of an XMLDecl line in the document. If
* present, this method will be called immediately following the
* startDocument call.
*
* @param version The XML version.
* @param encoding The IANA encoding name of the document, or null if
* not specified.
* @param standalone The standalone value, or null if not specified.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void xmlDecl(String version, String encoding, String standalone, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.xmlDecl(version, encoding, standalone, augs);
}
} // xmlDecl(String,String,String)
/**
* Notifies of the presence of the DOCTYPE line in the document.
*
* @param rootElement The name of the root element.
* @param publicId The public identifier if an external DTD or null
* if the external DTD is specified using SYSTEM.
* @param systemId The system identifier if an external DTD, null
* otherwise.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void doctypeDecl(String rootElement,
String publicId, String systemId, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs);
}
} // doctypeDecl(String,String,String)
/**
* A comment.
*
* @param text The text in the comment.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by application to signal an error.
*/
public void comment(XMLString text, Augmentations augs) throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.comment(text, augs);
}
} // comment(XMLString)
/**
* A processing instruction. Processing instructions consist of a
* target name and, optionally, text data. The data is only meaningful
* to the application.
* <p>
* Typically, a processing instruction's data will contain a series
* of pseudo-attributes. These pseudo-attributes follow the form of
* element attributes but are <strong>not</strong> parsed or presented
* to the application as anything other than text. The application is
* responsible for parsing the data.
*
* @param target The target.
* @param data The data or null if none specified.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void processingInstruction(String target, XMLString data, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.processingInstruction(target, data, augs);
}
} // processingInstruction(String,XMLString)
/**
* The start of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
* @param uri The URI bound to the prefix.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startPrefixMapping(String prefix, String uri, Augmentations augs)
throws XNIException {
// REVISIT: Should prefix mapping from previous stage in
// the pipeline affect the namespaces?
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.startPrefixMapping(prefix, uri, augs);
}
} // startPrefixMapping(String,String)
/**
* Binds the namespaces. This method will handle calling the
* document handler to start the prefix mappings.
* <p>
* <strong>Note:</strong> This method makes use of the
* fAttributeQName variable. Any contents of the variable will
* be destroyed. Caller should copy the values out of this
* temporary variable before calling this method.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
if (fNamespaces) {
handleStartElement(element, attributes, augs, false);
}
else if (fDocumentHandler != null) {
fDocumentHandler.startElement(element, attributes, augs);
}
} // startElement(QName,XMLAttributes)
/**
* An empty element.
*
* @param element The name of the element.
* @param attributes The element attributes.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
if (fNamespaces) {
handleStartElement(element, attributes, augs, true);
handleEndElement(element, augs, true);
}
else if (fDocumentHandler != null) {
fDocumentHandler.emptyElement(element, attributes, augs);
}
} // emptyElement(QName,XMLAttributes)
/**
* Character content.
*
* @param text The content.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void characters(XMLString text, Augmentations augs) throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.characters(text, augs);
}
} // characters(XMLString)
/**
* Ignorable whitespace. For this method to be called, the document
* source must have some way of determining that the text containing
* only whitespace characters should be considered ignorable. For
* example, the validator can determine if a length of whitespace
* characters in the document are ignorable based on the element
* content model.
*
* @param text The ignorable whitespace.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.ignorableWhitespace(text, augs);
}
} // ignorableWhitespace(XMLString)
/**
* The end of an element.
*
* @param element The name of the element.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endElement(QName element, Augmentations augs) throws XNIException {
if (fNamespaces) {
handleEndElement(element, augs, false);
}
else if (fDocumentHandler != null) {
fDocumentHandler.endElement(element, augs);
}
} // endElement(QName)
/**
* The end of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endPrefixMapping(String prefix, Augmentations augs) throws XNIException {
// REVISIT: Should prefix mapping from previous stage in
// the pipeline affect the namespaces?
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.endPrefixMapping(prefix, augs);
}
} // endPrefixMapping(String)
/**
* The start of a CDATA section.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startCDATA(Augmentations augs) throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.startCDATA(augs);
}
} // startCDATA()
/**
* The end of a CDATA section.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endCDATA(Augmentations augs) throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.endCDATA(augs);
}
} // endCDATA()
/**
* The end of the document.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endDocument(Augmentations augs) throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.endDocument(augs);
}
} // endDocument()
/**
* This method notifies the end of a general entity.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the entity.
* @param augs Additional information that may include infoset augmentations
*
* @exception XNIException
* Thrown by handler to signal an error.
*/
public void endGeneralEntity(String name, Augmentations augs) throws XNIException {
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
fDocumentHandler.endGeneralEntity(name, augs);
}
} // endEntity(String)
//
// Protected methods
//
/** Handles start element. */
protected void handleStartElement(QName element, XMLAttributes attributes,
Augmentations augs,
boolean isEmpty) throws XNIException {
// add new namespace context
fNamespaceSupport.pushContext();
// search for new namespace bindings
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
String localpart = attributes.getLocalName(i);
String prefix = attributes.getPrefix(i);
if (prefix == fXmlnsSymbol || localpart == fXmlnsSymbol) {
// check for duplicates
prefix = localpart != fXmlnsSymbol ? localpart : fEmptySymbol;
String uri = attributes.getValue(i);
uri = fSymbolTable.addSymbol(uri);
// http://www.w3.org/TR/1999/REC-xml-names-19990114/#dt-prefix
// We should only report an error if there is a prefix,
// that is, the local part is not "xmlns". -SG
if (uri == fEmptySymbol && localpart != fXmlnsSymbol) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"EmptyPrefixedAttName",
new Object[]{attributes.getQName(i)},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
continue;
}
// declare prefix in context
fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null);
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.startPrefixMapping(prefix, uri, augs);
}
}
}
// bind the element
String prefix = element.prefix != null
? element.prefix : fEmptySymbol;
element.uri = fNamespaceSupport.getURI(prefix);
if (element.prefix == null && element.uri != null) {
element.prefix = fEmptySymbol;
}
if (element.prefix != null && element.uri == null) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"ElementPrefixUnbound",
new Object[]{element.prefix, element.rawname},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
// bind the attributes
for (int i = 0; i < length; i++) {
attributes.getName(i, fAttributeQName);
String aprefix = fAttributeQName.prefix != null
? fAttributeQName.prefix : fEmptySymbol;
String arawname = fAttributeQName.rawname;
if (aprefix == fXmlSymbol) {
fAttributeQName.uri = fNamespaceSupport.getURI(fXmlSymbol);
attributes.setName(i, fAttributeQName);
}
else if (arawname != fXmlnsSymbol && !arawname.startsWith("xmlns:")) {
if (aprefix != fEmptySymbol) {
fAttributeQName.uri = fNamespaceSupport.getURI(aprefix);
if (fAttributeQName.uri == null) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"AttributePrefixUnbound",
new Object[]{aprefix, arawname},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
attributes.setName(i, fAttributeQName);
}
}
}
// verify that duplicate attributes don't exist
// Example: <foo xmlns:a='NS' xmlns:b='NS' a:attr='v1' b:attr='v2'/>
int attrCount = attributes.getLength();
for (int i = 0; i < attrCount - 1; i++) {
String alocalpart = attributes.getLocalName(i);
String auri = attributes.getURI(i);
+ String arawName = attributes.getQName(i);
for (int j = i + 1; j < attrCount; j++) {
String blocalpart = attributes.getLocalName(j);
String buri = attributes.getURI(j);
+ String brawName = attributes.getQName(j);
if (alocalpart == blocalpart && auri == buri) {
- fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
- "AttributeNSNotUnique",
- new Object[]{element.rawname,alocalpart, auri},
- XMLErrorReporter.SEVERITY_FATAL_ERROR);
+ if ((arawName == brawName) || (!arawName.startsWith("xmlns") && !brawName.startsWith("xmlns"))) {
+ fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
+ "AttributeNSNotUnique",
+ new Object[]{element.rawname,alocalpart, auri},
+ XMLErrorReporter.SEVERITY_FATAL_ERROR);
+ }
}
}
}
// call handler
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
if (isEmpty) {
fDocumentHandler.emptyElement(element, attributes, augs);
}
else {
fDocumentHandler.startElement(element, attributes, augs);
}
}
} // handleStartElement(QName,XMLAttributes,boolean)
/** Handles end element. */
protected void handleEndElement(QName element, Augmentations augs, boolean isEmpty)
throws XNIException {
// bind element
String eprefix = element.prefix != null ? element.prefix : fEmptySymbol;
element.uri = fNamespaceSupport.getURI(eprefix);
if (element.uri != null) {
element.prefix = eprefix;
}
// call handlers
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
if (!isEmpty) {
fDocumentHandler.endElement(element, augs);
}
}
// end prefix mappings
if (fDocumentHandler != null) {
int count = fNamespaceSupport.getDeclaredPrefixCount();
for (int i = count - 1; i >= 0; i--) {
String prefix = fNamespaceSupport.getDeclaredPrefixAt(i);
fDocumentHandler.endPrefixMapping(prefix, augs);
}
}
// pop context
fNamespaceSupport.popContext();
} // handleEndElement(QName,boolean)
} // class XMLNamespaceBinder
| false | true | protected void handleStartElement(QName element, XMLAttributes attributes,
Augmentations augs,
boolean isEmpty) throws XNIException {
// add new namespace context
fNamespaceSupport.pushContext();
// search for new namespace bindings
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
String localpart = attributes.getLocalName(i);
String prefix = attributes.getPrefix(i);
if (prefix == fXmlnsSymbol || localpart == fXmlnsSymbol) {
// check for duplicates
prefix = localpart != fXmlnsSymbol ? localpart : fEmptySymbol;
String uri = attributes.getValue(i);
uri = fSymbolTable.addSymbol(uri);
// http://www.w3.org/TR/1999/REC-xml-names-19990114/#dt-prefix
// We should only report an error if there is a prefix,
// that is, the local part is not "xmlns". -SG
if (uri == fEmptySymbol && localpart != fXmlnsSymbol) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"EmptyPrefixedAttName",
new Object[]{attributes.getQName(i)},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
continue;
}
// declare prefix in context
fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null);
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.startPrefixMapping(prefix, uri, augs);
}
}
}
// bind the element
String prefix = element.prefix != null
? element.prefix : fEmptySymbol;
element.uri = fNamespaceSupport.getURI(prefix);
if (element.prefix == null && element.uri != null) {
element.prefix = fEmptySymbol;
}
if (element.prefix != null && element.uri == null) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"ElementPrefixUnbound",
new Object[]{element.prefix, element.rawname},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
// bind the attributes
for (int i = 0; i < length; i++) {
attributes.getName(i, fAttributeQName);
String aprefix = fAttributeQName.prefix != null
? fAttributeQName.prefix : fEmptySymbol;
String arawname = fAttributeQName.rawname;
if (aprefix == fXmlSymbol) {
fAttributeQName.uri = fNamespaceSupport.getURI(fXmlSymbol);
attributes.setName(i, fAttributeQName);
}
else if (arawname != fXmlnsSymbol && !arawname.startsWith("xmlns:")) {
if (aprefix != fEmptySymbol) {
fAttributeQName.uri = fNamespaceSupport.getURI(aprefix);
if (fAttributeQName.uri == null) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"AttributePrefixUnbound",
new Object[]{aprefix, arawname},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
attributes.setName(i, fAttributeQName);
}
}
}
// verify that duplicate attributes don't exist
// Example: <foo xmlns:a='NS' xmlns:b='NS' a:attr='v1' b:attr='v2'/>
int attrCount = attributes.getLength();
for (int i = 0; i < attrCount - 1; i++) {
String alocalpart = attributes.getLocalName(i);
String auri = attributes.getURI(i);
for (int j = i + 1; j < attrCount; j++) {
String blocalpart = attributes.getLocalName(j);
String buri = attributes.getURI(j);
if (alocalpart == blocalpart && auri == buri) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"AttributeNSNotUnique",
new Object[]{element.rawname,alocalpart, auri},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
}
}
// call handler
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
if (isEmpty) {
fDocumentHandler.emptyElement(element, attributes, augs);
}
else {
fDocumentHandler.startElement(element, attributes, augs);
}
}
} // handleStartElement(QName,XMLAttributes,boolean)
| protected void handleStartElement(QName element, XMLAttributes attributes,
Augmentations augs,
boolean isEmpty) throws XNIException {
// add new namespace context
fNamespaceSupport.pushContext();
// search for new namespace bindings
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
String localpart = attributes.getLocalName(i);
String prefix = attributes.getPrefix(i);
if (prefix == fXmlnsSymbol || localpart == fXmlnsSymbol) {
// check for duplicates
prefix = localpart != fXmlnsSymbol ? localpart : fEmptySymbol;
String uri = attributes.getValue(i);
uri = fSymbolTable.addSymbol(uri);
// http://www.w3.org/TR/1999/REC-xml-names-19990114/#dt-prefix
// We should only report an error if there is a prefix,
// that is, the local part is not "xmlns". -SG
if (uri == fEmptySymbol && localpart != fXmlnsSymbol) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"EmptyPrefixedAttName",
new Object[]{attributes.getQName(i)},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
continue;
}
// declare prefix in context
fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null);
// call handler
if (fDocumentHandler != null) {
fDocumentHandler.startPrefixMapping(prefix, uri, augs);
}
}
}
// bind the element
String prefix = element.prefix != null
? element.prefix : fEmptySymbol;
element.uri = fNamespaceSupport.getURI(prefix);
if (element.prefix == null && element.uri != null) {
element.prefix = fEmptySymbol;
}
if (element.prefix != null && element.uri == null) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"ElementPrefixUnbound",
new Object[]{element.prefix, element.rawname},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
// bind the attributes
for (int i = 0; i < length; i++) {
attributes.getName(i, fAttributeQName);
String aprefix = fAttributeQName.prefix != null
? fAttributeQName.prefix : fEmptySymbol;
String arawname = fAttributeQName.rawname;
if (aprefix == fXmlSymbol) {
fAttributeQName.uri = fNamespaceSupport.getURI(fXmlSymbol);
attributes.setName(i, fAttributeQName);
}
else if (arawname != fXmlnsSymbol && !arawname.startsWith("xmlns:")) {
if (aprefix != fEmptySymbol) {
fAttributeQName.uri = fNamespaceSupport.getURI(aprefix);
if (fAttributeQName.uri == null) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"AttributePrefixUnbound",
new Object[]{aprefix, arawname},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
attributes.setName(i, fAttributeQName);
}
}
}
// verify that duplicate attributes don't exist
// Example: <foo xmlns:a='NS' xmlns:b='NS' a:attr='v1' b:attr='v2'/>
int attrCount = attributes.getLength();
for (int i = 0; i < attrCount - 1; i++) {
String alocalpart = attributes.getLocalName(i);
String auri = attributes.getURI(i);
String arawName = attributes.getQName(i);
for (int j = i + 1; j < attrCount; j++) {
String blocalpart = attributes.getLocalName(j);
String buri = attributes.getURI(j);
String brawName = attributes.getQName(j);
if (alocalpart == blocalpart && auri == buri) {
if ((arawName == brawName) || (!arawName.startsWith("xmlns") && !brawName.startsWith("xmlns"))) {
fErrorReporter.reportError(XMLMessageFormatter.XMLNS_DOMAIN,
"AttributeNSNotUnique",
new Object[]{element.rawname,alocalpart, auri},
XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
}
}
}
// call handler
if (fDocumentHandler != null && !fOnlyPassPrefixMappingEvents) {
if (isEmpty) {
fDocumentHandler.emptyElement(element, attributes, augs);
}
else {
fDocumentHandler.startElement(element, attributes, augs);
}
}
} // handleStartElement(QName,XMLAttributes,boolean)
|
diff --git a/src/org/geworkbench/parsers/TabDelimitedDataMatrixFileFormat.java b/src/org/geworkbench/parsers/TabDelimitedDataMatrixFileFormat.java
index 71da69d4..d137e912 100755
--- a/src/org/geworkbench/parsers/TabDelimitedDataMatrixFileFormat.java
+++ b/src/org/geworkbench/parsers/TabDelimitedDataMatrixFileFormat.java
@@ -1,482 +1,478 @@
package org.geworkbench.parsers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.ProgressMonitorInputStream;
import javax.swing.filechooser.FileFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.bison.datastructure.biocollections.DSDataSet;
import org.geworkbench.bison.datastructure.biocollections.microarrays.CSMicroarraySet;
import org.geworkbench.bison.datastructure.biocollections.microarrays.DSMicroarraySet;
import org.geworkbench.bison.datastructure.bioobjects.DSBioObject;
import org.geworkbench.bison.datastructure.bioobjects.markers.CSExpressionMarker;
import org.geworkbench.bison.datastructure.bioobjects.markers.DSGeneMarker;
import org.geworkbench.bison.datastructure.bioobjects.markers.annotationparser.AnnotationParser;
import org.geworkbench.bison.datastructure.bioobjects.microarray.CSExpressionMarkerValue;
import org.geworkbench.bison.datastructure.bioobjects.microarray.CSMicroarray;
import org.geworkbench.bison.datastructure.bioobjects.microarray.DSMicroarray;
import org.geworkbench.bison.parsers.resources.Resource;
/**
* Sequence and Pattern Plugin
*
* @author yc2480
* @version $Id$
*
*/
public class TabDelimitedDataMatrixFileFormat extends DataSetFileFormat {
static Log log = LogFactory.getLog(TabDelimitedDataMatrixFileFormat.class);
private static final String commentSign1 = "#";
private static final String commentSign2 = "!";
private static final String columnSeperator = "\t";
private static final String lineSeperator = "\n";
private static final String[] maExtensions = { "txt", "tsv" };
private static final String duplicateLabelModificator = "_2";
ExpressionResource resource = new ExpressionResource();
TabDelimitedFilter maFilter = null;
private int possibleMarkers = 0;
/**
*
*/
public TabDelimitedDataMatrixFileFormat() {
formatName = "Tab-Delimited Data Matrix";
maFilter = new TabDelimitedFilter();
Arrays.sort(maExtensions);
}
/*
* (non-Javadoc)
*
* @see org.geworkbench.components.parsers.FileFormat#getResource(java.io.File)
*/
public Resource getResource(File file) {
try {
resource.setReader(new BufferedReader(new FileReader(file)));
resource.setInputFileName(file.getName());
} catch (IOException ioe) {
ioe.printStackTrace(System.err);
}
return resource;
}
/*
* (non-Javadoc)
*
* @see org.geworkbench.components.parsers.FileFormat#getFileExtensions()
*/
public String[] getFileExtensions() {
return maExtensions;
}
/*
* (non-Javadoc)
*
* @see org.geworkbench.components.parsers.FileFormat#checkFormat(java.io.File)
* FIXME In here we should also check (among other things) that: The
* values of the data points respect their expected type. IMPORTANT!
* After Mantis #1551, this step will be required even if you don't
* want to checkFormat.
*/
public boolean checkFormat(File file) throws InterruptedIOException {
boolean columnsMatch = true;
boolean noDuplicateMarkers = true;
boolean noDuplicateArrays = true;
BufferedReader reader = null;
ProgressMonitorInputStream progressIn = null;
try {
FileInputStream fileIn = new FileInputStream(file);
progressIn = new ProgressMonitorInputStream(
null, "Checking File Format", fileIn);
reader = new BufferedReader(new InputStreamReader(
progressIn));
String line = null;
int totalColumns = 0;
List<String> markers = new ArrayList<String>();
List<String> arrays = new ArrayList<String>();
int lineIndex = 0;
int headerLineIndex = 0;
while ((line = reader.readLine()) != null) { // for each line
if ((line.indexOf(commentSign1) < 0)
&& (line.indexOf(commentSign2) != 0)
&& (line.length() > 0)) {// we'll skip comments and
// anything before header
if (headerLineIndex == 0)// no header detected yet, then
// this is the header.
headerLineIndex = lineIndex;
String token = null;
int columnIndex = 0;
int accessionIndex = 0;
StringTokenizer st = new StringTokenizer(line,
columnSeperator + lineSeperator);
while (st.hasMoreTokens()) { // for each column
token = st.nextToken().trim();
if (token.equals("")) {// header
accessionIndex = columnIndex;
} else if ((headerLineIndex > 0) && (columnIndex == 0)) {
/*
* if this line is after header, then first column
* should be our marker name
*/
if (markers.contains(token)) {// duplicate markers
noDuplicateMarkers = false;
log.error("Duplicate Markers: "+token);
return false;
} else {
markers.add(token);
}
} else if (headerLineIndex == lineIndex) {
/*
* this is header line
*/
if (arrays.contains(token)) {// duplicate arrays
noDuplicateArrays = false;
log.error("Duplicate Arrays labels " + token
+ " in " + file.getName());
return false;
} else {
arrays.add(token);
}
}
columnIndex++;
lineIndex++;
}
/* check if column match or not */
if (headerLineIndex > 0) {
/*
* if this line is real data, we assume lines after
* header are real data. (we might have bug here)
*/
if (totalColumns == 0) /* not been set yet */
totalColumns = columnIndex - accessionIndex;
else if (columnIndex != totalColumns)// if not equal
columnsMatch = false;
}
}
}
possibleMarkers = markers.size();
fileIn.close();
} catch (java.io.InterruptedIOException ie) {
if ( progressIn.getProgressMonitor().isCanceled())
{
throw ie;
}
else
ie.printStackTrace();
} catch (Exception e) {
log.error(formatName+" file format exception: " + e);
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
log.error(formatName+" file reader close exception: " + e);
e.printStackTrace();
}
}
if (columnsMatch && noDuplicateMarkers && noDuplicateArrays)
return true;
else
return false;
}
/*
* (non-Javadoc)
*
* @see org.geworkbench.components.parsers.microarray.DataSetFileFormat#getDataFile(java.io.File)
*/
public DSDataSet<? extends DSBioObject> getDataFile(File file) throws InputFileFormatException, InterruptedIOException{
return (DSDataSet<? extends DSBioObject>) getMArraySet(file);
}
/*
* (non-Javadoc)
*
* @see org.geworkbench.components.parsers.FileFormat#getMArraySet(java.io.File)
*/
private CSMicroarraySet getMArraySet(File file)
throws InputFileFormatException, InterruptedIOException {
/* the sign between file name and extesion, ex: file.ext */
final int extSeperater = '.';
try
{
if (!checkFormat(file)) {
log
.info("TabDelimitedDataMatrixFileFormat::getMArraySet - "
+ "Attempting to open a file that does not comply with the "
+ "Tab-Delimited Data Matrix file format.");
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the "
+ "Tab-Delimited Data Matrix file format.");
}
} catch (InterruptedIOException ie) {
throw ie;
}
CSMicroarraySet maSet = new CSMicroarraySet();
- String fileName = file.getName();
- int dotIndex = fileName.lastIndexOf(extSeperater);
- if (dotIndex != -1) {
- fileName = fileName.substring(0, dotIndex);
- }
+ String fileName = file.getName();
maSet.setLabel(fileName);
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
if (in != null) {
String header = in.readLine();
if (header == null) {
throw new InputFileFormatException("File is empty.");
}
while (header != null
&& (header.startsWith(commentSign1) || header
.startsWith(commentSign2))
|| StringUtils.isEmpty(header)) {
header = in.readLine();
}
if (header == null) {
throw new InputFileFormatException(
"File is empty or consists of only comments.\n"
+ formatName+" format expected");
}
/* for mantis issue:1349 */
header = StringUtils.replace(header, "\"", "");
StringTokenizer headerTokenizer = new StringTokenizer(header,
columnSeperator, false);
int n = headerTokenizer.countTokens();
if (n <= 1) {
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the Tab-Delimited Data Matrix format.\n"
+ "Invalid header: " + header);
}
n -= 1;
String line = in.readLine();
line = StringUtils.replace(line, "\"", "");
int m = 0;
/* Skip first token */
headerTokenizer.nextToken();
int duplicateLabels = 0;
for (int i = 0; i < n; i++) {
String arrayName = headerTokenizer.nextToken();
CSMicroarray array = new CSMicroarray(i, possibleMarkers,
arrayName,
DSMicroarraySet.affyTxtType);
maSet.add(array);
/*
* FIXME: this will only fix one duplicate per unique label.
* should handle unlimited duplicate.
*/
if (maSet.size() != (i + 1)) {
log.info("We got a duplicate label of array");
array.setLabel(array.getLabel()
+ duplicateLabelModificator);
maSet.add(array);
duplicateLabels++;
}
}
while ((line != null) // modified for mantis issue: 1349
&& (!StringUtils.isEmpty(line))
&& (!line.trim().startsWith(commentSign2))) {
String[] tokens = line.split(columnSeperator);
int length = tokens.length;
if (length != (n + 1)) {
log.error("Warning: Could not parse line #" + (m + 1)
+ ". Line should have " + (n + 1)
+ " lines, has " + length + ".");
if ((m == 0) && (length == n + 2))
// TODO Is this file from R's RMA, without first
// column in header?
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the "
+ formatName+ " format."
+ "\n"
+ "Warning: Could not parse line #"
+ (m + 1)
+ ". Line should have "
+ (n + 1)
+ " columns, but it has "
+ length
+ ".\n"
+ "This file looks like R's RMA format, which needs manually add a tab in the beginning of the header to make it a valid RMA format.");
else
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the "
+ formatName+" format." + "\n"
+ "Warning: Could not parse line #"
+ (m + 1) + ". Line should have "
+ (n + 1) + " columns, but it has "
+ length + ".");
}
String markerName = new String(tokens[0].trim());
CSExpressionMarker marker = new CSExpressionMarker(m);
marker.setLabel(markerName);
maSet.getMarkerVector().add(m, marker);
for (int i = 0; i < n; i++) {
String valString = "";
if ((i + 1) < tokens.length) {
valString = tokens[i + 1];
}
if (valString.trim().length() == 0) {
// put values directly into CSMicroarray inside of
// maSet
Float v = Float.NaN;
CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(
v);
DSMicroarray microarray = (DSMicroarray)maSet.get(i);
microarray.setMarkerValue(m, markerValue);
if (v.isNaN()) {
markerValue.setMissing(true);
} else {
markerValue.setPresent();
}
} else {
float value = Float.NaN;
try {
value = Float.parseFloat(valString);
} catch (NumberFormatException nfe) {
log.info("We expect a number, but we got: "
+ valString);
}
// put values directly into CSMicroarray inside of
// maSet
Float v = value;
CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(
v);
try {
DSMicroarray microarray = (DSMicroarray)maSet.get(i);
microarray.setMarkerValue(m, markerValue);
} catch (IndexOutOfBoundsException ioobe) {
log.error("i=" + i + ", m=" + m);
}
if (v.isNaN()) {
markerValue.setMissing(true);
} else {
markerValue.setPresent();
}
}
}
m++;
line = in.readLine();
line = StringUtils.replace(line, "\"", "");
}
// Set chip-type
String result = null;
for (int i = 0; i < m; i++) {
result = AnnotationParser.matchChipType(maSet, maSet
.getMarkerVector().get(i).getLabel(), false);
if (result != null) {
break;
}
}
if (result == null) {
AnnotationParser.matchChipType(maSet, "Unknown", true);
} else {
maSet.setCompatibilityLabel(result);
}
for (DSGeneMarker marker : maSet.getMarkerVector()) {
String token = marker.getLabel();
String[] locusResult = AnnotationParser.getInfo(token,
AnnotationParser.LOCUSLINK);
String locus = "";
if ((locusResult != null)
&& (!locusResult[0].trim().equals(""))) {
locus = locusResult[0].trim();
}
if (locus.compareTo("") != 0) {
try {
marker.setGeneId(Integer.parseInt(locus));
} catch (NumberFormatException e) {
log.info("Couldn't parse locus id: " + locus);
}
}
String[] geneNames = AnnotationParser.getInfo(token,
AnnotationParser.ABREV);
if (geneNames != null) {
marker.setGeneName(geneNames[0]);
}
marker.getUnigene().set(token);
}
}
} catch (InputFileFormatException e) {
throw e;
} catch (InterruptedIOException ie) {
throw ie;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return maSet;
}
/*
* (non-Javadoc)
*
* @see org.geworkbench.components.parsers.FileFormat#getFileFilter()
*/
public FileFilter getFileFilter() {
return maFilter;
}
/*
* (non-Javadoc)
*
* @see org.geworkbench.components.parsers.microarray.DataSetFileFormat#getDataFile(java.io.File[])
*/
public DSDataSet<? extends DSBioObject> getDataFile(File[] files) {
// org.geworkbench.components.parsers.microarray.DataSetFileFormat
// abstract method
throw new UnsupportedOperationException(
"Method getDataFile(File[] files) not yet implemented.");
}
private class TabDelimitedFilter extends FileFilter {
public String getDescription() {
return getFormatName();
}
public boolean accept(File f) {
boolean returnVal = false;
for (int i = 0; i < maExtensions.length; ++i)
if (f.isDirectory() || f.getName().toLowerCase().endsWith(maExtensions[i])) {
return true;
}
return returnVal;
}
}
}
| true | true | private CSMicroarraySet getMArraySet(File file)
throws InputFileFormatException, InterruptedIOException {
/* the sign between file name and extesion, ex: file.ext */
final int extSeperater = '.';
try
{
if (!checkFormat(file)) {
log
.info("TabDelimitedDataMatrixFileFormat::getMArraySet - "
+ "Attempting to open a file that does not comply with the "
+ "Tab-Delimited Data Matrix file format.");
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the "
+ "Tab-Delimited Data Matrix file format.");
}
} catch (InterruptedIOException ie) {
throw ie;
}
CSMicroarraySet maSet = new CSMicroarraySet();
String fileName = file.getName();
int dotIndex = fileName.lastIndexOf(extSeperater);
if (dotIndex != -1) {
fileName = fileName.substring(0, dotIndex);
}
maSet.setLabel(fileName);
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
if (in != null) {
String header = in.readLine();
if (header == null) {
throw new InputFileFormatException("File is empty.");
}
while (header != null
&& (header.startsWith(commentSign1) || header
.startsWith(commentSign2))
|| StringUtils.isEmpty(header)) {
header = in.readLine();
}
if (header == null) {
throw new InputFileFormatException(
"File is empty or consists of only comments.\n"
+ formatName+" format expected");
}
/* for mantis issue:1349 */
header = StringUtils.replace(header, "\"", "");
StringTokenizer headerTokenizer = new StringTokenizer(header,
columnSeperator, false);
int n = headerTokenizer.countTokens();
if (n <= 1) {
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the Tab-Delimited Data Matrix format.\n"
+ "Invalid header: " + header);
}
n -= 1;
String line = in.readLine();
line = StringUtils.replace(line, "\"", "");
int m = 0;
/* Skip first token */
headerTokenizer.nextToken();
int duplicateLabels = 0;
for (int i = 0; i < n; i++) {
String arrayName = headerTokenizer.nextToken();
CSMicroarray array = new CSMicroarray(i, possibleMarkers,
arrayName,
DSMicroarraySet.affyTxtType);
maSet.add(array);
/*
* FIXME: this will only fix one duplicate per unique label.
* should handle unlimited duplicate.
*/
if (maSet.size() != (i + 1)) {
log.info("We got a duplicate label of array");
array.setLabel(array.getLabel()
+ duplicateLabelModificator);
maSet.add(array);
duplicateLabels++;
}
}
while ((line != null) // modified for mantis issue: 1349
&& (!StringUtils.isEmpty(line))
&& (!line.trim().startsWith(commentSign2))) {
String[] tokens = line.split(columnSeperator);
int length = tokens.length;
if (length != (n + 1)) {
log.error("Warning: Could not parse line #" + (m + 1)
+ ". Line should have " + (n + 1)
+ " lines, has " + length + ".");
if ((m == 0) && (length == n + 2))
// TODO Is this file from R's RMA, without first
// column in header?
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the "
+ formatName+ " format."
+ "\n"
+ "Warning: Could not parse line #"
+ (m + 1)
+ ". Line should have "
+ (n + 1)
+ " columns, but it has "
+ length
+ ".\n"
+ "This file looks like R's RMA format, which needs manually add a tab in the beginning of the header to make it a valid RMA format.");
else
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the "
+ formatName+" format." + "\n"
+ "Warning: Could not parse line #"
+ (m + 1) + ". Line should have "
+ (n + 1) + " columns, but it has "
+ length + ".");
}
String markerName = new String(tokens[0].trim());
CSExpressionMarker marker = new CSExpressionMarker(m);
marker.setLabel(markerName);
maSet.getMarkerVector().add(m, marker);
for (int i = 0; i < n; i++) {
String valString = "";
if ((i + 1) < tokens.length) {
valString = tokens[i + 1];
}
if (valString.trim().length() == 0) {
// put values directly into CSMicroarray inside of
// maSet
Float v = Float.NaN;
CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(
v);
DSMicroarray microarray = (DSMicroarray)maSet.get(i);
microarray.setMarkerValue(m, markerValue);
if (v.isNaN()) {
markerValue.setMissing(true);
} else {
markerValue.setPresent();
}
} else {
float value = Float.NaN;
try {
value = Float.parseFloat(valString);
} catch (NumberFormatException nfe) {
log.info("We expect a number, but we got: "
+ valString);
}
// put values directly into CSMicroarray inside of
// maSet
Float v = value;
CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(
v);
try {
DSMicroarray microarray = (DSMicroarray)maSet.get(i);
microarray.setMarkerValue(m, markerValue);
} catch (IndexOutOfBoundsException ioobe) {
log.error("i=" + i + ", m=" + m);
}
if (v.isNaN()) {
markerValue.setMissing(true);
} else {
markerValue.setPresent();
}
}
}
m++;
line = in.readLine();
line = StringUtils.replace(line, "\"", "");
}
// Set chip-type
String result = null;
for (int i = 0; i < m; i++) {
result = AnnotationParser.matchChipType(maSet, maSet
.getMarkerVector().get(i).getLabel(), false);
if (result != null) {
break;
}
}
if (result == null) {
AnnotationParser.matchChipType(maSet, "Unknown", true);
} else {
maSet.setCompatibilityLabel(result);
}
for (DSGeneMarker marker : maSet.getMarkerVector()) {
String token = marker.getLabel();
String[] locusResult = AnnotationParser.getInfo(token,
AnnotationParser.LOCUSLINK);
String locus = "";
if ((locusResult != null)
&& (!locusResult[0].trim().equals(""))) {
locus = locusResult[0].trim();
}
if (locus.compareTo("") != 0) {
try {
marker.setGeneId(Integer.parseInt(locus));
} catch (NumberFormatException e) {
log.info("Couldn't parse locus id: " + locus);
}
}
String[] geneNames = AnnotationParser.getInfo(token,
AnnotationParser.ABREV);
if (geneNames != null) {
marker.setGeneName(geneNames[0]);
}
marker.getUnigene().set(token);
}
}
} catch (InputFileFormatException e) {
throw e;
} catch (InterruptedIOException ie) {
throw ie;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return maSet;
}
| private CSMicroarraySet getMArraySet(File file)
throws InputFileFormatException, InterruptedIOException {
/* the sign between file name and extesion, ex: file.ext */
final int extSeperater = '.';
try
{
if (!checkFormat(file)) {
log
.info("TabDelimitedDataMatrixFileFormat::getMArraySet - "
+ "Attempting to open a file that does not comply with the "
+ "Tab-Delimited Data Matrix file format.");
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the "
+ "Tab-Delimited Data Matrix file format.");
}
} catch (InterruptedIOException ie) {
throw ie;
}
CSMicroarraySet maSet = new CSMicroarraySet();
String fileName = file.getName();
maSet.setLabel(fileName);
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
if (in != null) {
String header = in.readLine();
if (header == null) {
throw new InputFileFormatException("File is empty.");
}
while (header != null
&& (header.startsWith(commentSign1) || header
.startsWith(commentSign2))
|| StringUtils.isEmpty(header)) {
header = in.readLine();
}
if (header == null) {
throw new InputFileFormatException(
"File is empty or consists of only comments.\n"
+ formatName+" format expected");
}
/* for mantis issue:1349 */
header = StringUtils.replace(header, "\"", "");
StringTokenizer headerTokenizer = new StringTokenizer(header,
columnSeperator, false);
int n = headerTokenizer.countTokens();
if (n <= 1) {
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the Tab-Delimited Data Matrix format.\n"
+ "Invalid header: " + header);
}
n -= 1;
String line = in.readLine();
line = StringUtils.replace(line, "\"", "");
int m = 0;
/* Skip first token */
headerTokenizer.nextToken();
int duplicateLabels = 0;
for (int i = 0; i < n; i++) {
String arrayName = headerTokenizer.nextToken();
CSMicroarray array = new CSMicroarray(i, possibleMarkers,
arrayName,
DSMicroarraySet.affyTxtType);
maSet.add(array);
/*
* FIXME: this will only fix one duplicate per unique label.
* should handle unlimited duplicate.
*/
if (maSet.size() != (i + 1)) {
log.info("We got a duplicate label of array");
array.setLabel(array.getLabel()
+ duplicateLabelModificator);
maSet.add(array);
duplicateLabels++;
}
}
while ((line != null) // modified for mantis issue: 1349
&& (!StringUtils.isEmpty(line))
&& (!line.trim().startsWith(commentSign2))) {
String[] tokens = line.split(columnSeperator);
int length = tokens.length;
if (length != (n + 1)) {
log.error("Warning: Could not parse line #" + (m + 1)
+ ". Line should have " + (n + 1)
+ " lines, has " + length + ".");
if ((m == 0) && (length == n + 2))
// TODO Is this file from R's RMA, without first
// column in header?
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the "
+ formatName+ " format."
+ "\n"
+ "Warning: Could not parse line #"
+ (m + 1)
+ ". Line should have "
+ (n + 1)
+ " columns, but it has "
+ length
+ ".\n"
+ "This file looks like R's RMA format, which needs manually add a tab in the beginning of the header to make it a valid RMA format.");
else
throw new InputFileFormatException(
"Attempting to open a file that does not comply with the "
+ formatName+" format." + "\n"
+ "Warning: Could not parse line #"
+ (m + 1) + ". Line should have "
+ (n + 1) + " columns, but it has "
+ length + ".");
}
String markerName = new String(tokens[0].trim());
CSExpressionMarker marker = new CSExpressionMarker(m);
marker.setLabel(markerName);
maSet.getMarkerVector().add(m, marker);
for (int i = 0; i < n; i++) {
String valString = "";
if ((i + 1) < tokens.length) {
valString = tokens[i + 1];
}
if (valString.trim().length() == 0) {
// put values directly into CSMicroarray inside of
// maSet
Float v = Float.NaN;
CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(
v);
DSMicroarray microarray = (DSMicroarray)maSet.get(i);
microarray.setMarkerValue(m, markerValue);
if (v.isNaN()) {
markerValue.setMissing(true);
} else {
markerValue.setPresent();
}
} else {
float value = Float.NaN;
try {
value = Float.parseFloat(valString);
} catch (NumberFormatException nfe) {
log.info("We expect a number, but we got: "
+ valString);
}
// put values directly into CSMicroarray inside of
// maSet
Float v = value;
CSExpressionMarkerValue markerValue = new CSExpressionMarkerValue(
v);
try {
DSMicroarray microarray = (DSMicroarray)maSet.get(i);
microarray.setMarkerValue(m, markerValue);
} catch (IndexOutOfBoundsException ioobe) {
log.error("i=" + i + ", m=" + m);
}
if (v.isNaN()) {
markerValue.setMissing(true);
} else {
markerValue.setPresent();
}
}
}
m++;
line = in.readLine();
line = StringUtils.replace(line, "\"", "");
}
// Set chip-type
String result = null;
for (int i = 0; i < m; i++) {
result = AnnotationParser.matchChipType(maSet, maSet
.getMarkerVector().get(i).getLabel(), false);
if (result != null) {
break;
}
}
if (result == null) {
AnnotationParser.matchChipType(maSet, "Unknown", true);
} else {
maSet.setCompatibilityLabel(result);
}
for (DSGeneMarker marker : maSet.getMarkerVector()) {
String token = marker.getLabel();
String[] locusResult = AnnotationParser.getInfo(token,
AnnotationParser.LOCUSLINK);
String locus = "";
if ((locusResult != null)
&& (!locusResult[0].trim().equals(""))) {
locus = locusResult[0].trim();
}
if (locus.compareTo("") != 0) {
try {
marker.setGeneId(Integer.parseInt(locus));
} catch (NumberFormatException e) {
log.info("Couldn't parse locus id: " + locus);
}
}
String[] geneNames = AnnotationParser.getInfo(token,
AnnotationParser.ABREV);
if (geneNames != null) {
marker.setGeneName(geneNames[0]);
}
marker.getUnigene().set(token);
}
}
} catch (InputFileFormatException e) {
throw e;
} catch (InterruptedIOException ie) {
throw ie;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return maSet;
}
|
diff --git a/SGDE-Dialogue/src/sgde/dialogue/DialogueMap.java b/SGDE-Dialogue/src/sgde/dialogue/DialogueMap.java
index f55044a..55e1541 100644
--- a/SGDE-Dialogue/src/sgde/dialogue/DialogueMap.java
+++ b/SGDE-Dialogue/src/sgde/dialogue/DialogueMap.java
@@ -1,66 +1,68 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sgde.dialogue;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author kdsweenx
*/
public class DialogueMap {
public static int END=Integer.MAX_VALUE;
ArrayList<DialogueOption> map;
public DialogueMap(String text) throws FileNotFoundException, IncorrectFormatException{
Scanner reader=new Scanner(new File(text));
DialogueOption DO=null;
while(reader.hasNext()){
String line=reader.next();
if(line.startsWith("$")){
DO=new DialogueOption(grabNum(line));
}
else if(line.contains("#")){
DO.addText(getMText(line));
}else if(line.contains("@")){
DO.addPC(getGoTo(line), getPCString(line));
+ }else if(line.contains("}") && line.length()<3){
+ map.add(DO.place, DO);
}
//Need something to make it look not bad
}
//done?
}
private int grabNum(String n){
int s=n.indexOf("$");
if(n.contains("START")){
return 0;
}
return Integer.parseInt(n.substring(s+1,n.indexOf("=")));
}
private String getMText(String ln){
return ln.substring(ln.indexOf("="+1),ln.indexOf(";"));
}
private int getGoTo(String ln){
String line=ln.substring(ln.indexOf(">")+1,ln.indexOf(";"));
if(line.contains("END")){
return END;
}
return Integer.parseInt(line);
}
private String getPCString(String ln){
return ln.substring(ln.indexOf("{")+1,ln.indexOf(";"));
}
}
| true | true | public DialogueMap(String text) throws FileNotFoundException, IncorrectFormatException{
Scanner reader=new Scanner(new File(text));
DialogueOption DO=null;
while(reader.hasNext()){
String line=reader.next();
if(line.startsWith("$")){
DO=new DialogueOption(grabNum(line));
}
else if(line.contains("#")){
DO.addText(getMText(line));
}else if(line.contains("@")){
DO.addPC(getGoTo(line), getPCString(line));
}
//Need something to make it look not bad
}
//done?
}
| public DialogueMap(String text) throws FileNotFoundException, IncorrectFormatException{
Scanner reader=new Scanner(new File(text));
DialogueOption DO=null;
while(reader.hasNext()){
String line=reader.next();
if(line.startsWith("$")){
DO=new DialogueOption(grabNum(line));
}
else if(line.contains("#")){
DO.addText(getMText(line));
}else if(line.contains("@")){
DO.addPC(getGoTo(line), getPCString(line));
}else if(line.contains("}") && line.length()<3){
map.add(DO.place, DO);
}
//Need something to make it look not bad
}
//done?
}
|
diff --git a/mydlp-ui-webapp/src/main/java/com/mydlp/ui/framework/servlet/DownloadServlet.java b/mydlp-ui-webapp/src/main/java/com/mydlp/ui/framework/servlet/DownloadServlet.java
index 505b15eb..baaee859 100644
--- a/mydlp-ui-webapp/src/main/java/com/mydlp/ui/framework/servlet/DownloadServlet.java
+++ b/mydlp-ui-webapp/src/main/java/com/mydlp/ui/framework/servlet/DownloadServlet.java
@@ -1,198 +1,206 @@
package com.mydlp.ui.framework.servlet;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.HttpRequestHandler;
import com.mydlp.ui.dao.IncidentLogDAO;
import com.mydlp.ui.dao.UserDAO;
import com.mydlp.ui.domain.AuthSecurityRole;
import com.mydlp.ui.domain.AuthUser;
import com.mydlp.ui.domain.IncidentLogFile;
import com.mydlp.ui.domain.IncidentLogFileContent;
import com.mydlp.ui.service.AuditTrailService;
import com.mydlp.ui.service.VersionService;
@Service("downloadServlet")
public class DownloadServlet implements HttpRequestHandler {
private static Logger logger = LoggerFactory.getLogger(DownloadServlet.class);
private static Logger errorLogger = LoggerFactory.getLogger("IERROR");
private static final String WINDOWS_AGENT_FOLDER = "/usr/share/mydlp/endpoint/win/msi/";
private static final int BUFFER_SIZE = 102400;
@Autowired
protected IncidentLogDAO incidentLogDAO;
@Autowired
protected UserDAO userDAO;
@Autowired
protected AuditTrailService auditTrailService;
@Autowired
protected VersionService versionService;
@Autowired
@Qualifier("policyTransactionTemplate")
protected TransactionTemplate transactionTemplate;
@Override
public void handleRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String urlKey = req.getParameter("key");
String urlId = req.getParameter("id");
final String username = req.getRemoteUser();
boolean isAdmin = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus arg0) {
AuthUser authUser = userDAO.findByName(username);
if (authUser == null)
return false;
else
return authUser.hasRole(AuthSecurityRole.ROLE_ADMIN);
}
});
boolean isSuperAdmin = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus arg0) {
AuthUser authUser = userDAO.findByName(username);
if (authUser == null)
return false;
else
return authUser.hasRole(AuthSecurityRole.ROLE_SUPER_ADMIN);
}
});
boolean isAuditor = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus arg0) {
AuthUser authUser = userDAO.findByName(username);
if (authUser == null)
return false;
else
return authUser.hasRole(AuthSecurityRole.ROLE_AUDITOR);
}
});
if( (urlKey != null && urlKey.equals("latest-windows-agent")) ||
(isAdmin && urlKey != null && urlKey.equals("user.der")) ||
+ (isAdmin && urlKey != null && urlKey.equals("DeviceConsole.exe")) ||
isSuperAdmin ||
(isAuditor && urlKey == null )
) {
try {
IncidentLogFile logFile = null;
if (urlKey != null) {
if (urlKey.equals("user.der")) {
logFile = new IncidentLogFile();
logFile.setFilename("mydlp-user-certificate.der");
IncidentLogFileContent content = new IncidentLogFileContent();
content.setMimeType("application/x-x509-ca-cert");
content.setLocalPath("/etc/mydlp/ssl/user.der");
logFile.setContent(content);
+ } else if (urlKey.equals("DeviceConsole.exe")) {
+ logFile = new IncidentLogFile();
+ logFile.setFilename("DeviceConsole.exe");
+ IncidentLogFileContent content = new IncidentLogFileContent();
+ content.setMimeType("application/x-dosexec");
+ content.setLocalPath("/usr/share/mydlp/endpoint/win/DeviceConsole.exe");
+ logFile.setContent(content);
} else if (urlKey.equals("latest-windows-agent")) {
String filename = getWindowsAgentFilename();
logFile = new IncidentLogFile();
logFile.setFilename(filename);
IncidentLogFileContent content = new IncidentLogFileContent();
content.setMimeType("application/x-msi");
content.setLocalPath(WINDOWS_AGENT_FOLDER + filename);
logFile.setContent(content);
- }
+ }
else {
errorLogger.error("Unknown download key: " + req.getParameter("key"));
return;
}
} else {
Integer logFileId = Integer.parseInt(urlId);
logFile = incidentLogDAO.geIncidentLogFile(logFileId);
if (logFile == null)
{
errorLogger.error("Null object returned from DAO. urlId: " + urlId);
return;
}
}
File localFile = new File(logFile.getContent().getLocalPath());
if (localFile.exists()) {
resp.setContentType(logFile.getContent().getMimeType());
resp.setContentLength((int) localFile.length());
resp.setHeader( "Content-Disposition", "attachment; filename=\"" + logFile.getFilename() + "\"" );
//
// Stream to the requester.
//
byte[] bbuf = new byte[BUFFER_SIZE];
DataInputStream in = new DataInputStream(new FileInputStream(localFile));
ServletOutputStream op = resp.getOutputStream();
int length = 0;
while ((in != null) && ((length = in.read(bbuf)) != -1))
{
op.write(bbuf,0,length);
}
in.close();
op.flush();
op.close();
}
else
{
resp.setContentType("text/plain");
resp.getWriter().println("File is not available");
errorLogger.error("File is not available: " + logFile.getContent().getLocalPath());
resp.getOutputStream().flush();
resp.getOutputStream().close();
}
auditTrailService.audit(getClass(), "download", new Object[]{urlKey, urlId});
} catch (NumberFormatException e) {
logger.error("Cannot format ", urlId , e);
} catch (FileNotFoundException e) {
logger.error("Cannot find file", e);
} catch (IOException e) {
logger.error("IOError occurred", e);
} catch (RuntimeException e) {
logger.error("Runtime error occured", e);
}
}
else
{
errorLogger.error("User ( " + username + " ) is not authticated to complete operation ( key: " + urlKey + " id: " + urlId + " ).");
}
}
protected String getWindowsAgentFilename() {
String version = versionService.getWindowsAgentVersion();
if (version == null || version.length() == 0) {
return "none";
}
return "mydlp_" + version.replace('.', '_') + ".msi";
}
}
| false | true | public void handleRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String urlKey = req.getParameter("key");
String urlId = req.getParameter("id");
final String username = req.getRemoteUser();
boolean isAdmin = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus arg0) {
AuthUser authUser = userDAO.findByName(username);
if (authUser == null)
return false;
else
return authUser.hasRole(AuthSecurityRole.ROLE_ADMIN);
}
});
boolean isSuperAdmin = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus arg0) {
AuthUser authUser = userDAO.findByName(username);
if (authUser == null)
return false;
else
return authUser.hasRole(AuthSecurityRole.ROLE_SUPER_ADMIN);
}
});
boolean isAuditor = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus arg0) {
AuthUser authUser = userDAO.findByName(username);
if (authUser == null)
return false;
else
return authUser.hasRole(AuthSecurityRole.ROLE_AUDITOR);
}
});
if( (urlKey != null && urlKey.equals("latest-windows-agent")) ||
(isAdmin && urlKey != null && urlKey.equals("user.der")) ||
isSuperAdmin ||
(isAuditor && urlKey == null )
) {
try {
IncidentLogFile logFile = null;
if (urlKey != null) {
if (urlKey.equals("user.der")) {
logFile = new IncidentLogFile();
logFile.setFilename("mydlp-user-certificate.der");
IncidentLogFileContent content = new IncidentLogFileContent();
content.setMimeType("application/x-x509-ca-cert");
content.setLocalPath("/etc/mydlp/ssl/user.der");
logFile.setContent(content);
} else if (urlKey.equals("latest-windows-agent")) {
String filename = getWindowsAgentFilename();
logFile = new IncidentLogFile();
logFile.setFilename(filename);
IncidentLogFileContent content = new IncidentLogFileContent();
content.setMimeType("application/x-msi");
content.setLocalPath(WINDOWS_AGENT_FOLDER + filename);
logFile.setContent(content);
}
else {
errorLogger.error("Unknown download key: " + req.getParameter("key"));
return;
}
} else {
Integer logFileId = Integer.parseInt(urlId);
logFile = incidentLogDAO.geIncidentLogFile(logFileId);
if (logFile == null)
{
errorLogger.error("Null object returned from DAO. urlId: " + urlId);
return;
}
}
File localFile = new File(logFile.getContent().getLocalPath());
if (localFile.exists()) {
resp.setContentType(logFile.getContent().getMimeType());
resp.setContentLength((int) localFile.length());
resp.setHeader( "Content-Disposition", "attachment; filename=\"" + logFile.getFilename() + "\"" );
//
// Stream to the requester.
//
byte[] bbuf = new byte[BUFFER_SIZE];
DataInputStream in = new DataInputStream(new FileInputStream(localFile));
ServletOutputStream op = resp.getOutputStream();
int length = 0;
while ((in != null) && ((length = in.read(bbuf)) != -1))
{
op.write(bbuf,0,length);
}
in.close();
op.flush();
op.close();
}
else
{
resp.setContentType("text/plain");
resp.getWriter().println("File is not available");
errorLogger.error("File is not available: " + logFile.getContent().getLocalPath());
resp.getOutputStream().flush();
resp.getOutputStream().close();
}
auditTrailService.audit(getClass(), "download", new Object[]{urlKey, urlId});
} catch (NumberFormatException e) {
logger.error("Cannot format ", urlId , e);
} catch (FileNotFoundException e) {
logger.error("Cannot find file", e);
} catch (IOException e) {
logger.error("IOError occurred", e);
} catch (RuntimeException e) {
logger.error("Runtime error occured", e);
}
}
else
{
errorLogger.error("User ( " + username + " ) is not authticated to complete operation ( key: " + urlKey + " id: " + urlId + " ).");
}
}
| public void handleRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String urlKey = req.getParameter("key");
String urlId = req.getParameter("id");
final String username = req.getRemoteUser();
boolean isAdmin = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus arg0) {
AuthUser authUser = userDAO.findByName(username);
if (authUser == null)
return false;
else
return authUser.hasRole(AuthSecurityRole.ROLE_ADMIN);
}
});
boolean isSuperAdmin = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus arg0) {
AuthUser authUser = userDAO.findByName(username);
if (authUser == null)
return false;
else
return authUser.hasRole(AuthSecurityRole.ROLE_SUPER_ADMIN);
}
});
boolean isAuditor = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus arg0) {
AuthUser authUser = userDAO.findByName(username);
if (authUser == null)
return false;
else
return authUser.hasRole(AuthSecurityRole.ROLE_AUDITOR);
}
});
if( (urlKey != null && urlKey.equals("latest-windows-agent")) ||
(isAdmin && urlKey != null && urlKey.equals("user.der")) ||
(isAdmin && urlKey != null && urlKey.equals("DeviceConsole.exe")) ||
isSuperAdmin ||
(isAuditor && urlKey == null )
) {
try {
IncidentLogFile logFile = null;
if (urlKey != null) {
if (urlKey.equals("user.der")) {
logFile = new IncidentLogFile();
logFile.setFilename("mydlp-user-certificate.der");
IncidentLogFileContent content = new IncidentLogFileContent();
content.setMimeType("application/x-x509-ca-cert");
content.setLocalPath("/etc/mydlp/ssl/user.der");
logFile.setContent(content);
} else if (urlKey.equals("DeviceConsole.exe")) {
logFile = new IncidentLogFile();
logFile.setFilename("DeviceConsole.exe");
IncidentLogFileContent content = new IncidentLogFileContent();
content.setMimeType("application/x-dosexec");
content.setLocalPath("/usr/share/mydlp/endpoint/win/DeviceConsole.exe");
logFile.setContent(content);
} else if (urlKey.equals("latest-windows-agent")) {
String filename = getWindowsAgentFilename();
logFile = new IncidentLogFile();
logFile.setFilename(filename);
IncidentLogFileContent content = new IncidentLogFileContent();
content.setMimeType("application/x-msi");
content.setLocalPath(WINDOWS_AGENT_FOLDER + filename);
logFile.setContent(content);
}
else {
errorLogger.error("Unknown download key: " + req.getParameter("key"));
return;
}
} else {
Integer logFileId = Integer.parseInt(urlId);
logFile = incidentLogDAO.geIncidentLogFile(logFileId);
if (logFile == null)
{
errorLogger.error("Null object returned from DAO. urlId: " + urlId);
return;
}
}
File localFile = new File(logFile.getContent().getLocalPath());
if (localFile.exists()) {
resp.setContentType(logFile.getContent().getMimeType());
resp.setContentLength((int) localFile.length());
resp.setHeader( "Content-Disposition", "attachment; filename=\"" + logFile.getFilename() + "\"" );
//
// Stream to the requester.
//
byte[] bbuf = new byte[BUFFER_SIZE];
DataInputStream in = new DataInputStream(new FileInputStream(localFile));
ServletOutputStream op = resp.getOutputStream();
int length = 0;
while ((in != null) && ((length = in.read(bbuf)) != -1))
{
op.write(bbuf,0,length);
}
in.close();
op.flush();
op.close();
}
else
{
resp.setContentType("text/plain");
resp.getWriter().println("File is not available");
errorLogger.error("File is not available: " + logFile.getContent().getLocalPath());
resp.getOutputStream().flush();
resp.getOutputStream().close();
}
auditTrailService.audit(getClass(), "download", new Object[]{urlKey, urlId});
} catch (NumberFormatException e) {
logger.error("Cannot format ", urlId , e);
} catch (FileNotFoundException e) {
logger.error("Cannot find file", e);
} catch (IOException e) {
logger.error("IOError occurred", e);
} catch (RuntimeException e) {
logger.error("Runtime error occured", e);
}
}
else
{
errorLogger.error("User ( " + username + " ) is not authticated to complete operation ( key: " + urlKey + " id: " + urlId + " ).");
}
}
|
diff --git a/src/ucbang/core/Card.java b/src/ucbang/core/Card.java
index bf870c8..beab1ee 100644
--- a/src/ucbang/core/Card.java
+++ b/src/ucbang/core/Card.java
@@ -1,357 +1,357 @@
package ucbang.core;
import java.util.Arrays;
public class Card {
public String description="";
public Enum e;
public String name;
public int ordinal;
public int type; // 1 = char, 2 = play, 3 = greenfield, 4 = miss, 5 = bluefield
public int target; // 1 = self, 2 = choose 1 player, 3 = all, 4 = all others
public int effect; // 1 = deal damage, 2 = heal, 3 = miss, 4 = draw
public int effect2; // secondary effects only affect player
public int special; // HP for char cards, ???? for other cards, 1 for beer
// and bangs, 1 for miss, 2 for dodge
public boolean discardToPlay; // cards that need a discard to play
public int range; // used for guns and panic and #cards drawn
public int location; //0 = in hand, 1 = on field, 2 = played
public static enum play {
DAMAGE, HEAL, MISS, DRAW, STEAL, DISCARD, DUEL, JAIL
}; // played cards
public static enum field {
DAMAGE, HEAL, MISS, DRAW, STEAL, DISCARD, BARREL, DYNAMITE, GUN, HORSE_RUN, HORSE_CHASE
}; // field cards
public Card(Enum e) {
this.e = e;
ordinal = e.ordinal();
name = e.toString();
if (e instanceof Deck.Characters) {
type = 1;
int[] threehp = new int[] { 3, 6, 8, 16, 21, 27, 28, 30 };
if (Arrays.binarySearch(threehp, ordinal) >= 0
&& ordinal == threehp[Arrays.binarySearch(threehp, ordinal)]) { // awkward
// way
// of
// doing
// contains
special = 3;
} else
special = 4;
} else {
// TODO: find out what kind of card it is
switch ((Deck.CardName) e) {
// put all direct damage cards here
case BACK:
break;
case BANG:
type = 2;
special = 1;
range = 1;
target = 2;
effect = play.DAMAGE.ordinal();
description = "BANG! cards are the main method to reduce other players' life points. \n" +
"If you want to play a BANG! card to hit one of the players, determine: a) what \n" +
"the distance to that player is, and b) if your weapon is capable of reaching that distance. ";
break;
case PUNCH:
type = 2;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
description="This cards has same effect as BANG! card, but on distance 1.\n" +
" This cards isnt count as BANG!";
break;
case GATLING:
type = 2;
target = 4;
effect = play.DAMAGE.ordinal();
description="The symbols show: a BANG! to all the other players.";
break;
case HOWITZER:
type = 3;
target = 4;
effect = play.DAMAGE.ordinal();
description="The current player play a Howitzer card in front of him.\n" +
"Starting with the next player's turn, he can discard it for BANG!\n" +
"effect to all players.. This card is not count as BANG!.";
break;
case INDIANS:
type = 2;
special = 2;
target = 4;
effect = play.DAMAGE.ordinal();
description="Each player, excluding the one who played this card, may discard a BANG!\n" +
" card, or lose a life point. Neither Missed! nor Barrel has effect in this case.";
break;
case KNIFE:
- type = 2;
+ type = 3;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
description="The current player play a Knife card in front of him. Starting with the next\n" +
"player's turn, he can discard it for BANG! effect. This card is not count as BANG!";
break;
case BUFFALO_RIFLE:
type = 3;
target = 2;
range = -1;
effect = play.DAMAGE.ordinal();
description="The current player play a Buffalo Rifle card in front of him. Starting with the\n" +
"next player's turn, he can discard it for BANG! effect to 1 player at every distance.\n" +
"This card is not count as BANG!";
break;
case SPRINGFIELD:
type = 2;
target = 2;
discardToPlay = true;
range = -1;
effect = play.DAMAGE.ordinal();
description="Player which is on turn, discard card Springfield together with another card on the\n" +
"deck. Than he choose one player, which is target of attack with BANG! effect.";
break;
case PEPPERBOX:
type = 3;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
description="The current player play a PepperBox card in front of him. Starting with the next\n" +
" player's turn, he can discard it for BANG! effect to 1 player at visible distance.\n" +
"This card is not count as BANG!.";
break; // TODO: make same range as bang
case DERRINGER:
type = 3;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
effect2 = play.DRAW.ordinal();
description="The current player plays a Derringer card in front of her. During one of her following\n" +
"turns, provided she still has the card in front of her, she can choose to discard it to a BANG!\n" +
"on a player at a distance of 1, and also draw a card from the deck. ";
break;
case DUEL:
type = 2;
target = 2;
range = -1;
effect = play.DUEL.ordinal();
description="The player playing this card challenges any other player (at any distance), staring him in\n" +
"the eyes. The challenged player may discard a BANG! card (even though it is not his turn!).\n" +
"If he does, the player who played the Duel card may discard a BANG! card, and so on: the first\n" +
"player failing to play a BANG! card loses one life point, and the duel is over. Note: you cannot\n" +
"use the Barrel or play Missed! cards during a duel, and the Duel is not considered a BANG! card.";
break;
case DYNAMITE:
type = 3;
target = 1;
effect = field.DYNAMITE.ordinal();
break;
case MISS:
type = 4;
special = 1;
effect = play.MISS.ordinal();
break;
case DODGE:
type = 4;
effect = play.MISS.ordinal();
effect2 = play.DRAW.ordinal();
break;
case BIBLE:
type = 3;
effect = play.MISS.ordinal();
effect2 = play.DRAW.ordinal();
break;
case IRON_PLATE:
type = 3;
effect = play.MISS.ordinal();
break;
case SOMBRERO:
type = 3;
effect = play.MISS.ordinal();
break;
case TEN_GALLON_HAT:
type = 3;
effect = play.MISS.ordinal();
break;
case BARREL:
type = 5;
effect = field.BARREL.ordinal();
break;
case WELLS_FARGO:
type = 2;
range = 3;
effect = play.DRAW.ordinal();
break;
case STAGECOACH:
type = 2;
range = 2;
effect = play.DRAW.ordinal();
break;
case CONESTOGA:
type = 3;
range = 2;
effect = play.DRAW.ordinal();
break;
case PONY_EXPRESS:
type = 3;
range = 3;
effect = play.DRAW.ordinal();
break;
case GENERAL_STORE:
type = 2;
target = 3;
range = 1;
effect = play.DRAW.ordinal();
break; //TODO: fix general store
case JAIL:
type = 2; //TODO: make special case for jail
range = -1;
effect = play.JAIL.ordinal();
break; // special case: even though jail remains on the field of
// a player, it is "played"
case APPALOOSA:
type = 5;
effect = field.HORSE_CHASE.ordinal();
break;
case SILVER:
type = 5;
effect = field.HORSE_CHASE.ordinal();
break;
case MUSTANG:
type = 5;
effect = field.HORSE_RUN.ordinal();
break;
case HIDEOUT:
type = 5;
effect = field.HORSE_RUN.ordinal();
break; // you heard me: a hideout is a horse.
case BEER:
type = 2;
target = 1;
range = 1;
special = 1;
effect = play.HEAL.ordinal();
break;
case TEQUILA:
type = 2;
target = 2;
range = 1;
discardToPlay = true;
effect = play.HEAL.ordinal();
break;
case WHISKY:
type = 2;
target = 1;
range = 2;
discardToPlay = true;
effect = play.HEAL.ordinal();
break; // special case: heals 2 hp, so i guess i'll use "range"
case CANTEEN:
type = 3;
target = 1;
range = 1;
effect = play.HEAL.ordinal();
break;
case SALOON:
type = 2;
target = 3;
range = 1;
effect = play.HEAL.ordinal();
break;
case BRAWL:
type = 2;
target = 4;
discardToPlay = true;
play.DISCARD.ordinal();
break;
case CAN_CAN:
type = 3;
target = 2;
range = -1;
effect = play.STEAL.ordinal();
break;
case RAG_TIME:
type = 2;
target = 2;
range = -1;
discardToPlay = true;
effect = play.STEAL.ordinal();
break;
case PANIC:
type = 2;
target = 2;
range = 1;
effect = play.STEAL.ordinal();
break;
case CAT_BALLOU:
type = 2;
target = 2;
range = -1;
effect = play.DISCARD.ordinal();
break;
case VOLCANIC:
type = 5;
special = 1;
range = 1;
effect = field.GUN.ordinal();
break;
case SCHOFIELD:
type = 5;
range = 2;
effect = field.GUN.ordinal();
break;
case REMINGTON:
type = 5;
range = 3;
effect = field.GUN.ordinal();
break;
case REV_CARBINE:
type = 5;
range = 4;
effect = field.GUN.ordinal();
break;
case WINCHESTER:
type = 5;
range = 5;
effect = field.GUN.ordinal();
break;
default:
break; // special = 1; type = 2; effect = play.DAMAGE.ordinal();
// break; //all cards left untreated are treated as
// bangs
}
/*if(type==3||type==5){ //TODO: remove this debug feature
setLocation((int)(2*Math.random()));
}
else{
setLocation((int)(2*Math.random())==0?0:2);
}*/
}
}
//for display purposes only:
public static Card playedCard(Enum e){
return null;
}
public void setLocation(int i){
location = i;
}
public String toString(){
return name;
}
}
| true | true | public Card(Enum e) {
this.e = e;
ordinal = e.ordinal();
name = e.toString();
if (e instanceof Deck.Characters) {
type = 1;
int[] threehp = new int[] { 3, 6, 8, 16, 21, 27, 28, 30 };
if (Arrays.binarySearch(threehp, ordinal) >= 0
&& ordinal == threehp[Arrays.binarySearch(threehp, ordinal)]) { // awkward
// way
// of
// doing
// contains
special = 3;
} else
special = 4;
} else {
// TODO: find out what kind of card it is
switch ((Deck.CardName) e) {
// put all direct damage cards here
case BACK:
break;
case BANG:
type = 2;
special = 1;
range = 1;
target = 2;
effect = play.DAMAGE.ordinal();
description = "BANG! cards are the main method to reduce other players' life points. \n" +
"If you want to play a BANG! card to hit one of the players, determine: a) what \n" +
"the distance to that player is, and b) if your weapon is capable of reaching that distance. ";
break;
case PUNCH:
type = 2;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
description="This cards has same effect as BANG! card, but on distance 1.\n" +
" This cards isnt count as BANG!";
break;
case GATLING:
type = 2;
target = 4;
effect = play.DAMAGE.ordinal();
description="The symbols show: a BANG! to all the other players.";
break;
case HOWITZER:
type = 3;
target = 4;
effect = play.DAMAGE.ordinal();
description="The current player play a Howitzer card in front of him.\n" +
"Starting with the next player's turn, he can discard it for BANG!\n" +
"effect to all players.. This card is not count as BANG!.";
break;
case INDIANS:
type = 2;
special = 2;
target = 4;
effect = play.DAMAGE.ordinal();
description="Each player, excluding the one who played this card, may discard a BANG!\n" +
" card, or lose a life point. Neither Missed! nor Barrel has effect in this case.";
break;
case KNIFE:
type = 2;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
description="The current player play a Knife card in front of him. Starting with the next\n" +
"player's turn, he can discard it for BANG! effect. This card is not count as BANG!";
break;
case BUFFALO_RIFLE:
type = 3;
target = 2;
range = -1;
effect = play.DAMAGE.ordinal();
description="The current player play a Buffalo Rifle card in front of him. Starting with the\n" +
"next player's turn, he can discard it for BANG! effect to 1 player at every distance.\n" +
"This card is not count as BANG!";
break;
case SPRINGFIELD:
type = 2;
target = 2;
discardToPlay = true;
range = -1;
effect = play.DAMAGE.ordinal();
description="Player which is on turn, discard card Springfield together with another card on the\n" +
"deck. Than he choose one player, which is target of attack with BANG! effect.";
break;
case PEPPERBOX:
type = 3;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
description="The current player play a PepperBox card in front of him. Starting with the next\n" +
" player's turn, he can discard it for BANG! effect to 1 player at visible distance.\n" +
"This card is not count as BANG!.";
break; // TODO: make same range as bang
case DERRINGER:
type = 3;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
effect2 = play.DRAW.ordinal();
description="The current player plays a Derringer card in front of her. During one of her following\n" +
"turns, provided she still has the card in front of her, she can choose to discard it to a BANG!\n" +
"on a player at a distance of 1, and also draw a card from the deck. ";
break;
case DUEL:
type = 2;
target = 2;
range = -1;
effect = play.DUEL.ordinal();
description="The player playing this card challenges any other player (at any distance), staring him in\n" +
"the eyes. The challenged player may discard a BANG! card (even though it is not his turn!).\n" +
"If he does, the player who played the Duel card may discard a BANG! card, and so on: the first\n" +
"player failing to play a BANG! card loses one life point, and the duel is over. Note: you cannot\n" +
"use the Barrel or play Missed! cards during a duel, and the Duel is not considered a BANG! card.";
break;
case DYNAMITE:
type = 3;
target = 1;
effect = field.DYNAMITE.ordinal();
break;
case MISS:
type = 4;
special = 1;
effect = play.MISS.ordinal();
break;
case DODGE:
type = 4;
effect = play.MISS.ordinal();
effect2 = play.DRAW.ordinal();
break;
case BIBLE:
type = 3;
effect = play.MISS.ordinal();
effect2 = play.DRAW.ordinal();
break;
case IRON_PLATE:
type = 3;
effect = play.MISS.ordinal();
break;
case SOMBRERO:
type = 3;
effect = play.MISS.ordinal();
break;
case TEN_GALLON_HAT:
type = 3;
effect = play.MISS.ordinal();
break;
case BARREL:
type = 5;
effect = field.BARREL.ordinal();
break;
case WELLS_FARGO:
type = 2;
range = 3;
effect = play.DRAW.ordinal();
break;
case STAGECOACH:
type = 2;
range = 2;
effect = play.DRAW.ordinal();
break;
case CONESTOGA:
type = 3;
range = 2;
effect = play.DRAW.ordinal();
break;
case PONY_EXPRESS:
type = 3;
range = 3;
effect = play.DRAW.ordinal();
break;
case GENERAL_STORE:
type = 2;
target = 3;
range = 1;
effect = play.DRAW.ordinal();
break; //TODO: fix general store
case JAIL:
type = 2; //TODO: make special case for jail
range = -1;
effect = play.JAIL.ordinal();
break; // special case: even though jail remains on the field of
// a player, it is "played"
case APPALOOSA:
type = 5;
effect = field.HORSE_CHASE.ordinal();
break;
case SILVER:
type = 5;
effect = field.HORSE_CHASE.ordinal();
break;
case MUSTANG:
type = 5;
effect = field.HORSE_RUN.ordinal();
break;
case HIDEOUT:
type = 5;
effect = field.HORSE_RUN.ordinal();
break; // you heard me: a hideout is a horse.
case BEER:
type = 2;
target = 1;
range = 1;
special = 1;
effect = play.HEAL.ordinal();
break;
case TEQUILA:
type = 2;
target = 2;
range = 1;
discardToPlay = true;
effect = play.HEAL.ordinal();
break;
case WHISKY:
type = 2;
target = 1;
range = 2;
discardToPlay = true;
effect = play.HEAL.ordinal();
break; // special case: heals 2 hp, so i guess i'll use "range"
case CANTEEN:
type = 3;
target = 1;
range = 1;
effect = play.HEAL.ordinal();
break;
case SALOON:
type = 2;
target = 3;
range = 1;
effect = play.HEAL.ordinal();
break;
case BRAWL:
type = 2;
target = 4;
discardToPlay = true;
play.DISCARD.ordinal();
break;
case CAN_CAN:
type = 3;
target = 2;
range = -1;
effect = play.STEAL.ordinal();
break;
case RAG_TIME:
type = 2;
target = 2;
range = -1;
discardToPlay = true;
effect = play.STEAL.ordinal();
break;
case PANIC:
type = 2;
target = 2;
range = 1;
effect = play.STEAL.ordinal();
break;
case CAT_BALLOU:
type = 2;
target = 2;
range = -1;
effect = play.DISCARD.ordinal();
break;
case VOLCANIC:
type = 5;
special = 1;
range = 1;
effect = field.GUN.ordinal();
break;
case SCHOFIELD:
type = 5;
range = 2;
effect = field.GUN.ordinal();
break;
case REMINGTON:
type = 5;
range = 3;
effect = field.GUN.ordinal();
break;
case REV_CARBINE:
type = 5;
range = 4;
effect = field.GUN.ordinal();
break;
case WINCHESTER:
type = 5;
range = 5;
effect = field.GUN.ordinal();
break;
default:
break; // special = 1; type = 2; effect = play.DAMAGE.ordinal();
// break; //all cards left untreated are treated as
// bangs
}
/*if(type==3||type==5){ //TODO: remove this debug feature
setLocation((int)(2*Math.random()));
}
else{
setLocation((int)(2*Math.random())==0?0:2);
}*/
}
| public Card(Enum e) {
this.e = e;
ordinal = e.ordinal();
name = e.toString();
if (e instanceof Deck.Characters) {
type = 1;
int[] threehp = new int[] { 3, 6, 8, 16, 21, 27, 28, 30 };
if (Arrays.binarySearch(threehp, ordinal) >= 0
&& ordinal == threehp[Arrays.binarySearch(threehp, ordinal)]) { // awkward
// way
// of
// doing
// contains
special = 3;
} else
special = 4;
} else {
// TODO: find out what kind of card it is
switch ((Deck.CardName) e) {
// put all direct damage cards here
case BACK:
break;
case BANG:
type = 2;
special = 1;
range = 1;
target = 2;
effect = play.DAMAGE.ordinal();
description = "BANG! cards are the main method to reduce other players' life points. \n" +
"If you want to play a BANG! card to hit one of the players, determine: a) what \n" +
"the distance to that player is, and b) if your weapon is capable of reaching that distance. ";
break;
case PUNCH:
type = 2;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
description="This cards has same effect as BANG! card, but on distance 1.\n" +
" This cards isnt count as BANG!";
break;
case GATLING:
type = 2;
target = 4;
effect = play.DAMAGE.ordinal();
description="The symbols show: a BANG! to all the other players.";
break;
case HOWITZER:
type = 3;
target = 4;
effect = play.DAMAGE.ordinal();
description="The current player play a Howitzer card in front of him.\n" +
"Starting with the next player's turn, he can discard it for BANG!\n" +
"effect to all players.. This card is not count as BANG!.";
break;
case INDIANS:
type = 2;
special = 2;
target = 4;
effect = play.DAMAGE.ordinal();
description="Each player, excluding the one who played this card, may discard a BANG!\n" +
" card, or lose a life point. Neither Missed! nor Barrel has effect in this case.";
break;
case KNIFE:
type = 3;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
description="The current player play a Knife card in front of him. Starting with the next\n" +
"player's turn, he can discard it for BANG! effect. This card is not count as BANG!";
break;
case BUFFALO_RIFLE:
type = 3;
target = 2;
range = -1;
effect = play.DAMAGE.ordinal();
description="The current player play a Buffalo Rifle card in front of him. Starting with the\n" +
"next player's turn, he can discard it for BANG! effect to 1 player at every distance.\n" +
"This card is not count as BANG!";
break;
case SPRINGFIELD:
type = 2;
target = 2;
discardToPlay = true;
range = -1;
effect = play.DAMAGE.ordinal();
description="Player which is on turn, discard card Springfield together with another card on the\n" +
"deck. Than he choose one player, which is target of attack with BANG! effect.";
break;
case PEPPERBOX:
type = 3;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
description="The current player play a PepperBox card in front of him. Starting with the next\n" +
" player's turn, he can discard it for BANG! effect to 1 player at visible distance.\n" +
"This card is not count as BANG!.";
break; // TODO: make same range as bang
case DERRINGER:
type = 3;
target = 2;
range = 1;
effect = play.DAMAGE.ordinal();
effect2 = play.DRAW.ordinal();
description="The current player plays a Derringer card in front of her. During one of her following\n" +
"turns, provided she still has the card in front of her, she can choose to discard it to a BANG!\n" +
"on a player at a distance of 1, and also draw a card from the deck. ";
break;
case DUEL:
type = 2;
target = 2;
range = -1;
effect = play.DUEL.ordinal();
description="The player playing this card challenges any other player (at any distance), staring him in\n" +
"the eyes. The challenged player may discard a BANG! card (even though it is not his turn!).\n" +
"If he does, the player who played the Duel card may discard a BANG! card, and so on: the first\n" +
"player failing to play a BANG! card loses one life point, and the duel is over. Note: you cannot\n" +
"use the Barrel or play Missed! cards during a duel, and the Duel is not considered a BANG! card.";
break;
case DYNAMITE:
type = 3;
target = 1;
effect = field.DYNAMITE.ordinal();
break;
case MISS:
type = 4;
special = 1;
effect = play.MISS.ordinal();
break;
case DODGE:
type = 4;
effect = play.MISS.ordinal();
effect2 = play.DRAW.ordinal();
break;
case BIBLE:
type = 3;
effect = play.MISS.ordinal();
effect2 = play.DRAW.ordinal();
break;
case IRON_PLATE:
type = 3;
effect = play.MISS.ordinal();
break;
case SOMBRERO:
type = 3;
effect = play.MISS.ordinal();
break;
case TEN_GALLON_HAT:
type = 3;
effect = play.MISS.ordinal();
break;
case BARREL:
type = 5;
effect = field.BARREL.ordinal();
break;
case WELLS_FARGO:
type = 2;
range = 3;
effect = play.DRAW.ordinal();
break;
case STAGECOACH:
type = 2;
range = 2;
effect = play.DRAW.ordinal();
break;
case CONESTOGA:
type = 3;
range = 2;
effect = play.DRAW.ordinal();
break;
case PONY_EXPRESS:
type = 3;
range = 3;
effect = play.DRAW.ordinal();
break;
case GENERAL_STORE:
type = 2;
target = 3;
range = 1;
effect = play.DRAW.ordinal();
break; //TODO: fix general store
case JAIL:
type = 2; //TODO: make special case for jail
range = -1;
effect = play.JAIL.ordinal();
break; // special case: even though jail remains on the field of
// a player, it is "played"
case APPALOOSA:
type = 5;
effect = field.HORSE_CHASE.ordinal();
break;
case SILVER:
type = 5;
effect = field.HORSE_CHASE.ordinal();
break;
case MUSTANG:
type = 5;
effect = field.HORSE_RUN.ordinal();
break;
case HIDEOUT:
type = 5;
effect = field.HORSE_RUN.ordinal();
break; // you heard me: a hideout is a horse.
case BEER:
type = 2;
target = 1;
range = 1;
special = 1;
effect = play.HEAL.ordinal();
break;
case TEQUILA:
type = 2;
target = 2;
range = 1;
discardToPlay = true;
effect = play.HEAL.ordinal();
break;
case WHISKY:
type = 2;
target = 1;
range = 2;
discardToPlay = true;
effect = play.HEAL.ordinal();
break; // special case: heals 2 hp, so i guess i'll use "range"
case CANTEEN:
type = 3;
target = 1;
range = 1;
effect = play.HEAL.ordinal();
break;
case SALOON:
type = 2;
target = 3;
range = 1;
effect = play.HEAL.ordinal();
break;
case BRAWL:
type = 2;
target = 4;
discardToPlay = true;
play.DISCARD.ordinal();
break;
case CAN_CAN:
type = 3;
target = 2;
range = -1;
effect = play.STEAL.ordinal();
break;
case RAG_TIME:
type = 2;
target = 2;
range = -1;
discardToPlay = true;
effect = play.STEAL.ordinal();
break;
case PANIC:
type = 2;
target = 2;
range = 1;
effect = play.STEAL.ordinal();
break;
case CAT_BALLOU:
type = 2;
target = 2;
range = -1;
effect = play.DISCARD.ordinal();
break;
case VOLCANIC:
type = 5;
special = 1;
range = 1;
effect = field.GUN.ordinal();
break;
case SCHOFIELD:
type = 5;
range = 2;
effect = field.GUN.ordinal();
break;
case REMINGTON:
type = 5;
range = 3;
effect = field.GUN.ordinal();
break;
case REV_CARBINE:
type = 5;
range = 4;
effect = field.GUN.ordinal();
break;
case WINCHESTER:
type = 5;
range = 5;
effect = field.GUN.ordinal();
break;
default:
break; // special = 1; type = 2; effect = play.DAMAGE.ordinal();
// break; //all cards left untreated are treated as
// bangs
}
/*if(type==3||type==5){ //TODO: remove this debug feature
setLocation((int)(2*Math.random()));
}
else{
setLocation((int)(2*Math.random())==0?0:2);
}*/
}
|
diff --git a/app/src/processing/app/EditorConsole.java b/app/src/processing/app/EditorConsole.java
index 97cf1221..7b8e3656 100644
--- a/app/src/processing/app/EditorConsole.java
+++ b/app/src/processing/app/EditorConsole.java
@@ -1,457 +1,460 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-06 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;
import static processing.app.I18n._;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;
/**
* Message console that sits below the editing area.
* <P>
* Debugging this class is tricky... If it's throwing exceptions,
* don't take over System.err, and debug while watching just System.out
* or just write println() or whatever directly to systemOut or systemErr.
*/
public class EditorConsole extends JScrollPane {
Editor editor;
JTextPane consoleTextPane;
BufferedStyledDocument consoleDoc;
MutableAttributeSet stdStyle;
MutableAttributeSet errStyle;
int maxLineCount;
static File errFile;
static File outFile;
static File tempFolder;
// Single static instance shared because there's only one real System.out.
// Within the input handlers, the currentConsole variable will be used to
// echo things to the correct location.
static public PrintStream systemOut;
static public PrintStream systemErr;
static PrintStream consoleOut;
static PrintStream consoleErr;
static OutputStream stdoutFile;
static OutputStream stderrFile;
static EditorConsole currentConsole;
public EditorConsole(Editor editor) {
this.editor = editor;
maxLineCount = Preferences.getInteger("console.length");
consoleDoc = new BufferedStyledDocument(10000, maxLineCount);
consoleTextPane = new JTextPane(consoleDoc);
consoleTextPane.setEditable(false);
// necessary?
MutableAttributeSet standard = new SimpleAttributeSet();
StyleConstants.setAlignment(standard, StyleConstants.ALIGN_LEFT);
consoleDoc.setParagraphAttributes(0, 0, standard, true);
// build styles for different types of console output
Color bgColor = Theme.getColor("console.color");
Color fgColorOut = Theme.getColor("console.output.color");
Color fgColorErr = Theme.getColor("console.error.color");
Font consoleFont = Theme.getFont("console.font");
Font editorFont = Preferences.getFont("editor.font");
Font font = new Font(consoleFont.getName(), consoleFont.getStyle(), editorFont.getSize());
stdStyle = new SimpleAttributeSet();
StyleConstants.setForeground(stdStyle, fgColorOut);
StyleConstants.setBackground(stdStyle, bgColor);
StyleConstants.setFontSize(stdStyle, font.getSize());
StyleConstants.setFontFamily(stdStyle, font.getFamily());
StyleConstants.setBold(stdStyle, font.isBold());
StyleConstants.setItalic(stdStyle, font.isItalic());
errStyle = new SimpleAttributeSet();
StyleConstants.setForeground(errStyle, fgColorErr);
StyleConstants.setBackground(errStyle, bgColor);
StyleConstants.setFontSize(errStyle, font.getSize());
StyleConstants.setFontFamily(errStyle, font.getFamily());
StyleConstants.setBold(errStyle, font.isBold());
StyleConstants.setItalic(errStyle, font.isItalic());
consoleTextPane.setBackground(bgColor);
// add the jtextpane to this scrollpane
this.setViewportView(consoleTextPane);
// calculate height of a line of text in pixels
// and size window accordingly
FontMetrics metrics = this.getFontMetrics(font);
int height = metrics.getAscent() + metrics.getDescent();
int lines = Preferences.getInteger("console.lines"); //, 4);
int sizeFudge = 6; //10; // unclear why this is necessary, but it is
setPreferredSize(new Dimension(1024, (height * lines) + sizeFudge));
setMinimumSize(new Dimension(1024, (height * 4) + sizeFudge));
if (systemOut == null) {
systemOut = System.out;
systemErr = System.err;
// Create a temporary folder which will have a randomized name. Has to
// be randomized otherwise another instance of Processing (or one of its
// sister IDEs) might collide with the file causing permissions problems.
// The files and folders are not deleted on exit because they may be
// needed for debugging or bug reporting.
tempFolder = Base.createTempFolder("console");
+ tempFolder.deleteOnExit();
try {
String outFileName = Preferences.get("console.output.file");
if (outFileName != null) {
outFile = new File(tempFolder, outFileName);
+ outFile.deleteOnExit();
stdoutFile = new FileOutputStream(outFile);
}
String errFileName = Preferences.get("console.error.file");
if (errFileName != null) {
errFile = new File(tempFolder, errFileName);
+ errFile.deleteOnExit();
stderrFile = new FileOutputStream(errFile);
}
} catch (IOException e) {
Base.showWarning(_("Console Error"),
_("A problem occurred while trying to open the\nfiles used to store the console output."), e);
}
consoleOut = new PrintStream(new EditorConsoleStream(false));
consoleErr = new PrintStream(new EditorConsoleStream(true));
if (Preferences.getBoolean("console")) {
try {
System.setOut(consoleOut);
System.setErr(consoleErr);
} catch (Exception e) {
e.printStackTrace(systemOut);
}
}
}
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
if (Base.isMacOS()) {
setBorder(null);
}
// periodically post buffered messages to the console
// should the interval come from the preferences file?
new javax.swing.Timer(250, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// only if new text has been added
if (consoleDoc.hasAppendage) {
// insert the text that's been added in the meantime
consoleDoc.insertAll();
// always move to the end of the text as it's added
consoleTextPane.setCaretPosition(consoleDoc.getLength());
}
}
}).start();
}
static public void setEditor(Editor editor) {
currentConsole = editor.console;
}
/**
* Close the streams so that the temporary files can be deleted.
* <p/>
* File.deleteOnExit() cannot be used because the stdout and stderr
* files are inside a folder, and have to be deleted before the
* folder itself is deleted, which can't be guaranteed when using
* the deleteOnExit() method.
*/
public void handleQuit() {
// replace original streams to remove references to console's streams
System.setOut(systemOut);
System.setErr(systemErr);
// close the PrintStream
consoleOut.close();
consoleErr.close();
// also have to close the original FileOutputStream
// otherwise it won't be shut down completely
try {
stdoutFile.close();
stderrFile.close();
} catch (IOException e) {
e.printStackTrace(systemOut);
}
outFile.delete();
errFile.delete();
tempFolder.delete();
}
public void write(byte b[], int offset, int length, boolean err) {
// we could do some cross platform CR/LF mangling here before outputting
// add text to output document
message(new String(b, offset, length), err, false);
}
// added sync for 0091.. not sure if it helps or hinders
synchronized public void message(String what, boolean err, boolean advance) {
if (err) {
systemErr.print(what);
//systemErr.print("CE" + what);
} else {
systemOut.print(what);
//systemOut.print("CO" + what);
}
if (advance) {
appendText("\n", err);
if (err) {
systemErr.println();
} else {
systemOut.println();
}
}
// to console display
appendText(what, err);
// moved down here since something is punting
}
/**
* Append a piece of text to the console.
* <P>
* Swing components are NOT thread-safe, and since the MessageSiphon
* instantiates new threads, and in those callbacks, they often print
* output to stdout and stderr, which are wrapped by EditorConsoleStream
* and eventually leads to EditorConsole.appendText(), which directly
* updates the Swing text components, causing deadlock.
* <P>
* Updates are buffered to the console and displayed at regular
* intervals on Swing's event-dispatching thread. (patch by David Mellis)
*/
synchronized private void appendText(String txt, boolean e) {
consoleDoc.appendString(txt, e ? errStyle : stdStyle);
}
public void clear() {
try {
consoleDoc.remove(0, consoleDoc.getLength());
} catch (BadLocationException e) {
// ignore the error otherwise this will cause an infinite loop
// maybe not a good idea in the long run?
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
private static class EditorConsoleStream extends OutputStream {
//static EditorConsole current;
final boolean err; // whether stderr or stdout
final byte single[] = new byte[1];
public EditorConsoleStream(boolean err) {
this.err = err;
}
public void close() { }
public void flush() { }
public void write(byte b[]) { // appears never to be used
if (currentConsole != null) {
currentConsole.write(b, 0, b.length, err);
} else {
try {
if (err) {
systemErr.write(b);
} else {
systemOut.write(b);
}
} catch (IOException e) { } // just ignore, where would we write?
}
OutputStream echo = err ? stderrFile : stdoutFile;
if (echo != null) {
try {
echo.write(b);
echo.flush();
} catch (IOException e) {
e.printStackTrace();
echo = null;
}
}
}
public void write(byte b[], int offset, int length) {
if (currentConsole != null) {
currentConsole.write(b, offset, length, err);
} else {
try {
if (err) {
systemErr.write(b);
} else {
systemOut.write(b);
}
} catch (IOException e) { } // just ignore, where would we write?
}
OutputStream echo = err ? stderrFile : stdoutFile;
if (echo != null) {
try {
echo.write(b, offset, length);
echo.flush();
} catch (IOException e) {
e.printStackTrace();
echo = null;
}
}
}
public void write(int b) {
single[0] = (byte)b;
if (currentConsole != null) {
currentConsole.write(single, 0, 1, err);
} else {
// redirect for all the extra handling above
write(new byte[] { (byte) b }, 0, 1);
}
OutputStream echo = err ? stderrFile : stdoutFile;
if (echo != null) {
try {
echo.write(b);
echo.flush();
} catch (IOException e) {
e.printStackTrace();
echo = null;
}
}
}
}
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/**
* Buffer updates to the console and output them in batches. For info, see:
* http://java.sun.com/products/jfc/tsc/articles/text/element_buffer and
* http://javatechniques.com/public/java/docs/gui/jtextpane-speed-part2.html
* appendString() is called from multiple threads, and insertAll from the
* swing event thread, so they need to be synchronized
*/
class BufferedStyledDocument extends DefaultStyledDocument {
ArrayList<ElementSpec> elements = new ArrayList<ElementSpec>();
int maxLineLength, maxLineCount;
int currentLineLength = 0;
boolean needLineBreak = false;
boolean hasAppendage = false;
public BufferedStyledDocument(int maxLineLength, int maxLineCount) {
this.maxLineLength = maxLineLength;
this.maxLineCount = maxLineCount;
}
/** buffer a string for insertion at the end of the DefaultStyledDocument */
public synchronized void appendString(String str, AttributeSet a) {
// do this so that it's only updated when needed (otherwise console
// updates every 250 ms when an app isn't even running.. see bug 180)
hasAppendage = true;
// process each line of the string
while (str.length() > 0) {
// newlines within an element have (almost) no effect, so we need to
// replace them with proper paragraph breaks (start and end tags)
if (needLineBreak || currentLineLength > maxLineLength) {
elements.add(new ElementSpec(a, ElementSpec.EndTagType));
elements.add(new ElementSpec(a, ElementSpec.StartTagType));
currentLineLength = 0;
}
if (str.indexOf('\n') == -1) {
elements.add(new ElementSpec(a, ElementSpec.ContentType,
str.toCharArray(), 0, str.length()));
currentLineLength += str.length();
needLineBreak = false;
str = str.substring(str.length()); // eat the string
} else {
elements.add(new ElementSpec(a, ElementSpec.ContentType,
str.toCharArray(), 0, str.indexOf('\n') + 1));
needLineBreak = true;
str = str.substring(str.indexOf('\n') + 1); // eat the line
}
}
}
/** insert the buffered strings */
public synchronized void insertAll() {
ElementSpec[] elementArray = new ElementSpec[elements.size()];
elements.toArray(elementArray);
try {
// check how many lines have been used so far
// if too many, shave off a few lines from the beginning
Element element = super.getDefaultRootElement();
int lineCount = element.getElementCount();
int overage = lineCount - maxLineCount;
if (overage > 0) {
// if 1200 lines, and 1000 lines is max,
// find the position of the end of the 200th line
//systemOut.println("overage is " + overage);
Element lineElement = element.getElement(overage);
if (lineElement == null) return; // do nuthin
int endOffset = lineElement.getEndOffset();
// remove to the end of the 200th line
super.remove(0, endOffset);
}
super.insert(super.getLength(), elementArray);
} catch (BadLocationException e) {
// ignore the error otherwise this will cause an infinite loop
// maybe not a good idea in the long run?
}
elements.clear();
hasAppendage = false;
}
}
| false | true | public EditorConsole(Editor editor) {
this.editor = editor;
maxLineCount = Preferences.getInteger("console.length");
consoleDoc = new BufferedStyledDocument(10000, maxLineCount);
consoleTextPane = new JTextPane(consoleDoc);
consoleTextPane.setEditable(false);
// necessary?
MutableAttributeSet standard = new SimpleAttributeSet();
StyleConstants.setAlignment(standard, StyleConstants.ALIGN_LEFT);
consoleDoc.setParagraphAttributes(0, 0, standard, true);
// build styles for different types of console output
Color bgColor = Theme.getColor("console.color");
Color fgColorOut = Theme.getColor("console.output.color");
Color fgColorErr = Theme.getColor("console.error.color");
Font consoleFont = Theme.getFont("console.font");
Font editorFont = Preferences.getFont("editor.font");
Font font = new Font(consoleFont.getName(), consoleFont.getStyle(), editorFont.getSize());
stdStyle = new SimpleAttributeSet();
StyleConstants.setForeground(stdStyle, fgColorOut);
StyleConstants.setBackground(stdStyle, bgColor);
StyleConstants.setFontSize(stdStyle, font.getSize());
StyleConstants.setFontFamily(stdStyle, font.getFamily());
StyleConstants.setBold(stdStyle, font.isBold());
StyleConstants.setItalic(stdStyle, font.isItalic());
errStyle = new SimpleAttributeSet();
StyleConstants.setForeground(errStyle, fgColorErr);
StyleConstants.setBackground(errStyle, bgColor);
StyleConstants.setFontSize(errStyle, font.getSize());
StyleConstants.setFontFamily(errStyle, font.getFamily());
StyleConstants.setBold(errStyle, font.isBold());
StyleConstants.setItalic(errStyle, font.isItalic());
consoleTextPane.setBackground(bgColor);
// add the jtextpane to this scrollpane
this.setViewportView(consoleTextPane);
// calculate height of a line of text in pixels
// and size window accordingly
FontMetrics metrics = this.getFontMetrics(font);
int height = metrics.getAscent() + metrics.getDescent();
int lines = Preferences.getInteger("console.lines"); //, 4);
int sizeFudge = 6; //10; // unclear why this is necessary, but it is
setPreferredSize(new Dimension(1024, (height * lines) + sizeFudge));
setMinimumSize(new Dimension(1024, (height * 4) + sizeFudge));
if (systemOut == null) {
systemOut = System.out;
systemErr = System.err;
// Create a temporary folder which will have a randomized name. Has to
// be randomized otherwise another instance of Processing (or one of its
// sister IDEs) might collide with the file causing permissions problems.
// The files and folders are not deleted on exit because they may be
// needed for debugging or bug reporting.
tempFolder = Base.createTempFolder("console");
try {
String outFileName = Preferences.get("console.output.file");
if (outFileName != null) {
outFile = new File(tempFolder, outFileName);
stdoutFile = new FileOutputStream(outFile);
}
String errFileName = Preferences.get("console.error.file");
if (errFileName != null) {
errFile = new File(tempFolder, errFileName);
stderrFile = new FileOutputStream(errFile);
}
} catch (IOException e) {
Base.showWarning(_("Console Error"),
_("A problem occurred while trying to open the\nfiles used to store the console output."), e);
}
consoleOut = new PrintStream(new EditorConsoleStream(false));
consoleErr = new PrintStream(new EditorConsoleStream(true));
if (Preferences.getBoolean("console")) {
try {
System.setOut(consoleOut);
System.setErr(consoleErr);
} catch (Exception e) {
e.printStackTrace(systemOut);
}
}
}
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
if (Base.isMacOS()) {
setBorder(null);
}
// periodically post buffered messages to the console
// should the interval come from the preferences file?
new javax.swing.Timer(250, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// only if new text has been added
if (consoleDoc.hasAppendage) {
// insert the text that's been added in the meantime
consoleDoc.insertAll();
// always move to the end of the text as it's added
consoleTextPane.setCaretPosition(consoleDoc.getLength());
}
}
}).start();
}
| public EditorConsole(Editor editor) {
this.editor = editor;
maxLineCount = Preferences.getInteger("console.length");
consoleDoc = new BufferedStyledDocument(10000, maxLineCount);
consoleTextPane = new JTextPane(consoleDoc);
consoleTextPane.setEditable(false);
// necessary?
MutableAttributeSet standard = new SimpleAttributeSet();
StyleConstants.setAlignment(standard, StyleConstants.ALIGN_LEFT);
consoleDoc.setParagraphAttributes(0, 0, standard, true);
// build styles for different types of console output
Color bgColor = Theme.getColor("console.color");
Color fgColorOut = Theme.getColor("console.output.color");
Color fgColorErr = Theme.getColor("console.error.color");
Font consoleFont = Theme.getFont("console.font");
Font editorFont = Preferences.getFont("editor.font");
Font font = new Font(consoleFont.getName(), consoleFont.getStyle(), editorFont.getSize());
stdStyle = new SimpleAttributeSet();
StyleConstants.setForeground(stdStyle, fgColorOut);
StyleConstants.setBackground(stdStyle, bgColor);
StyleConstants.setFontSize(stdStyle, font.getSize());
StyleConstants.setFontFamily(stdStyle, font.getFamily());
StyleConstants.setBold(stdStyle, font.isBold());
StyleConstants.setItalic(stdStyle, font.isItalic());
errStyle = new SimpleAttributeSet();
StyleConstants.setForeground(errStyle, fgColorErr);
StyleConstants.setBackground(errStyle, bgColor);
StyleConstants.setFontSize(errStyle, font.getSize());
StyleConstants.setFontFamily(errStyle, font.getFamily());
StyleConstants.setBold(errStyle, font.isBold());
StyleConstants.setItalic(errStyle, font.isItalic());
consoleTextPane.setBackground(bgColor);
// add the jtextpane to this scrollpane
this.setViewportView(consoleTextPane);
// calculate height of a line of text in pixels
// and size window accordingly
FontMetrics metrics = this.getFontMetrics(font);
int height = metrics.getAscent() + metrics.getDescent();
int lines = Preferences.getInteger("console.lines"); //, 4);
int sizeFudge = 6; //10; // unclear why this is necessary, but it is
setPreferredSize(new Dimension(1024, (height * lines) + sizeFudge));
setMinimumSize(new Dimension(1024, (height * 4) + sizeFudge));
if (systemOut == null) {
systemOut = System.out;
systemErr = System.err;
// Create a temporary folder which will have a randomized name. Has to
// be randomized otherwise another instance of Processing (or one of its
// sister IDEs) might collide with the file causing permissions problems.
// The files and folders are not deleted on exit because they may be
// needed for debugging or bug reporting.
tempFolder = Base.createTempFolder("console");
tempFolder.deleteOnExit();
try {
String outFileName = Preferences.get("console.output.file");
if (outFileName != null) {
outFile = new File(tempFolder, outFileName);
outFile.deleteOnExit();
stdoutFile = new FileOutputStream(outFile);
}
String errFileName = Preferences.get("console.error.file");
if (errFileName != null) {
errFile = new File(tempFolder, errFileName);
errFile.deleteOnExit();
stderrFile = new FileOutputStream(errFile);
}
} catch (IOException e) {
Base.showWarning(_("Console Error"),
_("A problem occurred while trying to open the\nfiles used to store the console output."), e);
}
consoleOut = new PrintStream(new EditorConsoleStream(false));
consoleErr = new PrintStream(new EditorConsoleStream(true));
if (Preferences.getBoolean("console")) {
try {
System.setOut(consoleOut);
System.setErr(consoleErr);
} catch (Exception e) {
e.printStackTrace(systemOut);
}
}
}
// to fix ugliness.. normally macosx java 1.3 puts an
// ugly white border around this object, so turn it off.
if (Base.isMacOS()) {
setBorder(null);
}
// periodically post buffered messages to the console
// should the interval come from the preferences file?
new javax.swing.Timer(250, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// only if new text has been added
if (consoleDoc.hasAppendage) {
// insert the text that's been added in the meantime
consoleDoc.insertAll();
// always move to the end of the text as it's added
consoleTextPane.setCaretPosition(consoleDoc.getLength());
}
}
}).start();
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java
index 42fc250e..ef68b63a 100644
--- a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java
+++ b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java
@@ -1,130 +1,130 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.bukkit.Server;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import static com.earth2me.essentials.I18n._;
public class Commandenchant extends EssentialsCommand
{
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<String, Enchantment>();
private static final transient Pattern NUMPATTERN = Pattern.compile("\\d+");
static
{
ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL);
ENCHANTMENTS.put("arthropodsdamage", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS);
ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD);
ENCHANTMENTS.put("undeaddmg", Enchantment.DAMAGE_UNDEAD);
ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED);
ENCHANTMENTS.put("durability", Enchantment.DURABILITY);
ENCHANTMENTS.put("dura", Enchantment.DURABILITY);
ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT);
ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT);
ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK);
ENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS);
ENCHANTMENTS.put("blocksbonus", Enchantment.LOOT_BONUS_BLOCKS);
ENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("mobsbonus", Enchantment.LOOT_BONUS_MOBS);
ENCHANTMENTS.put("oxygen", Enchantment.OXYGEN);
ENCHANTMENTS.put("environmentalprotection", Enchantment.PROTECTION_ENVIRONMENTAL);
ENCHANTMENTS.put("envprot", Enchantment.PROTECTION_ENVIRONMENTAL);
ENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS);
ENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL);
ENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE);
ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE);
ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE);
ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE);
ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH);
ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER);
}
public Commandenchant()
{
super("enchant");
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final ItemStack stack = user.getItemInHand();
if (stack == null)
{
throw new Exception(_("nothingInHand"));
}
if (args.length == 0)
{
final Set<String> enchantmentslist = new TreeSet<String>();
for (Map.Entry<String, Enchantment> entry : ENCHANTMENTS.entrySet())
{
final String enchantmentName = entry.getValue().getName().toLowerCase(Locale.ENGLISH);
if (enchantmentslist.contains(enchantmentName) || user.isAuthorized("essentials.enchant." + enchantmentName))
{
enchantmentslist.add(entry.getKey());
enchantmentslist.add(enchantmentName);
}
}
- throw new NotEnoughArgumentsException(_("entchantments", Util.joinList(enchantmentslist.toArray())));
+ throw new NotEnoughArgumentsException(_("enchantments", Util.joinList(enchantmentslist.toArray())));
}
int level = -1;
if (args.length > 1)
{
try
{
level = Integer.parseInt(args[1]);
}
catch (NumberFormatException ex)
{
level = -1;
}
}
Enchantment enchantment = getEnchantment(args[0], user);
if (level < enchantment.getStartLevel() || level > enchantment.getMaxLevel())
{
level = enchantment.getMaxLevel();
}
stack.addEnchantment(enchantment, level);
user.setItemInHand(stack);
user.updateInventory();
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
user.sendMessage(_("enchantmentApplied", enchantmentName.replace('_', ' ')));
}
public static Enchantment getEnchantment(final String name, final User user) throws Exception
{
Enchantment enchantment;
if (NUMPATTERN.matcher(name).matches()) {
enchantment = Enchantment.getById(Integer.parseInt(name));
} else {
enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH));
}
if (enchantment == null)
{
enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH));
}
if (enchantment == null)
{
throw new Exception(_("enchantmentNotFound"));
}
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
if (user != null && !user.isAuthorized("essentials.enchant." + enchantmentName))
{
throw new Exception(_("enchantmentPerm", enchantmentName));
}
return enchantment;
}
}
| true | true | protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final ItemStack stack = user.getItemInHand();
if (stack == null)
{
throw new Exception(_("nothingInHand"));
}
if (args.length == 0)
{
final Set<String> enchantmentslist = new TreeSet<String>();
for (Map.Entry<String, Enchantment> entry : ENCHANTMENTS.entrySet())
{
final String enchantmentName = entry.getValue().getName().toLowerCase(Locale.ENGLISH);
if (enchantmentslist.contains(enchantmentName) || user.isAuthorized("essentials.enchant." + enchantmentName))
{
enchantmentslist.add(entry.getKey());
enchantmentslist.add(enchantmentName);
}
}
throw new NotEnoughArgumentsException(_("entchantments", Util.joinList(enchantmentslist.toArray())));
}
int level = -1;
if (args.length > 1)
{
try
{
level = Integer.parseInt(args[1]);
}
catch (NumberFormatException ex)
{
level = -1;
}
}
Enchantment enchantment = getEnchantment(args[0], user);
if (level < enchantment.getStartLevel() || level > enchantment.getMaxLevel())
{
level = enchantment.getMaxLevel();
}
stack.addEnchantment(enchantment, level);
user.setItemInHand(stack);
user.updateInventory();
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
user.sendMessage(_("enchantmentApplied", enchantmentName.replace('_', ' ')));
}
| protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final ItemStack stack = user.getItemInHand();
if (stack == null)
{
throw new Exception(_("nothingInHand"));
}
if (args.length == 0)
{
final Set<String> enchantmentslist = new TreeSet<String>();
for (Map.Entry<String, Enchantment> entry : ENCHANTMENTS.entrySet())
{
final String enchantmentName = entry.getValue().getName().toLowerCase(Locale.ENGLISH);
if (enchantmentslist.contains(enchantmentName) || user.isAuthorized("essentials.enchant." + enchantmentName))
{
enchantmentslist.add(entry.getKey());
enchantmentslist.add(enchantmentName);
}
}
throw new NotEnoughArgumentsException(_("enchantments", Util.joinList(enchantmentslist.toArray())));
}
int level = -1;
if (args.length > 1)
{
try
{
level = Integer.parseInt(args[1]);
}
catch (NumberFormatException ex)
{
level = -1;
}
}
Enchantment enchantment = getEnchantment(args[0], user);
if (level < enchantment.getStartLevel() || level > enchantment.getMaxLevel())
{
level = enchantment.getMaxLevel();
}
stack.addEnchantment(enchantment, level);
user.setItemInHand(stack);
user.updateInventory();
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
user.sendMessage(_("enchantmentApplied", enchantmentName.replace('_', ' ')));
}
|
diff --git a/srcj/com/sun/electric/tool/erc/ERC.java b/srcj/com/sun/electric/tool/erc/ERC.java
index 65a537f61..c460396c6 100755
--- a/srcj/com/sun/electric/tool/erc/ERC.java
+++ b/srcj/com/sun/electric/tool/erc/ERC.java
@@ -1,178 +1,178 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: ERC.java
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.erc;
import com.sun.electric.database.text.Pref;
import com.sun.electric.database.prototype.ArcProto;
import com.sun.electric.tool.Tool;
import java.util.HashMap;
/**
* This is the Electrical Rule Checker tool.
*/
public class ERC extends Tool
{
/** the ERC tool. */ protected static ERC tool = new ERC();
/** Pref map for arc antenna ratio. */ private static HashMap defaultAntennaRatioPrefs = new HashMap();
/**
* The constructor sets up the ERC tool.
*/
private ERC()
{
super("erc");
}
/**
* Method to initialize the ERC tool.
*/
public void init()
{
}
/**
* Method to retrieve singlenton associated to ERC tool
* @return
*/
public static ERC getERCTool() { return tool; }
/****************************** OPTIONS ******************************/
private static Pref cachePWellCheck = Pref.makeIntPref("PWellCheck", ERC.tool.prefs, 0);
/**
* Method to tell how much P-Well contact checking the ERC should do.
* The values are:
* <UL>
* <LI>0: must have a contact in every well area.</LI>
* <LI>1: must have at least one contact.</LI>
* <LI>2: do not check for contact presence.</LI>
* </UL>
* The default is "0".
* @return how much P-Well contact checking the ERC should do.
*/
public static int getPWellCheck() { return cachePWellCheck.getInt(); }
/**
* Method to set how much P-Well contact checking the ERC should do.
* @param c how much P-Well contact checking the ERC should do:
* <UL>
* <LI>0: must have a contact in every well area.</LI>
* <LI>1: must have at least one contact.</LI>
* <LI>2: do not check for contact presence.</LI>
* </UL>
*/
public static void setPWellCheck(int c) { cachePWellCheck.setInt(c); }
private static Pref cacheMustConnectPWellToGround = Pref.makeBooleanPref("MustConnectPWellToGround", ERC.tool.prefs, true);
/**
* Method to tell whether ERC should check that all P-Well contacts connect to ground.
* The default is "true".
* @return true if ERC should check that all P-Well contacts connect to ground.
*/
public static boolean isMustConnectPWellToGround() { return cacheMustConnectPWellToGround.getBoolean(); }
/**
* Method to set whether ERC should check that all P-Well contacts connect to ground.
* @param on true if ERC should check that all P-Well contacts connect to ground.
*/
public static void setMustConnectPWellToGround(boolean on) { cacheMustConnectPWellToGround.setBoolean(on); }
private static Pref cacheNWellCheck = Pref.makeIntPref("NWellCheck", ERC.tool.prefs, 0);
/**
* Method to tell how much N-Well contact checking the ERC should do.
* The values are:
* <UL>
* <LI>0: must have a contact in every well area.</LI>
* <LI>1: must have at least one contact.</LI>
* <LI>2: do not check for contact presence.</LI>
* </UL>
* The default is "0".
* @return how much N-Well contact checking the ERC should do.
*/
public static int getNWellCheck() { return cacheNWellCheck.getInt(); }
/**
* Method to set how much N-Well contact checking the ERC should do.
* @param c how much N-Well contact checking the ERC should do:
* <UL>
* <LI>0: must have a contact in every well area.</LI>
* <LI>1: must have at least one contact.</LI>
* <LI>2: do not check for contact presence.</LI>
* </UL>
*/
public static void setNWellCheck(int c) { cacheNWellCheck.setInt(c); }
private static Pref cacheMustConnectNWellToPower = Pref.makeBooleanPref("MustConnectNWellToPower", ERC.tool.prefs, true);
/**
* Method to tell whether ERC should check that all N-Well contacts connect to power.
* The default is "true".
* @return true if ERC should check that all N-Well contacts connect to power.
*/
public static boolean isMustConnectNWellToPower() { return cacheMustConnectNWellToPower.getBoolean(); }
/**
* Method to set whether ERC should check that all N-Well contacts connect to power.
* @param on true if ERC should check that all N-Well contacts connect to power.
*/
public static void setMustConnectNWellToPower(boolean on) { cacheMustConnectNWellToPower.setBoolean(on); }
private static Pref cacheFindWorstCaseWellContact = Pref.makeBooleanPref("FindWorstCaseWell", ERC.tool.prefs, false);
/**
* Method to tell whether ERC should find the contact that is farthest from the well edge.
* The default is "false".
* @return true if ERC should find the contact that is farthest from the well edge.
*/
public static boolean isFindWorstCaseWell() { return cacheFindWorstCaseWellContact.getBoolean(); }
/**
* Method to set whether ERC should find the contact that is farthest from the well edge.
* @param on true if ERC should find the contact that is farthest from the well edge.
*/
public static void setFindWorstCaseWell(boolean on) { cacheFindWorstCaseWellContact.setBoolean(on); }
/**** ANTENNA Preferences ***/
private Pref getArcProtoAntennaPref(ArcProto ap)
{
- Pref pref = (Pref)defaultAntennaRatioPrefs.get(this);
+ Pref pref = (Pref)defaultAntennaRatioPrefs.get(ap);
if (pref == null)
{
double factory = ERCAntenna.DEFPOLYRATIO;
if (ap.getFunction().isMetal()) factory = ERCAntenna.DEFMETALRATIO;
pref = Pref.makeDoublePref("DefaultAntennaRatioFor" + ap.getName() + "IN" + ap.getTechnology().getTechName(), ERC.tool.prefs, factory);
- defaultAntennaRatioPrefs.put(this, pref);
+ defaultAntennaRatioPrefs.put(ap, pref);
}
return pref;
}
/**
* Method to set the antenna ratio of this ArcProto.
* Antenna ratios are used in antenna checks that make sure the ratio of the area of a layer is correct.
* @param ratio the antenna ratio of this ArcProto.
*/
public void setAntennaRatio(ArcProto ap, double ratio) { getArcProtoAntennaPref(ap).setDouble(ratio); }
/**
* Method to tell the antenna ratio of this ArcProto.
* Antenna ratios are used in antenna checks that make sure the ratio of the area of a layer is correct.
* @return the antenna ratio of this ArcProto.
*/
public double getAntennaRatio(ArcProto ap) { return getArcProtoAntennaPref(ap).getDouble(); }
}
| false | true | private Pref getArcProtoAntennaPref(ArcProto ap)
{
Pref pref = (Pref)defaultAntennaRatioPrefs.get(this);
if (pref == null)
{
double factory = ERCAntenna.DEFPOLYRATIO;
if (ap.getFunction().isMetal()) factory = ERCAntenna.DEFMETALRATIO;
pref = Pref.makeDoublePref("DefaultAntennaRatioFor" + ap.getName() + "IN" + ap.getTechnology().getTechName(), ERC.tool.prefs, factory);
defaultAntennaRatioPrefs.put(this, pref);
}
return pref;
}
| private Pref getArcProtoAntennaPref(ArcProto ap)
{
Pref pref = (Pref)defaultAntennaRatioPrefs.get(ap);
if (pref == null)
{
double factory = ERCAntenna.DEFPOLYRATIO;
if (ap.getFunction().isMetal()) factory = ERCAntenna.DEFMETALRATIO;
pref = Pref.makeDoublePref("DefaultAntennaRatioFor" + ap.getName() + "IN" + ap.getTechnology().getTechName(), ERC.tool.prefs, factory);
defaultAntennaRatioPrefs.put(ap, pref);
}
return pref;
}
|
diff --git a/weechat-android/src/com/ubergeek42/WeechatAndroid/WeechatChatviewActivity.java b/weechat-android/src/com/ubergeek42/WeechatAndroid/WeechatChatviewActivity.java
index 4d54543..8fe6095 100644
--- a/weechat-android/src/com/ubergeek42/WeechatAndroid/WeechatChatviewActivity.java
+++ b/weechat-android/src/com/ubergeek42/WeechatAndroid/WeechatChatviewActivity.java
@@ -1,291 +1,292 @@
package com.ubergeek42.WeechatAndroid;
import java.util.Arrays;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.ubergeek42.weechat.Buffer;
import com.ubergeek42.weechat.BufferObserver;
public class WeechatChatviewActivity extends Activity implements OnClickListener, OnKeyListener, BufferObserver, OnSharedPreferenceChangeListener {
private static Logger logger = LoggerFactory.getLogger(WeechatChatviewActivity.class);
private ListView chatlines;
private EditText inputBox;
private Button sendButton;
private boolean mBound;
private RelayServiceBinder rsb;
private String bufferName;
private Buffer buffer;
private ChatLinesAdapter chatlineAdapter;
private String[] nickCache;
// Settings for keeping track of the current tab completion stuff
private boolean tabCompletingInProgress;
private Vector<String> tabCompleteMatches;
private int tabCompleteCurrentIndex;
private int tabCompleteWordStart;
private int tabCompleteWordEnd;
private SharedPreferences prefs;
private boolean enableTabComplete = true;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatview_main);
Bundle extras = getIntent().getExtras();
if (extras == null) {
finish(); // quit if no view given..
}
prefs = PreferenceManager.getDefaultSharedPreferences(this.getBaseContext());
prefs.registerOnSharedPreferenceChangeListener(this);
enableTabComplete = prefs.getBoolean("tab_completion", true);
bufferName = extras.getString("buffer");
setTitle("Weechat - " + bufferName);
chatlines = (ListView) findViewById(R.id.chatview_lines);
inputBox = (EditText)findViewById(R.id.chatview_input);
sendButton = (Button)findViewById(R.id.chatview_send);
String[] message = {"Loading. Please wait..."};
chatlines.setAdapter(new ArrayAdapter<String>(this, R.layout.tips_list_item, message));
chatlines.setEmptyView(findViewById(android.R.id.empty));
sendButton.setOnClickListener(this);
inputBox.setOnKeyListener(this);
}
@Override
protected void onStart() {
super.onStart();
// Bind to the relay service in the background
Intent i = new Intent(this, RelayService.class);
mBound = bindService(i, mConnection, Context.BIND_AUTO_CREATE);
if (!mBound) {
finish();
}
}
@Override
protected void onStop() {
super.onStop();
if (buffer!=null) {
buffer.removeObserver(this);
rsb.unsubscribeBuffer(buffer.getPointer());
}
if(mBound) {
unbindService(mConnection);
mBound = false;
}
}
private void initView() { // Called once we have a connection with the backend
buffer = rsb.getBufferByName(bufferName);
buffer.addObserver(this);
// Subscribe to the buffer(gets the lines for it, and gets nicklist)
rsb.subscribeBuffer(buffer.getPointer());
chatlineAdapter = new ChatLinesAdapter(this, buffer);
chatlines.setAdapter(chatlineAdapter);
onLineAdded();
}
ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
rsb = (RelayServiceBinder) service;
mBound = true;
initView();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
rsb = null;
// Only called when the background service crashes...
}
};
// Sends the message if necessary
Runnable messageSender = new Runnable(){
@Override
public void run() {
String input = inputBox.getText().toString();
if (input.length() == 0) return; // Ignore empty input box
String message = "input " + bufferName + " " + input;
inputBox.setText("");
rsb.sendMessage(message + "\n");
}
};
// User pressed enter in the input box
@Override
public boolean onKey(View v, int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_ENTER && event.getAction()==KeyEvent.ACTION_UP) {
tabCompletingInProgress=false;
runOnUiThread(messageSender);
return true;
- } else if(keycode == KeyEvent.KEYCODE_TAB && event.getAction() == KeyEvent.ACTION_DOWN) {
+ } else if((keycode == KeyEvent.KEYCODE_TAB || keycode == KeyEvent.KEYCODE_SEARCH) && event.getAction() == KeyEvent.ACTION_DOWN) {
if (!enableTabComplete || nickCache == null) return true;
// Get the current input text
String txt = inputBox.getText().toString();
if (tabCompletingInProgress == false) {
int currentPos = inputBox.getSelectionStart()-1;
int start = currentPos;
// Search backwards to find the beginning of the word
while(start>0 && txt.charAt(start) != ' ') start--;
if (start>0) start++;
String prefix = txt.substring(start, currentPos+1).toLowerCase();
if (prefix.length()<2) {
//No tab completion
return true;
}
Vector<String> matches = new Vector<String>();
for(String possible: nickCache) {
String temp = possible.toLowerCase().trim();
if (temp.startsWith(prefix)) {
matches.add(possible.trim());
}
}
if (matches.size() == 0) return true;
tabCompletingInProgress = true;
tabCompleteMatches = matches;
tabCompleteCurrentIndex = 0;
tabCompleteWordStart = start;
tabCompleteWordEnd = currentPos;
} else {
tabCompleteWordEnd = tabCompleteWordStart + tabCompleteMatches.get(tabCompleteCurrentIndex).length()-1; // end of current tab complete word
tabCompleteCurrentIndex = (tabCompleteCurrentIndex+1)%tabCompleteMatches.size(); // next match
}
String newtext = txt.substring(0, tabCompleteWordStart) + tabCompleteMatches.get(tabCompleteCurrentIndex) + txt.substring(tabCompleteWordEnd+1);
tabCompleteWordEnd = tabCompleteWordStart + tabCompleteMatches.get(tabCompleteCurrentIndex).length(); // end of new tabcomplete word
inputBox.setText(newtext);
inputBox.setSelection(tabCompleteWordEnd);
return true;
- } else if(keycode == KeyEvent.KEYCODE_TAB && event.getAction() == KeyEvent.ACTION_UP) {
- return true; // eat the tab up, but don't reset tabCompletingInProgress to false
+ } else if(KeyEvent.isModifierKey(keycode) || keycode == KeyEvent.KEYCODE_TAB || keycode == KeyEvent.KEYCODE_SEARCH) {
+ // If it was a modifier key(or tab/search), don't kill tabCompletingInProgress
+ return true;
}
tabCompletingInProgress = false;
return false;
}
// Send button pressed
@Override
public void onClick(View arg0) {
runOnUiThread(messageSender);
}
@Override
public void onLineAdded() {
rsb.resetNotifications();
buffer.resetHighlight();
buffer.resetUnread();
chatlineAdapter.notifyChanged();
chatlines.post(new Runnable() {
@Override
public void run() {
chatlines.setSelectionFromTop(chatlineAdapter.getCount()-1, 0);
}
});
}
@Override
public void onBufferClosed() {
// Close when the buffer is closed
buffer.removeObserver(this);
finish();
}
@Override
public void onNicklistChanged() {
nickCache = buffer.getNicks();
Arrays.sort(nickCache);
}
//==== Options Menu
@Override
// Build the options menu
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
menu.add("Toggle Timestamps");
menu.add("Toggle Filters");
menu.add("Close");
menu.add("Settings");
return super.onPrepareOptionsMenu(menu);
}
@Override
// Handle the options when the user presses the Menu key
public boolean onOptionsItemSelected(MenuItem item) {
String s = (String) item.getTitle();
if (s.equals("Close")) {
buffer.removeObserver(this);
finish();
} else if (s.equals("Settings")) {
Intent i = new Intent(this, WeechatPreferencesActivity.class);
startActivity(i);
} else if (s.equals("Toggle Timestamps")) {
chatlineAdapter.toggleTimestamps();
} else if (s.equals("Toggle Filters")) {
chatlineAdapter.toggleFilters();
}
return true;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("tab_completion")) {
enableTabComplete = prefs.getBoolean("tab_completion", true);
}
}
}
| false | true | public boolean onKey(View v, int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_ENTER && event.getAction()==KeyEvent.ACTION_UP) {
tabCompletingInProgress=false;
runOnUiThread(messageSender);
return true;
} else if(keycode == KeyEvent.KEYCODE_TAB && event.getAction() == KeyEvent.ACTION_DOWN) {
if (!enableTabComplete || nickCache == null) return true;
// Get the current input text
String txt = inputBox.getText().toString();
if (tabCompletingInProgress == false) {
int currentPos = inputBox.getSelectionStart()-1;
int start = currentPos;
// Search backwards to find the beginning of the word
while(start>0 && txt.charAt(start) != ' ') start--;
if (start>0) start++;
String prefix = txt.substring(start, currentPos+1).toLowerCase();
if (prefix.length()<2) {
//No tab completion
return true;
}
Vector<String> matches = new Vector<String>();
for(String possible: nickCache) {
String temp = possible.toLowerCase().trim();
if (temp.startsWith(prefix)) {
matches.add(possible.trim());
}
}
if (matches.size() == 0) return true;
tabCompletingInProgress = true;
tabCompleteMatches = matches;
tabCompleteCurrentIndex = 0;
tabCompleteWordStart = start;
tabCompleteWordEnd = currentPos;
} else {
tabCompleteWordEnd = tabCompleteWordStart + tabCompleteMatches.get(tabCompleteCurrentIndex).length()-1; // end of current tab complete word
tabCompleteCurrentIndex = (tabCompleteCurrentIndex+1)%tabCompleteMatches.size(); // next match
}
String newtext = txt.substring(0, tabCompleteWordStart) + tabCompleteMatches.get(tabCompleteCurrentIndex) + txt.substring(tabCompleteWordEnd+1);
tabCompleteWordEnd = tabCompleteWordStart + tabCompleteMatches.get(tabCompleteCurrentIndex).length(); // end of new tabcomplete word
inputBox.setText(newtext);
inputBox.setSelection(tabCompleteWordEnd);
return true;
} else if(keycode == KeyEvent.KEYCODE_TAB && event.getAction() == KeyEvent.ACTION_UP) {
return true; // eat the tab up, but don't reset tabCompletingInProgress to false
}
tabCompletingInProgress = false;
return false;
}
| public boolean onKey(View v, int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_ENTER && event.getAction()==KeyEvent.ACTION_UP) {
tabCompletingInProgress=false;
runOnUiThread(messageSender);
return true;
} else if((keycode == KeyEvent.KEYCODE_TAB || keycode == KeyEvent.KEYCODE_SEARCH) && event.getAction() == KeyEvent.ACTION_DOWN) {
if (!enableTabComplete || nickCache == null) return true;
// Get the current input text
String txt = inputBox.getText().toString();
if (tabCompletingInProgress == false) {
int currentPos = inputBox.getSelectionStart()-1;
int start = currentPos;
// Search backwards to find the beginning of the word
while(start>0 && txt.charAt(start) != ' ') start--;
if (start>0) start++;
String prefix = txt.substring(start, currentPos+1).toLowerCase();
if (prefix.length()<2) {
//No tab completion
return true;
}
Vector<String> matches = new Vector<String>();
for(String possible: nickCache) {
String temp = possible.toLowerCase().trim();
if (temp.startsWith(prefix)) {
matches.add(possible.trim());
}
}
if (matches.size() == 0) return true;
tabCompletingInProgress = true;
tabCompleteMatches = matches;
tabCompleteCurrentIndex = 0;
tabCompleteWordStart = start;
tabCompleteWordEnd = currentPos;
} else {
tabCompleteWordEnd = tabCompleteWordStart + tabCompleteMatches.get(tabCompleteCurrentIndex).length()-1; // end of current tab complete word
tabCompleteCurrentIndex = (tabCompleteCurrentIndex+1)%tabCompleteMatches.size(); // next match
}
String newtext = txt.substring(0, tabCompleteWordStart) + tabCompleteMatches.get(tabCompleteCurrentIndex) + txt.substring(tabCompleteWordEnd+1);
tabCompleteWordEnd = tabCompleteWordStart + tabCompleteMatches.get(tabCompleteCurrentIndex).length(); // end of new tabcomplete word
inputBox.setText(newtext);
inputBox.setSelection(tabCompleteWordEnd);
return true;
} else if(KeyEvent.isModifierKey(keycode) || keycode == KeyEvent.KEYCODE_TAB || keycode == KeyEvent.KEYCODE_SEARCH) {
// If it was a modifier key(or tab/search), don't kill tabCompletingInProgress
return true;
}
tabCompletingInProgress = false;
return false;
}
|
diff --git a/WEB-INF/src/org/cdlib/xtf/saxonExt/exec/InputElement.java b/WEB-INF/src/org/cdlib/xtf/saxonExt/exec/InputElement.java
index 692a58e7..3b651ba3 100644
--- a/WEB-INF/src/org/cdlib/xtf/saxonExt/exec/InputElement.java
+++ b/WEB-INF/src/org/cdlib/xtf/saxonExt/exec/InputElement.java
@@ -1,221 +1,222 @@
package org.cdlib.xtf.saxonExt.exec;
/*
* Copyright (c) 2004, Regents of the University of California
* 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 University of California nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.ByteArrayOutputStream;
import java.util.Properties;
import net.sf.saxon.FeatureKeys;
import net.sf.saxon.expr.Expression;
import net.sf.saxon.expr.RoleLocator;
import net.sf.saxon.expr.TypeChecker;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.instruct.Executable;
import net.sf.saxon.instruct.GeneralVariable;
import net.sf.saxon.instruct.InstructionDetails;
import net.sf.saxon.instruct.TailCall;
import net.sf.saxon.om.*;
import net.sf.saxon.style.XSLGeneralVariable;
import net.sf.saxon.trace.InstructionInfo;
import net.sf.saxon.trace.Location;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.Value;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.cdlib.xtf.util.XTFSaxonErrorListener;
/**
* Represents an <input> element below a <run> instruction.
*
* @author Martin Haye
*/
public class InputElement extends XSLGeneralVariable {
/**
* Determine whether this node is an instruction.
* @return false - it is not an instruction
*/
public boolean isInstruction() {
return false;
}
/**
* Determine whether this type of element is allowed to contain a template-body
* @return false: no, it may not contain a template-body
*/
public boolean mayContainSequenceConstructor() {
return false;
}
public void prepareAttributes() throws TransformerConfigurationException
{
getVariableFingerprint();
AttributeCollection atts = getAttributeList();
String selectAtt = null;
for (int a=0; a<atts.getLength(); a++) {
String localName = atts.getLocalName(a);
if (localName.equals("select")) {
selectAtt = atts.getValue(a);
} else {
checkUnknownAttribute(atts.getNameCode(a));
}
}
if (selectAtt!=null) {
select = makeExpression(selectAtt);
}
} // prepareAttributes()
public void validate() throws TransformerConfigurationException
{
if (!(getParent() instanceof RunElement)) {
compileError("parent node must be exec:run");
}
if( select != null ) {
select = typeCheck("select", select);
try {
RoleLocator role =
new RoleLocator(RoleLocator.INSTRUCTION, "exec:run/input", 0, null);
select = TypeChecker.staticTypeCheck(select,
SequenceType.SINGLE_ATOMIC,
false, role, getStaticContext());
} catch (XPathException err) {
compileError(err);
}
}
} // validate()
public Expression compile(Executable exec) throws TransformerConfigurationException {
InputInstruction inst = new InputInstruction();
initializeInstruction(exec, inst);
return inst;
}
protected static class InputInstruction extends GeneralVariable {
public InputInstruction() {}
public InstructionInfo getInstructionInfo() {
InstructionDetails details = (InstructionDetails)super.getInstructionInfo();
details.setConstructType(Location.EXTENSION_INSTRUCTION);
return details;
}
public TailCall processLeavingTail(XPathContext context) {
return null;
}
/**
* Evaluate the variable (method exists only to satisfy the interface)
*/
public ValueRepresentation evaluateVariable(XPathContext context) throws XPathException {
throw new UnsupportedOperationException();
}
/**
* Gets a proper byte stream for the value. If the value is simply a
* string, it will be a UTF-8 encoding of that string. If the value is
* some structured XML, it will be XML with a header.
*
* @param context Context for the evaluation
* @return A byte stream, properly formatted
*/
public byte[] getStream( XPathContext context ) throws XPathException
{
try {
// Convert the value to a proper NodeInfo we can examine
Value value = Value.asValue( getSelectValue(context) );
NodeInfo node = (NodeInfo)
value.convertToJava( NodeInfo.class, context );
// Detect whether there are any elements in the document.
boolean anyElements = false;
AxisIterator iter = node.iterateAxis( Axis.CHILD );
while( true ) {
Item kid = iter.next();
if( kid == null )
break;
if( kid instanceof NodeInfo && ((NodeInfo)kid).hasChildNodes() )
anyElements = true;
}
// If no elements, get the simple string value.
if( !anyElements ) {
- String str = value.toString();
+ String str = value.toString() + "\n";
return str.getBytes( "UTF-8" );
}
// Convert to XML.
ByteArrayOutputStream outStream = new ByteArrayOutputStream( 100 );
StreamResult streamResult = new StreamResult( outStream );
TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl();
// Avoid NamePool translation, as it triggers a Saxon bug.
factory.setAttribute( FeatureKeys.NAME_POOL, node.getNamePool() );
Transformer trans = factory.newTransformer();
Properties props = trans.getOutputProperties();
props.put( "indent", "yes" );
props.put( "method", "xml" );
trans.setOutputProperties( props );
// Make sure errors get directed to the right place.
if( !(trans.getErrorListener() instanceof XTFSaxonErrorListener) )
trans.setErrorListener( new XTFSaxonErrorListener() );
trans.transform( node, streamResult );
// All done.
+ outStream.write( "\n".getBytes() );
outStream.close();
return outStream.toByteArray();
}
catch( Exception e ) {
dynamicError(
"Exception occurred converting input for external command: " + e,
context );
return null;
}
} // getStream()
} // class InputElement
} // class InputElement
| false | true | public byte[] getStream( XPathContext context ) throws XPathException
{
try {
// Convert the value to a proper NodeInfo we can examine
Value value = Value.asValue( getSelectValue(context) );
NodeInfo node = (NodeInfo)
value.convertToJava( NodeInfo.class, context );
// Detect whether there are any elements in the document.
boolean anyElements = false;
AxisIterator iter = node.iterateAxis( Axis.CHILD );
while( true ) {
Item kid = iter.next();
if( kid == null )
break;
if( kid instanceof NodeInfo && ((NodeInfo)kid).hasChildNodes() )
anyElements = true;
}
// If no elements, get the simple string value.
if( !anyElements ) {
String str = value.toString();
return str.getBytes( "UTF-8" );
}
// Convert to XML.
ByteArrayOutputStream outStream = new ByteArrayOutputStream( 100 );
StreamResult streamResult = new StreamResult( outStream );
TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl();
// Avoid NamePool translation, as it triggers a Saxon bug.
factory.setAttribute( FeatureKeys.NAME_POOL, node.getNamePool() );
Transformer trans = factory.newTransformer();
Properties props = trans.getOutputProperties();
props.put( "indent", "yes" );
props.put( "method", "xml" );
trans.setOutputProperties( props );
// Make sure errors get directed to the right place.
if( !(trans.getErrorListener() instanceof XTFSaxonErrorListener) )
trans.setErrorListener( new XTFSaxonErrorListener() );
trans.transform( node, streamResult );
// All done.
outStream.close();
return outStream.toByteArray();
}
catch( Exception e ) {
dynamicError(
"Exception occurred converting input for external command: " + e,
context );
return null;
}
} // getStream()
| public byte[] getStream( XPathContext context ) throws XPathException
{
try {
// Convert the value to a proper NodeInfo we can examine
Value value = Value.asValue( getSelectValue(context) );
NodeInfo node = (NodeInfo)
value.convertToJava( NodeInfo.class, context );
// Detect whether there are any elements in the document.
boolean anyElements = false;
AxisIterator iter = node.iterateAxis( Axis.CHILD );
while( true ) {
Item kid = iter.next();
if( kid == null )
break;
if( kid instanceof NodeInfo && ((NodeInfo)kid).hasChildNodes() )
anyElements = true;
}
// If no elements, get the simple string value.
if( !anyElements ) {
String str = value.toString() + "\n";
return str.getBytes( "UTF-8" );
}
// Convert to XML.
ByteArrayOutputStream outStream = new ByteArrayOutputStream( 100 );
StreamResult streamResult = new StreamResult( outStream );
TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl();
// Avoid NamePool translation, as it triggers a Saxon bug.
factory.setAttribute( FeatureKeys.NAME_POOL, node.getNamePool() );
Transformer trans = factory.newTransformer();
Properties props = trans.getOutputProperties();
props.put( "indent", "yes" );
props.put( "method", "xml" );
trans.setOutputProperties( props );
// Make sure errors get directed to the right place.
if( !(trans.getErrorListener() instanceof XTFSaxonErrorListener) )
trans.setErrorListener( new XTFSaxonErrorListener() );
trans.transform( node, streamResult );
// All done.
outStream.write( "\n".getBytes() );
outStream.close();
return outStream.toByteArray();
}
catch( Exception e ) {
dynamicError(
"Exception occurred converting input for external command: " + e,
context );
return null;
}
} // getStream()
|
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ECFTransport.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ECFTransport.java
index b33403aac..d4fb5b666 100644
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ECFTransport.java
+++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ECFTransport.java
@@ -1,123 +1,123 @@
/*******************************************************************************
* Copyright (c) 2007 IBM Corporation and others. All rights reserved. This
* program and the accompanying materials are made available under the terms of
* the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation Stefan Liebig -
* random tweaks
******************************************************************************/
package org.eclipse.equinox.internal.p2.artifact.repository;
import java.io.IOException;
import java.io.OutputStream;
import org.eclipse.core.runtime.*;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.filetransfer.*;
import org.eclipse.ecf.filetransfer.events.*;
import org.eclipse.ecf.filetransfer.identity.FileCreateException;
import org.eclipse.ecf.filetransfer.identity.FileIDFactory;
import org.eclipse.ecf.filetransfer.service.IRetrieveFileTransferFactory;
import org.eclipse.equinox.p2.core.helpers.LogHelper;
import org.osgi.util.tracker.ServiceTracker;
/**
* A transport implementation that uses ECF file transfer API.
*/
public class ECFTransport extends Transport {
/**
* The singleton transport instance.
*/
private static ECFTransport instance;
private final ServiceTracker retrievalFactoryTracker;
/**
* Returns an initialized instance of ECFTransport
*/
public static synchronized ECFTransport getInstance() {
if (instance == null) {
instance = new ECFTransport();
}
return instance;
}
/**
* Private to avoid client instantiation.
*/
private ECFTransport() {
retrievalFactoryTracker = new ServiceTracker(Activator.getContext(), IRetrieveFileTransferFactory.class.getName(), null);
retrievalFactoryTracker.open();
}
protected IStatus convertToStatus(Exception failure) {
if (failure == null)
return Status.OK_STATUS;
if (failure instanceof UserCancelledException)
return new Status(IStatus.CANCEL, Activator.ID, failure.getMessage(), failure);
return new Status(IStatus.ERROR, Activator.ID, "error during transfer", failure);
}
public IStatus download(String toDownload, OutputStream target, IProgressMonitor monitor) {
IRetrieveFileTransferFactory factory = (IRetrieveFileTransferFactory) retrievalFactoryTracker.getService();
if (factory == null)
return new Status(IStatus.ERROR, Activator.ID, "ECF Transfer manager not available");
return transfer(factory.newInstance(), toDownload, target, monitor);
}
private IStatus transfer(final IRetrieveFileTransferContainerAdapter retrievalContainer, final String toDownload, final OutputStream target, final IProgressMonitor monitor) {
final IStatus[] result = new IStatus[1];
IFileTransferListener listener = new IFileTransferListener() {
public void handleTransferEvent(IFileTransferEvent event) {
if (event instanceof IIncomingFileTransferReceiveStartEvent) {
IIncomingFileTransferReceiveStartEvent rse = (IIncomingFileTransferReceiveStartEvent) event;
try {
if (target != null) {
rse.receive(target);
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (event instanceof IIncomingFileTransferReceiveDataEvent) {
IIncomingFileTransfer source = ((IIncomingFileTransferReceiveDataEvent) event).getSource();
ID id = source.getID();
// TODO do proper monitor things here.
if (monitor != null) {
- monitor.subTask("Transferring " + id == null ? "" : id.getName() + " (" + (int) (source.getPercentComplete() * 100) + "% complete)");
+ monitor.subTask("Transferring " + (id == null ? "" : id.getName()) + " (" + (int) (source.getPercentComplete() * 100) + "% complete)");
if (monitor.isCanceled())
source.cancel();
}
}
if (event instanceof IIncomingFileTransferReceiveDoneEvent) {
IStatus status = convertToStatus(((IIncomingFileTransferReceiveDoneEvent) event).getException());
synchronized (result) {
- result[0] = status;;
+ result[0] = status;
result.notify();
}
}
}
};
try {
retrievalContainer.sendRetrieveRequest(FileIDFactory.getDefault().createFileID(retrievalContainer.getRetrieveNamespace(), toDownload), listener, null);
} catch (IncomingFileTransferException e) {
return new Status(IStatus.ERROR, Activator.ID, "error during transfer", e);
} catch (FileCreateException e) {
return new Status(IStatus.ERROR, Activator.ID, "error during transfer - could not create file", e);
}
synchronized (result) {
while (result[0] == null) {
boolean logged = false;
try {
result.wait();
} catch (InterruptedException e) {
if (!logged)
LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "Unexpected interrupt while waiting on ECF transfer", e)); //$NON-NLS-1$
}
}
}
return result[0];
}
}
| false | true | private IStatus transfer(final IRetrieveFileTransferContainerAdapter retrievalContainer, final String toDownload, final OutputStream target, final IProgressMonitor monitor) {
final IStatus[] result = new IStatus[1];
IFileTransferListener listener = new IFileTransferListener() {
public void handleTransferEvent(IFileTransferEvent event) {
if (event instanceof IIncomingFileTransferReceiveStartEvent) {
IIncomingFileTransferReceiveStartEvent rse = (IIncomingFileTransferReceiveStartEvent) event;
try {
if (target != null) {
rse.receive(target);
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (event instanceof IIncomingFileTransferReceiveDataEvent) {
IIncomingFileTransfer source = ((IIncomingFileTransferReceiveDataEvent) event).getSource();
ID id = source.getID();
// TODO do proper monitor things here.
if (monitor != null) {
monitor.subTask("Transferring " + id == null ? "" : id.getName() + " (" + (int) (source.getPercentComplete() * 100) + "% complete)");
if (monitor.isCanceled())
source.cancel();
}
}
if (event instanceof IIncomingFileTransferReceiveDoneEvent) {
IStatus status = convertToStatus(((IIncomingFileTransferReceiveDoneEvent) event).getException());
synchronized (result) {
result[0] = status;;
result.notify();
}
}
}
};
try {
retrievalContainer.sendRetrieveRequest(FileIDFactory.getDefault().createFileID(retrievalContainer.getRetrieveNamespace(), toDownload), listener, null);
} catch (IncomingFileTransferException e) {
return new Status(IStatus.ERROR, Activator.ID, "error during transfer", e);
} catch (FileCreateException e) {
return new Status(IStatus.ERROR, Activator.ID, "error during transfer - could not create file", e);
}
synchronized (result) {
while (result[0] == null) {
boolean logged = false;
try {
result.wait();
} catch (InterruptedException e) {
if (!logged)
LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "Unexpected interrupt while waiting on ECF transfer", e)); //$NON-NLS-1$
}
}
}
return result[0];
}
| private IStatus transfer(final IRetrieveFileTransferContainerAdapter retrievalContainer, final String toDownload, final OutputStream target, final IProgressMonitor monitor) {
final IStatus[] result = new IStatus[1];
IFileTransferListener listener = new IFileTransferListener() {
public void handleTransferEvent(IFileTransferEvent event) {
if (event instanceof IIncomingFileTransferReceiveStartEvent) {
IIncomingFileTransferReceiveStartEvent rse = (IIncomingFileTransferReceiveStartEvent) event;
try {
if (target != null) {
rse.receive(target);
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (event instanceof IIncomingFileTransferReceiveDataEvent) {
IIncomingFileTransfer source = ((IIncomingFileTransferReceiveDataEvent) event).getSource();
ID id = source.getID();
// TODO do proper monitor things here.
if (monitor != null) {
monitor.subTask("Transferring " + (id == null ? "" : id.getName()) + " (" + (int) (source.getPercentComplete() * 100) + "% complete)");
if (monitor.isCanceled())
source.cancel();
}
}
if (event instanceof IIncomingFileTransferReceiveDoneEvent) {
IStatus status = convertToStatus(((IIncomingFileTransferReceiveDoneEvent) event).getException());
synchronized (result) {
result[0] = status;
result.notify();
}
}
}
};
try {
retrievalContainer.sendRetrieveRequest(FileIDFactory.getDefault().createFileID(retrievalContainer.getRetrieveNamespace(), toDownload), listener, null);
} catch (IncomingFileTransferException e) {
return new Status(IStatus.ERROR, Activator.ID, "error during transfer", e);
} catch (FileCreateException e) {
return new Status(IStatus.ERROR, Activator.ID, "error during transfer - could not create file", e);
}
synchronized (result) {
while (result[0] == null) {
boolean logged = false;
try {
result.wait();
} catch (InterruptedException e) {
if (!logged)
LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "Unexpected interrupt while waiting on ECF transfer", e)); //$NON-NLS-1$
}
}
}
return result[0];
}
|
diff --git a/src/main/java/org/bukkit/command/defaults/HelpCommand.java b/src/main/java/org/bukkit/command/defaults/HelpCommand.java
index 17867c49..9ea5d6d6 100644
--- a/src/main/java/org/bukkit/command/defaults/HelpCommand.java
+++ b/src/main/java/org/bukkit/command/defaults/HelpCommand.java
@@ -1,92 +1,92 @@
package org.bukkit.command.defaults;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.help.HelpMap;
import org.bukkit.help.HelpTopic;
import org.bukkit.util.ChatPaginator;
import java.util.Arrays;
public class HelpCommand extends VanillaCommand {
public HelpCommand() {
super("help");
this.description = "Shows the help menu";
this.usageMessage = "/help <pageNumber>\n/help <topic>\n/help <topic> <pageNumber>";
this.setPermission("bukkit.command.help");
}
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
String command;
int pageNumber;
int pageHeight;
int pageWidth;
if (args.length == 0) {
command = "";
pageNumber = 1;
} else if (NumberUtils.isDigits(args[args.length - 1])) {
command = StringUtils.join(ArrayUtils.subarray(args, 0, args.length - 1), " ");
pageNumber = NumberUtils.createInteger(args[args.length - 1]);
} else {
command = StringUtils.join(args, " ");
pageNumber = 1;
}
if (sender instanceof ConsoleCommandSender) {
pageHeight = ChatPaginator.UNBOUNDED_PAGE_HEIGHT;
pageWidth = ChatPaginator.UNBOUNDED_PAGE_WIDTH;
} else {
pageHeight = ChatPaginator.CLOSED_CHAT_PAGE_HEIGHT - 1;
- pageWidth = ChatPaginator.AVERAGE_CHAT_PAGE_WIDTH;
+ pageWidth = ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH;
}
HelpMap helpMap = Bukkit.getServer().getHelpMap();
HelpTopic topic = helpMap.getHelpTopic(command);
if (topic == null) {
topic = helpMap.getHelpTopic("/" + command);
}
if (topic == null || !topic.canSee(sender)) {
sender.sendMessage(ChatColor.RED + "No help for " + command);
return true;
}
ChatPaginator.ChatPage page = ChatPaginator.paginate(topic.getFullText(sender), pageNumber, pageWidth, pageHeight);
StringBuilder header = new StringBuilder();
header.append(ChatColor.GREEN);
header.append("===== Help: ");
header.append(topic.getName());
header.append(" ");
if (page.getTotalPages() > 1) {
header.append("(");
header.append(page.getPageNumber());
header.append(" of ");
header.append(page.getTotalPages());
header.append(") ");
}
for (int i = header.length(); i < ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH; i++) {
header.append("=");
}
sender.sendMessage(header.toString());
sender.sendMessage(page.getLines());
return true;
}
@Override
public boolean matches(String input) {
return input.startsWith("help") || input.startsWith("?");
}
}
| true | true | public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
String command;
int pageNumber;
int pageHeight;
int pageWidth;
if (args.length == 0) {
command = "";
pageNumber = 1;
} else if (NumberUtils.isDigits(args[args.length - 1])) {
command = StringUtils.join(ArrayUtils.subarray(args, 0, args.length - 1), " ");
pageNumber = NumberUtils.createInteger(args[args.length - 1]);
} else {
command = StringUtils.join(args, " ");
pageNumber = 1;
}
if (sender instanceof ConsoleCommandSender) {
pageHeight = ChatPaginator.UNBOUNDED_PAGE_HEIGHT;
pageWidth = ChatPaginator.UNBOUNDED_PAGE_WIDTH;
} else {
pageHeight = ChatPaginator.CLOSED_CHAT_PAGE_HEIGHT - 1;
pageWidth = ChatPaginator.AVERAGE_CHAT_PAGE_WIDTH;
}
HelpMap helpMap = Bukkit.getServer().getHelpMap();
HelpTopic topic = helpMap.getHelpTopic(command);
if (topic == null) {
topic = helpMap.getHelpTopic("/" + command);
}
if (topic == null || !topic.canSee(sender)) {
sender.sendMessage(ChatColor.RED + "No help for " + command);
return true;
}
ChatPaginator.ChatPage page = ChatPaginator.paginate(topic.getFullText(sender), pageNumber, pageWidth, pageHeight);
StringBuilder header = new StringBuilder();
header.append(ChatColor.GREEN);
header.append("===== Help: ");
header.append(topic.getName());
header.append(" ");
if (page.getTotalPages() > 1) {
header.append("(");
header.append(page.getPageNumber());
header.append(" of ");
header.append(page.getTotalPages());
header.append(") ");
}
for (int i = header.length(); i < ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH; i++) {
header.append("=");
}
sender.sendMessage(header.toString());
sender.sendMessage(page.getLines());
return true;
}
| public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
String command;
int pageNumber;
int pageHeight;
int pageWidth;
if (args.length == 0) {
command = "";
pageNumber = 1;
} else if (NumberUtils.isDigits(args[args.length - 1])) {
command = StringUtils.join(ArrayUtils.subarray(args, 0, args.length - 1), " ");
pageNumber = NumberUtils.createInteger(args[args.length - 1]);
} else {
command = StringUtils.join(args, " ");
pageNumber = 1;
}
if (sender instanceof ConsoleCommandSender) {
pageHeight = ChatPaginator.UNBOUNDED_PAGE_HEIGHT;
pageWidth = ChatPaginator.UNBOUNDED_PAGE_WIDTH;
} else {
pageHeight = ChatPaginator.CLOSED_CHAT_PAGE_HEIGHT - 1;
pageWidth = ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH;
}
HelpMap helpMap = Bukkit.getServer().getHelpMap();
HelpTopic topic = helpMap.getHelpTopic(command);
if (topic == null) {
topic = helpMap.getHelpTopic("/" + command);
}
if (topic == null || !topic.canSee(sender)) {
sender.sendMessage(ChatColor.RED + "No help for " + command);
return true;
}
ChatPaginator.ChatPage page = ChatPaginator.paginate(topic.getFullText(sender), pageNumber, pageWidth, pageHeight);
StringBuilder header = new StringBuilder();
header.append(ChatColor.GREEN);
header.append("===== Help: ");
header.append(topic.getName());
header.append(" ");
if (page.getTotalPages() > 1) {
header.append("(");
header.append(page.getPageNumber());
header.append(" of ");
header.append(page.getTotalPages());
header.append(") ");
}
for (int i = header.length(); i < ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH; i++) {
header.append("=");
}
sender.sendMessage(header.toString());
sender.sendMessage(page.getLines());
return true;
}
|
diff --git a/router/java/src/net/i2p/router/transport/udp/OutboundMessageState.java b/router/java/src/net/i2p/router/transport/udp/OutboundMessageState.java
index 276ec13c3..600ad3c4f 100644
--- a/router/java/src/net/i2p/router/transport/udp/OutboundMessageState.java
+++ b/router/java/src/net/i2p/router/transport/udp/OutboundMessageState.java
@@ -1,485 +1,490 @@
package net.i2p.router.transport.udp;
import java.util.Date;
import net.i2p.I2PAppContext;
import net.i2p.data.Base64;
import net.i2p.data.ByteArray;
import net.i2p.data.i2np.I2NPMessage;
import net.i2p.router.OutNetMessage;
import net.i2p.router.util.CDPQEntry;
import net.i2p.util.ByteCache;
import net.i2p.util.Log;
/**
* Maintain the outbound fragmentation for resending, for a single message.
*
*/
class OutboundMessageState implements CDPQEntry {
private final I2PAppContext _context;
private final Log _log;
/** may be null if we are part of the establishment */
private final OutNetMessage _message;
private final long _messageId;
/** will be null, unless we are part of the establishment */
private final PeerState _peer;
private final long _expiration;
private ByteArray _messageBuf;
/** fixed fragment size across the message */
private int _fragmentSize;
/** size of the I2NP message */
private final int _totalSize;
/** sends[i] is how many times the fragment has been sent, or -1 if ACKed */
private short _fragmentSends[];
private final long _startedOn;
private long _nextSendTime;
private int _pushCount;
private short _maxSends;
// private int _nextSendFragment;
/** for tracking use-after-free bugs */
private boolean _released;
private Exception _releasedBy;
// we can't use the ones in _message since it is null for injections
private long _enqueueTime;
private long _seqNum;
public static final int MAX_MSG_SIZE = 32 * 1024;
private static final int CACHE4_BYTES = MAX_MSG_SIZE;
private static final int CACHE3_BYTES = CACHE4_BYTES / 4;
private static final int CACHE2_BYTES = CACHE3_BYTES / 4;
private static final int CACHE1_BYTES = CACHE2_BYTES / 4;
private static final int CACHE1_MAX = 256;
private static final int CACHE2_MAX = CACHE1_MAX / 4;
private static final int CACHE3_MAX = CACHE2_MAX / 4;
private static final int CACHE4_MAX = CACHE3_MAX / 4;
private static final ByteCache _cache1 = ByteCache.getInstance(CACHE1_MAX, CACHE1_BYTES);
private static final ByteCache _cache2 = ByteCache.getInstance(CACHE2_MAX, CACHE2_BYTES);
private static final ByteCache _cache3 = ByteCache.getInstance(CACHE3_MAX, CACHE3_BYTES);
private static final ByteCache _cache4 = ByteCache.getInstance(CACHE4_MAX, CACHE4_BYTES);
private static final long EXPIRATION = 10*1000;
/**
* Called from UDPTransport
* TODO make two constructors, remove this, and make more things final
* @return success
* @throws IAE if too big
*/
public OutboundMessageState(I2PAppContext context, I2NPMessage msg, PeerState peer) {
this(context, null, msg, peer);
}
/**
* Called from OutboundMessageFragments
* TODO make two constructors, remove this, and make more things final
* @return success
* @throws IAE if too big
*/
public OutboundMessageState(I2PAppContext context, OutNetMessage m, PeerState peer) {
this(context, m, m.getMessage(), peer);
}
/**
* Called from OutboundMessageFragments
* @param m null if msg is "injected"
* @return success
* @throws IAE if too big
*/
private OutboundMessageState(I2PAppContext context, OutNetMessage m, I2NPMessage msg, PeerState peer) {
if (msg == null || peer == null)
throw new IllegalArgumentException();
_context = context;
_log = _context.logManager().getLog(OutboundMessageState.class);
_message = m;
_peer = peer;
int size = msg.getRawMessageSize();
acquireBuf(size);
_totalSize = msg.toRawByteArray(_messageBuf.getData());
_messageBuf.setValid(_totalSize);
_messageId = msg.getUniqueId();
_startedOn = _context.clock().now();
_nextSendTime = _startedOn;
_expiration = _startedOn + EXPIRATION;
//_expiration = msg.getExpiration();
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("Raw byte array for " + _messageId + ": " + Base64.encode(_messageBuf.getData(), 0, len));
}
/**
* @throws IAE if too big
* @since 0.9.3
*/
private void acquireBuf(int size) {
if (_messageBuf != null)
releaseBuf();
if (size <= CACHE1_BYTES)
_messageBuf = _cache1.acquire();
else if (size <= CACHE2_BYTES)
_messageBuf = _cache2.acquire();
else if (size <= CACHE3_BYTES)
_messageBuf = _cache3.acquire();
else if (size <= CACHE4_BYTES)
_messageBuf = _cache4.acquire();
else
throw new IllegalArgumentException("Size too large! " + size);
}
/**
* @since 0.9.3
*/
private void releaseBuf() {
if (_messageBuf == null)
return;
int size = _messageBuf.getData().length;
if (size == CACHE1_BYTES)
_cache1.release(_messageBuf);
else if (size == CACHE2_BYTES)
_cache2.release(_messageBuf);
else if (size == CACHE3_BYTES)
_cache3.release(_messageBuf);
else if (size == CACHE4_BYTES)
_cache4.release(_messageBuf);
_messageBuf = null;
_released = true;
}
/**
* This is synchronized with writeFragment(),
* so we do not release (probably due to an ack) while we are retransmitting.
* Also prevent double-free
*/
public synchronized void releaseResources() {
if (_messageBuf != null && !_released) {
releaseBuf();
if (_log.shouldLog(Log.WARN))
_releasedBy = new Exception ("Released on " + new Date() + " by:");
}
//_messageBuf = null;
}
public OutNetMessage getMessage() { return _message; }
public long getMessageId() { return _messageId; }
public PeerState getPeer() { return _peer; }
public boolean isExpired() {
return _expiration < _context.clock().now();
}
public boolean isComplete() {
short sends[] = _fragmentSends;
if (sends == null) return false;
for (int i = 0; i < sends.length; i++)
if (sends[i] >= 0)
return false;
// nothing else pending ack
return true;
}
public int getUnackedSize() {
short fragmentSends[] = _fragmentSends;
ByteArray messageBuf = _messageBuf;
int rv = 0;
if ( (messageBuf != null) && (fragmentSends != null) ) {
int lastSize = _totalSize % _fragmentSize;
if (lastSize == 0)
lastSize = _fragmentSize;
for (int i = 0; i < fragmentSends.length; i++) {
if (fragmentSends[i] >= (short)0) {
if (i + 1 == fragmentSends.length)
rv += lastSize;
else
rv += _fragmentSize;
}
}
}
return rv;
}
public boolean needsSending(int fragment) {
short sends[] = _fragmentSends;
if ( (sends == null) || (fragment >= sends.length) || (fragment < 0) )
return false;
return (sends[fragment] >= (short)0);
}
public long getLifetime() { return _context.clock().now() - _startedOn; }
/**
* Ack all the fragments in the ack list. As a side effect, if there are
* still unacked fragments, the 'next send' time will be updated under the
* assumption that that all of the packets within a volley would reach the
* peer within that ack frequency (2-400ms).
*
* @return true if the message was completely ACKed
*/
public boolean acked(ACKBitfield bitfield) {
// stupid brute force, but the cardinality should be trivial
short sends[] = _fragmentSends;
if (sends != null)
for (int i = 0; i < bitfield.fragmentCount() && i < sends.length; i++)
if (bitfield.received(i))
sends[i] = (short)-1;
boolean rv = isComplete();
/****
if (!rv && false) { // don't do the fast retransmit... lets give it time to get ACKed
long nextTime = _context.clock().now() + Math.max(_peer.getRTT(), ACKSender.ACK_FREQUENCY);
//_nextSendTime = Math.max(now, _startedOn+PeerState.MIN_RTO);
if (_nextSendTime <= 0)
_nextSendTime = nextTime;
else
_nextSendTime = Math.min(_nextSendTime, nextTime);
//if (now + 100 > _nextSendTime)
// _nextSendTime = now + 100;
//_nextSendTime = now;
}
****/
return rv;
}
public long getNextSendTime() { return _nextSendTime; }
public void setNextSendTime(long when) { _nextSendTime = when; }
/**
* The max number of sends for any fragment, which is the
* same as the push count, at least as it's coded now.
*/
public int getMaxSends() { return _maxSends; }
/**
* The number of times we've pushed some fragments, which is the
* same as the max sends, at least as it's coded now.
*/
public int getPushCount() { return _pushCount; }
/** note that we have pushed the message fragments */
public void push() {
// these will never be different...
_pushCount++;
if (_pushCount > _maxSends)
_maxSends = (short)_pushCount;
if (_fragmentSends != null)
for (int i = 0; i < _fragmentSends.length; i++)
if (_fragmentSends[i] >= (short)0)
_fragmentSends[i] = (short)(1 + _fragmentSends[i]);
}
/**
* Whether fragment() has been called.
* NOT whether it has more than one fragment.
*
* Caller should synchronize
*
* @return true iff fragment() has been called previously
*/
public boolean isFragmented() { return _fragmentSends != null; }
/**
* Prepare the message for fragmented delivery, using no more than
* fragmentSize bytes per fragment.
*
* Caller should synchronize
*
* @throws IllegalStateException if called more than once
*/
public void fragment(int fragmentSize) {
if (_fragmentSends != null)
throw new IllegalStateException();
int numFragments = _totalSize / fragmentSize;
if (numFragments * fragmentSize < _totalSize)
numFragments++;
// This should never happen, as 534 bytes * 64 fragments > 32KB, and we won't bid on > 32KB
if (numFragments > InboundMessageState.MAX_FRAGMENTS)
throw new IllegalArgumentException("Fragmenting a " + _totalSize + " message into " + numFragments + " fragments - too many!");
if (_log.shouldLog(Log.DEBUG))
_log.debug("Fragmenting a " + _totalSize + " message into " + numFragments + " fragments");
//_fragmentEnd = new int[numFragments];
_fragmentSends = new short[numFragments];
//Arrays.fill(_fragmentEnd, -1);
//Arrays.fill(_fragmentSends, (short)0);
_fragmentSize = fragmentSize;
}
/**
* How many fragments in the message.
* Only valid after fragment() has been called.
* Returns -1 before then.
*
* Caller should synchronize
*/
public int getFragmentCount() {
if (_fragmentSends == null)
return -1;
else
return _fragmentSends.length;
}
/**
* The size of the I2NP message. Does not include any SSU overhead.
*
* Caller should synchronize
*/
public int getMessageSize() { return _totalSize; }
/**
* Should we continue sending this fragment?
* Only valid after fragment() has been called.
* Throws NPE before then.
*
* Caller should synchronize
*/
public boolean shouldSend(int fragmentNum) { return _fragmentSends[fragmentNum] >= (short)0; }
public int fragmentSize(int fragmentNum) {
if (_messageBuf == null) return -1;
if (fragmentNum + 1 == _fragmentSends.length) {
int valid = _totalSize;
if (valid <= _fragmentSize)
return valid;
// bugfix 0.8.12
int mod = valid % _fragmentSize;
return mod == 0 ? _fragmentSize : mod;
} else {
return _fragmentSize;
}
}
/**
* Write a part of the the message onto the specified buffer.
* See releaseResources() above for synchhronization information.
*
* @param out target to write
* @param outOffset into outOffset to begin writing
* @param fragmentNum fragment to write (0 indexed)
* @return bytesWritten
*/
public synchronized int writeFragment(byte out[], int outOffset, int fragmentNum) {
if (_messageBuf == null) return -1;
if (_released) {
/******
Solved by synchronization with releaseResources() and simply returning -1.
Previous output:
23:50:57.013 ERROR [acket pusher] sport.udp.OutboundMessageState: SSU OMS Use after free
java.lang.Exception: Released on Wed Dec 23 23:50:57 GMT 2009 by:
at net.i2p.router.transport.udp.OutboundMessageState.releaseResources(OutboundMessageState.java:133)
at net.i2p.router.transport.udp.PeerState.acked(PeerState.java:1391)
at net.i2p.router.transport.udp.OutboundMessageFragments.acked(OutboundMessageFragments.java:404)
at net.i2p.router.transport.udp.InboundMessageFragments.receiveACKs(InboundMessageFragments.java:191)
at net.i2p.router.transport.udp.InboundMessageFragments.receiveData(InboundMessageFragments.java:77)
at net.i2p.router.transport.udp.PacketHandler$Handler.handlePacket(PacketHandler.java:485)
at net.i2p.router.transport.udp.PacketHandler$Handler.receivePacket(PacketHandler.java:282)
at net.i2p.router.transport.udp.PacketHandler$Handler.handlePacket(PacketHandler.java:231)
at net.i2p.router.transport.udp.PacketHandler$Handler.run(PacketHandler.java:136)
at java.lang.Thread.run(Thread.java:619)
at net.i2p.util.I2PThread.run(I2PThread.java:71)
23:50:57.014 ERROR [acket pusher] ter.transport.udp.PacketPusher: SSU Output Queue Error
java.lang.RuntimeException: SSU OMS Use after free: Message 2381821417 with 4 fragments of size 0 volleys: 2 lifetime: 1258 pending fragments: 0 1 2 3
at net.i2p.router.transport.udp.OutboundMessageState.writeFragment(OutboundMessageState.java:298)
at net.i2p.router.transport.udp.PacketBuilder.buildPacket(PacketBuilder.java:170)
at net.i2p.router.transport.udp.OutboundMessageFragments.preparePackets(OutboundMessageFragments.java:332)
at net.i2p.router.transport.udp.OutboundMessageFragments.getNextVolley(OutboundMessageFragments.java:297)
at net.i2p.router.transport.udp.PacketPusher.run(PacketPusher.java:38)
at java.lang.Thread.run(Thread.java:619)
at net.i2p.util.I2PThread.run(I2PThread.java:71)
*******/
if (_log.shouldLog(Log.WARN))
_log.log(Log.WARN, "SSU OMS Use after free: " + toString(), _releasedBy);
return -1;
//throw new RuntimeException("SSU OMS Use after free: " + toString());
}
int start = _fragmentSize * fragmentNum;
int end = start + fragmentSize(fragmentNum);
int toSend = end - start;
byte buf[] = _messageBuf.getData();
- if ( (buf != null) && (start + toSend < buf.length) && (out != null) && (outOffset + toSend < out.length) ) {
- System.arraycopy(_messageBuf.getData(), start, out, outOffset, toSend);
+ if ( (buf != null) && (start + toSend <= buf.length) && (outOffset + toSend <= out.length) ) {
+ System.arraycopy(buf, start, out, outOffset, toSend);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Raw fragment[" + fragmentNum + "] for " + _messageId
+ "[" + start + "-" + (start+toSend) + "/" + _totalSize + "/" + _fragmentSize + "]: "
+ Base64.encode(out, outOffset, toSend));
return toSend;
+ } else if (buf == null) {
+ if (_log.shouldLog(Log.WARN))
+ _log.warn("Error: null buf");
} else {
- return -1;
+ if (_log.shouldLog(Log.WARN))
+ _log.warn("Error: " + start + '/' + end + '/' + outOffset + '/' + out.length);
}
+ return -1;
}
/**
* For CDQ
* @since 0.9.3
*/
public void setEnqueueTime(long now) {
_enqueueTime = now;
}
/**
* For CDQ
* @since 0.9.3
*/
public long getEnqueueTime() {
return _enqueueTime;
}
/**
* For CDQ
* @since 0.9.3
*/
public void drop() {
_peer.getTransport().failed(this, false);
releaseResources();
}
/**
* For CDPQ
* @since 0.9.3
*/
public void setSeqNum(long num) {
_seqNum = num;
}
/**
* For CDPQ
* @since 0.9.3
*/
public long getSeqNum() {
return _seqNum;
}
/**
* For CDPQ
* @return OutNetMessage priority or 1000 for injected
* @since 0.9.3
*/
public int getPriority() {
return _message != null ? _message.getPriority() : 1000;
}
@Override
public String toString() {
short sends[] = _fragmentSends;
StringBuilder buf = new StringBuilder(256);
buf.append("OB Message ").append(_messageId);
if (sends != null)
buf.append(" with ").append(sends.length).append(" fragments");
buf.append(" of size ").append(_totalSize);
buf.append(" volleys: ").append(_maxSends);
buf.append(" lifetime: ").append(getLifetime());
if (sends != null) {
buf.append(" pending fragments: ");
for (int i = 0; i < sends.length; i++)
if (sends[i] >= 0)
buf.append(i).append(' ');
}
return buf.toString();
}
}
| false | true | public synchronized int writeFragment(byte out[], int outOffset, int fragmentNum) {
if (_messageBuf == null) return -1;
if (_released) {
/******
Solved by synchronization with releaseResources() and simply returning -1.
Previous output:
23:50:57.013 ERROR [acket pusher] sport.udp.OutboundMessageState: SSU OMS Use after free
java.lang.Exception: Released on Wed Dec 23 23:50:57 GMT 2009 by:
at net.i2p.router.transport.udp.OutboundMessageState.releaseResources(OutboundMessageState.java:133)
at net.i2p.router.transport.udp.PeerState.acked(PeerState.java:1391)
at net.i2p.router.transport.udp.OutboundMessageFragments.acked(OutboundMessageFragments.java:404)
at net.i2p.router.transport.udp.InboundMessageFragments.receiveACKs(InboundMessageFragments.java:191)
at net.i2p.router.transport.udp.InboundMessageFragments.receiveData(InboundMessageFragments.java:77)
at net.i2p.router.transport.udp.PacketHandler$Handler.handlePacket(PacketHandler.java:485)
at net.i2p.router.transport.udp.PacketHandler$Handler.receivePacket(PacketHandler.java:282)
at net.i2p.router.transport.udp.PacketHandler$Handler.handlePacket(PacketHandler.java:231)
at net.i2p.router.transport.udp.PacketHandler$Handler.run(PacketHandler.java:136)
at java.lang.Thread.run(Thread.java:619)
at net.i2p.util.I2PThread.run(I2PThread.java:71)
23:50:57.014 ERROR [acket pusher] ter.transport.udp.PacketPusher: SSU Output Queue Error
java.lang.RuntimeException: SSU OMS Use after free: Message 2381821417 with 4 fragments of size 0 volleys: 2 lifetime: 1258 pending fragments: 0 1 2 3
at net.i2p.router.transport.udp.OutboundMessageState.writeFragment(OutboundMessageState.java:298)
at net.i2p.router.transport.udp.PacketBuilder.buildPacket(PacketBuilder.java:170)
at net.i2p.router.transport.udp.OutboundMessageFragments.preparePackets(OutboundMessageFragments.java:332)
at net.i2p.router.transport.udp.OutboundMessageFragments.getNextVolley(OutboundMessageFragments.java:297)
at net.i2p.router.transport.udp.PacketPusher.run(PacketPusher.java:38)
at java.lang.Thread.run(Thread.java:619)
at net.i2p.util.I2PThread.run(I2PThread.java:71)
*******/
if (_log.shouldLog(Log.WARN))
_log.log(Log.WARN, "SSU OMS Use after free: " + toString(), _releasedBy);
return -1;
//throw new RuntimeException("SSU OMS Use after free: " + toString());
}
int start = _fragmentSize * fragmentNum;
int end = start + fragmentSize(fragmentNum);
int toSend = end - start;
byte buf[] = _messageBuf.getData();
if ( (buf != null) && (start + toSend < buf.length) && (out != null) && (outOffset + toSend < out.length) ) {
System.arraycopy(_messageBuf.getData(), start, out, outOffset, toSend);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Raw fragment[" + fragmentNum + "] for " + _messageId
+ "[" + start + "-" + (start+toSend) + "/" + _totalSize + "/" + _fragmentSize + "]: "
+ Base64.encode(out, outOffset, toSend));
return toSend;
} else {
return -1;
}
}
| public synchronized int writeFragment(byte out[], int outOffset, int fragmentNum) {
if (_messageBuf == null) return -1;
if (_released) {
/******
Solved by synchronization with releaseResources() and simply returning -1.
Previous output:
23:50:57.013 ERROR [acket pusher] sport.udp.OutboundMessageState: SSU OMS Use after free
java.lang.Exception: Released on Wed Dec 23 23:50:57 GMT 2009 by:
at net.i2p.router.transport.udp.OutboundMessageState.releaseResources(OutboundMessageState.java:133)
at net.i2p.router.transport.udp.PeerState.acked(PeerState.java:1391)
at net.i2p.router.transport.udp.OutboundMessageFragments.acked(OutboundMessageFragments.java:404)
at net.i2p.router.transport.udp.InboundMessageFragments.receiveACKs(InboundMessageFragments.java:191)
at net.i2p.router.transport.udp.InboundMessageFragments.receiveData(InboundMessageFragments.java:77)
at net.i2p.router.transport.udp.PacketHandler$Handler.handlePacket(PacketHandler.java:485)
at net.i2p.router.transport.udp.PacketHandler$Handler.receivePacket(PacketHandler.java:282)
at net.i2p.router.transport.udp.PacketHandler$Handler.handlePacket(PacketHandler.java:231)
at net.i2p.router.transport.udp.PacketHandler$Handler.run(PacketHandler.java:136)
at java.lang.Thread.run(Thread.java:619)
at net.i2p.util.I2PThread.run(I2PThread.java:71)
23:50:57.014 ERROR [acket pusher] ter.transport.udp.PacketPusher: SSU Output Queue Error
java.lang.RuntimeException: SSU OMS Use after free: Message 2381821417 with 4 fragments of size 0 volleys: 2 lifetime: 1258 pending fragments: 0 1 2 3
at net.i2p.router.transport.udp.OutboundMessageState.writeFragment(OutboundMessageState.java:298)
at net.i2p.router.transport.udp.PacketBuilder.buildPacket(PacketBuilder.java:170)
at net.i2p.router.transport.udp.OutboundMessageFragments.preparePackets(OutboundMessageFragments.java:332)
at net.i2p.router.transport.udp.OutboundMessageFragments.getNextVolley(OutboundMessageFragments.java:297)
at net.i2p.router.transport.udp.PacketPusher.run(PacketPusher.java:38)
at java.lang.Thread.run(Thread.java:619)
at net.i2p.util.I2PThread.run(I2PThread.java:71)
*******/
if (_log.shouldLog(Log.WARN))
_log.log(Log.WARN, "SSU OMS Use after free: " + toString(), _releasedBy);
return -1;
//throw new RuntimeException("SSU OMS Use after free: " + toString());
}
int start = _fragmentSize * fragmentNum;
int end = start + fragmentSize(fragmentNum);
int toSend = end - start;
byte buf[] = _messageBuf.getData();
if ( (buf != null) && (start + toSend <= buf.length) && (outOffset + toSend <= out.length) ) {
System.arraycopy(buf, start, out, outOffset, toSend);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Raw fragment[" + fragmentNum + "] for " + _messageId
+ "[" + start + "-" + (start+toSend) + "/" + _totalSize + "/" + _fragmentSize + "]: "
+ Base64.encode(out, outOffset, toSend));
return toSend;
} else if (buf == null) {
if (_log.shouldLog(Log.WARN))
_log.warn("Error: null buf");
} else {
if (_log.shouldLog(Log.WARN))
_log.warn("Error: " + start + '/' + end + '/' + outOffset + '/' + out.length);
}
return -1;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.