diff
stringlengths 164
2.11M
| is_single_chunk
bool 2
classes | is_single_function
bool 2
classes | buggy_function
stringlengths 0
335k
⌀ | fixed_function
stringlengths 23
335k
⌀ |
---|---|---|---|---|
diff --git a/IRMS/IRMS-war/src/java/ACMS/managedbean/ReservationManagedBean.java b/IRMS/IRMS-war/src/java/ACMS/managedbean/ReservationManagedBean.java
index 3806a52b..891ef1be 100644
--- a/IRMS/IRMS-war/src/java/ACMS/managedbean/ReservationManagedBean.java
+++ b/IRMS/IRMS-war/src/java/ACMS/managedbean/ReservationManagedBean.java
@@ -1,327 +1,327 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ACMS.managedbean;
import ACMS.entity.ReservationEntity;
import ACMS.session.ReservationSessionBean;
import ERMS.session.EmailSessionBean;
import Exception.ExistException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Cookie
*/
@ManagedBean
@ViewScoped
public class ReservationManagedBean implements Serializable {
@EJB
private EmailSessionBean emailSessionBean;
@EJB
private ReservationSessionBean reservationSessionBean;
private List<ReservationEntity> reservationList;
private ReservationEntity selectReservation;
private ReservationEntity newReservation;
private String searchId;
private String searchName;
private String searchEmail;
public EmailSessionBean getEmailSessionBean() {
return emailSessionBean;
}
public void setEmailSessionBean(EmailSessionBean emailSessionBean) {
this.emailSessionBean = emailSessionBean;
}
public ReservationSessionBean getReservationSessionBean() {
return reservationSessionBean;
}
public void setReservationSessionBean(ReservationSessionBean reservationSessionBean) {
this.reservationSessionBean = reservationSessionBean;
}
public List<ReservationEntity> getReservationList() {
return reservationList;
}
public void setReservationList(List<ReservationEntity> reservationList) {
this.reservationList = reservationList;
}
public ReservationEntity getNewReservation() {
return newReservation;
}
public void setNewReservation(ReservationEntity newReservation) {
this.newReservation = newReservation;
}
public String getSearchName() {
return searchName;
}
public void setSearchName(String searchName) {
this.searchName = searchName;
}
public String getSearchEmail() {
return searchEmail;
}
public void setSearchEmail(String searchEmail) {
this.searchEmail = searchEmail;
}
public String getSearchId() {
System.out.println("No3: we are in setearchId" + searchId);
return searchId;
}
public void setSearchId(String searchId) {
this.searchId = searchId;
}
/**
* Creates a new instance of ReservationManagedBean
*/
public ReservationManagedBean() {
this.selectReservation = new ReservationEntity();
this.newReservation = new ReservationEntity();
}
public void searchById(ActionEvent event) throws IOException, ExistException {
System.out.println("NO6 we are in searchById function " + searchId);
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
selectReservation = reservationSessionBean.getReservationById(Long.valueOf(getSearchId()));
if (selectReservation == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Reservation does not exist!", ""));
return;
} else {
System.out.println("we are after search");
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("selectReservation", selectReservation);
System.out.println("we are after setting parameter");
request.getSession().setAttribute("reservationId", Long.valueOf(getSearchId()));
System.out.println("we are after setting reservationId session attribute");
FacesContext.getCurrentInstance().getExternalContext().redirect("ReservationSearchResult.xhtml");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error occurs when searching", ""));
return;
}
}
public void selectThisReservation(ActionEvent event) throws IOException {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
if (selectReservation == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Reservation does not exist!", ""));
return;
} else {
System.out.println("we are after search");
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("selectReservation", selectReservation);
System.out.println("we are after setting parameter");
request.getSession().setAttribute("reservationId", Long.valueOf(getSearchId()));
System.out.println("we are after setting reservationId session attribute");
FacesContext.getCurrentInstance().getExternalContext().redirect("ReservationSearchResult.xhtml");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error occurs when searching", ""));
return;
}
}
public void searchByName(ActionEvent event) throws IOException, ExistException {
System.out.println("NO6 we are in searchByName function " + searchName);
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
reservationList = reservationSessionBean.getReservationByName(searchName);
if (reservationList == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Reservation does not exist!", ""));
return;
} else {
System.out.println("we are after search");
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("reservationList", reservationList);
System.out.println("we are after setting parameter");
request.getSession().setAttribute("rcName", searchName);
System.out.println("we are after setting reservationId session attribute");
FacesContext.getCurrentInstance().getExternalContext().redirect("listReservations.xhtml");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error occurs when searching", ""));
return;
}
}
public void searchByEmail(ActionEvent event) throws IOException, ExistException {
System.out.println("NO6 we are in searchByName function " + searchEmail);
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
reservationList = reservationSessionBean.getReservationByEmail(searchEmail);
if (reservationList == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Reservation does not exist!", ""));
return;
} else {
System.out.println("we are after search");
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("reservationList", reservationList);
System.out.println("we are after setting parameter");
request.getSession().setAttribute("rcEmail", searchEmail);
System.out.println("we are after setting reservationId session attribute");
FacesContext.getCurrentInstance().getExternalContext().redirect("listReservations.xhtml");
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error occurs when searching", ""));
return;
}
}
public void getTodayReservations(ActionEvent event) throws IOException, ExistException {
System.out.println("NO6 we are in getting today reservation function ");
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
- reservationList = rm.getTodayReservations();
+ reservationList = reservationSessionBean.getTodayReservations();
System.out.println("we are after session bean");
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("reservationList", reservationList);
System.out.println("we are after setting parameter");
FacesContext.getCurrentInstance().getExternalContext().redirect("listReservations.xhtml");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error occurs when searching", ""));
return;
}
}
public void getBeforeReservations(ActionEvent event) throws IOException, ExistException {
System.out.println("NO6 we are in getting before reservation function ");
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
- reservationList = rm.getBeforeReservations();
+ reservationList = reservationSessionBean.getBeforeReservations();
System.out.println("we are after session bean");
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("reservationList", reservationList);
System.out.println("we are after setting parameter");
FacesContext.getCurrentInstance().getExternalContext().redirect("listReservations.xhtml");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error occurs when searching", ""));
return;
}
}
public void getAllReservations(ActionEvent event) throws IOException, ExistException {
System.out.println("NO6 we are in getting all reservation function ");
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
- reservationList = rm.getAllReservations();
+ reservationList = reservationSessionBean.getAllReservations();
System.out.println("we are after session bean");
FacesContext.getCurrentInstance().getExternalContext().getFlash().put("reservationList", reservationList);
System.out.println("we are after setting parameter");
FacesContext.getCurrentInstance().getExternalContext().redirect("listReservations.xhtml");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error occurs when searching", ""));
return;
}
}
//javax.el.PropertyNotFoundException: /acms/checkIncheckOut.xhtml @45,154 value="#{reservationManagedBean.selectReservation.rcName}": Target Unreachable, 'null' returned null
public void addReservation(ActionEvent event) throws IOException {
try {
System.out.println("we are in addReservation in managedbean" + newReservation.getRcName());
if (newReservation.getReservationRoomType().equals("1")) {
newReservation.setReservationRoomType("superior");
}
if (newReservation.getReservationRoomType().equals("2")) {
newReservation.setReservationRoomType("deluxe");
}
if (newReservation.getReservationRoomType().equals("3")) {
newReservation.setReservationRoomType("deluxe suite");
}
if (newReservation.getReservationRoomType().equals("4")) {
newReservation.setReservationRoomType("orchard suite");
}
if (newReservation.getReservationRoomType().equals("5")) {
newReservation.setReservationRoomType("chairman suite");
}
reservationSessionBean.addReservation(newReservation);
System.out.println("we are after add reservation in managedbean");
selectReservation = reservationSessionBean.getReservationById(newReservation.getReservationId());
FacesContext.getCurrentInstance().getExternalContext().redirect("ReservationSearchResult.xhtml");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error occurs when adding new reservation", ""));
e.printStackTrace();
return;
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "New Reservation saved.", ""));
// emailSessionBean.emailInitialPassward(employee.getPersonalEmail(), initialPwd); //send email
emailSessionBean.emailReservationConfirmation(newReservation.getRcEmail(), newReservation);
System.out.println("email already sent");
FacesContext.getCurrentInstance().getExternalContext().redirect("ReservationSearchResult.xhtml");
newReservation = new ReservationEntity();
}
public List<ReservationEntity> getReservatioinList() {
return reservationList;
}
public void setReservatioinList(List<ReservationEntity> reservatioinList) {
this.reservationList = reservatioinList;
}
public ReservationEntity getSelectReservation() {
return selectReservation;
}
public void setSelectReservation(ReservationEntity selectReservation) {
this.selectReservation = selectReservation;
}
public List<String> complete(String query) throws ExistException {
System.out.println("NO4: we are in complete bean BEFORE");
List<String> results = new ArrayList<String>();
reservationList = reservationSessionBean.getAllReservations();
for (Object o : reservationList) {
ReservationEntity rve = (ReservationEntity) o;
if ((rve.getReservationId()).toString().startsWith(query)) {
results.add((rve.getReservationId()).toString());
}
}
System.out.println("NO5: we are in complete bean AFTER");
return results;
}
// public boolean containReservation() {
// return ("Hotel".equals(employee.getEmployeeDepartment()));
// }
}
diff --git a/IRMS/IRMS-war/src/java/SMMS/managedbean/MerchantManagedBean.java b/IRMS/IRMS-war/src/java/SMMS/managedbean/MerchantManagedBean.java
index 54a0eda6..a292deb1 100644
--- a/IRMS/IRMS-war/src/java/SMMS/managedbean/MerchantManagedBean.java
+++ b/IRMS/IRMS-war/src/java/SMMS/managedbean/MerchantManagedBean.java
@@ -1,150 +1,151 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package SMMS.managedbean;
import ERMS.session.EPasswordHashSessionBean;
import ERMS.session.EmailSessionBean;
import Exception.ExistException;
import SMMS.entity.MerchantEntity;
import SMMS.session.MerchantSessionBean;
import java.io.IOException;
+import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.SessionContext;
import javax.ejb.Timeout;
import javax.ejb.TimerService;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
/**
*
* @author Cookie
*/
@ManagedBean
@ViewScoped
public class MerchantManagedBean implements Serializable{
@EJB
private EmailSessionBean emailSessionBean;
@EJB
private EPasswordHashSessionBean ePasswordHashSessionBean;
@EJB
private MerchantSessionBean merchantSessionBean;
private MerchantEntity merchant;
@PostConstruct
public void init() {
FacesContext.getCurrentInstance().getExternalContext().getSession(true);
}
public MerchantManagedBean() {
merchant = new MerchantEntity();
}
// public void createTimers(ActionEvent event) {
// System.out.println("in creating timers");
// merchantSessionBean.createTimers();
// }
////
// public void cancelTimers() {
// TimerService timerService = ctx.getTimerService();
// Collection timers = timerService.getTimers();
// for (Object obj : timers) {
// Timer timer = (Timer) obj;
// if (timer.getInfo().toString()) {
// timer.cancel();
// }
// }
// }
// @Timeout
// public void handleTimeout(Timer timer) {
//// if (timer.toString().equals("EJBTIMER")) {//Do something}}}
// Date currentDate = new Date();
// System.out.println("No1: we are in merchant managedbean: trying this hahaha lalala" + currentDate);
- }
+// }
// public static int count = 0;
// public Timer timer = new Timer();
// public TimerTask task = new TimerTask() {
// @Override
// public void run() {
// count++;
// if (count > 6) {
// timer.cancel();
// timer.purge();
// }
// Date currentDate = new Date();
// System.out.println("No2: we are in merchant managedbean: trying this hahaha lalala" + currentDate);
// }
// };
//
// public void test(ActionEvent event) {
// System.out.println("No1: in test");
//// timer.scheduleAtFixedRate(task, 0, 1000);
// timer.scheduleAtFixedRate(task, 0, 1000);
// }
/**
* Creates a new instance of AddEmployeeManagedBean
*/
public void saveNewMerchant(ActionEvent event) throws IOException, ExistException {
System.out.println("add new merchant: " + merchant.getMerchantEmail());
if (merchantSessionBean.getMerchantById(merchant.getMerchantEmail()) != null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Mercant already exists", ""));
return;
} else {
String initialPwd = "";
String uuid = UUID.randomUUID().toString();
String[] sArray = uuid.split("-");
initialPwd = sArray[0];
merchant.setMerchantPassword(initialPwd);
System.out.println("add new merchant hash password!");
merchant.setMerchantPassword(ePasswordHashSessionBean.hashPassword(merchant.getMerchantPassword()));
System.out.println("finished hashing");
try {
System.out.println("we are in save new merchant in managedbean" + merchant.getMerchantEmail());
merchantSessionBean.addMerchant(merchant);
System.out.println("we are after adding merchant in managedbean");
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Error occurs when adding new merchant", ""));
return;
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "New Merchant saved.", ""));
// emailSessionBean.emailInitialPassward(employee.getPersonalEmail(), initialPwd); //send email
emailSessionBean.emailInitialPassward(merchant.getMerchantEmail(), initialPwd);
System.out.println("email already sent");
merchant = new MerchantEntity();
}
}
public void oneMore(ActionEvent event) throws IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect("addMerchant.xhtml");
}
public MerchantEntity getMerchant() {
return merchant;
}
public void setMerchant(MerchantEntity merchant) {
this.merchant = merchant;
}
/**
* Creates a new instance of MerchantManagedBean
*/
}
| false | false | null | null |
diff --git a/src/org/eclipse/core/resources/IFile.java b/src/org/eclipse/core/resources/IFile.java
index 8c9dc1fb..ba0bea4d 100644
--- a/src/org/eclipse/core/resources/IFile.java
+++ b/src/org/eclipse/core/resources/IFile.java
@@ -1,1116 +1,1118 @@
/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
+ * Copyright (c) 2000, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.resources;
import java.io.InputStream;
import java.io.Reader;
import java.net.URI;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.content.IContentTypeManager;
/**
* Files are leaf resources which contain data.
* The contents of a file resource is stored as a file in the local
* file system.
* <p>
* Files, like folders, may exist in the workspace but
* not be local; non-local file resources serve as place-holders for
* files whose content and properties have not yet been fetched from
* a repository.
* </p>
* <p>
* Files implement the <code>IAdaptable</code> interface;
* extensions are managed by the platform's adapter manager.
* </p>
*
* @see Platform#getAdapterManager()
* @noimplement This interface is not intended to be implemented by clients.
* @noextend This interface is not intended to be extended by clients.
*/
public interface IFile extends IResource, IEncodedStorage, IAdaptable {
/**
* Character encoding constant (value 0) which identifies
* files that have an unknown character encoding scheme.
*
* @see IFile#getEncoding()
* @deprecated see getEncoding for details
*/
public int ENCODING_UNKNOWN = 0;
/**
* Character encoding constant (value 1) which identifies
* files that are encoded with the US-ASCII character encoding scheme.
*
* @see IFile#getEncoding()
* @deprecated see getEncoding for details
*/
public int ENCODING_US_ASCII = 1;
/**
* Character encoding constant (value 2) which identifies
* files that are encoded with the ISO-8859-1 character encoding scheme,
* also known as ISO-LATIN-1.
*
* @see IFile#getEncoding()
* @deprecated see getEncoding for details
*/
public int ENCODING_ISO_8859_1 = 2;
/**
* Character encoding constant (value 3) which identifies
* files that are encoded with the UTF-8 character encoding scheme.
*
* @see IFile#getEncoding()
* @deprecated see getEncoding for details
*/
public int ENCODING_UTF_8 = 3;
/**
* Character encoding constant (value 4) which identifies
* files that are encoded with the UTF-16BE character encoding scheme.
*
* @see IFile#getEncoding()
* @deprecated see getEncoding for details
*/
public int ENCODING_UTF_16BE = 4;
/**
* Character encoding constant (value 5) which identifies
* files that are encoded with the UTF-16LE character encoding scheme.
*
* @see IFile#getEncoding()
* @deprecated see getEncoding for details
*/
public int ENCODING_UTF_16LE = 5;
/**
* Character encoding constant (value 6) which identifies
* files that are encoded with the UTF-16 character encoding scheme.
*
* @see IFile#getEncoding()
* @deprecated see getEncoding for details
*/
public int ENCODING_UTF_16 = 6;
/**
* Appends the entire contents of the given stream to this file.
* <p>
* This is a convenience method, fully equivalent to:
* <pre>
* appendContents(source, (keepHistory ? KEEP_HISTORY : IResource.NONE) | (force ? FORCE : IResource.NONE), monitor);
* </pre>
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this file's content have been changed.
* </p>
* <p>
* This method is long-running; progress and cancelation are provided
* by the given progress monitor.
* </p>
*
* @param source an input stream containing the new contents of the file
* @param force a flag controlling how to deal with resources that
* are not in sync with the local file system
* @param keepHistory a flag indicating whether or not to store
* the current contents in the local history
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* <li> The workspace is not in sync with the corresponding location
* in the local file system and <code>force </code> is <code>false</code>.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li> The file modification validator disallowed the change.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see #appendContents(java.io.InputStream,int,IProgressMonitor)
*/
public void appendContents(InputStream source, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException;
/**
* Appends the entire contents of the given stream to this file.
* The stream, which must not be <code>null</code>, will get closed
* whether this method succeeds or fails.
* <p>
* The <code>FORCE</code> update flag controls how this method deals with
* cases where the workspace is not completely in sync with the local file
* system. If <code>FORCE</code> is not specified, the method will only attempt
* to overwrite a corresponding file in the local file system provided
* it is in sync with the workspace. This option ensures there is no
* unintended data loss; it is the recommended setting.
* However, if <code>FORCE</code> is specified, an attempt will be made
* to write a corresponding file in the local file system, overwriting any
* existing one if need be. In either case, if this method succeeds, the
* resource will be marked as being local (even if it wasn't before).
* </p>
* <p>
* If this file is non-local then this method will always fail. The only exception
* is when <code>FORCE</code> is specified and the file exists in the local
* file system. In this case the file is made local and the given contents are appended.
* </p>
* <p>
* The <code>KEEP_HISTORY</code> update flag controls whether or not a copy of
* current contents of this file should be captured in the workspace's local
* history (properties are not recorded in the local history). The local history
* mechanism serves as a safety net to help the user recover from mistakes that
* might otherwise result in data loss. Specifying <code>KEEP_HISTORY</code>
* is recommended except in circumstances where past states of the files are of
* no conceivable interest to the user. Note that local history is maintained
* with each individual project, and gets discarded when a project is deleted
* from the workspace. This flag is ignored if the file was not previously local.
* </p>
* <p>
* Update flags other than <code>FORCE</code> and <code>KEEP_HISTORY</code>
* are ignored.
* </p>
* <p>
* Prior to modifying the contents of this file, the file modification validator (if provided
* by the VCM plug-in), will be given a chance to perform any last minute preparations. Validation
* is performed by calling <code>IFileModificationValidator.validateSave</code> on this file.
* If the validation fails, then this operation will fail.
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this file's content have been changed.
* </p>
* <p>
* This method is long-running; progress and cancelation are provided
* by the given progress monitor.
* </p>
*
* @param source an input stream containing the new contents of the file
* @param updateFlags bit-wise or of update flag constants
* (<code>FORCE</code> and <code>KEEP_HISTORY</code>)
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* <li> The workspace is not in sync with the corresponding location
* in the local file system and <code>FORCE</code> is not specified.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li> The file modification validator disallowed the change.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResourceRuleFactory#modifyRule(IResource)
* @since 2.0
*/
public void appendContents(InputStream source, int updateFlags, IProgressMonitor monitor) throws CoreException;
/**
* Creates a new file resource as a member of this handle's parent resource.
* <p>
* This is a convenience method, fully equivalent to:
* <pre>
* create(source, (force ? FORCE : IResource.NONE), monitor);
* </pre>
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that the file has been added to its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param source an input stream containing the initial contents of the file,
* or <code>null</code> if the file should be marked as not local
* @param force a flag controlling how to deal with resources that
* are not in sync with the local file system
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource already exists in the workspace.</li>
* <li> The parent of this resource does not exist.</li>
+ * <li> The parent of this resource is a virtual folder.</li>
* <li> The project of this resource is not accessible.</li>
* <li> The parent contains a resource of a different type
* at the same path as this resource.</li>
* <li> The name of this resource is not valid (according to
* <code>IWorkspace.validateName</code>).</li>
* <li> The corresponding location in the local file system is occupied
* by a directory.</li>
* <li> The corresponding location in the local file system is occupied
* by a file and <code>force </code> is <code>false</code>.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
*/
public void create(InputStream source, boolean force, IProgressMonitor monitor) throws CoreException;
/**
* Creates a new file resource as a member of this handle's parent resource.
* The resource's contents are supplied by the data in the given stream.
* This method closes the stream whether it succeeds or fails.
* If the stream is <code>null</code> then a file is not created in the local
* file system and the created file resource is marked as being non-local.
* <p>
* The {@link IResource#FORCE} update flag controls how this method deals with
* cases where the workspace is not completely in sync with the local file
* system. If {@link IResource#FORCE} is not specified, the method will only attempt
* to write a file in the local file system if it does not already exist.
* This option ensures there is no unintended data loss; it is the recommended
* setting. However, if {@link IResource#FORCE} is specified, this method will
* attempt to write a corresponding file in the local file system,
* overwriting any existing one if need be.
* </p>
* <p>
* The {@link IResource#DERIVED} update flag indicates that this resource
* should immediately be set as a derived resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setDerived(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* The {@link IResource#TEAM_PRIVATE} update flag indicates that this resource
* should immediately be set as a team private resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setTeamPrivateMember(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* The {@link IResource#HIDDEN} update flag indicates that this resource
* should immediately be set as a hidden resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setHidden(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* Update flags other than those listed above are ignored.
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that the file has been added to its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param source an input stream containing the initial contents of the file,
* or <code>null</code> if the file should be marked as not local
* @param updateFlags bit-wise or of update flag constants
* ({@link IResource#FORCE}, {@link IResource#DERIVED}, and {@link IResource#TEAM_PRIVATE})
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource already exists in the workspace.</li>
* <li> The parent of this resource does not exist.</li>
+ * <li> The parent of this resource is a virtual folder.</li>
* <li> The project of this resource is not accessible.</li>
* <li> The parent contains a resource of a different type
* at the same path as this resource.</li>
* <li> The name of this resource is not valid (according to
* <code>IWorkspace.validateName</code>).</li>
* <li> The corresponding location in the local file system is occupied
* by a directory.</li>
* <li> The corresponding location in the local file system is occupied
* by a file and <code>FORCE</code> is not specified.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResourceRuleFactory#createRule(IResource)
* @since 2.0
*/
public void create(InputStream source, int updateFlags, IProgressMonitor monitor) throws CoreException;
/**
* Creates a new file resource as a member of this handle's parent resource.
* The file's contents will be located in the file specified by the given
* file system path. The given path must be either an absolute file system
* path, or a relative path whose first segment is the name of a workspace path
* variable.
* <p>
* The {@link IResource#ALLOW_MISSING_LOCAL} update flag controls how this
* method deals with cases where the local file system file to be linked does
* not exist, or is relative to a workspace path variable that is not defined.
* If {@link IResource#ALLOW_MISSING_LOCAL} is specified, the operation will succeed
* even if the local file is missing, or the path is relative to an undefined
* variable. If {@link IResource#ALLOW_MISSING_LOCAL} is not specified, the operation
* will fail in the case where the local file system file does not exist or the
* path is relative to an undefined variable.
* </p>
* <p>
* The {@link IResource#REPLACE} update flag controls how this
* method deals with cases where a resource of the same name as the
* prospective link already exists. If {@link IResource#REPLACE}
* is specified, then the existing linked resource's location is replaced
* by localLocation's value. This does <b>not</b>
* cause the underlying file system contents of that resource to be deleted.
* If {@link IResource#REPLACE} is not specified, this method will
* fail if an existing resource exists of the same name.
* </p>
* <p>
* The {@link IResource#HIDDEN} update flag indicates that this resource
* should immediately be set as a hidden resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setHidden(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* Update flags other than those listed above are ignored.
* </p>
* <p>
* This method synchronizes this resource with the local file system at the given
* location.
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that the file has been added to its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param localLocation a file system path where the file should be linked
* @param updateFlags bit-wise or of update flag constants
* ({@link IResource#ALLOW_MISSING_LOCAL}, {@link IResource#REPLACE} and {@link IResource#HIDDEN})
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource already exists in the workspace.</li>
* <li> The workspace contains a resource of a different type
* at the same path as this resource.</li>
* <li> The parent of this resource does not exist.</li>
* <li> The parent of this resource is not an open project</li>
* <li> The name of this resource is not valid (according to
* <code>IWorkspace.validateName</code>).</li>
* <li> The corresponding location in the local file system does not exist, or
* is relative to an undefined variable, and <code>ALLOW_MISSING_LOCAL</code> is
* not specified.</li>
* <li> The corresponding location in the local file system is occupied
* by a directory (as opposed to a file).</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li>The team provider for the project which contains this folder does not permit
* linked resources.</li>
* <li>This folder's project contains a nature which does not permit linked resources.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResource#isLinked()
* @see IResource#ALLOW_MISSING_LOCAL
* @see IResource#REPLACE
* @see IResource#HIDDEN
* @since 2.1
*/
public void createLink(IPath localLocation, int updateFlags, IProgressMonitor monitor) throws CoreException;
/**
* Creates a new file resource as a member of this handle's parent resource.
* The file's contents will be located in the file specified by the given
* URI. The given URI must be either absolute, or a relative URI whose first path
* segment is the name of a workspace path variable.
* <p>
* The <code>ALLOW_MISSING_LOCAL</code> update flag controls how this
* method deals with cases where the file system file to be linked does
* not exist, or is relative to a workspace path variable that is not defined.
* If <code>ALLOW_MISSING_LOCAL</code> is specified, the operation will succeed
* even if the local file is missing, or the path is relative to an undefined
* variable. If <code>ALLOW_MISSING_LOCAL</code> is not specified, the operation
* will fail in the case where the file system file does not exist or the
* path is relative to an undefined variable.
* </p>
* <p>
* The {@link IResource#REPLACE} update flag controls how this
* method deals with cases where a resource of the same name as the
* prospective link already exists. If {@link IResource#REPLACE}
* is specified, then any existing resource with the same name is removed
* from the workspace to make way for creation of the link. This does <b>not</b>
* cause the underlying file system contents of that resource to be deleted.
* If {@link IResource#REPLACE} is not specified, this method will
* fail if an existing resource exists of the same name.
* </p>
* <p>
* The {@link IResource#HIDDEN} update flag indicates that this resource
* should immediately be set as a hidden resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setHidden(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* Update flags other than those listed above are ignored.
* </p>
* <p>
* This method synchronizes this resource with the file system at the given
* location.
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that the file has been added to its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param location a file system URI where the file should be linked
* @param updateFlags bit-wise or of update flag constants
* ({@link IResource#ALLOW_MISSING_LOCAL}, {@link IResource#REPLACE} and {@link IResource#HIDDEN})
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource already exists in the workspace.</li>
* <li> The workspace contains a resource of a different type
* at the same path as this resource.</li>
* <li> The parent of this resource does not exist.</li>
* <li> The parent of this resource is not an open project</li>
* <li> The name of this resource is not valid (according to
* <code>IWorkspace.validateName</code>).</li>
* <li> The corresponding location in the file system does not exist, or
* is relative to an undefined variable, and <code>ALLOW_MISSING_LOCAL</code> is
* not specified.</li>
* <li> The corresponding location in the file system is occupied
* by a directory (as opposed to a file).</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li>The team provider for the project which contains this folder does not permit
* linked resources.</li>
* <li>This folder's project contains a nature which does not permit linked resources.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResource#isLinked()
* @see IResource#ALLOW_MISSING_LOCAL
* @see IResource#REPLACE
* @see IResource#HIDDEN
* @since 3.2
*/
public void createLink(URI location, int updateFlags, IProgressMonitor monitor) throws CoreException;
/**
* Deletes this file from the workspace.
* <p>
* This is a convenience method, fully equivalent to:
* <pre>
* delete((keepHistory ? KEEP_HISTORY : IResource.NONE) | (force ? FORCE : IResource.NONE), monitor);
* </pre>
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this folder has been removed from its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param force a flag controlling whether resources that are not
* in sync with the local file system will be tolerated
* @param keepHistory a flag controlling whether files under this folder
* should be stored in the workspace's local history
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource could not be deleted for some reason.</li>
* <li> This resource is out of sync with the local file system
* and <code>force</code> is <code>false</code>.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResource#delete(int,IProgressMonitor)
* @see IResourceRuleFactory#deleteRule(IResource)
*/
public void delete(boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException;
/**
* Returns the name of a charset to be used when decoding the contents of this
* file into characters.
* <p>
* This refinement of the corresponding {@link IEncodedStorage} method
* is a convenience method, fully equivalent to:
* <pre>
* getCharset(true);
* </pre>
* </p><p>
* <b>Note 1</b>: this method does not check whether the result is a supported
* charset name. Callers should be prepared to handle
* <code>UnsupportedEncodingException</code> where this charset is used.
* </p>
* <p>
* <b>Note 2</b>: this method returns a cached value for the encoding
* that may be out of date if the file is not synchronized with the local file system
* and the encoding has since changed in the file system.
* </p>
*
* @return the name of a charset
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource could not be read.</li>
* <li> This resource is not local.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* </ul>
* @see IFile#getCharset(boolean)
* @see IEncodedStorage#getCharset()
* @see IContainer#getDefaultCharset()
* @since 3.0
*/
public String getCharset() throws CoreException;
/**
* Returns the name of a charset to be used when decoding the contents of this
* file into characters.
* <p>
* If checkImplicit is <code>false</code>, this method will return the
* charset defined by calling <code>setCharset</code>, provided this file
* exists, or <code>null</code> otherwise.
* </p><p>
* If checkImplicit is <code>true</code>, this method uses the following
* algorithm to determine the charset to be returned:
* <ol>
* <li>the charset defined by calling #setCharset, if any, and this file
* exists, or</li>
* <li>the charset automatically discovered based on this file's contents,
* if one can be determined, or</li>
* <li>the default encoding for this file's parent (as defined by
* <code>IContainer#getDefaultCharset</code>).</li>
* </ol>
* </p><p>
* <b>Note 1</b>: this method does not check whether the result is a supported
* charset name. Callers should be prepared to handle
* <code>UnsupportedEncodingException</code> where this charset is used.
* </p>
* <p>
* <b>Note 2</b>: this method returns a cached value for the encoding
* that may be out of date if the file is not synchronized with the local file system
* and the encoding has since changed in the file system.
* </p>
*
* @return the name of a charset, or <code>null</code>
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource could not be read.</li>
* <li> This resource is not local.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* </ul>
* @see IEncodedStorage#getCharset()
* @see IContainer#getDefaultCharset()
* @since 3.0
*/
public String getCharset(boolean checkImplicit) throws CoreException;
/**
* Returns the name of a charset to be used to encode the given contents
* when saving to this file. This file does not have to exist. The character stream is <em>not</em> automatically closed.
* <p>
* This method uses the following algorithm to determine the charset to be returned:
* <ol>
* <li>if this file exists, the charset returned by IFile#getCharset(false), if one is defined, or</li>
* <li>the charset automatically discovered based on the file name and the given contents,
* if one can be determined, or</li>
* <li>the default encoding for the parent resource (as defined by
* <code>IContainer#getDefaultCharset</code>).</li>
* </ol>
* </p><p>
* <b>Note</b>: this method does not check whether the result is a supported
* charset name. Callers should be prepared to handle
* <code>UnsupportedEncodingException</code> where this charset is used.
* </p>
*
* @param reader a character stream containing the contents to be saved into this file
* @return the name of a charset
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li>The given character stream could not be read.</li>
* </ul>
* @see #getCharset(boolean)
* @see IContainer#getDefaultCharset()
* @since 3.1
*/
public String getCharsetFor(Reader reader) throws CoreException;
/**
* Returns a description for this file's current contents. Returns
* <code>null</code> if a description cannot be obtained.
* <p>
* Calling this method produces a similar effect as calling
* <code>getDescriptionFor(getContents(), getName(), IContentDescription.ALL)</code>
* on <code>IContentTypeManager</code>, but provides better
* opportunities for improved performance. Therefore, when manipulating
* <code>IFile</code>s, clients should call this method instead of
* <code>IContentTypeManager.getDescriptionFor</code>.
* </p>
*
* @return a description for this file's current contents, or
* <code>null</code>
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> This resource could not be read.</li>
* <li> This resource is not local.</li>
* <li> The workspace is not in sync with the corresponding location
* in the local file system.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* </ul>
* @see IContentDescription
* @see IContentTypeManager#getDescriptionFor(InputStream, String, QualifiedName[])
* @since 3.0
*/
public IContentDescription getContentDescription() throws CoreException;
/**
* Returns an open input stream on the contents of this file.
* This refinement of the corresponding <code>IStorage</code> method
* returns an open input stream on the contents of this file.
* The client is responsible for closing the stream when finished.
*
* @return an input stream containing the contents of the file
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> This resource is not local.</li>
* <li> The workspace is not in sync with the corresponding location
* in the local file system.</li>
* </ul>
*/
public InputStream getContents() throws CoreException;
/**
* This refinement of the corresponding <code>IStorage</code> method
* returns an open input stream on the contents of this file.
* The client is responsible for closing the stream when finished.
* If force is <code>true</code> the file is opened and an input
* stream returned regardless of the sync state of the file. The file
* is not synchronized with the workspace.
* If force is <code>false</code> the method fails if not in sync.
*
* @param force a flag controlling how to deal with resources that
* are not in sync with the local file system
* @return an input stream containing the contents of the file
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> This resource is not local.</li>
* <li> The workspace is not in sync with the corresponding location
* in the local file system and force is <code>false</code>.</li>
* </ul>
*/
public InputStream getContents(boolean force) throws CoreException;
/**
* Returns a constant identifying the character encoding of this file, or
* ENCODING_UNKNOWN if it could not be determined. The returned constant
* will be one of the ENCODING_* constants defined on IFile.
*
* This method attempts to guess the file's character encoding by analyzing
* the first few bytes of the file. If no identifying pattern is found at the
* beginning of the file, ENC_UNKNOWN will be returned. This method will
* not attempt any complex analysis of the file to make a guess at the
* encoding that is used.
*
* @return The character encoding of this file
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> This resource could not be read.</li>
* <li> This resource is not local.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* </ul>
* @deprecated use IFile#getCharset instead
*/
public int getEncoding() throws CoreException;
/**
* Returns the full path of this file.
* This refinement of the corresponding <code>IStorage</code> and <code>IResource</code>
* methods links the semantics of resource and storage object paths such that
* <code>IFile</code>s always have a path and that path is relative to the
* containing workspace.
*
* @see IResource#getFullPath()
* @see IStorage#getFullPath()
*/
public IPath getFullPath();
/**
* Returns a list of past states of this file known to this workspace.
* Recently added states first.
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @return an array of states of this file
* @exception CoreException if this method fails.
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
*/
public IFileState[] getHistory(IProgressMonitor monitor) throws CoreException;
/**
* Returns the name of this file.
* This refinement of the corresponding <code>IStorage</code> and <code>IResource</code>
* methods links the semantics of resource and storage object names such that
* <code>IFile</code>s always have a name and that name equivalent to the
* last segment of its full path.
*
* @see IResource#getName()
* @see IStorage#getName()
*/
public String getName();
/**
* Returns whether this file is read-only.
* This refinement of the corresponding <code>IStorage</code> and <code>IResource</code>
* methods links the semantics of read-only resources and read-only storage objects.
*
* @see IResource#isReadOnly()
* @see IStorage#isReadOnly()
*/
public boolean isReadOnly();
/**
* Moves this resource to be at the given location.
* <p>
* This is a convenience method, fully equivalent to:
* <pre>
* move(destination, (keepHistory ? KEEP_HISTORY : IResource.NONE) | (force ? FORCE : IResource.NONE), monitor);
* </pre>
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this file has been removed from its parent and a new file
* has been added to the parent of the destination.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param destination the destination path
* @param force a flag controlling whether resources that are not
* in sync with the local file system will be tolerated
* @param keepHistory a flag controlling whether files under this folder
* should be stored in the workspace's local history
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this resource could not be moved. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> This resource is not local.</li>
* <li> The resource corresponding to the parent destination path does not exist.</li>
* <li> The resource corresponding to the parent destination path is a closed
* project.</li>
* <li> A resource at destination path does exist.</li>
* <li> A resource of a different type exists at the destination path.</li>
* <li> This resource is out of sync with the local file system
* and <code>force</code> is <code>false</code>.</li>
* <li> The workspace and the local file system are out of sync
* at the destination resource or one of its descendents.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
*
* @see IResource#move(IPath,int,IProgressMonitor)
* @see IResourceRuleFactory#moveRule(IResource, IResource)
*/
public void move(IPath destination, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException;
/**
* Sets the charset for this file. Passing a value of <code>null</code>
* will remove the charset setting for this resource.
*
* @param newCharset a charset name, or <code>null</code>
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> An error happened while persisting this setting.</li>
* </ul>
* @see #getCharset()
* @since 3.0
* @deprecated Replaced by {@link #setCharset(String, IProgressMonitor)} which
* is a workspace operation and reports changes in resource deltas.
*/
public void setCharset(String newCharset) throws CoreException;
/**
* Sets the charset for this file. Passing a value of <code>null</code>
* will remove the charset setting for this resource.
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this file's encoding has changed.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param newCharset a charset name, or <code>null</code>
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> An error happened while persisting this setting.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See {@link IResourceChangeEvent} for more details.</li>
* </ul>
* @see #getCharset()
* @see IResourceRuleFactory#charsetRule(IResource)
* @since 3.0
*/
public void setCharset(String newCharset, IProgressMonitor monitor) throws CoreException;
/**
* Sets the contents of this file to the bytes in the given input stream.
* <p>
* This is a convenience method, fully equivalent to:
* <pre>
* setContents(source, (keepHistory ? KEEP_HISTORY : IResource.NONE) | (force ? FORCE : IResource.NONE), monitor);
* </pre>
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this file's contents have been changed.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param source an input stream containing the new contents of the file
* @param force a flag controlling how to deal with resources that
* are not in sync with the local file system
* @param keepHistory a flag indicating whether or not store
* the current contents in the local history
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* <li> The workspace is not in sync with the corresponding location
* in the local file system and <code>force </code> is <code>false</code>.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li> The file modification validator disallowed the change.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see #setContents(java.io.InputStream,int,IProgressMonitor)
*/
public void setContents(InputStream source, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException;
/**
* Sets the contents of this file to the bytes in the given file state.
* <p>
* This is a convenience method, fully equivalent to:
* <pre>
* setContents(source, (keepHistory ? KEEP_HISTORY : IResource.NONE) | (force ? FORCE : IResource.NONE), monitor);
* </pre>
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this file's content have been changed.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param source a previous state of this resource
* @param force a flag controlling how to deal with resources that
* are not in sync with the local file system
* @param keepHistory a flag indicating whether or not store
* the current contents in the local history
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> The state does not exist.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* <li> The workspace is not in sync with the corresponding location
* in the local file system and <code>force </code> is <code>false</code>.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li> The file modification validator disallowed the change.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see #setContents(IFileState,int,IProgressMonitor)
*/
public void setContents(IFileState source, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException;
/**
* Sets the contents of this file to the bytes in the given input stream.
* The stream will get closed whether this method succeeds or fails.
* If the stream is <code>null</code> then the content is set to be the
* empty sequence of bytes.
* <p>
* The <code>FORCE</code> update flag controls how this method deals with
* cases where the workspace is not completely in sync with the local file
* system. If <code>FORCE</code> is not specified, the method will only attempt
* to overwrite a corresponding file in the local file system provided
* it is in sync with the workspace. This option ensures there is no
* unintended data loss; it is the recommended setting.
* However, if <code>FORCE</code> is specified, an attempt will be made
* to write a corresponding file in the local file system, overwriting any
* existing one if need be. In either case, if this method succeeds, the
* resource will be marked as being local (even if it wasn't before).
* </p>
* <p>
* The <code>KEEP_HISTORY</code> update flag controls whether or not a copy of
* current contents of this file should be captured in the workspace's local
* history (properties are not recorded in the local history). The local history
* mechanism serves as a safety net to help the user recover from mistakes that
* might otherwise result in data loss. Specifying <code>KEEP_HISTORY</code>
* is recommended except in circumstances where past states of the files are of
* no conceivable interest to the user. Note that local history is maintained
* with each individual project, and gets discarded when a project is deleted
* from the workspace. This flag is ignored if the file was not previously local.
* </p>
* <p>
* Update flags other than <code>FORCE</code> and <code>KEEP_HISTORY</code>
* are ignored.
* </p>
* <p>
* Prior to modifying the contents of this file, the file modification validator (if provided
* by the VCM plug-in), will be given a chance to perform any last minute preparations. Validation
* is performed by calling <code>IFileModificationValidator.validateSave</code> on this file.
* If the validation fails, then this operation will fail.
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this file's content have been changed.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param source an input stream containing the new contents of the file
* @param updateFlags bit-wise or of update flag constants
* (<code>FORCE</code> and <code>KEEP_HISTORY</code>)
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* <li> The workspace is not in sync with the corresponding location
* in the local file system and <code>FORCE</code> is not specified.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li> The file modification validator disallowed the change.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResourceRuleFactory#modifyRule(IResource)
* @since 2.0
*/
public void setContents(InputStream source, int updateFlags, IProgressMonitor monitor) throws CoreException;
/**
* Sets the contents of this file to the bytes in the given file state.
* <p>
* The <code>FORCE</code> update flag controls how this method deals with
* cases where the workspace is not completely in sync with the local file
* system. If <code>FORCE</code> is not specified, the method will only attempt
* to overwrite a corresponding file in the local file system provided
* it is in sync with the workspace. This option ensures there is no
* unintended data loss; it is the recommended setting.
* However, if <code>FORCE</code> is specified, an attempt will be made
* to write a corresponding file in the local file system, overwriting any
* existing one if need be. In either case, if this method succeeds, the
* resource will be marked as being local (even if it wasn't before).
* </p>
* <p>
* The <code>KEEP_HISTORY</code> update flag controls whether or not a copy of
* current contents of this file should be captured in the workspace's local
* history (properties are not recorded in the local history). The local history
* mechanism serves as a safety net to help the user recover from mistakes that
* might otherwise result in data loss. Specifying <code>KEEP_HISTORY</code>
* is recommended except in circumstances where past states of the files are of
* no conceivable interest to the user. Note that local history is maintained
* with each individual project, and gets discarded when a project is deleted
* from the workspace. This flag is ignored if the file was not previously local.
* </p>
* <p>
* Update flags other than <code>FORCE</code> and <code>KEEP_HISTORY</code>
* are ignored.
* </p>
* <p>
* Prior to modifying the contents of this file, the file modification validator (if provided
* by the VCM plug-in), will be given a chance to perform any last minute preparations. Validation
* is performed by calling <code>IFileModificationValidator.validateSave</code> on this file.
* If the validation fails, then this operation will fail.
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this file's content have been changed.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param source a previous state of this resource
* @param updateFlags bit-wise or of update flag constants
* (<code>FORCE</code> and <code>KEEP_HISTORY</code>)
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> The state does not exist.</li>
* <li> The corresponding location in the local file system
* is occupied by a directory.</li>
* <li> The workspace is not in sync with the corresponding location
* in the local file system and <code>FORCE</code> is not specified.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li> The file modification validator disallowed the change.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResourceRuleFactory#modifyRule(IResource)
* @since 2.0
*/
public void setContents(IFileState source, int updateFlags, IProgressMonitor monitor) throws CoreException;
}
diff --git a/src/org/eclipse/core/resources/IFolder.java b/src/org/eclipse/core/resources/IFolder.java
index bc7633dd..d1efd1a8 100644
--- a/src/org/eclipse/core/resources/IFolder.java
+++ b/src/org/eclipse/core/resources/IFolder.java
@@ -1,459 +1,461 @@
/*******************************************************************************
* Copyright (c) 2000, 2010 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
* Serge Beauchamp (Freescale Semiconductor) - [229633] Group Support
*******************************************************************************/
package org.eclipse.core.resources;
import java.net.URI;
import org.eclipse.core.runtime.*;
/**
* Folders may be leaf or non-leaf resources and may contain files and/or other folders.
* A folder resource is stored as a directory in the local file system.
* <p>
* Folders, like other resource types, may exist in the workspace but
* not be local; non-local folder resources serve as place-holders for
* folders whose properties have not yet been fetched from a repository.
* </p>
* <p>
* Folders implement the <code>IAdaptable</code> interface;
* extensions are managed by the platform's adapter manager.
* </p>
*
* @see Platform#getAdapterManager()
* @noimplement This interface is not intended to be implemented by clients.
* @noextend This interface is not intended to be extended by clients.
*/
public interface IFolder extends IContainer, IAdaptable {
/**
* Creates a new folder resource as a member of this handle's parent resource.
* <p>
* This is a convenience method, fully equivalent to:
* <pre>
* create((force ? FORCE : IResource.NONE), local, monitor);
* </pre>
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that the folder has been added to its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param force a flag controlling how to deal with resources that
* are not in sync with the local file system
* @param local a flag controlling whether or not the folder will be local
* after the creation
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource already exists in the workspace.</li>
* <li> The workspace contains a resource of a different type
* at the same path as this resource.</li>
* <li> The parent of this resource does not exist.</li>
* <li> The parent of this resource is a project that is not open.</li>
* <li> The parent contains a resource of a different type
* at the same path as this resource.</li>
+ * <li> The parent of this resource is virtual, but this resource is not.</li>
* <li> The name of this resource is not valid (according to
* <code>IWorkspace.validateName</code>).</li>
* <li> The corresponding location in the local file system is occupied
* by a file (as opposed to a directory).</li>
* <li> The corresponding location in the local file system is occupied
* by a folder and <code>force </code> is <code>false</code>.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IFolder#create(int,boolean,IProgressMonitor)
*/
public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException;
/**
* Creates a new folder resource as a member of this handle's parent resource.
* <p>
* The <code>FORCE</code> update flag controls how this method deals with
* cases where the workspace is not completely in sync with the local file
* system. If <code>FORCE</code> is not specified, the method will only attempt
* to create a directory in the local file system if there isn't one already.
* This option ensures there is no unintended data loss; it is the recommended
* setting. However, if <code>FORCE</code> is specified, this method will
* be deemed a success even if there already is a corresponding directory.
* </p>
* <p>
* The {@link IResource#DERIVED} update flag indicates that this resource
* should immediately be set as a derived resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setDerived(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* The {@link IResource#TEAM_PRIVATE} update flag indicates that this resource
* should immediately be set as a team private resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setTeamPrivateMember(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* The {@link IResource#HIDDEN} update flag indicates that this resource
* should immediately be set as a hidden resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setHidden(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* Update flags other than those listed above are ignored.
* </p>
* <p>
* This method synchronizes this resource with the local file system.
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that the folder has been added to its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param updateFlags bit-wise or of update flag constants
* ({@link IResource#FORCE}, {@link IResource#DERIVED}, {@link IResource#TEAM_PRIVATE})
* and {@link IResource#VIRTUAL})
* @param local a flag controlling whether or not the folder will be local
* after the creation
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource already exists in the workspace.</li>
* <li> The workspace contains a resource of a different type
* at the same path as this resource.</li>
* <li> The parent of this resource does not exist.</li>
* <li> The parent of this resource is a project that is not open.</li>
* <li> The parent contains a resource of a different type
* at the same path as this resource.</li>
+ * <li> The parent of this resource is virtual, but this resource is not.</li>
* <li> The name of this resource is not valid (according to
* <code>IWorkspace.validateName</code>).</li>
* <li> The corresponding location in the local file system is occupied
* by a file (as opposed to a directory).</li>
* <li> The corresponding location in the local file system is occupied
* by a folder and <code>FORCE</code> is not specified.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResourceRuleFactory#createRule(IResource)
* @since 2.0
*/
public void create(int updateFlags, boolean local, IProgressMonitor monitor) throws CoreException;
/**
* Creates a new folder resource as a member of this handle's parent resource.
* The folder's contents will be located in the directory specified by the given
* file system path. The given path must be either an absolute file system
* path, or a relative path whose first segment is the name of a workspace path
* variable.
* <p>
* The <code>ALLOW_MISSING_LOCAL</code> update flag controls how this
* method deals with cases where the local file system directory to be linked does
* not exist, or is relative to a workspace path variable that is not defined.
* If <code>ALLOW_MISSING_LOCAL</code> is specified, the operation will succeed
* even if the local directory is missing, or the path is relative to an
* undefined variable. If <code>ALLOW_MISSING_LOCAL</code> is not specified, the
* operation will fail in the case where the local file system directory does
* not exist or the path is relative to an undefined variable.
* </p>
* <p>
* The {@link IResource#REPLACE} update flag controls how this
* method deals with cases where a resource of the same name as the
* prospective link already exists. If {@link IResource#REPLACE}
* is specified, then the existing linked resource's location is replaced
* by localLocation's value. This does <b>not</b>
* cause the underlying file system contents of that resource to be deleted.
* If {@link IResource#REPLACE} is not specified, this method will
* fail if an existing resource exists of the same name.
* </p>
* <p>
* The {@link IResource#BACKGROUND_REFRESH} update flag controls how
* this method synchronizes the new resource with the filesystem. If this flag is
* specified, resources on disk will be synchronized in the background after the
* method returns. Child resources of the link may not be available until
* this background refresh completes. If this flag is not specified, resources are
* synchronized in the foreground before this method returns.
* </p>
* <p>
* The {@link IResource#HIDDEN} update flag indicates that this resource
* should immediately be set as a hidden resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setHidden(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* Update flags other than those listed above are ignored.
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that the folder has been added to its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param localLocation a file system path where the folder should be linked
* @param updateFlags bit-wise or of update flag constants
* ({@link IResource#ALLOW_MISSING_LOCAL}, {@link IResource#REPLACE}, {@link IResource#BACKGROUND_REFRESH}, and {@link IResource#HIDDEN})
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource already exists in the workspace.</li>
* <li> The workspace contains a resource of a different type
* at the same path as this resource.</li>
* <li> The parent of this resource does not exist.</li>
* <li> The parent of this resource is not an open project</li>
* <li> The name of this resource is not valid (according to
* <code>IWorkspace.validateName</code>).</li>
* <li> The corresponding location in the local file system does not exist, or
* is relative to an undefined variable, and <code>ALLOW_MISSING_LOCAL</code> is
* not specified.</li>
* <li> The corresponding location in the local file system is occupied
* by a file (as opposed to a directory).</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li>The team provider for the project which contains this folder does not permit
* linked resources.</li>
* <li>This folder's project contains a nature which does not permit linked resources.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResource#isLinked()
* @see IResource#ALLOW_MISSING_LOCAL
* @see IResource#REPLACE
* @see IResource#BACKGROUND_REFRESH
* @see IResource#HIDDEN
* @since 2.1
*/
public void createLink(IPath localLocation, int updateFlags, IProgressMonitor monitor) throws CoreException;
/**
* Creates a new folder resource as a member of this handle's parent resource.
* The folder's contents will be located in the directory specified by the given
* file system URI. The given URI must be either absolute, or a relative URI
* whose first path segment is the name of a workspace path variable.
* <p>
* The <code>ALLOW_MISSING_LOCAL</code> update flag controls how this
* method deals with cases where the local file system directory to be linked does
* not exist, or is relative to a workspace path variable that is not defined.
* If <code>ALLOW_MISSING_LOCAL</code> is specified, the operation will succeed
* even if the local directory is missing, or the path is relative to an
* undefined variable. If <code>ALLOW_MISSING_LOCAL</code> is not specified, the
* operation will fail in the case where the local file system directory does
* not exist or the path is relative to an undefined variable.
* </p>
* <p>
* The {@link IResource#REPLACE} update flag controls how this
* method deals with cases where a resource of the same name as the
* prospective link already exists. If {@link IResource#REPLACE}
* is specified, then any existing resource with the same name is removed
* from the workspace to make way for creation of the link. This does <b>not</b>
* cause the underlying file system contents of that resource to be deleted.
* If {@link IResource#REPLACE} is not specified, this method will
* fail if an existing resource exists of the same name.
* </p>
* <p>
* The {@link IResource#BACKGROUND_REFRESH} update flag controls how
* this method synchronizes the new resource with the filesystem. If this flag is
* specified, resources on disk will be synchronized in the background after the
* method returns. Child resources of the link may not be available until
* this background refresh completes. If this flag is not specified, resources are
* synchronized in the foreground before this method returns.
* </p>
* <p>
* The {@link IResource#HIDDEN} update flag indicates that this resource
* should immediately be set as a hidden resource. Specifying this flag
* is equivalent to atomically calling {@link IResource#setHidden(boolean)}
* with a value of <code>true</code> immediately after creating the resource.
* </p>
* <p>
* Update flags other than those listed above are ignored.
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that the folder has been added to its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param location a file system path where the folder should be linked
* @param updateFlags bit-wise or of update flag constants
* ({@link IResource#ALLOW_MISSING_LOCAL}, {@link IResource#REPLACE}, {@link IResource#BACKGROUND_REFRESH}, and {@link IResource#HIDDEN})
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource already exists in the workspace.</li>
* <li> The workspace contains a resource of a different type
* at the same path as this resource.</li>
* <li> The parent of this resource does not exist.</li>
* <li> The parent of this resource is not an open project</li>
* <li> The name of this resource is not valid (according to
* <code>IWorkspace.validateName</code>).</li>
* <li> The corresponding location in the local file system does not exist, or
* is relative to an undefined variable, and <code>ALLOW_MISSING_LOCAL</code> is
* not specified.</li>
* <li> The corresponding location in the local file system is occupied
* by a file (as opposed to a directory).</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* <li>The team provider for the project which contains this folder does not permit
* linked resources.</li>
* <li>This folder's project contains a nature which does not permit linked resources.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
* @see IResource#isLinked()
* @see IResource#ALLOW_MISSING_LOCAL
* @see IResource#REPLACE
* @see IResource#BACKGROUND_REFRESH
* @see IResource#HIDDEN
* @since 3.2
*/
public void createLink(URI location, int updateFlags, IProgressMonitor monitor) throws CoreException;
/**
* Deletes this resource from the workspace.
* <p>
* This is a convenience method, fully equivalent to:
* <pre>
* delete((keepHistory ? KEEP_HISTORY : IResource.NONE) | (force ? FORCE : IResource.NONE), monitor);
* </pre>
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this folder has been removed from its parent.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param force a flag controlling whether resources that are not
* in sync with the local file system will be tolerated
* @param keepHistory a flag controlling whether files under this folder
* should be stored in the workspace's local history
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this method fails. Reasons include:
* <ul>
* <li> This resource could not be deleted for some reason.</li>
* <li> This resource is out of sync with the local file system
* and <code>force</code> is <code>false</code>.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
*
* @see IResourceRuleFactory#deleteRule(IResource)
* @see IResource#delete(int,IProgressMonitor)
*/
public void delete(boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException;
/**
* Returns a handle to the file with the given name in this folder.
* <p>
* This is a resource handle operation; neither the resource nor
* the result need exist in the workspace.
* The validation check on the resource name/path is not done
* when the resource handle is constructed; rather, it is done
* automatically as the resource is created.
* </p>
*
* @param name the string name of the member file
* @return the (handle of the) member file
* @see #getFolder(String)
*/
public IFile getFile(String name);
/**
* Returns a handle to the folder with the given name in this folder.
* <p>
* This is a resource handle operation; neither the container
* nor the result need exist in the workspace.
* The validation check on the resource name/path is not done
* when the resource handle is constructed; rather, it is done
* automatically as the resource is created.
* </p>
*
* @param name the string name of the member folder
* @return the (handle of the) member folder
* @see #getFile(String)
*/
public IFolder getFolder(String name);
/**
* Moves this resource so that it is located at the given path.
* <p>
* This is a convenience method, fully equivalent to:
* <pre>
* move(destination, (keepHistory ? KEEP_HISTORY : IResource.NONE) | (force ? FORCE : IResource.NONE), monitor);
* </pre>
* </p>
* <p>
* This method changes resources; these changes will be reported
* in a subsequent resource change event, including an indication
* that this folder has been removed from its parent and a new folder
* has been added to the parent of the destination.
* </p>
* <p>
* This method is long-running; progress and cancellation are provided
* by the given progress monitor.
* </p>
*
* @param destination the destination path
* @param force a flag controlling whether resources that are not
* in sync with the local file system will be tolerated
* @param keepHistory a flag controlling whether files under this folder
* should be stored in the workspace's local history
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting is not desired
* @exception CoreException if this resource could not be moved. Reasons include:
* <ul>
* <li> This resource does not exist.</li>
* <li> This resource or one of its descendents is not local.</li>
* <li> The resource corresponding to the parent destination path does not exist.</li>
* <li> The resource corresponding to the parent destination path is a closed
* project.</li>
* <li> A resource at destination path does exist.</li>
* <li> A resource of a different type exists at the destination path.</li>
* <li> This resource or one of its descendents is out of sync with the local file system
* and <code>force</code> is <code>false</code>.</li>
* <li> The workspace and the local file system are out of sync
* at the destination resource or one of its descendents.</li>
* <li> Resource changes are disallowed during certain types of resource change
* event notification. See <code>IResourceChangeEvent</code> for more details.</li>
* </ul>
* @exception OperationCanceledException if the operation is canceled.
* Cancelation can occur even if no progress monitor is provided.
*
* @see IResourceRuleFactory#moveRule(IResource, IResource)
* @see IResource#move(IPath,int,IProgressMonitor)
*/
public void move(IPath destination, boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException;
}
| false | false | null | null |
diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactResolver.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactResolver.java
index c1eade0..b0ed149 100644
--- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactResolver.java
+++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/StubArtifactResolver.java
@@ -1,188 +1,188 @@
package org.apache.maven.plugin.testing.stubs;
/*
* 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 java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugin.testing.ArtifactStubFactory;
/**
* Stub resolver. The constructor allows the specification of the exception to throw so that handling can be tested too.
*
* @author <a href="mailto:[email protected]">Brian Fox</a>
* @version $Id: $
*/
public class StubArtifactResolver
implements ArtifactResolver
{
boolean throwArtifactResolutionException;
boolean throwArtifactNotFoundException;
ArtifactStubFactory factory;
/**
* Default constructor
*
* @param factory
* @param throwArtifactResolutionException
* @param throwArtifactNotFoundException
*/
public StubArtifactResolver( ArtifactStubFactory factory, boolean throwArtifactResolutionException,
boolean throwArtifactNotFoundException )
{
this.throwArtifactNotFoundException = throwArtifactNotFoundException;
this.throwArtifactResolutionException = throwArtifactResolutionException;
this.factory = factory;
}
/*
* Creates dummy file and sets it in the artifact to simulate resolution
* (non-Javadoc)
*
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolve(org.apache.maven.artifact.Artifact,
* java.util.List,
* org.apache.maven.artifact.repository.ArtifactRepository)
*/
public void resolve( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
if ( !this.throwArtifactNotFoundException && !this.throwArtifactResolutionException )
{
try
{
if ( factory != null )
{
- factory.setArtifactFile( artifact );
+ factory.setArtifactFile( artifact, factory.getWorkingDir() );
}
}
catch ( IOException e )
{
throw new ArtifactResolutionException( "IOException: " + e.getMessage(), artifact, e );
}
}
else
{
if ( throwArtifactResolutionException )
{
throw new ArtifactResolutionException( "Catch!", artifact );
}
throw new ArtifactNotFoundException( "Catch!", artifact );
}
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.List, org.apache.maven.artifact.repository.ArtifactRepository, org.apache.maven.artifact.metadata.ArtifactMetadataSource)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
List remoteRepositories, ArtifactRepository localRepository,
ArtifactMetadataSource source )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.List, org.apache.maven.artifact.repository.ArtifactRepository, org.apache.maven.artifact.metadata.ArtifactMetadataSource, java.util.List)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
List remoteRepositories, ArtifactRepository localRepository,
ArtifactMetadataSource source, List listeners )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, org.apache.maven.artifact.repository.ArtifactRepository, java.util.List, org.apache.maven.artifact.metadata.ArtifactMetadataSource, org.apache.maven.artifact.resolver.filter.ArtifactFilter)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
ArtifactRepository localRepository, List remoteRepositories,
ArtifactMetadataSource source, ArtifactFilter filter )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.Map, org.apache.maven.artifact.repository.ArtifactRepository, java.util.List, org.apache.maven.artifact.metadata.ArtifactMetadataSource)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List remoteRepositories, ArtifactMetadataSource source )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.Map, org.apache.maven.artifact.repository.ArtifactRepository, java.util.List, org.apache.maven.artifact.metadata.ArtifactMetadataSource, org.apache.maven.artifact.resolver.filter.ArtifactFilter)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List remoteRepositories, ArtifactMetadataSource source,
ArtifactFilter filter )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* @return <code>null</code>.
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveTransitively(java.util.Set, org.apache.maven.artifact.Artifact, java.util.Map, org.apache.maven.artifact.repository.ArtifactRepository, java.util.List, org.apache.maven.artifact.metadata.ArtifactMetadataSource, org.apache.maven.artifact.resolver.filter.ArtifactFilter, java.util.List)
*/
public ArtifactResolutionResult resolveTransitively( Set artifacts, Artifact originatingArtifact,
Map managedVersions, ArtifactRepository localRepository,
List remoteRepositories, ArtifactMetadataSource source,
ArtifactFilter filter, List listeners )
throws ArtifactResolutionException, ArtifactNotFoundException
{
return null;
}
/**
* By default, do nothing.
*
* @see org.apache.maven.artifact.resolver.ArtifactResolver#resolveAlways(org.apache.maven.artifact.Artifact, java.util.List, org.apache.maven.artifact.repository.ArtifactRepository)
*/
public void resolveAlways( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
// nop
}
}
| true | true | public void resolve( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
if ( !this.throwArtifactNotFoundException && !this.throwArtifactResolutionException )
{
try
{
if ( factory != null )
{
factory.setArtifactFile( artifact );
}
}
catch ( IOException e )
{
throw new ArtifactResolutionException( "IOException: " + e.getMessage(), artifact, e );
}
}
else
{
if ( throwArtifactResolutionException )
{
throw new ArtifactResolutionException( "Catch!", artifact );
}
throw new ArtifactNotFoundException( "Catch!", artifact );
}
}
| public void resolve( Artifact artifact, List remoteRepositories, ArtifactRepository localRepository )
throws ArtifactResolutionException, ArtifactNotFoundException
{
if ( !this.throwArtifactNotFoundException && !this.throwArtifactResolutionException )
{
try
{
if ( factory != null )
{
factory.setArtifactFile( artifact, factory.getWorkingDir() );
}
}
catch ( IOException e )
{
throw new ArtifactResolutionException( "IOException: " + e.getMessage(), artifact, e );
}
}
else
{
if ( throwArtifactResolutionException )
{
throw new ArtifactResolutionException( "Catch!", artifact );
}
throw new ArtifactNotFoundException( "Catch!", artifact );
}
}
|
diff --git a/servicemix-core/src/main/java/org/apache/servicemix/jbi/view/DotViewFlowListener.java b/servicemix-core/src/main/java/org/apache/servicemix/jbi/view/DotViewFlowListener.java
index e56b675d3..333cd2194 100644
--- a/servicemix-core/src/main/java/org/apache/servicemix/jbi/view/DotViewFlowListener.java
+++ b/servicemix-core/src/main/java/org/apache/servicemix/jbi/view/DotViewFlowListener.java
@@ -1,223 +1,223 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicemix.jbi.view;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.servicedesc.ServiceEndpoint;
import org.apache.servicemix.JbiConstants;
import org.apache.servicemix.jbi.event.ComponentEvent;
import org.apache.servicemix.jbi.event.ComponentListener;
import org.apache.servicemix.jbi.event.EndpointEvent;
import org.apache.servicemix.jbi.event.ExchangeEvent;
import org.apache.servicemix.jbi.event.ExchangeListener;
import org.apache.servicemix.jbi.framework.ComponentMBeanImpl;
import org.apache.servicemix.jbi.framework.Registry;
import org.apache.servicemix.jbi.messaging.MessageExchangeImpl;
+import org.apache.servicemix.jbi.servicedesc.AbstractServiceEndpoint;
import org.apache.servicemix.jbi.servicedesc.EndpointSupport;
import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
import edu.emory.mathcs.backport.java.util.concurrent.CopyOnWriteArraySet;
/**
* Creates a <a href="http://www.graphviz.org/">DOT</a> file showing the JBI MessageExchange
* flow within the JBI Container.
* @org.apache.xbean.XBean
* description="Generates DOT visualisations of the exchanges flow inside ServiceMix"
*
* @version $Revision: 391707 $
*/
public class DotViewFlowListener extends DotViewEndpointListener
implements ExchangeListener, ComponentListener {
private Map flow;
private Set flowLinks;
private Set usedComponents;
private Set componentsAsConsumer;
private boolean displayComponents = true;
public DotViewFlowListener() {
setFile("ServiceMixFlow.dot");
flow = new ConcurrentHashMap();
flowLinks = new CopyOnWriteArraySet();
usedComponents = new CopyOnWriteArraySet();
componentsAsConsumer = new CopyOnWriteArraySet();
}
// Implementation methods
// -------------------------------------------------------------------------
protected void generateFile(PrintWriter writer) throws Exception {
writer.println("digraph \"Apache ServiceMix\" {");
writer.println();
writer.println("label = \"Apache ServiceMix flow\";");
writer.println("node [ shape = box, style = \"rounded,filled\", fontname = \"Helvetica-Oblique\", fontsize = 8 ];");
writer.println();
List brokerLinks = new ArrayList();
Registry registry = getContainer().getRegistry();
Collection components = registry.getComponents();
for (Iterator iter = components.iterator(); iter.hasNext();) {
ComponentMBeanImpl component = (ComponentMBeanImpl) iter.next();
ServiceEndpoint[] ses = registry.getEndpointRegistry().getAllEndpointsForComponent(component.getComponentNameSpace());
String name = component.getName();
if (!usedComponents.contains(name)) {
continue;
}
// If we want to display components, create
// a sub graph, grouping all the components
// endpoints
if (isDisplayComponents()) {
String id = encode(name);
writer.println("subgraph cluster_" + id + " {");
writer.println(" label=\"" + name + "\";");
if (componentsAsConsumer.contains(name)) {
writer.println(" " + id + " [ fillcolor = gray, label = \"" + name + "\" ];");
}
}
for (int i = 0; i < ses.length; i++) {
String key = EndpointSupport.getUniqueKey(ses[i]);
String epname = formatEndpoint(key);
if (!isDisplayComponents()) {
epname += "\\n" + name;
}
String color = "lightgray";
if (epname.startsWith("internal")) {
epname = epname.substring(10);
color = "#6699ff";
} else if (epname.startsWith("external")) {
epname = epname.substring(10);
color = "#66ccff";
} else if (epname.startsWith("dynamic")) {
epname = epname.substring(9);
color = "#6666ff";
} else if (epname.startsWith("linked")) {
epname = epname.substring(8);
color = "#66ffff";
} else {
color = "#f3f3f3";
}
String epid = encode(key);
writer.println(" " + epid + " [fillcolor = \"" + color + "\", label=\"" + epname + "\"];");
}
if (isDisplayComponents()) {
writer.println("}");
}
}
writer.println();
generateLinks(writer, brokerLinks);
writer.println();
generateLinks(writer, flowLinks);
writer.println("}");
}
public void exchangeSent(ExchangeEvent event) {
MessageExchange me = event.getExchange();
- if (me.getEndpoint() != null &&
- me instanceof MessageExchangeImpl) {
+ if (me.getEndpoint() instanceof AbstractServiceEndpoint && me instanceof MessageExchangeImpl) {
MessageExchangeImpl mei = (MessageExchangeImpl) me;
String source = (String) me.getProperty(JbiConstants.SENDER_ENDPOINT);
if (source == null) {
source = mei.getSourceId().getName();
componentsAsConsumer.add(source);
} else {
ServiceEndpoint[] ses = getContainer().getRegistry().getEndpointRegistry().getAllEndpointsForComponent(mei.getSourceId());
for (int i = 0; i < ses.length; i++) {
if (EndpointSupport.getKey(ses[i]).equals(source)) {
source = EndpointSupport.getUniqueKey(ses[i]);
break;
}
}
}
usedComponents.add(mei.getSourceId().getName());
- usedComponents.add(mei.getDestinationId().getName());
+ usedComponents.add(((AbstractServiceEndpoint) mei.getEndpoint()).getComponentNameSpace().getName());
String dest = EndpointSupport.getUniqueKey(mei.getEndpoint());
Map componentFlow = createSource(source);
if (componentFlow.put(dest, Boolean.TRUE) == null) {
flowLinks.add(encode(source) + " -> " + encode(dest));
viewIsDirty(mei.getEndpoint());
}
}
}
protected Map createSource(String name) {
synchronized (flow) {
Map componentFlow = (Map) flow.get(name);
if (componentFlow == null) {
componentFlow = new ConcurrentHashMap();
flow.put(name, componentFlow);
}
return componentFlow;
}
}
public void internalEndpointRegistered(EndpointEvent event) {
String key = EndpointSupport.getUniqueKey(event.getEndpoint());
createSource(key);
super.internalEndpointRegistered(event);
}
public void externalEndpointRegistered(EndpointEvent event) {
String key = EndpointSupport.getUniqueKey(event.getEndpoint());
createSource(key);
super.externalEndpointRegistered(event);
}
public void linkedEndpointRegistered(EndpointEvent event) {
String key = EndpointSupport.getUniqueKey(event.getEndpoint());
createSource(key);
super.linkedEndpointRegistered(event);
}
public void componentInstalled(ComponentEvent event) {
createSource(event.getComponent().getName());
}
public void componentStarted(ComponentEvent event) {
createSource(event.getComponent().getName());
}
public void componentStopped(ComponentEvent event) {
}
public void componentShutDown(ComponentEvent event) {
}
public void componentUninstalled(ComponentEvent event) {
}
public boolean isDisplayComponents() {
return displayComponents;
}
public void setDisplayComponents(boolean displayComponents) {
this.displayComponents = displayComponents;
}
}
| false | false | null | null |
diff --git a/ActiveMtl/src/com/nurun/activemtl/ActiveMtlConfiguration.java b/ActiveMtl/src/com/nurun/activemtl/ActiveMtlConfiguration.java
index d59d112..dce017e 100644
--- a/ActiveMtl/src/com/nurun/activemtl/ActiveMtlConfiguration.java
+++ b/ActiveMtl/src/com/nurun/activemtl/ActiveMtlConfiguration.java
@@ -1,124 +1,124 @@
package com.nurun.activemtl;
import java.io.IOException;
import java.util.Properties;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.text.TextUtils;
import com.nurun.activemtl.model.EventType;
public class ActiveMtlConfiguration {
private final Properties properties = new Properties();
private static ActiveMtlConfiguration faCConfiguration;
private ActiveMtlConfiguration(Context context) throws NotFoundException, IOException {
properties.load(context.getResources().openRawResource(R.raw.config));
}
public static ActiveMtlConfiguration getInstance(Context context) {
if (faCConfiguration == null) {
try {
faCConfiguration = new ActiveMtlConfiguration(context);
} catch (Exception e) {
throw new RuntimeException("Invalid config file");
}
}
return faCConfiguration;
}
public String getHomeListUrl() {
return getBaseUrl() + properties.getProperty("homelist.url");
}
public String getListUrl(EventType eventType, double lat, double lon) {
switch (eventType) {
case Challenge:
return getBaseUrl() + String.format(properties.getProperty("challengelist.url"), lat, lon);
case Idea:
return getBaseUrl() + String.format(properties.getProperty("idealist.url"), lat, lon);
case Alert:
return getBaseUrl() + String.format(properties.getProperty("issuelist.url"), lat, lon);
default:
return getHomeListUrl();
}
}
public String getDetailUrl(Context context, String id) {
String url = getBaseUrl() + String.format(properties.getProperty("detail.url"), id);
String userId = PreferenceHelper.getUserId(context);
if (TextUtils.isEmpty(userId)) {
return url;
}
return url += "?user=" + userId;
}
private String getBaseUrl() {
return properties.getProperty("base.url");
}
public String getListUrl(EventType eventType) {
switch (eventType) {
case Challenge:
return getBaseUrl() + properties.getProperty("challengelist.default.url.default");
case Idea:
return getBaseUrl() + properties.getProperty("idealist.default.url");
case Alert:
return getBaseUrl() + properties.getProperty("issuelist.default.url");
default:
return getHomeListUrl();
}
}
public int getDistrictRadius() {
return Integer.parseInt(properties.getProperty("district.radius"));
}
private String getGooleProfilePictureUrl(Context context, int resolution) {
- return String.format(properties.getProperty("profile.picture.google.url"), PreferenceHelper.getUserId(context), resolution, resolution);
+ return String.format(properties.getProperty("profile.picture.google.url"), PreferenceHelper.getUserId(context), resolution);
}
private String getFacebookProfilePictureUrl(Context context, int resolution) {
- return String.format(properties.getProperty("profile.picture.facebook.url"), PreferenceHelper.getUserId(context), resolution);
+ return String.format(properties.getProperty("profile.picture.facebook.url"), PreferenceHelper.getUserId(context), resolution, resolution);
}
private String getSmallGooleProfilePictureUrl(Context context) {
return getGooleProfilePictureUrl(context, context.getResources().getInteger(R.integer.small_resolution));
}
private String getSmallFacebookProfilePictureUrl(Context context) {
return getFacebookProfilePictureUrl(context, context.getResources().getInteger(R.integer.small_resolution));
}
private String getNormalGooleProfilePictureUrl(Context context) {
return getGooleProfilePictureUrl(context, context.getResources().getInteger(R.integer.normal_resolution));
}
private String getNormalFacebookProfilePictureUrl(Context context) {
return getFacebookProfilePictureUrl(context, context.getResources().getInteger(R.integer.normal_resolution));
}
public String getProfilePictureUrl(Context context) {
switch (PreferenceHelper.getSocialMediaConnection(context)) {
case Facebook:
return getNormalFacebookProfilePictureUrl(context);
case Google_plus:
return getNormalGooleProfilePictureUrl(context);
default:
throw new IllegalStateException("Wrong social media : " + PreferenceHelper.getSocialMediaConnection(context));
}
}
public String getSmallProfilePictureUrl(Context context) {
switch (PreferenceHelper.getSocialMediaConnection(context)) {
case Facebook:
return getSmallFacebookProfilePictureUrl(context);
case Google_plus:
return getSmallGooleProfilePictureUrl(context);
default:
throw new IllegalStateException("Wrong social media : " + PreferenceHelper.getSocialMediaConnection(context));
}
}
}
diff --git a/ActiveMtl/src/com/nurun/activemtl/ui/LoginActivity.java b/ActiveMtl/src/com/nurun/activemtl/ui/LoginActivity.java
index b141ea7..3554610 100644
--- a/ActiveMtl/src/com/nurun/activemtl/ui/LoginActivity.java
+++ b/ActiveMtl/src/com/nurun/activemtl/ui/LoginActivity.java
@@ -1,185 +1,185 @@
package com.nurun.activemtl.ui;
import java.util.Arrays;
import java.util.List;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.Person;
import com.nurun.activemtl.PreferenceHelper;
import com.nurun.activemtl.R;
import com.nurun.activemtl.SocialMediaConnection;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
public class LoginActivity extends FragmentActivity {
private PlusClient mPlusClient;
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
protected ConnectionResult mConnectionResult;
private ProgressDialog mConnectionProgressDialog;
public static Intent newIntent(Context context) {
return new Intent(context, LoginActivity.class);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
Session session = Session.getActiveSession();
mPlusClient = new PlusClient.Builder(this, connectionCallback, connectionFailListener).setVisibleActivities("http://schemas.google.com/AddActivity",
"http://schemas.google.com/BuyActivity").build();
// Barre de progression à afficher si l'échec de connexion n'est pas
// résolu.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
if (mPlusClient.isConnected()) {
mPlusClient.clearDefaultAccount();
mPlusClient.disconnect();
}
if (session != null && !session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
@Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == FragmentActivity.RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
} else {
ParseFacebookUtils.finishAuthentication(requestCode, responseCode, intent);
}
}
private void goToNextScreen() {
getFragmentManager().popBackStack();
setResult(200);
finish();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private ConnectionCallbacks connectionCallback = new ConnectionCallbacks() {
@Override
public void onDisconnected() {
}
@Override
public void onConnected(Bundle arg0) {
mConnectionProgressDialog.dismiss();
Person currentPerson = mPlusClient.getCurrentPerson();
PreferenceHelper.setSocialMediaConnection(LoginActivity.this, SocialMediaConnection.Google_plus);
PreferenceHelper.setUserId(LoginActivity.this, currentPerson.getId());
PreferenceHelper.setUserName(LoginActivity.this, currentPerson.getDisplayName());
goToNextScreen();
}
};
private OnConnectionFailedListener connectionFailListener = new OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(LoginActivity.this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
mConnectionResult = result;
}
};
public void onFacebookConnectionClicked() {
mConnectionProgressDialog.show();
List<String> permissions = Arrays.asList("basic_info", "user_about_me");
ParseFacebookUtils.logIn(permissions, this, new LogInCallback() {
@Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d(getClass().getSimpleName(), "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d(getClass().getSimpleName(), "User signed up and logged in through Facebook!");
saveUserDatas(user);
} else {
Log.d(getClass().getSimpleName(), "User logged in through Facebook!");
saveUserDatas(user);
}
}
});
}
protected void saveUserDatas(ParseUser user) {
if (user != null) {
ParseFacebookUtils.link(user, this);
Request request = Request.newMeRequest(ParseFacebookUtils.getSession(), new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
+ PreferenceHelper.setSocialMediaConnection(LoginActivity.this, SocialMediaConnection.Facebook);
PreferenceHelper.setUserId(LoginActivity.this, user.getId());
PreferenceHelper.setUserName(LoginActivity.this, user.getName());
- PreferenceHelper.setSocialMediaConnection(LoginActivity.this, SocialMediaConnection.Facebook);
goToNextScreen();
} else if (response.getError() != null) {
if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
|| (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
Log.d(getClass().getSimpleName(), "The facebook session was invalidated.");
PreferenceHelper.clearUserInfos(getApplicationContext());
ParseUser.logOut();
} else {
Log.d(getClass().getSimpleName(), "Some other error: " + response.getError().getErrorMessage());
}
}
mConnectionProgressDialog.dismiss();
}
});
request.executeAsync();
}
}
public void onGooglePlusConnectionClicked() {
mConnectionProgressDialog.show();
if (mConnectionResult == null) {
mPlusClient.connect();
} else {
try {
mConnectionProgressDialog.show();
mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Nouvelle tentative de connexion
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
| false | false | null | null |
diff --git a/modules/webserver/test/xqtl/XqtlSeleniumTest.java b/modules/webserver/test/xqtl/XqtlSeleniumTest.java
index 56652a1e9..9be2ea92a 100644
--- a/modules/webserver/test/xqtl/XqtlSeleniumTest.java
+++ b/modules/webserver/test/xqtl/XqtlSeleniumTest.java
@@ -1,718 +1,714 @@
package test.xqtl;
import java.io.File;
import org.molgenis.util.DetectOS;
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import test.Helper;
import app.servlet.MolgenisServlet;
import boot.RunStandalone;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.HttpCommandProcessor;
import com.thoughtworks.selenium.Selenium;
/**
*
* The complete xQTL Selenium web test.
* Has a section for init/helpers and section for the real tests.
*
*/
public class XqtlSeleniumTest
{
/**
*******************************************************************
************************* Init and helpers **********************
*******************************************************************
*/
-
- // skip asserts which may always succeed locally, but for some reason give
- // unpredictable results when running elsewhere (i.e. Hudson)
- boolean excused = true;
Selenium selenium;
String pageLoadTimeout = "30000";
boolean tomcat = false;
String appName;
/**
* Configure Selenium server and delete the database
*/
@BeforeClass
public void start() throws Exception
{
appName = MolgenisServlet.getMolgenisVariantID();
int webserverPort = 8080;
if (!tomcat) webserverPort = Helper.getAvailablePort(11000, 100);
String seleniumUrl = "http://localhost:" + webserverPort + "/";
String seleniumHost = "localhost";
String seleniumBrowser = "firefox";
int seleniumPort = Helper.getAvailablePort(9080, 100);
RemoteControlConfiguration rcc = new RemoteControlConfiguration();
rcc.setSingleWindow(true);
rcc.setPort(seleniumPort);
try
{
SeleniumServer server = new SeleniumServer(false, rcc);
server.boot();
}
catch (Exception e)
{
throw new IllegalStateException("Cannot start selenium server: ", e);
}
HttpCommandProcessor proc = new HttpCommandProcessor(seleniumHost, seleniumPort, seleniumBrowser, seleniumUrl);
selenium = new DefaultSelenium(proc);
selenium.start();
Helper.deleteDatabase();
if (!tomcat) new RunStandalone(webserverPort);
}
/**
* Stop Selenium server and remove files
*/
@AfterClass
public void stop() throws Exception
{
selenium.stop();
Helper.deleteStorage();
}
/**
* Start the app and verify home page
*/
@Test
public void startup() throws InterruptedException
{
selenium.open("/" + appName + "/molgenis.do");
selenium.waitForPageToLoad(pageLoadTimeout);
// Assert.assertTrue(selenium.getTitle().toLowerCase().contains("xQTL workbench".toLowerCase()));
Assert.assertTrue(selenium.isTextPresent("Welcome"));
Assert.assertEquals(selenium.getText("link=R api"), "R api");
}
/**
* Login as admin and redirect
*/
@Test(dependsOnMethods =
{ "startup" })
public void login() throws InterruptedException
{
clickAndWait("id=UserLogin_tab_button");
Assert.assertEquals(selenium.getText("link=Register"), "Register");
selenium.type("id=username", "admin");
selenium.type("id=password", "admin");
clickAndWait("id=Login");
// note: page now redirects to the Home screen ('auth_redirect' in
// properties)
Assert.assertTrue(selenium
.isTextPresent("You are logged in as admin, and the database does not contain any investigations or other users."));
}
/**
* Press 'Load' example data
*/
@Test(dependsOnMethods =
{ "login" })
public void loadExampleData() throws InterruptedException
{
selenium.type("id=inputBox", storagePath());
clickAndWait("id=loadExamples");
Assert.assertTrue(selenium.isTextPresent("File path '" + storagePath()
+ "' was validated and the dataloader succeeded"));
}
/**
* Function that sets the application to a 'default' state after setting up.
* All downstream test functions require this to be done.
*/
@Test(dependsOnMethods =
{ "loadExampleData" })
public void returnHome() throws InterruptedException
{
clickAndWait("id=ClusterDemo_tab_button");
}
/**
* Helper function. Click a target and wait.
*/
public void clickAndWait(String target)
{
selenium.click(target);
selenium.waitForPageToLoad(pageLoadTimeout);
}
/**
* Helper function. Get DOM property using JavaScript.
*/
public String propertyScript(String element, String property)
{
return "var x = window.document.getElementById('" + element
+ "'); window.document.defaultView.getComputedStyle(x,null).getPropertyValue('" + property + "');";
}
/**
* Helper function. Get the storage path to use in test.
*/
public String storagePath()
{
String storagePath = new File(".").getAbsolutePath() + File.separator + "tmp_selenium_test_data";
if (DetectOS.getOS().startsWith("windows"))
{
return storagePath.replace("\\", "/");
}
else
{
return storagePath;
}
}
/**
*******************************************************************
************************** Assorted tests ***********************
*******************************************************************
*/
@Test(dependsOnMethods =
{ "returnHome" })
public void exploreExampleData() throws InterruptedException
{
// browse to Overview and check links
clickAndWait("id=Investigations_tab_button");
clickAndWait("id=Overview_tab_button");
Assert.assertEquals(selenium.getText("link=Marker (117)"), "Marker (117)");
// click link to a matrix and check values
clickAndWait("link=metaboliteexpression");
Assert.assertTrue(selenium.isTextPresent("942") && selenium.isTextPresent("4857")
&& selenium.isTextPresent("20716"));
//restore state
clickAndWait("id=remove_filter_0");
}
@Test(dependsOnMethods =
{ "returnHome" })
public void compactView() throws InterruptedException
{
// browse to Data tab
clickAndWait("id=Investigations_tab_button");
clickAndWait("id=Datas_tab_button");
// assert if the hide investigation and data table rows are hidden
Assert.assertEquals(selenium.getEval(propertyScript("Investigations_collapse_tr_id", "display")), "none");
Assert.assertEquals(selenium.getEval(propertyScript("Datas_collapse_tr_id", "display")), "none");
// click both unhide buttons
selenium.click("id=Investigations_collapse_button_id");
selenium.click("id=Datas_collapse_button_id");
// assert if the hide investigation and data table rows are exposed
Assert.assertEquals(selenium.getEval(propertyScript("Investigations_collapse_tr_id", "display")), "table-row");
Assert.assertEquals(selenium.getEval(propertyScript("Datas_collapse_tr_id", "display")), "table-row");
// click both unhide buttons
selenium.click("id=Investigations_collapse_button_id");
selenium.click("id=Datas_collapse_button_id");
// assert if the hide investigation and data table rows are hidden again
Assert.assertEquals(selenium.getEval(propertyScript("Investigations_collapse_tr_id", "display")), "none");
Assert.assertEquals(selenium.getEval(propertyScript("Datas_collapse_tr_id", "display")), "none");
}
@Test(dependsOnMethods =
{ "returnHome" })
public void individualForms() throws Exception
{
// browse to individuals
clickAndWait("id=Investigations_tab_button");
clickAndWait("id=BasicAnnotations_tab_button");
clickAndWait("id=Individuals_tab_button");
clickAndWait("id=first_Individuals");
// check some values here
Assert.assertEquals(selenium.getText("//form[@id='Individuals_form']/div[3]/div/div/table/tbody/tr[7]/td[4]"),
"X7");
Assert.assertTrue(selenium.isTextPresent("xgap_rqtl_straintype_riself"));
// switch to edit view and check some values there too
clickAndWait("id=Individuals_editview");
Assert.assertEquals(selenium.getValue("id=Individual_name"), "X1");
Assert.assertEquals(selenium.getText("css=#Individual_ontologyReference_chzn > a.chzn-single > span"),
"xgap_rqtl_straintype_riself");
Assert.assertEquals(
selenium.getText("//img[@onclick=\"if ($('#Individuals_form').valid() && validateForm(document.forms.Individuals_form,new Array())) {setInput('Individuals_form','_self','','Individuals','update','iframe'); document.forms.Individuals_form.submit();}\"]"),
"");
// click add new, wait for popup, and select it
selenium.click("id=Individuals_edit_new");
selenium.waitForPopUp("molgenis_edit_new", "30000");
selenium.selectWindow("name=molgenis_edit_new");
// fill in the form and click add
selenium.type("id=Individual_name", "testindv");
clickAndWait("id=Add");
// select main window and check if add was successful
selenium.selectWindow("title=xQTL workbench");
Assert.assertTrue(selenium.isTextPresent("ADD SUCCESS: affected 1"));
// page back and forth and check values
clickAndWait("id=prev_Individuals");
Assert.assertEquals(selenium.getValue("id=Individual_name"), "X193");
clickAndWait("id=last_Individuals");
Assert.assertEquals(selenium.getValue("id=Individual_name"), "testindv");
// delete the test individual and check if it happened
selenium.click("id=delete_Individuals");
Assert.assertEquals(selenium.getConfirmation(),
"You are about to delete a record. If you click [yes] you won't be able to undo this operation.");
selenium.waitForPageToLoad(pageLoadTimeout);
Assert.assertTrue(selenium.isTextPresent("REMOVE SUCCESS: affected 1"));
}
@Test(dependsOnMethods =
{ "returnHome" })
public void enumInput() throws Exception
{
// browse to 'Data' view and expand compact view
clickAndWait("id=Investigations_tab_button");
clickAndWait("id=Datas_tab_button");
selenium.click("id=Datas_collapse_button_id");
// assert content of enum fields
Assert.assertEquals(
selenium.getTable("css=#Datas_form > div.screenbody > div.screenpadding > table > tbody > tr > td > table.5.1"),
"Individual\n\nChromosomeDerivedTraitEnvironmentalFactorGeneIndividualMarkerMassPeakMeasurementMetabolitePanelProbeSampleSpot");
Assert.assertEquals(
selenium.getTable("css=#Datas_form > div.screenbody > div.screenpadding > table > tbody > tr > td > table.6.1"),
"Metabolite\n\nChromosomeDerivedTraitEnvironmentalFactorGeneIndividualMarkerMassPeakMeasurementMetabolitePanelProbeSampleSpot");
// change Individual to Gene and save
selenium.click("css=#Data_FeatureType_chzn > a.chzn-single > span");
selenium.click("id=Data_FeatureType_chzn_o_3");
selenium.click("id=save_Datas");
selenium.waitForPageToLoad(pageLoadTimeout);
Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1"));
// expand compact view again and check value has changed
selenium.click("id=Datas_collapse_button_id");
Assert.assertEquals(
selenium.getTable("css=#Datas_form > div.screenbody > div.screenpadding > table > tbody > tr > td > table.5.1"),
"Gene\n\nChromosomeDerivedTraitEnvironmentalFactorGeneIndividualMarkerMassPeakMeasurementMetabolitePanelProbeSampleSpot");
// change back to Individual and save
selenium.click("css=#Data_FeatureType_chzn > a.chzn-single > span");
selenium.click("id=Data_FeatureType_chzn_o_4");
clickAndWait("id=save_Datas");
Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1"));
// expand compact view again and check value is back to normal again
selenium.click("id=Datas_collapse_button_id");
Assert.assertEquals(
selenium.getTable("css=#Datas_form > div.screenbody > div.screenpadding > table > tbody > tr > td > table.5.1"),
"Individual\n\nChromosomeDerivedTraitEnvironmentalFactorGeneIndividualMarkerMassPeakMeasurementMetabolitePanelProbeSampleSpot");
}
@Test(dependsOnMethods =
{ "returnHome" })
public void qtlImporter() throws Exception
{
// not much to test here, cannot upload actual files
// could only be tested on an API level, or manually
// go to Import data and check the screen contents of the QTL importer
clickAndWait("id=ImportDataMenu_tab_button");
clickAndWait("id=QTLWizard_tab_button");
Assert.assertTrue(selenium.isTextPresent("Again, your individuals must be in the first line."));
- if(!excused) Assert.assertEquals(selenium.getText("name=invSelect"), "ClusterDemo");
- if(!excused) Assert.assertEquals(selenium.getText("name=cross"),"xgap_rqtl_straintype_f2xgap_rqtl_straintype_bcxgap_rqtl_straintype_riselfxgap_rqtl_straintype_risibxgap_rqtl_straintype_4wayxgap_rqtl_straintype_dhxgap_rqtl_straintype_specialxgap_rqtl_straintype_naturalxgap_rqtl_straintype_parentalxgap_rqtl_straintype_f1xgap_rqtl_straintype_rccxgap_rqtl_straintype_cssxgap_rqtl_straintype_unknownxgap_rqtl_straintype_other");
- if(!excused) Assert.assertEquals(selenium.getText("name=trait"),"MeasurementDerivedTraitEnvironmentalFactorGeneMarkerMassPeakMetaboliteProbe");
+ Assert.assertEquals(selenium.getText("name=invSelect"), "ClusterDemo");
+ Assert.assertEquals(selenium.getText("name=cross"),"xgap_rqtl_straintype_f2xgap_rqtl_straintype_bcxgap_rqtl_straintype_riselfxgap_rqtl_straintype_risibxgap_rqtl_straintype_4wayxgap_rqtl_straintype_dhxgap_rqtl_straintype_specialxgap_rqtl_straintype_naturalxgap_rqtl_straintype_parentalxgap_rqtl_straintype_f1xgap_rqtl_straintype_rccxgap_rqtl_straintype_cssxgap_rqtl_straintype_unknownxgap_rqtl_straintype_other");
+ Assert.assertEquals(selenium.getText("name=trait"),"MeasurementDerivedTraitEnvironmentalFactorGeneMarkerMassPeakMetaboliteProbe");
// try pressing a button and see if the error pops up
clickAndWait("id=upload_genotypes");
Assert.assertTrue(selenium.isTextPresent("No file selected"));
}
@Test(dependsOnMethods =
{ "returnHome" })
public void runMapping() throws Exception
{
// we're not going to test actual execution, just page around
// go to Run QTL mapping
clickAndWait("id=Cluster_tab_button");
Assert.assertTrue(selenium.isTextPresent("This is the main menu for starting a new analysis"));
// page from starting page to Step 2
clickAndWait("id=start_new_analysis");
Assert.assertEquals(selenium.getValue("name=outputDataName"), "MyOutput");
clickAndWait("id=toStep2");
Assert.assertTrue(selenium.isTextPresent("You have selected: Rqtl_analysis"));
Assert.assertEquals(selenium.getText("name=phenotypes"), "Fu_LCMS_data");
// go back to starting page
clickAndWait("id=toStep1");
clickAndWait("id=toStep0");
// go to job manager
clickAndWait("id=view_running_analysis");
Assert.assertTrue(selenium.isTextPresent("No running analysis to display."));
// go back to starting page
clickAndWait("id=back_to_start");
Assert.assertTrue(selenium.isTextPresent("No settings saved."));
}
@Test(dependsOnMethods =
{ "returnHome" })
public void configureAnalysis() throws Exception
{
// browse to Configure Analysis and check values
clickAndWait("id=AnalysisSettings_tab_button");
Assert.assertEquals(selenium.getTable("css=table.listtable.1.3"), "Rqtl_analysis");
Assert.assertEquals(selenium.getTable("css=table.listtable.1.4"),
"This is a basic QTL analysis performed in the R environment for statistical computing, powered by th...");
// browse to R scripts and add a script
clickAndWait("id=RScripts_tab_button");
selenium.click("id=RScripts_edit_new");
selenium.waitForPopUp("molgenis_edit_new", "30000");
selenium.selectWindow("name=molgenis_edit_new");
selenium.type("id=RScript_name", "test");
selenium.type("id=RScript_Extension", "r");
selenium.click("css=span");
//from: http://blog.browsermob.com/2011/03/selenium-tips-wait-with-waitforcondition/
//"Now for the killer part, for sites that use jQuery, if all you need is to confirm there aren't any active asynchronous requests, then the following does the trick:"
selenium.waitForCondition("selenium.browserbot.getUserWindow().$.active == 0", "10000");
selenium.click("css=span");
clickAndWait("id=Add");
// add content and save
selenium.selectWindow("title=xQTL workbench");
Assert.assertTrue(selenium.isTextPresent("ADD SUCCESS: affected 1"))
;
Assert.assertTrue(selenium.isTextPresent("No file found. Please upload it here."));
selenium.type("name=inputTextArea", "content");
clickAndWait("id=uploadTextArea");
Assert.assertFalse(selenium.isTextPresent("No file found. Please upload it here."));
// delete script and content
selenium.click("id=delete_RScripts");
Assert.assertEquals(selenium.getConfirmation(),
"You are about to delete a record. If you click [yes] you won't be able to undo this operation.");
selenium.waitForPageToLoad(pageLoadTimeout);
Assert.assertTrue(selenium.isTextPresent("REMOVE SUCCESS: affected 1"));
// browse to Tag data and click the hide/show buttons
clickAndWait("id=MatrixWizard_tab_button");
Assert.assertTrue(selenium
.isTextPresent("This screen provides an overview of all data matrices stored in your database."));
Assert.assertTrue(selenium.isTextPresent("ClusterDemo / genotypes"));
Assert.assertTrue(selenium.isTextPresent("Rqtl_data -> genotypes"));
clickAndWait("id=hide_verified");
Assert.assertTrue(selenium.isTextPresent("Nothing to display"));
clickAndWait("id=show_verified");
Assert.assertTrue(selenium.isTextPresent("Binary"));
}
@Test(dependsOnMethods =
{ "returnHome" })
public void search() throws Exception
{
// browse to Search
clickAndWait("id=SimpleDbSearch_tab_button");
selenium.type("name=searchThis", "ee");
clickAndWait("id=simple_search");
Assert.assertTrue(selenium.isTextPresent("Found 2 result(s)"));
Assert.assertTrue(selenium.isTextPresent("Type: BinaryDataMatrix"));
selenium.type("name=searchThis", "e");
clickAndWait("id=simple_search");
Assert.assertTrue(selenium.isTextPresent("Found 339 result(s)"));
Assert.assertTrue(selenium.isTextPresent("bioinformatician"));
}
@Test(dependsOnMethods =
{ "returnHome" })
public void molgenisFileMenu() throws Exception
{
// browse to chromosomes and click 'Update selected' in File
clickAndWait("id=Investigations_tab_button");
clickAndWait("id=BasicAnnotations_tab_button");
clickAndWait("Chromosomes_tab_button");
selenium.click("id=Chromosomes_menu_Edit");
selenium.click("id=Chromosomes_edit_update_selected_submenuitem");
// select the popup and verify the message
selenium.waitForPopUp("molgenis_edit_update_selected", "5000");
selenium.selectWindow("name=molgenis_edit_update_selected");
Assert.assertTrue(selenium.isTextPresent("No records were selected for updating."));
// cancel and select main window
selenium.click("id=Cancel");
selenium.selectWindow("title=xQTL workbench");
// TODO: select records, update 2+, verify values changed, change them
// back, verify values changed back
// TODO: Add in batch/upload CSV(as best as possible w/o uploading)
// TODO: Upload CSV file (as best as possible w/o uploading)
}
@Test(dependsOnMethods =
{ "returnHome" })
public void userRoleMenuVisibility() throws Exception
{
//find out if admin can see the correct tabs
Assert.assertTrue(selenium.isTextPresent("Home*Login*Browse data*Import data*Run QTL mapping*Configure analysis*Search*Settings"));
clickAndWait("id=Settings_tab_button");
Assert.assertTrue(selenium.isTextPresent("Users and permissions*Database status*File storage*Install R packages*Ontologies*Utilities"));
clickAndWait("id=OtherAdmin_tab_button");
Assert.assertTrue(selenium.isTextPresent("Job table"));
//logout and see if the correct tabs are visible
clickAndWait("id=UserLogin_tab_button");
clickAndWait("id=Logout");
Assert.assertTrue(selenium.isTextPresent("Home*Login"));
Assert.assertFalse(selenium.isTextPresent("Browse data*Import data*Run QTL mapping*Configure analysis*Search*Settings"));
//login as biologist and see if the correct tabs are visible
selenium.type("id=username", "bio-user");
selenium.type("id=password", "bio");
clickAndWait("id=Login");
Assert.assertTrue(selenium.isTextPresent("Home*Login*Browse data*Import data*Run QTL mapping*Search*Settings"));
Assert.assertFalse(selenium.isTextPresent("Configure analysis"));
clickAndWait("id=Settings_tab_button");
clickAndWait("id=OtherAdmin_tab_button");
Assert.assertTrue(selenium.isTextPresent("Advanced import*Format names*Rename duplicates"));
Assert.assertFalse(selenium.isTextPresent("Job table"));
Assert.assertFalse(selenium.isTextPresent("KEGG converter"));
//login as bioinformatician and see if the correct tabs are visible
clickAndWait("id=UserLogin_tab_button");
clickAndWait("id=Logout");
selenium.type("id=username", "bioinfo-user");
selenium.type("id=password", "bioinfo");
clickAndWait("id=Login");
Assert.assertTrue(selenium.isTextPresent("Home*Login*Browse data*Import data*Run QTL mapping*Configure analysis*Search*Settings"));
clickAndWait("id=Settings_tab_button");
clickAndWait("id=OtherAdmin_tab_button");
Assert.assertTrue(selenium.isTextPresent("Advanced import*Format names*Rename duplicates*KEGG converter"));
Assert.assertFalse(selenium.isTextPresent("Job table"));
//log back in as admin
clickAndWait("id=UserLogin_tab_button");
clickAndWait("id=Logout");
selenium.type("id=username", "admin");
selenium.type("id=password", "admin");
clickAndWait("id=Login");
}
@Test(dependsOnMethods =
{ "returnHome" })
public void namePolicy() throws Exception
{
//find out of the strict policy is in effect for entities
// browse to individuals
clickAndWait("id=Investigations_tab_button");
clickAndWait("id=BasicAnnotations_tab_button");
clickAndWait("Individuals_tab_button");
// click add new, wait for popup, and select it
selenium.click("id=Individuals_edit_new");
selenium.waitForPopUp("molgenis_edit_new", "30000");
selenium.selectWindow("name=molgenis_edit_new");
// fill in the form and click add
selenium.type("id=Individual_name", "#");
clickAndWait("id=Add");
// select main window and check if add failed
selenium.selectWindow("title=xQTL workbench");
Assert.assertTrue(selenium.isTextPresent("ADD FAILED: Illegal character (#) in name '#'. Use only a-z, A-Z, 0-9, and underscore."));
// click add new, wait for popup, and select it
selenium.click("id=Individuals_edit_new");
selenium.waitForPopUp("molgenis_edit_new", "30000");
selenium.selectWindow("name=molgenis_edit_new");
// fill in the form and click add
selenium.type("id=Individual_name", "1");
clickAndWait("id=Add");
// select main window and check if add failed
selenium.selectWindow("title=xQTL workbench");
Assert.assertTrue(selenium.isTextPresent("ADD FAILED: Name '1' is not allowed to start with a numeral (1)."));
//find out of the strict policy is in effect for data matrix (files)
clickAndWait("id=Datas_tab_button");
Assert.assertTrue(selenium.isTextPresent("metaboliteexpression"));
// click add new, wait for popup, and select it
selenium.click("id=Datas_edit_new");
selenium.waitForPopUp("molgenis_edit_new", "30000");
selenium.selectWindow("name=molgenis_edit_new");
// fill in the form and click add
selenium.type("id=Data_name", "#");
clickAndWait("id=Add");
// select main window and check if add failed
selenium.selectWindow("title=xQTL workbench");
Assert.assertTrue(selenium.isTextPresent("ADD FAILED: Illegal character (#) in name '#'. Use only a-z, A-Z, 0-9, and underscore."));
// click add new, wait for popup, and select it
selenium.click("id=Datas_edit_new");
selenium.waitForPopUp("molgenis_edit_new", "30000");
selenium.selectWindow("name=molgenis_edit_new");
// fill in the form and click add
// notice the name is allowed, but not OK for files!
selenium.type("id=Data_name", "metaboliteExpression");
clickAndWait("id=Add");
// select main window and check if add succeeded
selenium.selectWindow("title=xQTL workbench");
Assert.assertTrue(selenium.isTextPresent("ADD SUCCESS: affected 1"));
//add some content and try to save - this must fail
selenium.type("id=matrixInputTextArea", "qw er\nty 1 2");
clickAndWait("id=matrixUploadTextArea");
Assert.assertTrue(selenium.isTextPresent("File name 'metaboliteExpression' already exists in database when escaped to filesafe format. ('metaboliteexpression')"));
// delete the test data and check if it happened
selenium.click("id=delete_Datas");
Assert.assertEquals(selenium.getConfirmation(),
"You are about to delete a record. If you click [yes] you won't be able to undo this operation.");
selenium.waitForPageToLoad(pageLoadTimeout);
Assert.assertTrue(selenium.isTextPresent("REMOVE SUCCESS: affected 1"));
}
@Test(dependsOnMethods =
{ "returnHome" })
public void guiNestingXrefDefault() throws Exception
{
// find out if nested forms by XREF display this relation by default
// when adding new entities
// browse to individuals
clickAndWait("id=Investigations_tab_button");
clickAndWait("id=BasicAnnotations_tab_button");
clickAndWait("Individuals_tab_button");
// click add new, wait for popup, and select it
selenium.click("id=Individuals_edit_new");
selenium.waitForPopUp("molgenis_edit_new", "30000");
selenium.selectWindow("name=molgenis_edit_new");
//check if the proper xreffed investigation is selected
Assert.assertEquals(selenium.getText("css=span"), "ClusterDemo");
//cancel and return
selenium.click("id=cancel");
selenium.selectWindow("title=xQTL workbench");
//change and save
selenium.type("id=Investigation_name", "TestIfThisWorks");
clickAndWait("id=save_Investigations");
- if(!excused) Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1"));
+ Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1"));
// click add new, wait for popup, and select it
selenium.click("id=Individuals_edit_new");
selenium.waitForPopUp("molgenis_edit_new", "30000");
selenium.selectWindow("name=molgenis_edit_new");
//check if the proper xreffed investigation is selected
Assert.assertEquals(selenium.getText("css=span"), "TestIfThisWorks");
//cancel and return
selenium.click("id=cancel");
selenium.selectWindow("title=xQTL workbench");
//revert and save
selenium.type("id=Investigation_name", "ClusterDemo");
clickAndWait("id=save_Investigations");
- if(!excused) Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1"));
+ Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1"));
}
@Test(dependsOnMethods =
{ "returnHome" })
public void startAnalysis() throws Exception
{
// start a default analysis and check if jobs have
// been created, regardless of further outcome
// start QTL mapping
clickAndWait("id=Cluster_tab_button");
clickAndWait("id=start_new_analysis");
clickAndWait("id=toStep2");
clickAndWait("id=startAnalysis");
Assert.assertTrue(selenium.isTextPresent("Refresh page every"));
Assert.assertTrue(selenium.isTextPresent("Running analysis"));
Assert.assertTrue(selenium.isTextPresent("[view all local logs]"));
//check created job/subjobs
clickAndWait("id=Settings_tab_button");
clickAndWait("id=OtherAdmin_tab_button");
clickAndWait("id=Jobs_tab_button");
Assert.assertEquals(selenium.getText("css=span"), "Rqtl_analysis");
Assert.assertEquals(selenium.getText("css=#Job_ComputeResource_chzn > a.chzn-single > span"), "local");
Assert.assertTrue(selenium.isTextPresent("MyOutput*Subjobs*1 - 6 of 6"));
}
@Test(dependsOnMethods =
{ "returnHome" })
public void pageMatrix() throws Exception
{
// page around in the matrix and see if the correct
// values are displayed in the viewer
}
@Test(dependsOnMethods =
{ "returnHome" })
public void addMatrix() throws Exception
{
// add a new matrix record
// add data by typing in the text area and store
// - as binary
// - as database
// - as csv
// backend deletes inbetween
}
}
| false | false | null | null |
diff --git a/src/main/java/org/jboss/nio2/server/async/Nio2AsyncServer.java b/src/main/java/org/jboss/nio2/server/async/Nio2AsyncServer.java
index 1dda94b..8374edb 100644
--- a/src/main/java/org/jboss/nio2/server/async/Nio2AsyncServer.java
+++ b/src/main/java/org/jboss/nio2/server/async/Nio2AsyncServer.java
@@ -1,187 +1,188 @@
/**
* JBoss, Home of Professional Open Source. Copyright 2011, Red Hat, Inc., and
* individual contributors as indicated by the @author tags. See the
* copyright.txt file in the distribution for a full listing of individual
* contributors.
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.jboss.nio2.server.async;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@code NioAsyncServer}
*
* Created on Oct 27, 2011 at 5:47:30 PM
*
* @author <a href="mailto:[email protected]">Nabil Benothman</a>
*/
public class Nio2AsyncServer {
public static final int SERVER_PORT = 8081;
private static final Logger logger = Logger.getLogger(Nio2AsyncServer.class.getName());
+ private static final long TIMEOUT = 20;
+ private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
/**
* Create a new instance of {@code Nio2AsyncServer}
*/
public Nio2AsyncServer() {
super();
}
/**
*
* @return
*/
public static String generateId() {
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws Exception {
int port = SERVER_PORT;
if (args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
}
}
logger.log(Level.INFO, "Starting NIO2 Synchronous Sever on port {0} ...", port);
ExecutorService pool = Executors.newFixedThreadPool(400);
AsynchronousChannelGroup threadGroup = AsynchronousChannelGroup.withThreadPool(pool);
final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open(
threadGroup).bind(new InetSocketAddress(port));
boolean running = true;
logger.log(Level.INFO, "Asynchronous Sever started...");
while (running) {
logger.info("Waiting for new connections...");
Future<AsynchronousSocketChannel> future = listener.accept();
final AsynchronousSocketChannel channel = future.get();
final ByteBuffer buffer = ByteBuffer.allocate(512);
- channel.read(buffer, 1000, TimeUnit.MILLISECONDS, channel, new CompletionHandlerImpl(
- buffer));
+ channel.read(buffer, TIMEOUT, TIME_UNIT, channel, new CompletionHandlerImpl(buffer));
/*
* channel.read(buffer, null, new CompletionHandler<Integer, Void>()
* { boolean initialized = false; private String response; private
* String sessionId;
*
* @Override public void completed(Integer nBytes, Void attachment)
* { if (nBytes > 0) { byte bytes[] = new byte[nBytes];
* buffer.flip(); buffer.get(bytes);
*
* if (!initialized) { this.sessionId = generateId(); initialized =
* true; response = "JSESSION_ID: " + sessionId + "\n"; } else {
* response = "[" + this.sessionId + "] Pong from server\n"; }
* System.out.println("[" + this.sessionId + "] " + new
* String(bytes).trim()); buffer.clear();
* buffer.put(response.getBytes()); buffer.flip();
* channel.write(buffer); buffer.clear(); } // Read again with the
* this CompletionHandler channel.read(buffer, null, this); }
*
* @Override public void failed(Throwable exc, Void attachment) {
* try { System.out.println("Closing connection for session : [" +
* this.sessionId + "]"); channel.close(); } catch (IOException e) {
* e.printStackTrace(); } } });
*/
}
listener.close();
}
private static class CompletionHandlerImpl implements
CompletionHandler<Integer, AsynchronousSocketChannel> {
boolean initialized = false;
private String response;
private String sessionId;
final ByteBuffer buffer;
/**
* Create a new instance of {@code CompletionHandlerImpl}
*/
public CompletionHandlerImpl(ByteBuffer buffer) {
this.buffer = buffer;
}
/*
* (non-Javadoc)
*
* @see java.nio.channels.CompletionHandler#completed(java.lang.Object,
* java.lang.Object)
*/
@Override
public void completed(Integer nBytes, AsynchronousSocketChannel channel) {
if (nBytes > 0) {
byte bytes[] = new byte[nBytes];
buffer.flip();
buffer.get(bytes);
if (!initialized) {
this.sessionId = generateId();
initialized = true;
response = "JSESSION_ID: " + sessionId + "\n";
} else {
response = "[" + this.sessionId + "] Pong from server\n";
}
System.out.println("[" + this.sessionId + "] " + new String(bytes).trim());
buffer.clear();
buffer.put(response.getBytes());
buffer.flip();
channel.write(buffer);
buffer.clear();
}
// Read again with the this CompletionHandler
- channel.read(buffer, 1000, TimeUnit.MILLISECONDS, channel, this);
+ channel.read(buffer, TIMEOUT, TIME_UNIT, channel, this);
}
/*
* (non-Javadoc)
*
* @see java.nio.channels.CompletionHandler#failed(java.lang.Throwable,
* java.lang.Object)
*/
@Override
public void failed(Throwable exc, AsynchronousSocketChannel channel) {
exc.printStackTrace();
}
}
}
| false | false | null | null |
diff --git a/src/org/broad/igv/tdf/TDFReader.java b/src/org/broad/igv/tdf/TDFReader.java
index 1617a2343..3cd3ca68b 100644
--- a/src/org/broad/igv/tdf/TDFReader.java
+++ b/src/org/broad/igv/tdf/TDFReader.java
@@ -1,551 +1,551 @@
/*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.tdf;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.exceptions.DataLoadException;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.track.TrackType;
import org.broad.igv.track.WindowFunction;
import org.broad.igv.util.CompressionUtils;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.StringUtils;
import org.broad.igv.util.collections.LRUCache;
import org.broad.igv.util.stream.IGVSeekableStreamFactory;
import org.broad.tribble.util.SeekableStream;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
/**
* @author jrobinso
*/
public class TDFReader {
static final Logger log = Logger.getLogger(TDFReader.class);
public static final int GZIP_FLAG = 0x1;
private SeekableStream seekableStream = null;
private int version;
private Map<String, IndexEntry> datasetIndex;
private Map<String, IndexEntry> groupIndex;
private TrackType trackType;
private String trackLine;
private String[] trackNames;
private String genomeId;
LRUCache<String, TDFGroup> groupCache = new LRUCache(this, 20);
LRUCache<String, TDFDataset> datasetCache = new LRUCache(this, 20);
TDFTile wgTile;
Map<WindowFunction, Double> valueCache = new HashMap();
private List<WindowFunction> windowFunctions;
ResourceLocator locator;
boolean compressed = false;
Set<String> chrNames;
private final CompressionUtils compressionUtils;
//private String path;
public static TDFReader getReader(String path) {
return getReader(new ResourceLocator(path));
}
public static TDFReader getReader(ResourceLocator locator) {
return new TDFReader(locator);
}
public TDFReader(ResourceLocator locator) {
//this.path = path;
this.locator = locator;
try {
seekableStream = IGVSeekableStreamFactory.getStreamFor(locator.getPath());
readHeader();
} catch (IOException ex) {
log.error("Error loading file: " + locator.getPath(), ex);
throw new DataLoadException("Error loading file: " + ex.toString(), locator.getPath());
}
compressionUtils = new CompressionUtils();
}
public void close() {
try {
seekableStream.close();
} catch (IOException e) {
log.error("Error closing reader for: " + getPath(), e);
}
}
public String getPath() {
return locator.getPath();
}
private void readHeader() throws IOException {
// Buffer for the magic number, version, index position, and index
// byte count + header byte count (4 + 4 + 8 + 4 + 4)
//byte[] buffer = new byte[24];
//readFully(buffer);
byte[] buffer = readBytes(0, 24);
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
int magicNumber = byteBuffer.getInt();
byte[] magicBytes = new byte[4];
System.arraycopy(buffer, 0, magicBytes, 0, 4);
String magicString = new String(magicBytes);
if (!(magicString.startsWith("TDF") || !magicString.startsWith("IBF"))) {
String msg = "Error reading header: bad magic number.";
// throw new DataLoadException(msg, locator.getPath());
}
version = byteBuffer.getInt();
long idxPosition = byteBuffer.getLong();
int idxByteCount = byteBuffer.getInt();
int nHeaderBytes = byteBuffer.getInt();
byte[] bytes = readBytes(24, nHeaderBytes);
byteBuffer = ByteBuffer.wrap(bytes);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
if (version >= 2) {
int nWFs = byteBuffer.getInt();
this.windowFunctions = new ArrayList(nWFs);
for (int i = 0; i < nWFs; i++) {
String wfName = StringUtils.readString(byteBuffer);
try {
windowFunctions.add(WindowFunction.valueOf(wfName));
} catch (Exception e) {
log.error("Error creating window function: " + wfName, e);
}
}
} else {
windowFunctions = Arrays.asList(WindowFunction.mean);
}
// Track type
try {
trackType = TrackType.valueOf(StringUtils.readString(byteBuffer));
} catch (Exception e) {
trackType = TrackType.OTHER;
}
// Track line
trackLine = StringUtils.readString(byteBuffer).trim();
int nTracks = byteBuffer.getInt();
trackNames = new String[nTracks];
for (int i = 0; i < nTracks; i++) {
trackNames[i] = StringUtils.readString(byteBuffer);
}
// Flags
if (version > 2) {
genomeId = StringUtils.readString(byteBuffer);
int flags = byteBuffer.getInt();
compressed = (flags & GZIP_FLAG) != 0;
} else {
compressed = false;
}
readMasterIndex(idxPosition, idxByteCount);
}
private void readMasterIndex(long idxPosition, int nBytes) throws IOException {
try {
//fis.seek(idxPosition);
//byte[] bytes = new byte[nBytes];
//readFully(bytes);
byte[] bytes = readBytes(idxPosition, nBytes);
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
int nDatasets = byteBuffer.getInt();
datasetIndex = new LinkedHashMap(nDatasets);
for (int i = 0; i < nDatasets; i++) {
String name = StringUtils.readString(byteBuffer);
long fPosition = byteBuffer.getLong();
int n = byteBuffer.getInt();
datasetIndex.put(name, new IndexEntry(fPosition, n));
}
int nGroups = byteBuffer.getInt();
groupIndex = new LinkedHashMap(nGroups);
for (int i = 0; i < nGroups; i++) {
String name = StringUtils.readString(byteBuffer);
long fPosition = byteBuffer.getLong();
int n = byteBuffer.getInt();
groupIndex.put(name, new IndexEntry(fPosition, n));
}
} catch (BufferUnderflowException e) {
// We intermittently see this exception in this method. Log as much info as possible
log.error("BufferUnderflowException. path=" + getPath() + " idxPosition=" + idxPosition + " nBytes=" + nBytes);
throw e;
}
}
public TDFDataset getDataset(String chr, int zoom, WindowFunction windowFunction) {
// Version 1 only had mean
String wf = getVersion() < 2 ? "" : "/" + windowFunction.toString();
-
- String dsName = "/" + chr + "/z" + zoom + wf;
+ String zoomString = chr.equals(Globals.CHR_ALL) ? "0" : String.valueOf(zoom);
+ String dsName = "/" + chr + "/z" + zoomString + wf;
TDFDataset ds = getDataset(dsName);
return ds;
}
public synchronized TDFDataset getDataset(String name) {
if (datasetCache.containsKey(name)) {
return datasetCache.get(name);
}
try {
if (datasetIndex.containsKey(name)) {
IndexEntry ie = datasetIndex.get(name);
long position = ie.position;
int nBytes = ie.nBytes;
//fis.seek(position);
//byte[] buffer = new byte[nBytes];
//readFully(buffer);
byte[] buffer = readBytes(position, nBytes);
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
TDFDataset ds = new TDFDataset(name, byteBuffer, this);
datasetCache.put(name, ds);
return ds;
} else {
datasetCache.put(name, null);
return null;
}
} catch (IOException ex) {
log.error("Error reading dataset: " + getPath() + " (" + name + ")", ex);
throw new RuntimeException("System error occured while reading dataset: " + name);
}
}
public Collection<String> getDatasetNames() {
return datasetIndex.keySet();
}
public Collection<String> getGroupNames() {
return groupIndex.keySet();
}
public synchronized TDFGroup getGroup(String name) {
if (groupCache.containsKey(name)) {
return groupCache.get(name);
}
try {
IndexEntry ie = groupIndex.get(name);
long position = ie.position;
int nBytes = ie.nBytes;
//fis.seek(position);
//byte[] buffer = new byte[nBytes];
//readFully(buffer);
byte[] buffer = readBytes(position, nBytes);
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
TDFGroup group = new TDFGroup(name, byteBuffer);
groupCache.put(name, group);
return group;
} catch (IOException ex) {
log.error("Error reading group: " + name, ex);
throw new RuntimeException("System error occured while reading group: " + name);
}
}
// TODO -- move to dataset class
public TDFTile readTile(TDFDataset ds, int tileNumber) {
try {
if (tileNumber >= ds.tilePositions.length) {
// TODO - return empty tile
return null;
}
long position = ds.tilePositions[tileNumber];
if (position < 0) {
// Indicates empty tile
// TODO -- return an empty tile?
return null;
}
int nBytes = ds.tileSizes[tileNumber];
//fis.seek(position);
//byte[] buffer = new byte[nBytes];
//readFully(buffer);
byte[] buffer = readBytes(position, nBytes);
if (compressed) {
buffer = compressionUtils.decompress(buffer);
}
return TileFactory.createTile(buffer, trackNames.length);
} catch (IOException ex) {
String tileName = ds.getName() + "[" + tileNumber + "]";
log.error("Error reading data tile: " + tileName, ex);
throw new RuntimeException("System error occured while reading tile: " + tileName);
}
}
/**
* @return the version
*/
public int getVersion() {
return version;
}
/**
* @return the trackType
*/
public TrackType getTrackType() {
return trackType;
}
/**
* @return the trackLine
*/
public String getTrackLine() {
return trackLine;
}
/**
* @return the trackNames
*/
public String[] getTrackNames() {
return trackNames;
}
/**
* Only available for version >= 3.
*
* @return
*/
public String getGenomeId() {
return genomeId;
}
private Double getValue(WindowFunction wf) {
if (!valueCache.containsKey(wf)) {
TDFGroup rootGroup = getGroup("/");
String maxString = rootGroup.getAttribute(wf.getValue());
try {
valueCache.put(wf, Double.parseDouble(maxString));
} catch (Exception e) {
log.info("Warning: value '" + wf.toString() + "' not found in tdf value " + getPath());
valueCache.put(wf, null);
}
}
return valueCache.get(wf);
}
/**
* Return the default upper value for the data range. A check is made to see if both upper and lower limits
* are equal to zero, within a tolerance. If they are the upper limit is arbitrarily set to "100". This is
* protection against the pathological case that can occur with datasets consisting of largely zero values.
*
* @return
*/
public double getUpperLimit() {
Double val = getValue(WindowFunction.percentile98);
double upperLimit = val == null ? getDataMax() : val;
if (upperLimit < 1.0e-30 && getLowerLimit() < 1.0e-30) {
upperLimit = 100;
}
return upperLimit;
}
public double getLowerLimit() {
Double val = getValue(WindowFunction.percentile2);
return val == null ? getDataMin() : val;
}
public double getDataMax() {
Double val = getValue(WindowFunction.max);
return val == null ? 100 : val;
}
public double getDataMin() {
Double val = getValue(WindowFunction.min);
return val == null ? 0 : val;
}
public synchronized byte[] readBytes(long position, int nBytes) throws IOException {
seekableStream.seek(position);
byte[] buffer = new byte[nBytes];
seekableStream.read(buffer, 0, nBytes);
return buffer;
}
/**
* @return the windowFunctions
*/
public List<WindowFunction> getWindowFunctions() {
return windowFunctions;
}
/**
* Return a list of all chromosome names represented in this dataset
* TODO -- record this explicitly in the TDF file
*
* @return
*/
public Set<String> getChromosomeNames() {
if (chrNames == null) {
///DatasetIndex /chr1/z0/mean=org.broad.igv.tdf.TDFReader$IndexEntry@6a493b65
chrNames = new HashSet();
for (String key : datasetIndex.keySet()) {
String[] tokens = Globals.forwardSlashPattern.split(key);
int nTokens = tokens.length;
if (nTokens > 1) {
chrNames.add(tokens[1]);
}
}
}
return chrNames;
}
class IndexEntry {
long position;
int nBytes;
public IndexEntry(long position, int nBytes) {
this.position = position;
this.nBytes = nBytes;
}
}
/**
* Print index entries (for debugging)
*/
public void dumpIndex() {
for (Map.Entry<String, IndexEntry> entry : datasetIndex.entrySet()) {
String dsName = entry.getKey();
TDFDataset ds = getDataset(dsName);
int size = 0;
for (int sz : ds.tileSizes) {
size += sz;
}
System.out.println(dsName + "\t" + size);
datasetCache.clear();
}
}
public TDFTile getWholeGenomeTile(Genome genome, WindowFunction wf) {
if (wgTile == null) {
int binCount = 700;
int nTracks = this.getTrackNames().length; // TODO -- is there a more direct way to know this?
double binSize = (genome.getNominalLength() / 1000) / binCount;
Accumulator[][] accumulators = new Accumulator[nTracks][binCount];
for (String chrName : genome.getLongChromosomeNames()) {
TDFDataset chrDataset = getDataset(chrName, 0, wf);
if(chrDataset == null) continue;
List<TDFTile> chrTiles = chrDataset.getTiles();
chrDataset.clearCache(); // Don't cache these
for (TDFTile t : chrTiles) {
int[] chrStart = t.getStart();
int[] chrEnd = t.getEnd();
for (int p = 0; p < chrStart.length; p++) {
int gStart = genome.getGenomeCoordinate(chrName, chrStart[p]);
int gEnd = genome.getGenomeCoordinate(chrName, chrEnd[p]);
int binStart = (int) (gStart / binSize);
int binEnd = Math.min(binCount - 1, (int) (gEnd / binSize));
for (int b = binStart; b <= binEnd; b++) {
for (int n = 0; n < nTracks; n++) {
Accumulator acc = accumulators[n][b];
if (acc == null) {
acc = new Accumulator(WindowFunction.mean);
accumulators[n][b] = acc;
}
int basesCovered = Math.min(gEnd, binEnd) - Math.max(gStart, binStart);
acc.add(basesCovered, t.getData(n)[p], null);
}
}
}
}
}
// Fill data array for "wg tile"
float[][] data = new float[nTracks][binCount];
for (int n = 0; n < nTracks; n++) {
Accumulator[] accArray = accumulators[n];
for (int p = 0; p < accArray.length; p++) {
Accumulator acc = accArray[p];
if (acc != null) {
acc.finish();
data[n][p] = acc.getValue();
}
}
}
// public TDFFixedTile(int tileStart, int start, double span, float[][] data) {
wgTile = new TDFFixedTile(0, 0, binSize, data);
}
return wgTile;
}
}
\ No newline at end of file
diff --git a/src/org/broad/igv/track/DataSourceTrack.java b/src/org/broad/igv/track/DataSourceTrack.java
index 25f8c23e5..bfd9d664b 100644
--- a/src/org/broad/igv/track/DataSourceTrack.java
+++ b/src/org/broad/igv/track/DataSourceTrack.java
@@ -1,115 +1,115 @@
/*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
package org.broad.igv.track;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.data.CoverageDataSource;
import org.broad.igv.data.DataSource;
import org.broad.igv.feature.LocusScore;
import org.broad.igv.renderer.DataRange;
import org.broad.igv.session.IGVSessionReader;
import org.broad.igv.session.SubtlyImportant;
import org.broad.igv.util.ResourceLocator;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author jrobinso
*/
@XmlType(factoryMethod = "getNextTrack")
public class DataSourceTrack extends DataTrack {
private static Logger log = Logger.getLogger(DataSourceTrack.class);
private DataSource dataSource;
public DataSourceTrack(ResourceLocator locator, String id, String name, DataSource dataSource) {
super(locator, id, name);
this.dataSource = dataSource;
setTrackType(dataSource.getTrackType());
- List<LocusScore> scores = this.dataSource.getSummaryScoresForRange(Globals.CHR_ALL, -1, -1, -1);
+ List<LocusScore> scores = this.dataSource.getSummaryScoresForRange(Globals.CHR_ALL, -1, -1, 0);
float min = (float) dataSource.getDataMin();
float max = (float) dataSource.getDataMax();
float baseline = 0;
// If the range is all + numbers set the min to zero
if (min > 0) {
min = 0;
}
for (LocusScore score : scores) {
max = Math.max(max, score.getScore());
}
setDataRange(new DataRange(min, baseline, max));
}
public List<LocusScore> getSummaryScores(String chr, int startLocation, int endLocation, int zoom) {
List<LocusScore> tmp = dataSource.getSummaryScoresForRange(chr, startLocation, endLocation, zoom);
return tmp == null ? new ArrayList() : tmp;
}
@Override
public void setWindowFunction(WindowFunction statType) {
clearCaches();
dataSource.setWindowFunction(statType);
}
public boolean isLogNormalized() {
return dataSource.isLogNormalized();
}
public WindowFunction getWindowFunction() {
return dataSource.getWindowFunction();
}
@Override
public Collection<WindowFunction> getAvailableWindowFunctions() {
return dataSource.getAvailableWindowFunctions();
}
@SubtlyImportant
@XmlAttribute
private void setNormalize(boolean normalize){
if (dataSource != null && dataSource instanceof CoverageDataSource) {
((CoverageDataSource) dataSource).setNormalize(normalize);
}
}
@SubtlyImportant
private boolean getNormalize(){
if (dataSource != null && dataSource instanceof CoverageDataSource) {
return ((CoverageDataSource) dataSource).getNormalize();
}
return false;
}
@SubtlyImportant
private static DataSourceTrack getNextTrack(){
return (DataSourceTrack) IGVSessionReader.getNextTrack();
}
}
| false | false | null | null |
diff --git a/swc-parser-lazy/src/test/java/org/sweble/wikitext/lazy/EncodingValidatorTest.java b/swc-parser-lazy/src/test/java/org/sweble/wikitext/lazy/EncodingValidatorTest.java
index 5af9854..408163e 100644
--- a/swc-parser-lazy/src/test/java/org/sweble/wikitext/lazy/EncodingValidatorTest.java
+++ b/swc-parser-lazy/src/test/java/org/sweble/wikitext/lazy/EncodingValidatorTest.java
@@ -1,104 +1,104 @@
/**
* Copyright 2011 The Open Source Research Group,
- * University of Erlangen-Nürnberg
+ * University of Erlangen-Nuernberg
*
* 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.sweble.wikitext.lazy;
import static junit.framework.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test;
import org.sweble.wikitext.lazy.encval.IllegalCodePoint;
import org.sweble.wikitext.lazy.encval.IllegalCodePointType;
import de.fau.cs.osr.ptk.common.EntityMap;
import de.fau.cs.osr.ptk.common.ast.Location;
public class EncodingValidatorTest
{
@Test
public void testEncodingValidator() throws IOException
{
String title = "dummy";
StringBuilder source = new StringBuilder();
source.append("Ein einfacher Test-String\n"); // L 0
source.append("mit ein paar \uE800 und \r\n"); // L 1:13
- source.append("natürlich ein paar \uFDEE.\n"); // L 2:19
+ source.append("natuerlich ein paar \uFDEE.\n"); // L 2:19
source.append("Aber auch \uDBEF und \uDC80 \r"); // L 3:10, 3:16
- source.append("dürfen nicht fehlen. Zu guter \n");// L4
+ source.append("duerfen nicht fehlen. Zu guter \n");// L4
source.append("Letzt noch ein Wohlklang \u0007."); // L 5:25
/* Ruins the test string!
InputStreamReader in = new InputStreamReader(
IOUtils.toInputStream(source.toString(), "UTF-8"));
*/
/*
StringReader in = new StringReader(source.toString());
while (true)
{
int c = in.read();
if (c == -1)
break;
System.out.format("%c: U+%04x\n", c, (int) c);
}
in.close();
*/
EntityMap entityMap = new EntityMap();
LazyEncodingValidator v = new LazyEncodingValidator();
String result = v.validate(source.toString(), title, entityMap);
IllegalCodePoint x0 = (IllegalCodePoint) entityMap.getEntity(0);
assertEquals("\uE800", x0.getCodePoint());
assertEquals(IllegalCodePointType.PRIVATE_USE_CHARACTER, x0.getType());
assertEquals(new Location(title, 1, 13), x0.getNativeLocation());
IllegalCodePoint x1 = (IllegalCodePoint) entityMap.getEntity(1);
assertEquals("\uFDEE", x1.getCodePoint());
assertEquals(IllegalCodePointType.NON_CHARACTER, x1.getType());
assertEquals(new Location(title, 2, 19), x1.getNativeLocation());
IllegalCodePoint x2 = (IllegalCodePoint) entityMap.getEntity(2);
assertEquals("\uDBEF", x2.getCodePoint());
assertEquals(IllegalCodePointType.ISOLATED_SURROGATE, x2.getType());
assertEquals(new Location(title, 3, 10), x2.getNativeLocation());
IllegalCodePoint x3 = (IllegalCodePoint) entityMap.getEntity(3);
assertEquals("\uDC80", x3.getCodePoint());
assertEquals(IllegalCodePointType.ISOLATED_SURROGATE, x3.getType());
assertEquals(new Location(title, 3, 16), x3.getNativeLocation());
IllegalCodePoint x4 = (IllegalCodePoint) entityMap.getEntity(4);
assertEquals("\u0007", x4.getCodePoint());
assertEquals(IllegalCodePointType.CONTROL_CHARACTER, x4.getType());
assertEquals(new Location(title, 5, 25), x4.getNativeLocation());
StringBuilder ref = new StringBuilder();
ref.append("Ein einfacher Test-String\n");
ref.append("mit ein paar \uE0000\uE001 und \r\n");
- ref.append("natürlich ein paar \uE0001\uE001.\n");
+ ref.append("natuerlich ein paar \uE0001\uE001.\n");
ref.append("Aber auch \uE0002\uE001 und \uE0003\uE001 \r");
- ref.append("dürfen nicht fehlen. Zu guter \n");
+ ref.append("duerfen nicht fehlen. Zu guter \n");
ref.append("Letzt noch ein Wohlklang \uE0004\uE001.");
assertEquals(ref.toString(), result);
}
}
| false | false | null | null |
diff --git a/src/main/java/com/minesnap/dcpu/assembler/Assembler.java b/src/main/java/com/minesnap/dcpu/assembler/Assembler.java
index baa98c3..b526cd7 100644
--- a/src/main/java/com/minesnap/dcpu/assembler/Assembler.java
+++ b/src/main/java/com/minesnap/dcpu/assembler/Assembler.java
@@ -1,517 +1,530 @@
package com.minesnap.dcpu.assembler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.ListIterator;
public class Assembler {
private boolean littleEndian = true;
private boolean optimize = true;
private boolean positionIndependent = false;
private Map<String, Integer> newNBOpcodes = null;
private ResolverList resolvables = null;
private boolean assembled = false;
public Assembler() {
}
public void setLittleEndian(boolean littleEndian) {
this.littleEndian = littleEndian;
}
public void setOptimizations(boolean optimize) {
this.optimize = optimize;
}
public void setPositionIndependent(boolean positionIndependent) {
this.positionIndependent = positionIndependent;
}
public void setNewNBOpcodes(Map<String, Integer> newNBOpcodes) {
for(Integer value : newNBOpcodes.values()) {
if(value < 0x02 || value > 0x3f) {
throw new IllegalArgumentException("Custom non-basic opcodes must be between 0x02 and 0x3f");
}
}
this.newNBOpcodes = newNBOpcodes;
}
public void assemble(String filename)
throws FileNotFoundException, CompileError, IOException {
File sourceDir;
Reader in;
if(filename.equals("-")) {
sourceDir = new File(".");
in = new InputStreamReader(System.in, "UTF-8");
} else {
File sourcefile = new File(filename);
sourceDir = sourcefile.getParentFile();
in = new InputStreamReader(new FileInputStream(sourcefile), "UTF-8");
}
List<Token> tokens;
try {
tokens = ASMTokenizer.tokenize(in, sourceDir, filename);
} finally {
in.close();
}
assembled = false;
resolvables = new ResolverList();
ListIterator<Token> tokensI = tokens.listIterator();
boolean newlineRequired = false;
while(tokensI.hasNext()) {
Token opToken = tokensI.next();
if(opToken.getText().equals("\n")) {
newlineRequired = false;
continue;
}
// Handle labels
String opterm = opToken.getText();
if(opToken instanceof LabelToken) {
try {
resolvables.addLabel(((LabelToken)opToken).getName());
} catch (LabelAlreadyExistsError e) {
throw new TokenCompileError("Duplicate label found", opToken);
}
continue;
}
// A newline is required after an instruction before
// another instruction can be read.
if(newlineRequired) {
throw new TokenCompileError("Expected newline", opToken);
}
newlineRequired = true;
Opcode opcode = Opcode.getByName(opterm, newNBOpcodes);
if(opcode == null) {
// Turns out that token wasn't a real opcode
throw new TokenCompileError("Unknown opcode", opToken);
}
int datRepeat = 1;
switch(opcode.getType()) {
case RESERVE:
{
Token countToken = tokensI.next();
int count;
if(countToken instanceof IntToken) {
count = ((IntToken)countToken).getValue();
} else {
throw new TokenCompileError("Expected integer", countToken);
}
List<UnresolvedData> dataList = new ArrayList<UnresolvedData>(1);
dataList.add(new UnresolvedData(null, 0));
resolvables.add(new UnresolvedMultiData(dataList, count));
break;
}
case TIMES:
{
Token countToken = tokensI.next();
if(countToken instanceof IntToken) {
datRepeat = ((IntToken)countToken).getValue();
} else {
throw new TokenCompileError("Expected integer", countToken);
}
opToken = tokensI.next();
opterm = opToken.getText();
opcode = Opcode.getByName(opterm, newNBOpcodes);
if(opcode == null) {
throw new TokenCompileError("Unknown opcode", opToken);
}
if(opcode.getType() != OpcodeType.DAT) {
throw new TokenCompileError("Expected DAT opcode after TIMES/DUP opcode", opToken);
}
// Fall through to DAT
}
case DAT:
{
boolean isFirst = true;
List<UnresolvedData> dataList = new ArrayList<UnresolvedData>();
while(tokensI.hasNext()) {
if(!isFirst) {
Token comma = tokensI.next();
if(comma.getText().equals("\n")) {
// Put the newline back so that way it's
// detected later properly.
tokensI.previous();
break;
} else if(!comma.getText().equals(",")) {
throw new TokenCompileError("Expected comma", comma);
}
} else {
isFirst = false;
}
Token dataToken = tokensI.next();
if(dataToken instanceof StringToken) {
StringToken sdataToken = (StringToken)dataToken;
byte[] bytes = sdataToken.getValue().getBytes(Charset.forName("UTF-16LE"));
assert(bytes.length%2 == 0);
for(int k=0; k<bytes.length; k+=2) {
dataList.add(new UnresolvedData(dataToken, bytes[k] | (bytes[k+1]<<8)));
}
} else {
tokensI.previous();
dataList.add(parseLiteralExpression(tokensI));
}
}
resolvables.add(new UnresolvedMultiData(dataList, datRepeat));
break;
}
case BRK:
{
// Replace BRK with SUB PC, 1
Instruction instr = new Instruction(Opcode.get(OpcodeType.SUB));
instr.setValueA(new Value(ValueType.PC));
instr.setValueB(new Value(ValueType.LITERAL, new UnresolvedData(null, 1)));
resolvables.add(instr);
break;
}
case JMP:
case BRA:
{
UnresolvedData data = parseLiteralExpression(tokensI);
if(positionIndependent || opcode.getType() == OpcodeType.BRA) {
BRAInstruction bra = new BRAInstruction(data);
resolvables.add(bra);
} else {
JMPInstruction jmp = new JMPInstruction(data);
resolvables.add(jmp);
}
break;
}
case INCBIN:
{
Token incfilenameToken = tokensI.next();
if(!(incfilenameToken instanceof StringToken)) {
throw new TokenCompileError("Expected string for filename", incfilenameToken);
}
String incfilename = ((StringToken)incfilenameToken).getValue();
File incfile = new File(incfilenameToken.getSourceDir(), incfilename);
Token typeToken = tokensI.next();
String typeS = typeToken.getText();
boolean incLittleEndian;
if(typeS.equals("\n")) {
// Put the newline back so that way it's detected
// later properly.
tokensI.previous();
// Default to whatever this file is using
typeS = "THIS";
}
if(typeS.equals("THIS")) {
incLittleEndian = littleEndian;
} else if(typeS.equals("BE")) {
incLittleEndian = false;
} else if(typeS.equals("LE")) {
incLittleEndian = true;
} else {
throw new TokenCompileError("Unknown endian type", typeToken);
}
try {
resolvables.add(new BinInclude(incfile, incLittleEndian));
} catch(IllegalIncludeException e) {
throw new TokenCompileError(e.getMessage(), incfilenameToken);
}
break;
}
case INCLUDE:
{
Token incfilenameToken = tokensI.next();
if(!(incfilenameToken instanceof StringToken)) {
throw new TokenCompileError("Expected string for filename", incfilenameToken);
}
String incfilename = ((StringToken)incfilenameToken).getValue();
File incfile = new File(incfilenameToken.getSourceDir(), incfilename);
Reader incIn = new InputStreamReader(new FileInputStream(incfile), "UTF-8");
List<Token> incTokens;
try {
incTokens = ASMTokenizer.tokenize(incIn, incfile.getParentFile(), incfile.getName());
} finally {
incIn.close();
}
// Add the included tokens after what should be the
// newline following this directive.
tokens.addAll(tokensI.nextIndex()+1, incTokens);
// Reset the tokensI iterator or else it will complain
// about a concurrent modification.
tokensI = tokens.listIterator(tokensI.nextIndex());
break;
}
default:
{
Instruction instr = new Instruction(opcode);
instr.setValueA(parseValueTokens(tokensI));
// If this opcode has 2 arguments
if(opcode.isBasic()) {
Token comma = tokensI.next();
if(!comma.getText().equals(","))
throw new TokenCompileError("Expected comma", comma);
instr.setValueB(parseValueTokens(tokensI));
}
if(optimize) {
if(instr.getOpcode().getType() == OpcodeType.SET
&& instr.getValueA().getType() == ValueType.PC
&& instr.getValueB().getType() == ValueType.LITERAL) {
UnresolvedData data = instr.getValueB().getData();
JMPInstruction jmp = new JMPInstruction(data);
resolvables.add(jmp);
instr = null;
}
}
// This will be null if we replaced this with an
// optimized instruction and that means we've already
// added the optimized version.
if(instr != null) {
resolvables.add(instr);
}
}
}
}
resolvables.prepare();
assembled = true;
}
public void writeTo(String outname)
throws IOException {
if(!assembled) {
throw new IllegalStateException("assemble method must be called before writeTo");
}
WordWriter out;
if(outname.equals("-")) {
out = new WordWriter(System.out, littleEndian);
} else {
out = new WordWriter(new FileOutputStream(outname, false), littleEndian);
}
try {
resolvables.writeTo(out);
} finally {
out.close();
}
}
private static UnresolvedData parseLiteralExpression(ListIterator<Token> tokensI)
throws TokenCompileError {
Token firstToken = tokensI.next();
tokensI.previous();
int offset = 0;
String labelRef = null;
boolean nextIsNegative = false;
while(true) {
Token expToken = tokensI.next();
String expTokenS = expToken.getText();
if(expToken instanceof SymbolToken) {
if(expTokenS.equals("-")) {
if(nextIsNegative) {
throw new TokenCompileError("Multiple '-' symbols may not be chained here", expToken);
} else {
nextIsNegative = true;
}
continue;
} else {
throw new TokenCompileError("Was not expecting symbol", expToken);
}
} else if(expToken instanceof IntToken) {
int value = ((IntToken)expToken).getValue();
if(nextIsNegative) {
value = -value;
nextIsNegative = false;
}
offset += value;
} else {
if(nextIsNegative) {
throw new TokenCompileError("You can not subtract the value of a label", expToken);
}
try {
ValueType register = ValueType.valueOf(expTokenS);
throw new TokenCompileError("Can not add register in literal", expToken);
} catch (IllegalArgumentException e) {
// This token is a label and not a register.
if(!ASMTokenizer.is_legal_label(expTokenS))
throw new TokenCompileError("Is not a legal label name", expToken);
if(labelRef != null)
throw new TokenCompileError("Can not have multiple labels in expression", expToken);
labelRef = expTokenS;
}
}
// Now we have either a '+', ',' or '\n' coming up.
Token sepToken = tokensI.next();
String sepTokenS = sepToken.getText();
if(sepTokenS.equals(",") || sepTokenS.equals("\n")) {
// Put that token back for the caller to process.
tokensI.previous();
break;
} else if(sepTokenS.equals("+")) {
nextIsNegative = false;
continue;
} else if(sepTokenS.equals("-")) {
nextIsNegative = true;
continue;
} else {
throw new TokenCompileError("Expected a '+', '-', ',' or '\\n'", sepToken);
}
}
if(labelRef == null) {
checkIntWordRange(firstToken, offset);
return new UnresolvedData(firstToken, offset & 0xffff);
} else {
return new UnresolvedOffset(firstToken, labelRef, offset);
}
}
// Returns the value that must be passed to Instruction.setValueA or B
private static Value parseValueTokens(ListIterator<Token> tokensI)
throws TokenCompileError {
Token first = tokensI.next();
if(!first.getText().equals("[")) {
// We're about to process some expression that is the name
// of a register, or is an arbitrary amount of numbers
// added together optionally added to a label.
String firstS = first.getText();
try {
ValueType register = ValueType.valueOf(firstS);
return new Value(register);
} catch (IllegalArgumentException e) {
// If it wasn't a register, then it's some literal
// expression.
tokensI.previous();
UnresolvedData data = parseLiteralExpression(tokensI);
return new Value(ValueType.LITERAL, data);
}
} else {
// We're about to process some dereference expression like
// [--SP], [SP++], [B], [B+3], [somelabel+B],
// [somelabel+1], [somelabel+B+1], etc. Note that we don't
// use parseLiteralExpression because this expression can
// have a single register in it.
int offset = 0;
ValueType register = null;
String labelRef = null;
boolean nextIsNegative = false;
while(true) {
Token expToken = tokensI.next();
String expTokenS = expToken.getText();
if(expTokenS.equals("\n")) {
throw new TokenCompileError("Was not expecting newline", expToken);
} else if(expToken instanceof IntToken) {
int value = ((IntToken)expToken).getValue();
if(nextIsNegative) {
value = -value;
nextIsNegative = false;
}
offset += value;
} else if(expTokenS.equals("+")) {
- // if(register == ValueType.SP) {
- // register = ValueType.POP;
- // } else {
+ if(register == ValueType.SP) {
+ register = ValueType.POP;
+ } else {
throw new TokenCompileError("Invalid dereference expression", expToken);
- // }
+ }
} else if(expTokenS.equals("-")) {
if(nextIsNegative) {
- throw new TokenCompileError("Multiple '-' symbols may not be chained here", expToken);
+ // We have two '-' symbols in a row. This is only legal if it precedes "SP".
+ if(register != null)
+ throw new TokenCompileError("Invalid dereference expression", expToken);
+
+ expToken = tokensI.next();
+ expTokenS = expToken.getText();
+ try {
+ register = ValueType.valueOf(expTokenS);
+ } catch (IllegalArgumentException e) {
+ throw new TokenCompileError("Multiple '-' symbols may not be chained here", expToken);
+ }
+ if(register != ValueType.SP)
+ throw new TokenCompileError("Can not decrement non-SP register", expToken);
+ register = ValueType.PUSH;
} else {
nextIsNegative = true;
continue;
}
} else {
// This token is either a label or register
// name. Note that we can only have up to one
// label per deref expression, and we can only
// have up to one register per deref expression.
if(nextIsNegative) {
throw new TokenCompileError("You can not subtract the value of a label or register", expToken);
}
try {
ValueType temp = ValueType.valueOf(expTokenS);
if(register != null)
throw new TokenCompileError("Can not have multiple registers in dereference expression", expToken);
register = temp;
} catch (IllegalArgumentException e) {
// This token is a label and not a register.
if(!ASMTokenizer.is_legal_label(expTokenS))
throw new TokenCompileError("Is not a legal label name", expToken);
if(labelRef != null)
throw new TokenCompileError("Can not have multiple labels in dereference expression", expToken);
labelRef = expTokenS;
}
}
// Now we have either a + or ] coming up.
Token sepToken = tokensI.next();
String sepTokenS = sepToken.getText();
if(sepTokenS.equals("]")) {
break;
} else if(sepTokenS.equals("+")) {
nextIsNegative = false;
continue;
} else if(sepTokenS.equals("-")) {
nextIsNegative = true;
continue;
} else {
throw new TokenCompileError("Expected a ']', '+', or '-'", sepToken);
}
}
if(register == null) {
if(labelRef == null) {
checkIntWordRange(first, offset);
return new Value(ValueType.DN, new UnresolvedData(first, offset & 0xffff));
} else {
return new Value(ValueType.DN, new UnresolvedOffset(first, labelRef, offset));
}
} else {
if(register == ValueType.POP || register == ValueType.PUSH) {
if(labelRef == null && offset == 0) {
return new Value(register);
} else {
throw new TokenCompileError("Invalid dereference expression", first);
}
}
if(labelRef == null && offset == 0) {
register = register.dereference();
return new Value(register);
} else {
register = register.dereferenceNextPlus();
if(labelRef == null) {
assert(offset != 0);
checkIntWordRange(first, offset);
return new Value(register, new UnresolvedData(first, offset & 0xffff));
} else {
return new Value(register, new UnresolvedOffset(first, labelRef, offset));
}
}
}
}
}
private static void checkIntWordRange(Token token, int value)
throws TokenCompileError {
if((value >= 0 && (value & 0xffff0000) != 0)
|| (value < 0 && (value & 0xffff8000) != 0xffff8000)) {
throw new TokenCompileError("Value can not fit in 16 bits", token);
}
}
}
| false | false | null | null |
diff --git a/src/com/android/camera/PhotoModule.java b/src/com/android/camera/PhotoModule.java
index 1bcd3969..bc901eac 100644
--- a/src/com/android/camera/PhotoModule.java
+++ b/src/com/android/camera/PhotoModule.java
@@ -1,2584 +1,2585 @@
/*
* Copyright (C) 2012 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.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Face;
import android.hardware.Camera.FaceDetectionListener;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.location.Location;
import android.media.CameraProfile;
import android.net.Uri;
import android.os.Bundle;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.camera.CameraManager.CameraProxy;
import com.android.camera.ui.AbstractSettingPopup;
import com.android.camera.ui.FaceView;
import com.android.camera.ui.PieRenderer;
import com.android.camera.ui.PopupManager;
import com.android.camera.ui.PreviewSurfaceView;
import com.android.camera.ui.RenderOverlay;
import com.android.camera.ui.Rotatable;
import com.android.camera.ui.RotateTextToast;
import com.android.camera.ui.TwoStateImageView;
import com.android.camera.ui.ZoomRenderer;
-import com.android.gallery3d.app.CropImage;
import com.android.gallery3d.common.ApiHelper;
+import com.android.gallery3d.filtershow.FilterShowActivity;
+import com.android.gallery3d.filtershow.CropExtras;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Formatter;
import java.util.List;
public class PhotoModule
implements CameraModule,
FocusOverlayManager.Listener,
CameraPreference.OnPreferenceChangedListener,
LocationManager.Listener,
PreviewFrameLayout.OnSizeChangedListener,
ShutterButton.OnShutterButtonListener,
SurfaceHolder.Callback,
PieRenderer.PieListener {
private static final String TAG = "CAM_PhotoModule";
// We number the request code from 1000 to avoid collision with Gallery.
private static final int REQUEST_CROP = 1000;
private static final int SETUP_PREVIEW = 1;
private static final int FIRST_TIME_INIT = 2;
private static final int CLEAR_SCREEN_DELAY = 3;
private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 4;
private static final int CHECK_DISPLAY_ROTATION = 5;
private static final int SHOW_TAP_TO_FOCUS_TOAST = 6;
private static final int SWITCH_CAMERA = 7;
private static final int SWITCH_CAMERA_START_ANIMATION = 8;
private static final int CAMERA_OPEN_DONE = 9;
private static final int START_PREVIEW_DONE = 10;
private static final int OPEN_CAMERA_FAIL = 11;
private static final int CAMERA_DISABLED = 12;
// The subset of parameters we need to update in setCameraParameters().
private static final int UPDATE_PARAM_INITIALIZE = 1;
private static final int UPDATE_PARAM_ZOOM = 2;
private static final int UPDATE_PARAM_PREFERENCE = 4;
private static final int UPDATE_PARAM_ALL = -1;
// This is the timeout to keep the camera in onPause for the first time
// after screen on if the activity is started from secure lock screen.
private static final int KEEP_CAMERA_TIMEOUT = 1000; // ms
// copied from Camera hierarchy
private CameraActivity mActivity;
private View mRootView;
private CameraProxy mCameraDevice;
private int mCameraId;
private Parameters mParameters;
private boolean mPaused;
private AbstractSettingPopup mPopup;
// these are only used by Camera
// The activity is going to switch to the specified camera id. This is
// needed because texture copy is done in GL thread. -1 means camera is not
// switching.
protected int mPendingSwitchCameraId = -1;
private boolean mOpenCameraFail;
private boolean mCameraDisabled;
// When setCameraParametersWhenIdle() is called, we accumulate the subsets
// needed to be updated in mUpdateSet.
private int mUpdateSet;
private static final int SCREEN_DELAY = 2 * 60 * 1000;
private int mZoomValue; // The current zoom value.
private int mZoomMax;
private List<Integer> mZoomRatios;
private Parameters mInitialParams;
private boolean mFocusAreaSupported;
private boolean mMeteringAreaSupported;
private boolean mAeLockSupported;
private boolean mAwbLockSupported;
private boolean mContinousFocusSupported;
// The degrees of the device rotated clockwise from its natural orientation.
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
private ComboPreferences mPreferences;
private static final String sTempCropFilename = "crop-temp";
private ContentProviderClient mMediaProviderClient;
private ShutterButton mShutterButton;
private boolean mFaceDetectionStarted = false;
private PreviewFrameLayout mPreviewFrameLayout;
private Object mSurfaceTexture;
// for API level 10
private PreviewSurfaceView mPreviewSurfaceView;
private volatile SurfaceHolder mCameraSurfaceHolder;
private FaceView mFaceView;
private RenderOverlay mRenderOverlay;
private Rotatable mReviewCancelButton;
private Rotatable mReviewDoneButton;
private View mReviewRetakeButton;
// mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
private String mCropValue;
private Uri mSaveUri;
private View mMenu;
private View mBlocker;
// Small indicators which show the camera settings in the viewfinder.
private ImageView mExposureIndicator;
private ImageView mFlashIndicator;
private ImageView mSceneIndicator;
private ImageView mHdrIndicator;
// A view group that contains all the small indicators.
private View mOnScreenIndicators;
// We use a thread in ImageSaver to do the work of saving images. This
// reduces the shot-to-shot time.
private ImageSaver mImageSaver;
// Similarly, we use a thread to generate the name of the picture and insert
// it into MediaStore while picture taking is still in progress.
private ImageNamer mImageNamer;
private Runnable mDoSnapRunnable = new Runnable() {
@Override
public void run() {
onShutterButtonClick();
}
};
private final StringBuilder mBuilder = new StringBuilder();
private final Formatter mFormatter = new Formatter(mBuilder);
private final Object[] mFormatterArgs = new Object[1];
/**
* An unpublished intent flag requesting to return as soon as capturing
* is completed.
*
* TODO: consider publishing by moving into MediaStore.
*/
private static final String EXTRA_QUICK_CAPTURE =
"android.intent.extra.quickCapture";
// The display rotation in degrees. This is only valid when mCameraState is
// not PREVIEW_STOPPED.
private int mDisplayRotation;
// The value for android.hardware.Camera.setDisplayOrientation.
private int mCameraDisplayOrientation;
// The value for UI components like indicators.
private int mDisplayOrientation;
// The value for android.hardware.Camera.Parameters.setRotation.
private int mJpegRotation;
private boolean mFirstTimeInitialized;
private boolean mIsImageCaptureIntent;
private static final int PREVIEW_STOPPED = 0;
private static final int IDLE = 1; // preview is active
// Focus is in progress. The exact focus state is in Focus.java.
private static final int FOCUSING = 2;
private static final int SNAPSHOT_IN_PROGRESS = 3;
// Switching between cameras.
private static final int SWITCHING_CAMERA = 4;
private int mCameraState = PREVIEW_STOPPED;
private boolean mSnapshotOnIdle = false;
private ContentResolver mContentResolver;
private LocationManager mLocationManager;
private final ShutterCallback mShutterCallback = new ShutterCallback();
private final PostViewPictureCallback mPostViewPictureCallback =
new PostViewPictureCallback();
private final RawPictureCallback mRawPictureCallback =
new RawPictureCallback();
private final AutoFocusCallback mAutoFocusCallback =
new AutoFocusCallback();
private final Object mAutoFocusMoveCallback =
ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK
? new AutoFocusMoveCallback()
: null;
private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
private long mFocusStartTime;
private long mShutterCallbackTime;
private long mPostViewPictureCallbackTime;
private long mRawPictureCallbackTime;
private long mJpegPictureCallbackTime;
private long mOnResumeTime;
private byte[] mJpegImageData;
// These latency time are for the CameraLatency test.
public long mAutoFocusTime;
public long mShutterLag;
public long mShutterToPictureDisplayedTime;
public long mPictureDisplayedToJpegCallbackTime;
public long mJpegCallbackFinishTime;
public long mCaptureStartTime;
// This handles everything about focus.
private FocusOverlayManager mFocusManager;
private PieRenderer mPieRenderer;
private PhotoController mPhotoControl;
private ZoomRenderer mZoomRenderer;
private String mSceneMode;
private Toast mNotSelectableToast;
private final Handler mHandler = new MainHandler();
private PreferenceGroup mPreferenceGroup;
private boolean mQuickCapture;
CameraStartUpThread mCameraStartUpThread;
ConditionVariable mStartPreviewPrerequisiteReady = new ConditionVariable();
private PreviewGestures mGestures;
// The purpose is not to block the main thread in onCreate and onResume.
private class CameraStartUpThread extends Thread {
private volatile boolean mCancelled;
public void cancel() {
mCancelled = true;
}
@Override
public void run() {
try {
// We need to check whether the activity is paused before long
// operations to ensure that onPause() can be done ASAP.
if (mCancelled) return;
mCameraDevice = Util.openCamera(mActivity, mCameraId);
mParameters = mCameraDevice.getParameters();
// Wait until all the initialization needed by startPreview are
// done.
mStartPreviewPrerequisiteReady.block();
initializeCapabilities();
if (mFocusManager == null) initializeFocusManager();
if (mCancelled) return;
setCameraParameters(UPDATE_PARAM_ALL);
mHandler.sendEmptyMessage(CAMERA_OPEN_DONE);
if (mCancelled) return;
startPreview();
mHandler.sendEmptyMessage(START_PREVIEW_DONE);
mOnResumeTime = SystemClock.uptimeMillis();
mHandler.sendEmptyMessage(CHECK_DISPLAY_ROTATION);
} catch (CameraHardwareException e) {
mHandler.sendEmptyMessage(OPEN_CAMERA_FAIL);
} catch (CameraDisabledException e) {
mHandler.sendEmptyMessage(CAMERA_DISABLED);
}
}
}
/**
* This Handler is used to post message back onto the main thread of the
* application
*/
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SETUP_PREVIEW: {
setupPreview();
break;
}
case CLEAR_SCREEN_DELAY: {
mActivity.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
break;
}
case FIRST_TIME_INIT: {
initializeFirstTime();
break;
}
case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
setCameraParametersWhenIdle(0);
break;
}
case CHECK_DISPLAY_ROTATION: {
// Set the display orientation if display rotation has changed.
// Sometimes this happens when the device is held upside
// down and camera app is opened. Rotation animation will
// take some time and the rotation value we have got may be
// wrong. Framework does not have a callback for this now.
if (Util.getDisplayRotation(mActivity) != mDisplayRotation) {
setDisplayOrientation();
}
if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
break;
}
case SHOW_TAP_TO_FOCUS_TOAST: {
showTapToFocusToast();
break;
}
case SWITCH_CAMERA: {
switchCamera();
break;
}
case SWITCH_CAMERA_START_ANIMATION: {
((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
break;
}
case CAMERA_OPEN_DONE: {
initializeAfterCameraOpen();
break;
}
case START_PREVIEW_DONE: {
mCameraStartUpThread = null;
setCameraState(IDLE);
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
// This may happen if surfaceCreated has arrived.
mCameraDevice.setPreviewDisplayAsync(mCameraSurfaceHolder);
}
startFaceDetection();
locationFirstRun();
break;
}
case OPEN_CAMERA_FAIL: {
mCameraStartUpThread = null;
mOpenCameraFail = true;
Util.showErrorAndFinish(mActivity,
R.string.cannot_connect_camera);
break;
}
case CAMERA_DISABLED: {
mCameraStartUpThread = null;
mCameraDisabled = true;
Util.showErrorAndFinish(mActivity,
R.string.camera_disabled);
break;
}
}
}
}
@Override
public void init(CameraActivity activity, View parent, boolean reuseNail) {
mActivity = activity;
mRootView = parent;
mPreferences = new ComboPreferences(mActivity);
CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
mCameraId = getPreferredCameraId(mPreferences);
mContentResolver = mActivity.getContentResolver();
// To reduce startup time, open the camera and start the preview in
// another thread.
mCameraStartUpThread = new CameraStartUpThread();
mCameraStartUpThread.start();
mActivity.getLayoutInflater().inflate(R.layout.photo_module, (ViewGroup) mRootView);
// Surface texture is from camera screen nail and startPreview needs it.
// This must be done before startPreview.
mIsImageCaptureIntent = isImageCaptureIntent();
if (reuseNail) {
mActivity.reuseCameraScreenNail(!mIsImageCaptureIntent);
} else {
mActivity.createCameraScreenNail(!mIsImageCaptureIntent);
}
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
// we need to reset exposure for the preview
resetExposureCompensation();
// Starting the preview needs preferences, camera screen nail, and
// focus area indicator.
mStartPreviewPrerequisiteReady.open();
initializeControlByIntent();
mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
initializeMiscControls();
mLocationManager = new LocationManager(mActivity, this);
initOnScreenIndicator();
}
// Prompt the user to pick to record location for the very first run of
// camera only
private void locationFirstRun() {
if (RecordLocationPreference.isSet(mPreferences)) {
return;
}
if (mActivity.isSecureCamera()) return;
// Check if the back camera exists
int backCameraId = CameraHolder.instance().getBackCameraId();
if (backCameraId == -1) {
// If there is no back camera, do not show the prompt.
return;
}
new AlertDialog.Builder(mActivity)
.setTitle(R.string.remember_location_title)
.setMessage(R.string.remember_location_prompt)
.setPositiveButton(R.string.remember_location_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
setLocationPreference(RecordLocationPreference.VALUE_ON);
}
})
.setNegativeButton(R.string.remember_location_no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.cancel();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
setLocationPreference(RecordLocationPreference.VALUE_OFF);
}
})
.show();
}
private void setLocationPreference(String value) {
mPreferences.edit()
.putString(CameraSettings.KEY_RECORD_LOCATION, value)
.apply();
// TODO: Fix this to use the actual onSharedPreferencesChanged listener
// instead of invoking manually
onSharedPreferenceChanged();
}
private void initializeRenderOverlay() {
if (mPieRenderer != null) {
mRenderOverlay.addRenderer(mPieRenderer);
mFocusManager.setFocusRenderer(mPieRenderer);
}
if (mZoomRenderer != null) {
mRenderOverlay.addRenderer(mZoomRenderer);
}
if (mGestures != null) {
mGestures.clearTouchReceivers();
mGestures.setRenderOverlay(mRenderOverlay);
mGestures.addTouchReceiver(mMenu);
mGestures.addTouchReceiver(mBlocker);
if (isImageCaptureIntent()) {
if (mReviewCancelButton != null) {
mGestures.addTouchReceiver((View) mReviewCancelButton);
}
if (mReviewDoneButton != null) {
mGestures.addTouchReceiver((View) mReviewDoneButton);
}
}
}
mRenderOverlay.requestLayout();
}
private void initializeAfterCameraOpen() {
if (mPieRenderer == null) {
mPieRenderer = new PieRenderer(mActivity);
mPhotoControl = new PhotoController(mActivity, this, mPieRenderer);
mPhotoControl.setListener(this);
mPieRenderer.setPieListener(this);
}
if (mZoomRenderer == null) {
mZoomRenderer = new ZoomRenderer(mActivity);
}
if (mGestures == null) {
// this will handle gesture disambiguation and dispatching
mGestures = new PreviewGestures(mActivity, this, mZoomRenderer, mPieRenderer);
}
initializeRenderOverlay();
initializePhotoControl();
// These depend on camera parameters.
setPreviewFrameLayoutAspectRatio();
mFocusManager.setPreviewSize(mPreviewFrameLayout.getWidth(),
mPreviewFrameLayout.getHeight());
loadCameraPreferences();
initializeZoom();
updateOnScreenIndicators();
showTapToFocusToastIfNeeded();
onFullScreenChanged(mActivity.isInCameraApp());
}
private void initializePhotoControl() {
loadCameraPreferences();
if (mPhotoControl != null) {
mPhotoControl.initialize(mPreferenceGroup);
}
updateSceneModeUI();
}
private void resetExposureCompensation() {
String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
CameraSettings.EXPOSURE_DEFAULT_VALUE);
if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
Editor editor = mPreferences.edit();
editor.putString(CameraSettings.KEY_EXPOSURE, "0");
editor.apply();
}
}
private void keepMediaProviderInstance() {
// We want to keep a reference to MediaProvider in camera's lifecycle.
// TODO: Utilize mMediaProviderClient instance to replace
// ContentResolver calls.
if (mMediaProviderClient == null) {
mMediaProviderClient = mContentResolver
.acquireContentProviderClient(MediaStore.AUTHORITY);
}
}
// Snapshots can only be taken after this is called. It should be called
// once only. We could have done these things in onCreate() but we want to
// make preview screen appear as soon as possible.
private void initializeFirstTime() {
if (mFirstTimeInitialized) return;
// Initialize location service.
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
keepMediaProviderInstance();
// Initialize shutter button.
mShutterButton = mActivity.getShutterButton();
mShutterButton.setImageResource(R.drawable.btn_new_shutter);
mShutterButton.setOnShutterButtonListener(this);
mShutterButton.setVisibility(View.VISIBLE);
mImageSaver = new ImageSaver();
mImageNamer = new ImageNamer();
mFirstTimeInitialized = true;
addIdleHandler();
mActivity.updateStorageSpaceAndHint();
}
private void showTapToFocusToastIfNeeded() {
// Show the tap to focus toast if this is the first start.
if (mFocusAreaSupported &&
mPreferences.getBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, true)) {
// Delay the toast for one second to wait for orientation.
mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_FOCUS_TOAST, 1000);
}
}
private void addIdleHandler() {
MessageQueue queue = Looper.myQueue();
queue.addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
Storage.ensureOSXCompatible();
return false;
}
});
}
// If the activity is paused and resumed, this method will be called in
// onResume.
private void initializeSecondTime() {
// Start location update if needed.
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
mImageSaver = new ImageSaver();
mImageNamer = new ImageNamer();
initializeZoom();
keepMediaProviderInstance();
hidePostCaptureAlert();
if (mPhotoControl != null) {
mPhotoControl.reloadPreferences();
}
}
private class ZoomChangeListener implements ZoomRenderer.OnZoomChangedListener {
@Override
public void onZoomValueChanged(int index) {
// Not useful to change zoom value when the activity is paused.
if (mPaused) return;
mZoomValue = index;
if (mParameters == null || mCameraDevice == null) return;
// Set zoom parameters asynchronously
mParameters.setZoom(mZoomValue);
mCameraDevice.setParametersAsync(mParameters);
if (mZoomRenderer != null) {
Parameters p = mCameraDevice.getParameters();
mZoomRenderer.setZoomValue(mZoomRatios.get(p.getZoom()));
}
}
@Override
public void onZoomStart() {
if (mPieRenderer != null) {
mPieRenderer.setBlockFocus(true);
}
}
@Override
public void onZoomEnd() {
if (mPieRenderer != null) {
mPieRenderer.setBlockFocus(false);
}
}
}
private void initializeZoom() {
if ((mParameters == null) || !mParameters.isZoomSupported()
|| (mZoomRenderer == null)) return;
mZoomMax = mParameters.getMaxZoom();
mZoomRatios = mParameters.getZoomRatios();
// Currently we use immediate zoom for fast zooming to get better UX and
// there is no plan to take advantage of the smooth zoom.
if (mZoomRenderer != null) {
mZoomRenderer.setZoomMax(mZoomMax);
mZoomRenderer.setZoom(mParameters.getZoom());
mZoomRenderer.setZoomValue(mZoomRatios.get(mParameters.getZoom()));
mZoomRenderer.setOnZoomChangeListener(new ZoomChangeListener());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void startFaceDetection() {
if (!ApiHelper.HAS_FACE_DETECTION) return;
if (mFaceDetectionStarted) return;
if (mParameters.getMaxNumDetectedFaces() > 0) {
mFaceDetectionStarted = true;
mFaceView.clear();
mFaceView.setVisibility(View.VISIBLE);
mFaceView.setDisplayOrientation(mDisplayOrientation);
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFaceView.resume();
mFocusManager.setFaceView(mFaceView);
mCameraDevice.setFaceDetectionListener(new FaceDetectionListener() {
@Override
public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
mFaceView.setFaces(faces);
}
});
mCameraDevice.startFaceDetection();
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void stopFaceDetection() {
if (!ApiHelper.HAS_FACE_DETECTION) return;
if (!mFaceDetectionStarted) return;
if (mParameters.getMaxNumDetectedFaces() > 0) {
mFaceDetectionStarted = false;
mCameraDevice.setFaceDetectionListener(null);
mCameraDevice.stopFaceDetection();
if (mFaceView != null) mFaceView.clear();
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent m) {
if (mCameraState == SWITCHING_CAMERA) return true;
if (mPopup != null) {
return mActivity.superDispatchTouchEvent(m);
} else if (mGestures != null && mRenderOverlay != null) {
return mGestures.dispatchTouch(m);
}
return false;
}
private void initOnScreenIndicator() {
mOnScreenIndicators = mRootView.findViewById(R.id.on_screen_indicators);
mExposureIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_exposure_indicator);
mFlashIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_flash_indicator);
mSceneIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_scenemode_indicator);
mHdrIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_hdr_indicator);
}
@Override
public void showGpsOnScreenIndicator(boolean hasSignal) { }
@Override
public void hideGpsOnScreenIndicator() { }
private void updateExposureOnScreenIndicator(int value) {
if (mExposureIndicator == null) {
return;
}
int id = 0;
float step = mParameters.getExposureCompensationStep();
value = (int) Math.round(value * step);
switch(value) {
case -3:
id = R.drawable.ic_indicator_ev_n3;
break;
case -2:
id = R.drawable.ic_indicator_ev_n2;
break;
case -1:
id = R.drawable.ic_indicator_ev_n1;
break;
case 0:
id = R.drawable.ic_indicator_ev_0;
break;
case 1:
id = R.drawable.ic_indicator_ev_p1;
break;
case 2:
id = R.drawable.ic_indicator_ev_p2;
break;
case 3:
id = R.drawable.ic_indicator_ev_p3;
break;
}
mExposureIndicator.setImageResource(id);
}
private void updateFlashOnScreenIndicator(String value) {
if (mFlashIndicator == null) {
return;
}
if (value == null || Parameters.FLASH_MODE_OFF.equals(value)) {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_off);
} else {
if (Parameters.FLASH_MODE_AUTO.equals(value)) {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_auto);
} else if (Parameters.FLASH_MODE_ON.equals(value)) {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_on);
} else {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_off);
}
}
}
private void updateSceneOnScreenIndicator(String value) {
if (mSceneIndicator == null) {
return;
}
if ((value == null) || Parameters.SCENE_MODE_AUTO.equals(value)
|| Parameters.SCENE_MODE_HDR.equals(value)) {
mSceneIndicator.setImageResource(R.drawable.ic_indicator_sce_off);
} else {
mSceneIndicator.setImageResource(R.drawable.ic_indicator_sce_on);
}
}
private void updateHdrOnScreenIndicator(String value) {
if (mHdrIndicator == null) {
return;
}
if ((value != null) && Parameters.SCENE_MODE_HDR.equals(value)) {
mHdrIndicator.setImageResource(R.drawable.ic_indicator_hdr_on);
} else {
mHdrIndicator.setImageResource(R.drawable.ic_indicator_hdr_off);
}
}
private void updateOnScreenIndicators() {
updateSceneOnScreenIndicator(mParameters.getSceneMode());
updateExposureOnScreenIndicator(CameraSettings.readExposure(mPreferences));
updateFlashOnScreenIndicator(mParameters.getFlashMode());
updateHdrOnScreenIndicator(mParameters.getSceneMode());
}
private final class ShutterCallback
implements android.hardware.Camera.ShutterCallback {
@Override
public void onShutter() {
mShutterCallbackTime = System.currentTimeMillis();
mShutterLag = mShutterCallbackTime - mCaptureStartTime;
Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
}
}
private final class PostViewPictureCallback implements PictureCallback {
@Override
public void onPictureTaken(
byte [] data, android.hardware.Camera camera) {
mPostViewPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToPostViewCallbackTime = "
+ (mPostViewPictureCallbackTime - mShutterCallbackTime)
+ "ms");
}
}
private final class RawPictureCallback implements PictureCallback {
@Override
public void onPictureTaken(
byte [] rawData, android.hardware.Camera camera) {
mRawPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToRawCallbackTime = "
+ (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
}
}
private final class JpegPictureCallback implements PictureCallback {
Location mLocation;
public JpegPictureCallback(Location loc) {
mLocation = loc;
}
@Override
public void onPictureTaken(
final byte [] jpegData, final android.hardware.Camera camera) {
if (mPaused) {
return;
}
if (mSceneMode == Util.SCENE_MODE_HDR) {
mActivity.showSwitcher();
mActivity.setSwipingEnabled(true);
}
mJpegPictureCallbackTime = System.currentTimeMillis();
// If postview callback has arrived, the captured image is displayed
// in postview callback. If not, the captured image is displayed in
// raw picture callback.
if (mPostViewPictureCallbackTime != 0) {
mShutterToPictureDisplayedTime =
mPostViewPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
} else {
mShutterToPictureDisplayedTime =
mRawPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mRawPictureCallbackTime;
}
Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
+ mPictureDisplayedToJpegCallbackTime + "ms");
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Finish capture animation
((CameraScreenNail) mActivity.mCameraScreenNail).animateSlide();
}
mFocusManager.updateFocusUI(); // Ensure focus indicator is hidden.
if (!mIsImageCaptureIntent) {
if (ApiHelper.CAN_START_PREVIEW_IN_JPEG_CALLBACK) {
setupPreview();
} else {
// Camera HAL of some devices have a bug. Starting preview
// immediately after taking a picture will fail. Wait some
// time before starting the preview.
mHandler.sendEmptyMessageDelayed(SETUP_PREVIEW, 300);
}
}
if (!mIsImageCaptureIntent) {
// Calculate the width and the height of the jpeg.
Size s = mParameters.getPictureSize();
int orientation = Exif.getOrientation(jpegData);
int width, height;
if ((mJpegRotation + orientation) % 180 == 0) {
width = s.width;
height = s.height;
} else {
width = s.height;
height = s.width;
}
Uri uri = mImageNamer.getUri();
mActivity.addSecureAlbumItemIfNeeded(false, uri);
String title = mImageNamer.getTitle();
mImageSaver.addImage(jpegData, uri, title, mLocation,
width, height, orientation);
} else {
mJpegImageData = jpegData;
if (!mQuickCapture) {
showPostCaptureAlert();
} else {
doAttach();
}
}
// Check this in advance of each shot so we don't add to shutter
// latency. It's true that someone else could write to the SD card in
// the mean time and fill it, but that could have happened between the
// shutter press and saving the JPEG too.
mActivity.updateStorageSpaceAndHint();
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
}
}
private final class AutoFocusCallback
implements android.hardware.Camera.AutoFocusCallback {
@Override
public void onAutoFocus(
boolean focused, android.hardware.Camera camera) {
if (mPaused) return;
mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
setCameraState(IDLE);
mFocusManager.onAutoFocus(focused, mShutterButton.isPressed());
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private final class AutoFocusMoveCallback
implements android.hardware.Camera.AutoFocusMoveCallback {
@Override
public void onAutoFocusMoving(
boolean moving, android.hardware.Camera camera) {
mFocusManager.onAutoFocusMoving(moving);
}
}
// Each SaveRequest remembers the data needed to save an image.
private static class SaveRequest {
byte[] data;
Uri uri;
String title;
Location loc;
int width, height;
int orientation;
}
// We use a queue to store the SaveRequests that have not been completed
// yet. The main thread puts the request into the queue. The saver thread
// gets it from the queue, does the work, and removes it from the queue.
//
// The main thread needs to wait for the saver thread to finish all the work
// in the queue, when the activity's onPause() is called, we need to finish
// all the work, so other programs (like Gallery) can see all the images.
//
// If the queue becomes too long, adding a new request will block the main
// thread until the queue length drops below the threshold (QUEUE_LIMIT).
// If we don't do this, we may face several problems: (1) We may OOM
// because we are holding all the jpeg data in memory. (2) We may ANR
// when we need to wait for saver thread finishing all the work (in
// onPause() or gotoGallery()) because the time to finishing a long queue
// of work may be too long.
private class ImageSaver extends Thread {
private static final int QUEUE_LIMIT = 3;
private ArrayList<SaveRequest> mQueue;
private boolean mStop;
// Runs in main thread
public ImageSaver() {
mQueue = new ArrayList<SaveRequest>();
start();
}
// Runs in main thread
public void addImage(final byte[] data, Uri uri, String title,
Location loc, int width, int height, int orientation) {
SaveRequest r = new SaveRequest();
r.data = data;
r.uri = uri;
r.title = title;
r.loc = (loc == null) ? null : new Location(loc); // make a copy
r.width = width;
r.height = height;
r.orientation = orientation;
synchronized (this) {
while (mQueue.size() >= QUEUE_LIMIT) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
mQueue.add(r);
notifyAll(); // Tell saver thread there is new work to do.
}
}
// Runs in saver thread
@Override
public void run() {
while (true) {
SaveRequest r;
synchronized (this) {
if (mQueue.isEmpty()) {
notifyAll(); // notify main thread in waitDone
// Note that we can only stop after we saved all images
// in the queue.
if (mStop) break;
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
continue;
}
r = mQueue.get(0);
}
storeImage(r.data, r.uri, r.title, r.loc, r.width, r.height,
r.orientation);
synchronized (this) {
mQueue.remove(0);
notifyAll(); // the main thread may wait in addImage
}
}
}
// Runs in main thread
public void waitDone() {
synchronized (this) {
while (!mQueue.isEmpty()) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
}
}
// Runs in main thread
public void finish() {
waitDone();
synchronized (this) {
mStop = true;
notifyAll();
}
try {
join();
} catch (InterruptedException ex) {
// ignore.
}
}
// Runs in saver thread
private void storeImage(final byte[] data, Uri uri, String title,
Location loc, int width, int height, int orientation) {
boolean ok = Storage.updateImage(mContentResolver, uri, title, loc,
orientation, data, width, height);
if (ok) {
Util.broadcastNewPicture(mActivity, uri);
}
}
}
private static class ImageNamer extends Thread {
private boolean mRequestPending;
private ContentResolver mResolver;
private long mDateTaken;
private int mWidth, mHeight;
private boolean mStop;
private Uri mUri;
private String mTitle;
// Runs in main thread
public ImageNamer() {
start();
}
// Runs in main thread
public synchronized void prepareUri(ContentResolver resolver,
long dateTaken, int width, int height, int rotation) {
if (rotation % 180 != 0) {
int tmp = width;
width = height;
height = tmp;
}
mRequestPending = true;
mResolver = resolver;
mDateTaken = dateTaken;
mWidth = width;
mHeight = height;
notifyAll();
}
// Runs in main thread
public synchronized Uri getUri() {
// wait until the request is done.
while (mRequestPending) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
// return the uri generated
Uri uri = mUri;
mUri = null;
return uri;
}
// Runs in main thread, should be called after getUri().
public synchronized String getTitle() {
return mTitle;
}
// Runs in namer thread
@Override
public synchronized void run() {
while (true) {
if (mStop) break;
if (!mRequestPending) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
continue;
}
cleanOldUri();
generateUri();
mRequestPending = false;
notifyAll();
}
cleanOldUri();
}
// Runs in main thread
public synchronized void finish() {
mStop = true;
notifyAll();
}
// Runs in namer thread
private void generateUri() {
mTitle = Util.createJpegName(mDateTaken);
mUri = Storage.newImage(mResolver, mTitle, mDateTaken, mWidth, mHeight);
}
// Runs in namer thread
private void cleanOldUri() {
if (mUri == null) return;
Storage.deleteImage(mResolver, mUri);
mUri = null;
}
}
private void setCameraState(int state) {
mCameraState = state;
switch (state) {
case PREVIEW_STOPPED:
case SNAPSHOT_IN_PROGRESS:
case FOCUSING:
case SWITCHING_CAMERA:
if (mGestures != null) mGestures.setEnabled(false);
break;
case IDLE:
if (mGestures != null && mActivity.mShowCameraAppView) {
// Enable gestures only when the camera app view is visible
mGestures.setEnabled(true);
}
break;
}
}
private void animateFlash() {
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Start capture animation.
((CameraScreenNail) mActivity.mCameraScreenNail).animateFlash(mDisplayRotation);
}
}
@Override
public boolean capture() {
// If we are already in the middle of taking a snapshot then ignore.
if (mCameraDevice == null || mCameraState == SNAPSHOT_IN_PROGRESS
|| mCameraState == SWITCHING_CAMERA) {
return false;
}
mCaptureStartTime = System.currentTimeMillis();
mPostViewPictureCallbackTime = 0;
mJpegImageData = null;
final boolean animateBefore = (mSceneMode == Util.SCENE_MODE_HDR);
if (animateBefore) {
animateFlash();
}
// Set rotation and gps data.
mJpegRotation = Util.getJpegRotation(mCameraId, mOrientation);
mParameters.setRotation(mJpegRotation);
Location loc = mLocationManager.getCurrentLocation();
Util.setGpsParameters(mParameters, loc);
mCameraDevice.setParameters(mParameters);
mCameraDevice.takePicture2(mShutterCallback, mRawPictureCallback,
mPostViewPictureCallback, new JpegPictureCallback(loc),
mCameraState, mFocusManager.getFocusState());
if (!animateBefore) {
animateFlash();
}
Size size = mParameters.getPictureSize();
mImageNamer.prepareUri(mContentResolver, mCaptureStartTime,
size.width, size.height, mJpegRotation);
mFaceDetectionStarted = false;
setCameraState(SNAPSHOT_IN_PROGRESS);
return true;
}
@Override
public void setFocusParameters() {
setCameraParameters(UPDATE_PARAM_PREFERENCE);
}
private int getPreferredCameraId(ComboPreferences preferences) {
int intentCameraId = Util.getCameraFacingIntentExtras(mActivity);
if (intentCameraId != -1) {
// Testing purpose. Launch a specific camera through the intent
// extras.
return intentCameraId;
} else {
return CameraSettings.readPreferredCameraId(preferences);
}
}
private void setShowMenu(boolean show) {
if (mOnScreenIndicators != null) {
mOnScreenIndicators.setVisibility(show ? View.VISIBLE : View.GONE);
}
if (mMenu != null) {
mMenu.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
@Override
public void onFullScreenChanged(boolean full) {
if (mFaceView != null) {
mFaceView.setBlockDraw(!full);
}
if (mPopup != null) {
dismissPopup(false, full);
}
if (mGestures != null) {
mGestures.setEnabled(full);
}
if (mRenderOverlay != null) {
// this can not happen in capture mode
mRenderOverlay.setVisibility(full ? View.VISIBLE : View.GONE);
}
if (mPieRenderer != null) {
mPieRenderer.setBlockFocus(!full);
}
setShowMenu(full);
if (mBlocker != null) {
mBlocker.setVisibility(full ? View.VISIBLE : View.GONE);
}
if (ApiHelper.HAS_SURFACE_TEXTURE) {
if (mActivity.mCameraScreenNail != null) {
((CameraScreenNail) mActivity.mCameraScreenNail).setFullScreen(full);
}
return;
}
if (full) {
mPreviewSurfaceView.expand();
} else {
mPreviewSurfaceView.shrink();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "surfaceChanged:" + holder + " width=" + width + ". height="
+ height);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated: " + holder);
mCameraSurfaceHolder = holder;
// Do not access the camera if camera start up thread is not finished.
if (mCameraDevice == null || mCameraStartUpThread != null) return;
mCameraDevice.setPreviewDisplayAsync(holder);
// This happens when onConfigurationChanged arrives, surface has been
// destroyed, and there is no onFullScreenChanged.
if (mCameraState == PREVIEW_STOPPED) {
setupPreview();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "surfaceDestroyed: " + holder);
mCameraSurfaceHolder = null;
stopPreview();
}
private void updateSceneModeUI() {
// If scene mode is set, we cannot set flash mode, white balance, and
// focus mode, instead, we read it from driver
if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
overrideCameraSettings(mParameters.getFlashMode(),
mParameters.getWhiteBalance(), mParameters.getFocusMode());
} else {
overrideCameraSettings(null, null, null);
}
}
private void overrideCameraSettings(final String flashMode,
final String whiteBalance, final String focusMode) {
if (mPhotoControl != null) {
// mPieControl.enableFilter(true);
mPhotoControl.overrideSettings(
CameraSettings.KEY_FLASH_MODE, flashMode,
CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
CameraSettings.KEY_FOCUS_MODE, focusMode);
// mPieControl.enableFilter(false);
}
}
private void loadCameraPreferences() {
CameraSettings settings = new CameraSettings(mActivity, mInitialParams,
mCameraId, CameraHolder.instance().getCameraInfo());
mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
}
@Override
public boolean collapseCameraControls() {
// Remove all the popups/dialog boxes
boolean ret = false;
if (mPopup != null) {
dismissPopup(false);
ret = true;
}
return ret;
}
public boolean removeTopLevelPopup() {
// Remove the top level popup or dialog box and return true if there's any
if (mPopup != null) {
dismissPopup(true);
return true;
}
return false;
}
@Override
public void onOrientationChanged(int orientation) {
// We keep the last known orientation. So if the user first orient
// the camera then point the camera to floor or sky, we still have
// the correct orientation.
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) return;
mOrientation = Util.roundOrientation(orientation, mOrientation);
// Show the toast after getting the first orientation changed.
if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) {
mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST);
showTapToFocusToast();
}
}
@Override
public void onStop() {
if (mMediaProviderClient != null) {
mMediaProviderClient.release();
mMediaProviderClient = null;
}
}
// onClick handler for R.id.btn_done
@OnClickAttr
public void onReviewDoneClicked(View v) {
doAttach();
}
// onClick handler for R.id.btn_cancel
@OnClickAttr
public void onReviewCancelClicked(View v) {
doCancel();
}
// onClick handler for R.id.btn_retake
@OnClickAttr
public void onReviewRetakeClicked(View v) {
if (mPaused)
return;
hidePostCaptureAlert();
setupPreview();
}
private void doAttach() {
if (mPaused) {
return;
}
byte[] data = mJpegImageData;
if (mCropValue == null) {
// First handle the no crop case -- just return the value. If the
// caller specifies a "save uri" then write the data to its
// stream. Otherwise, pass back a scaled down version of the bitmap
// directly in the extras.
if (mSaveUri != null) {
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(mSaveUri);
outputStream.write(data);
outputStream.close();
mActivity.setResultEx(Activity.RESULT_OK);
mActivity.finish();
} catch (IOException ex) {
// ignore exception
} finally {
Util.closeSilently(outputStream);
}
} else {
int orientation = Exif.getOrientation(data);
Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
bitmap = Util.rotate(bitmap, orientation);
mActivity.setResultEx(Activity.RESULT_OK,
new Intent("inline-data").putExtra("data", bitmap));
mActivity.finish();
}
} else {
// Save the image to a temp file and invoke the cropper
Uri tempUri = null;
FileOutputStream tempStream = null;
try {
File path = mActivity.getFileStreamPath(sTempCropFilename);
path.delete();
tempStream = mActivity.openFileOutput(sTempCropFilename, 0);
tempStream.write(data);
tempStream.close();
tempUri = Uri.fromFile(path);
} catch (FileNotFoundException ex) {
mActivity.setResultEx(Activity.RESULT_CANCELED);
mActivity.finish();
return;
} catch (IOException ex) {
mActivity.setResultEx(Activity.RESULT_CANCELED);
mActivity.finish();
return;
} finally {
Util.closeSilently(tempStream);
}
Bundle newExtras = new Bundle();
if (mCropValue.equals("circle")) {
newExtras.putString("circleCrop", "true");
}
if (mSaveUri != null) {
newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
} else {
- newExtras.putBoolean("return-data", true);
+ newExtras.putBoolean(CropExtras.KEY_RETURN_DATA, true);
}
if (mActivity.isSecureCamera()) {
- newExtras.putBoolean(CropImage.KEY_SHOW_WHEN_LOCKED, true);
+ newExtras.putBoolean(CropExtras.KEY_SHOW_WHEN_LOCKED, true);
}
- Intent cropIntent = new Intent("com.android.camera.action.CROP");
+ Intent cropIntent = new Intent(FilterShowActivity.CROP_ACTION);
cropIntent.setData(tempUri);
cropIntent.putExtras(newExtras);
mActivity.startActivityForResult(cropIntent, REQUEST_CROP);
}
}
private void doCancel() {
mActivity.setResultEx(Activity.RESULT_CANCELED, new Intent());
mActivity.finish();
}
@Override
public void onShutterButtonFocus(boolean pressed) {
if (mPaused || collapseCameraControls()
|| (mCameraState == SNAPSHOT_IN_PROGRESS)
|| (mCameraState == PREVIEW_STOPPED)) return;
// Do not do focus if there is not enough storage.
if (pressed && !canTakePicture()) return;
if (pressed) {
if (mSceneMode == Util.SCENE_MODE_HDR) {
mActivity.hideSwitcher();
mActivity.setSwipingEnabled(false);
}
mFocusManager.onShutterDown();
} else {
mFocusManager.onShutterUp();
}
}
@Override
public void onShutterButtonClick() {
if (mPaused || collapseCameraControls()
|| (mCameraState == SWITCHING_CAMERA)
|| (mCameraState == PREVIEW_STOPPED)) return;
// Do not take the picture if there is not enough storage.
if (mActivity.getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) {
Log.i(TAG, "Not enough space or storage not ready. remaining="
+ mActivity.getStorageSpace());
return;
}
Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState);
// If the user wants to do a snapshot while the previous one is still
// in progress, remember the fact and do it after we finish the previous
// one and re-start the preview. Snapshot in progress also includes the
// state that autofocus is focusing and a picture will be taken when
// focus callback arrives.
if ((mFocusManager.isFocusingSnapOnFinish() || mCameraState == SNAPSHOT_IN_PROGRESS)
&& !mIsImageCaptureIntent) {
mSnapshotOnIdle = true;
return;
}
mSnapshotOnIdle = false;
mFocusManager.doSnap();
}
@Override
public void installIntentFilter() {
}
@Override
public boolean updateStorageHintOnResume() {
return mFirstTimeInitialized;
}
@Override
public void updateCameraAppView() {
}
@Override
public void onResumeBeforeSuper() {
mPaused = false;
}
@Override
public void onResumeAfterSuper() {
if (mOpenCameraFail || mCameraDisabled) return;
mJpegPictureCallbackTime = 0;
mZoomValue = 0;
// Start the preview if it is not started.
if (mCameraState == PREVIEW_STOPPED && mCameraStartUpThread == null) {
resetExposureCompensation();
mCameraStartUpThread = new CameraStartUpThread();
mCameraStartUpThread.start();
}
// If first time initialization is not finished, put it in the
// message queue.
if (!mFirstTimeInitialized) {
mHandler.sendEmptyMessage(FIRST_TIME_INIT);
} else {
initializeSecondTime();
}
keepScreenOnAwhile();
// Dismiss open menu if exists.
PopupManager.getInstance(mActivity).notifyShowPopup(null);
}
void waitCameraStartUpThread() {
try {
if (mCameraStartUpThread != null) {
mCameraStartUpThread.cancel();
mCameraStartUpThread.join();
mCameraStartUpThread = null;
setCameraState(IDLE);
}
} catch (InterruptedException e) {
// ignore
}
}
@Override
public void onPauseBeforeSuper() {
mPaused = true;
}
@Override
public void onPauseAfterSuper() {
// Wait the camera start up thread to finish.
waitCameraStartUpThread();
// When camera is started from secure lock screen for the first time
// after screen on, the activity gets onCreate->onResume->onPause->onResume.
// To reduce the latency, keep the camera for a short time so it does
// not need to be opened again.
if (mCameraDevice != null && mActivity.isSecureCamera()
&& ActivityBase.isFirstStartAfterScreenOn()) {
ActivityBase.resetFirstStartAfterScreenOn();
CameraHolder.instance().keep(KEEP_CAMERA_TIMEOUT);
}
// Reset the focus first. Camera CTS does not guarantee that
// cancelAutoFocus is allowed after preview stops.
if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
mCameraDevice.cancelAutoFocus();
}
stopPreview();
// Close the camera now because other activities may need to use it.
closeCamera();
if (mSurfaceTexture != null) {
((CameraScreenNail) mActivity.mCameraScreenNail).releaseSurfaceTexture();
mSurfaceTexture = null;
}
resetScreenOn();
// Clear UI.
collapseCameraControls();
if (mFaceView != null) mFaceView.clear();
if (mFirstTimeInitialized) {
if (mImageSaver != null) {
mImageSaver.finish();
mImageSaver = null;
mImageNamer.finish();
mImageNamer = null;
}
}
if (mLocationManager != null) mLocationManager.recordLocation(false);
// If we are in an image capture intent and has taken
// a picture, we just clear it in onPause.
mJpegImageData = null;
// Remove the messages in the event queue.
mHandler.removeMessages(SETUP_PREVIEW);
mHandler.removeMessages(FIRST_TIME_INIT);
mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
mHandler.removeMessages(SWITCH_CAMERA);
mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION);
mHandler.removeMessages(CAMERA_OPEN_DONE);
mHandler.removeMessages(START_PREVIEW_DONE);
mHandler.removeMessages(OPEN_CAMERA_FAIL);
mHandler.removeMessages(CAMERA_DISABLED);
mPendingSwitchCameraId = -1;
if (mFocusManager != null) mFocusManager.removeMessages();
}
private void initializeControlByIntent() {
mBlocker = mRootView.findViewById(R.id.blocker);
mMenu = mRootView.findViewById(R.id.menu);
mMenu.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mPieRenderer != null) {
mPieRenderer.showInCenter();
}
}
});
if (mIsImageCaptureIntent) {
mActivity.hideSwitcher();
// Cannot use RotateImageView for "done" and "cancel" button because
// the tablet layout uses RotateLayout, which cannot be cast to
// RotateImageView.
mReviewDoneButton = (Rotatable) mRootView.findViewById(R.id.btn_done);
mReviewCancelButton = (Rotatable) mRootView.findViewById(R.id.btn_cancel);
mReviewRetakeButton = mRootView.findViewById(R.id.btn_retake);
((View) mReviewCancelButton).setVisibility(View.VISIBLE);
((View) mReviewDoneButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onReviewDoneClicked(v);
}
});
((View) mReviewCancelButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onReviewCancelClicked(v);
}
});
mReviewRetakeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onReviewRetakeClicked(v);
}
});
// Not grayed out upon disabled, to make the follow-up fade-out
// effect look smooth. Note that the review done button in tablet
// layout is not a TwoStateImageView.
if (mReviewDoneButton instanceof TwoStateImageView) {
((TwoStateImageView) mReviewDoneButton).enableFilter(false);
}
setupCaptureParams();
}
}
/**
* The focus manager is the first UI related element to get initialized,
* and it requires the RenderOverlay, so initialize it here
*/
private void initializeFocusManager() {
// Create FocusManager object. startPreview needs it.
mRenderOverlay = (RenderOverlay) mRootView.findViewById(R.id.render_overlay);
// if mFocusManager not null, reuse it
// otherwise create a new instance
if (mFocusManager != null) {
mFocusManager.removeMessages();
} else {
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
String[] defaultFocusModes = mActivity.getResources().getStringArray(
R.array.pref_camera_focusmode_default_array);
mFocusManager = new FocusOverlayManager(mPreferences, defaultFocusModes,
mInitialParams, this, mirror,
mActivity.getMainLooper());
}
}
private void initializeMiscControls() {
// startPreview needs this.
mPreviewFrameLayout = (PreviewFrameLayout) mRootView.findViewById(R.id.frame);
// Set touch focus listener.
mActivity.setSingleTapUpListener(mPreviewFrameLayout);
mFaceView = (FaceView) mRootView.findViewById(R.id.face_view);
mPreviewFrameLayout.setOnSizeChangedListener(this);
mPreviewFrameLayout.setOnLayoutChangeListener(mActivity);
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
mPreviewSurfaceView =
(PreviewSurfaceView) mRootView.findViewById(R.id.preview_surface_view);
mPreviewSurfaceView.setVisibility(View.VISIBLE);
mPreviewSurfaceView.getHolder().addCallback(this);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.v(TAG, "onConfigurationChanged");
setDisplayOrientation();
((ViewGroup) mRootView).removeAllViews();
LayoutInflater inflater = mActivity.getLayoutInflater();
inflater.inflate(R.layout.photo_module, (ViewGroup) mRootView);
// from onCreate()
initializeControlByIntent();
initializeFocusManager();
initializeMiscControls();
loadCameraPreferences();
// from initializeFirstTime()
mShutterButton = mActivity.getShutterButton();
mShutterButton.setOnShutterButtonListener(this);
initializeZoom();
initOnScreenIndicator();
updateOnScreenIndicators();
if (mFaceView != null) {
mFaceView.clear();
mFaceView.setVisibility(View.VISIBLE);
mFaceView.setDisplayOrientation(mDisplayOrientation);
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFaceView.resume();
mFocusManager.setFaceView(mFaceView);
}
initializeRenderOverlay();
onFullScreenChanged(mActivity.isInCameraApp());
if (mJpegImageData != null) { // Jpeg data found, picture has been taken.
showPostCaptureAlert();
}
}
@Override
public void onActivityResult(
int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CROP: {
Intent intent = new Intent();
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
intent.putExtras(extras);
}
}
mActivity.setResultEx(resultCode, intent);
mActivity.finish();
File path = mActivity.getFileStreamPath(sTempCropFilename);
path.delete();
break;
}
}
}
private boolean canTakePicture() {
return isCameraIdle() && (mActivity.getStorageSpace() > Storage.LOW_STORAGE_THRESHOLD);
}
@Override
public void autoFocus() {
mFocusStartTime = System.currentTimeMillis();
mCameraDevice.autoFocus(mAutoFocusCallback);
setCameraState(FOCUSING);
}
@Override
public void cancelAutoFocus() {
mCameraDevice.cancelAutoFocus();
setCameraState(IDLE);
setCameraParameters(UPDATE_PARAM_PREFERENCE);
}
// Preview area is touched. Handle touch focus.
@Override
public void onSingleTapUp(View view, int x, int y) {
if (mPaused || mCameraDevice == null || !mFirstTimeInitialized
|| mCameraState == SNAPSHOT_IN_PROGRESS
|| mCameraState == SWITCHING_CAMERA
|| mCameraState == PREVIEW_STOPPED) {
return;
}
// Do not trigger touch focus if popup window is opened.
if (removeTopLevelPopup()) return;
// Check if metering area or focus area is supported.
if (!mFocusAreaSupported && !mMeteringAreaSupported) return;
mFocusManager.onSingleTapUp(x, y);
}
@Override
public boolean onBackPressed() {
if (mPieRenderer != null && mPieRenderer.showsItems()) {
mPieRenderer.hide();
return true;
}
// In image capture mode, back button should:
// 1) if there is any popup, dismiss them, 2) otherwise, get out of image capture
if (mIsImageCaptureIntent) {
if (!removeTopLevelPopup()) {
// no popup to dismiss, cancel image capture
doCancel();
}
return true;
} else if (!isCameraIdle()) {
// ignore backs while we're taking a picture
return true;
} else {
return removeTopLevelPopup();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
onShutterButtonFocus(true);
}
return true;
case KeyEvent.KEYCODE_CAMERA:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
onShutterButtonClick();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
// If we get a dpad center event without any focused view, move
// the focus to the shutter button and press it.
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
// Start auto-focus immediately to reduce shutter lag. After
// the shutter button gets the focus, onShutterButtonFocus()
// will be called again but it is fine.
if (removeTopLevelPopup()) return true;
onShutterButtonFocus(true);
if (mShutterButton.isInTouchMode()) {
mShutterButton.requestFocusFromTouch();
} else {
mShutterButton.requestFocus();
}
mShutterButton.setPressed(true);
}
return true;
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized) {
onShutterButtonFocus(false);
}
return true;
}
return false;
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void closeCamera() {
if (mCameraDevice != null) {
mCameraDevice.setZoomChangeListener(null);
if(ApiHelper.HAS_FACE_DETECTION) {
mCameraDevice.setFaceDetectionListener(null);
}
mCameraDevice.setErrorCallback(null);
CameraHolder.instance().release();
mFaceDetectionStarted = false;
mCameraDevice = null;
setCameraState(PREVIEW_STOPPED);
mFocusManager.onCameraReleased();
}
}
private void setDisplayOrientation() {
mDisplayRotation = Util.getDisplayRotation(mActivity);
mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId);
if (mFaceView != null) {
mFaceView.setDisplayOrientation(mDisplayOrientation);
}
if (mFocusManager != null) {
mFocusManager.setDisplayOrientation(mDisplayOrientation);
}
// GLRoot also uses the DisplayRotation, and needs to be told to layout to update
mActivity.getGLRoot().requestLayoutContentPane();
}
// Only called by UI thread.
private void setupPreview() {
mFocusManager.resetTouchFocus();
startPreview();
setCameraState(IDLE);
startFaceDetection();
}
// This can be called by UI Thread or CameraStartUpThread. So this should
// not modify the views.
private void startPreview() {
mCameraDevice.setErrorCallback(mErrorCallback);
// ICS camera frameworks has a bug. Face detection state is not cleared
// after taking a picture. Stop the preview to work around it. The bug
// was fixed in JB.
if (mCameraState != PREVIEW_STOPPED) stopPreview();
setDisplayOrientation();
if (!mSnapshotOnIdle) {
// If the focus mode is continuous autofocus, call cancelAutoFocus to
// resume it because it may have been paused by autoFocus call.
if (Util.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mFocusManager.getFocusMode())) {
mCameraDevice.cancelAutoFocus();
}
mFocusManager.setAeAwbLock(false); // Unlock AE and AWB.
}
setCameraParameters(UPDATE_PARAM_ALL);
if (ApiHelper.HAS_SURFACE_TEXTURE) {
CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
if (mSurfaceTexture == null) {
Size size = mParameters.getPreviewSize();
if (mCameraDisplayOrientation % 180 == 0) {
screenNail.setSize(size.width, size.height);
} else {
screenNail.setSize(size.height, size.width);
}
screenNail.enableAspectRatioClamping();
mActivity.notifyScreenNailChanged();
screenNail.acquireSurfaceTexture();
mSurfaceTexture = screenNail.getSurfaceTexture();
}
mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation);
mCameraDevice.setPreviewTextureAsync((SurfaceTexture) mSurfaceTexture);
} else {
mCameraDevice.setDisplayOrientation(mDisplayOrientation);
mCameraDevice.setPreviewDisplayAsync(mCameraSurfaceHolder);
}
Log.v(TAG, "startPreview");
mCameraDevice.startPreviewAsync();
mFocusManager.onPreviewStarted();
if (mSnapshotOnIdle) {
mHandler.post(mDoSnapRunnable);
}
}
private void stopPreview() {
if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
Log.v(TAG, "stopPreview");
mCameraDevice.stopPreview();
mFaceDetectionStarted = false;
}
setCameraState(PREVIEW_STOPPED);
if (mFocusManager != null) mFocusManager.onPreviewStopped();
}
@SuppressWarnings("deprecation")
private void updateCameraParametersInitialize() {
// Reset preview frame rate to the maximum because it may be lowered by
// video camera application.
List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
if (frameRates != null) {
Integer max = Collections.max(frameRates);
mParameters.setPreviewFrameRate(max);
}
mParameters.set(Util.RECORDING_HINT, Util.FALSE);
// Disable video stabilization. Convenience methods not available in API
// level <= 14
String vstabSupported = mParameters.get("video-stabilization-supported");
if ("true".equals(vstabSupported)) {
mParameters.set("video-stabilization", "false");
}
}
private void updateCameraParametersZoom() {
// Set zoom.
if (mParameters.isZoomSupported()) {
mParameters.setZoom(mZoomValue);
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void setAutoExposureLockIfSupported() {
if (mAeLockSupported) {
mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock());
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void setAutoWhiteBalanceLockIfSupported() {
if (mAwbLockSupported) {
mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setFocusAreasIfSupported() {
if (mFocusAreaSupported) {
mParameters.setFocusAreas(mFocusManager.getFocusAreas());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setMeteringAreasIfSupported() {
if (mMeteringAreaSupported) {
// Use the same area for focus and metering.
mParameters.setMeteringAreas(mFocusManager.getMeteringAreas());
}
}
private void updateCameraParametersPreference() {
setAutoExposureLockIfSupported();
setAutoWhiteBalanceLockIfSupported();
setFocusAreasIfSupported();
setMeteringAreasIfSupported();
// Set picture size.
String pictureSize = mPreferences.getString(
CameraSettings.KEY_PICTURE_SIZE, null);
if (pictureSize == null) {
CameraSettings.initialCameraPictureSize(mActivity, mParameters);
} else {
List<Size> supported = mParameters.getSupportedPictureSizes();
CameraSettings.setCameraPictureSize(
pictureSize, supported, mParameters);
}
Size size = mParameters.getPictureSize();
// Set a preview size that is closest to the viewfinder height and has
// the right aspect ratio.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size optimalSize = Util.getOptimalPreviewSize(mActivity, sizes,
(double) size.width / size.height);
Size original = mParameters.getPreviewSize();
if (!original.equals(optimalSize)) {
mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
// Zoom related settings will be changed for different preview
// sizes, so set and read the parameters to get latest values
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
// Since changing scene mode may change supported values, set scene mode
// first. HDR is a scene mode. To promote it in UI, it is stored in a
// separate preference.
String hdr = mPreferences.getString(CameraSettings.KEY_CAMERA_HDR,
mActivity.getString(R.string.pref_camera_hdr_default));
if (mActivity.getString(R.string.setting_on_value).equals(hdr)) {
mSceneMode = Util.SCENE_MODE_HDR;
} else {
mSceneMode = mPreferences.getString(
CameraSettings.KEY_SCENE_MODE,
mActivity.getString(R.string.pref_camera_scenemode_default));
}
if (Util.isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
if (!mParameters.getSceneMode().equals(mSceneMode)) {
mParameters.setSceneMode(mSceneMode);
// Setting scene mode will change the settings of flash mode,
// white balance, and focus mode. Here we read back the
// parameters, so we can know those settings.
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
} else {
mSceneMode = mParameters.getSceneMode();
if (mSceneMode == null) {
mSceneMode = Parameters.SCENE_MODE_AUTO;
}
}
// Set JPEG quality.
int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
CameraProfile.QUALITY_HIGH);
mParameters.setJpegQuality(jpegQuality);
// For the following settings, we need to check if the settings are
// still supported by latest driver, if not, ignore the settings.
// Set exposure compensation
int value = CameraSettings.readExposure(mPreferences);
int max = mParameters.getMaxExposureCompensation();
int min = mParameters.getMinExposureCompensation();
if (value >= min && value <= max) {
mParameters.setExposureCompensation(value);
} else {
Log.w(TAG, "invalid exposure range: " + value);
}
if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
// Set flash mode.
String flashMode = mPreferences.getString(
CameraSettings.KEY_FLASH_MODE,
mActivity.getString(R.string.pref_camera_flashmode_default));
List<String> supportedFlash = mParameters.getSupportedFlashModes();
if (Util.isSupported(flashMode, supportedFlash)) {
mParameters.setFlashMode(flashMode);
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = mActivity.getString(
R.string.pref_camera_flashmode_no_flash);
}
}
// Set white balance parameter.
String whiteBalance = mPreferences.getString(
CameraSettings.KEY_WHITE_BALANCE,
mActivity.getString(R.string.pref_camera_whitebalance_default));
if (Util.isSupported(whiteBalance,
mParameters.getSupportedWhiteBalance())) {
mParameters.setWhiteBalance(whiteBalance);
} else {
whiteBalance = mParameters.getWhiteBalance();
if (whiteBalance == null) {
whiteBalance = Parameters.WHITE_BALANCE_AUTO;
}
}
// Set focus mode.
mFocusManager.overrideFocusMode(null);
mParameters.setFocusMode(mFocusManager.getFocusMode());
} else {
mFocusManager.overrideFocusMode(mParameters.getFocusMode());
}
if (mContinousFocusSupported && ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK) {
updateAutoFocusMoveCallback();
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void updateAutoFocusMoveCallback() {
if (mParameters.getFocusMode().equals(Util.FOCUS_MODE_CONTINUOUS_PICTURE)) {
mCameraDevice.setAutoFocusMoveCallback(
(AutoFocusMoveCallback) mAutoFocusMoveCallback);
} else {
mCameraDevice.setAutoFocusMoveCallback(null);
}
}
// We separate the parameters into several subsets, so we can update only
// the subsets actually need updating. The PREFERENCE set needs extra
// locking because the preference can be changed from GLThread as well.
private void setCameraParameters(int updateSet) {
if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
updateCameraParametersInitialize();
}
if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
updateCameraParametersZoom();
}
if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
updateCameraParametersPreference();
}
mCameraDevice.setParameters(mParameters);
}
// If the Camera is idle, update the parameters immediately, otherwise
// accumulate them in mUpdateSet and update later.
private void setCameraParametersWhenIdle(int additionalUpdateSet) {
mUpdateSet |= additionalUpdateSet;
if (mCameraDevice == null) {
// We will update all the parameters when we open the device, so
// we don't need to do anything now.
mUpdateSet = 0;
return;
} else if (isCameraIdle()) {
setCameraParameters(mUpdateSet);
updateSceneModeUI();
mUpdateSet = 0;
} else {
if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
mHandler.sendEmptyMessageDelayed(
SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
}
}
}
private boolean isCameraIdle() {
return (mCameraState == IDLE) ||
((mFocusManager != null) && mFocusManager.isFocusCompleted()
&& (mCameraState != SWITCHING_CAMERA));
}
private boolean isImageCaptureIntent() {
String action = mActivity.getIntent().getAction();
return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)
|| ActivityBase.ACTION_IMAGE_CAPTURE_SECURE.equals(action));
}
private void setupCaptureParams() {
Bundle myExtras = mActivity.getIntent().getExtras();
if (myExtras != null) {
mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
mCropValue = myExtras.getString("crop");
}
}
private void showPostCaptureAlert() {
if (mIsImageCaptureIntent) {
mOnScreenIndicators.setVisibility(View.GONE);
mMenu.setVisibility(View.GONE);
Util.fadeIn((View) mReviewDoneButton);
mShutterButton.setVisibility(View.INVISIBLE);
Util.fadeIn(mReviewRetakeButton);
}
}
private void hidePostCaptureAlert() {
if (mIsImageCaptureIntent) {
mOnScreenIndicators.setVisibility(View.VISIBLE);
mMenu.setVisibility(View.VISIBLE);
Util.fadeOut((View) mReviewDoneButton);
mShutterButton.setVisibility(View.VISIBLE);
Util.fadeOut(mReviewRetakeButton);
}
}
@Override
public void onSharedPreferenceChanged() {
// ignore the events after "onPause()"
if (mPaused) return;
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
setPreviewFrameLayoutAspectRatio();
updateOnScreenIndicators();
}
@Override
public void onCameraPickerClicked(int cameraId) {
if (mPaused || mPendingSwitchCameraId != -1) return;
mPendingSwitchCameraId = cameraId;
if (ApiHelper.HAS_SURFACE_TEXTURE) {
Log.v(TAG, "Start to copy texture. cameraId=" + cameraId);
// We need to keep a preview frame for the animation before
// releasing the camera. This will trigger onPreviewTextureCopied.
((CameraScreenNail) mActivity.mCameraScreenNail).copyTexture();
// Disable all camera controls.
setCameraState(SWITCHING_CAMERA);
} else {
switchCamera();
}
}
private void switchCamera() {
if (mPaused) return;
Log.v(TAG, "Start to switch camera. id=" + mPendingSwitchCameraId);
mCameraId = mPendingSwitchCameraId;
mPendingSwitchCameraId = -1;
mPhotoControl.setCameraId(mCameraId);
// from onPause
closeCamera();
collapseCameraControls();
if (mFaceView != null) mFaceView.clear();
if (mFocusManager != null) mFocusManager.removeMessages();
// Restart the camera and initialize the UI. From onCreate.
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
try {
mCameraDevice = Util.openCamera(mActivity, mCameraId);
mParameters = mCameraDevice.getParameters();
} catch (CameraHardwareException e) {
Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera);
return;
} catch (CameraDisabledException e) {
Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
return;
}
initializeCapabilities();
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFocusManager.setMirror(mirror);
mFocusManager.setParameters(mInitialParams);
setupPreview();
loadCameraPreferences();
initializePhotoControl();
// from initializeFirstTime
initializeZoom();
updateOnScreenIndicators();
showTapToFocusToastIfNeeded();
if (ApiHelper.HAS_SURFACE_TEXTURE) {
// Start switch camera animation. Post a message because
// onFrameAvailable from the old camera may already exist.
mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION);
}
}
@Override
public void onPieOpened(int centerX, int centerY) {
mActivity.cancelActivityTouchHandling();
mActivity.setSwipingEnabled(false);
if (mFaceView != null) {
mFaceView.setBlockDraw(true);
}
}
@Override
public void onPieClosed() {
mActivity.setSwipingEnabled(true);
if (mFaceView != null) {
mFaceView.setBlockDraw(false);
}
}
// Preview texture has been copied. Now camera can be released and the
// animation can be started.
@Override
public void onPreviewTextureCopied() {
mHandler.sendEmptyMessage(SWITCH_CAMERA);
}
@Override
public void onCaptureTextureCopied() {
}
@Override
public void onUserInteraction() {
if (!mActivity.isFinishing()) keepScreenOnAwhile();
}
private void resetScreenOn() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void keepScreenOnAwhile() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
}
// TODO: Delete this function after old camera code is removed
@Override
public void onRestorePreferencesClicked() {
}
@Override
public void onOverriddenPreferencesClicked() {
if (mPaused) return;
if (mNotSelectableToast == null) {
String str = mActivity.getResources().getString(R.string.not_selectable_in_scene_mode);
mNotSelectableToast = Toast.makeText(mActivity, str, Toast.LENGTH_SHORT);
}
mNotSelectableToast.show();
}
private void showTapToFocusToast() {
// TODO: Use a toast?
new RotateTextToast(mActivity, R.string.tap_to_focus, 0).show();
// Clear the preference.
Editor editor = mPreferences.edit();
editor.putBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, false);
editor.apply();
}
private void initializeCapabilities() {
mInitialParams = mCameraDevice.getParameters();
mFocusAreaSupported = Util.isFocusAreaSupported(mInitialParams);
mMeteringAreaSupported = Util.isMeteringAreaSupported(mInitialParams);
mAeLockSupported = Util.isAutoExposureLockSupported(mInitialParams);
mAwbLockSupported = Util.isAutoWhiteBalanceLockSupported(mInitialParams);
mContinousFocusSupported = mInitialParams.getSupportedFocusModes().contains(
Util.FOCUS_MODE_CONTINUOUS_PICTURE);
}
// PreviewFrameLayout size has changed.
@Override
public void onSizeChanged(int width, int height) {
if (mFocusManager != null) mFocusManager.setPreviewSize(width, height);
}
void setPreviewFrameLayoutAspectRatio() {
// Set the preview frame aspect ratio according to the picture size.
Size size = mParameters.getPictureSize();
mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
}
@Override
public boolean needsSwitcher() {
return !mIsImageCaptureIntent;
}
public void showPopup(AbstractSettingPopup popup) {
mActivity.hideUI();
mBlocker.setVisibility(View.INVISIBLE);
setShowMenu(false);
mPopup = popup;
mPopup.setVisibility(View.VISIBLE);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
((FrameLayout) mRootView).addView(mPopup, lp);
}
public void dismissPopup(boolean topPopupOnly) {
dismissPopup(topPopupOnly, true);
}
private void dismissPopup(boolean topOnly, boolean fullScreen) {
if (fullScreen) {
mActivity.showUI();
mBlocker.setVisibility(View.VISIBLE);
}
setShowMenu(fullScreen);
if (mPopup != null) {
((FrameLayout) mRootView).removeView(mPopup);
mPopup = null;
}
mPhotoControl.popupDismissed(topOnly);
}
@Override
public void onShowSwitcherPopup() {
if (mPieRenderer != null && mPieRenderer.showsItems()) {
mPieRenderer.hide();
}
}
}
| false | false | null | null |
diff --git a/galaxyCar/src/org/psywerx/car/GalaxyCarActivity.java b/galaxyCar/src/org/psywerx/car/GalaxyCarActivity.java
index afa62a1..6ed23cb 100644
--- a/galaxyCar/src/org/psywerx/car/GalaxyCarActivity.java
+++ b/galaxyCar/src/org/psywerx/car/GalaxyCarActivity.java
@@ -1,443 +1,455 @@
package org.psywerx.car;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.psywerx.car.bluetooth.BtHelper;
import org.psywerx.car.bluetooth.BtListener;
import org.psywerx.car.bluetooth.DeviceListActivity;
import org.psywerx.car.seekbar.VerticalSeekBar;
import org.psywerx.car.view.PospeskiView;
import org.psywerx.car.view.SteeringWheelView;
import org.psywerx.car.view.StevecView;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Vibrator;
+import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.ToggleButton;
/**
* Main application activity
*
*/
public class GalaxyCarActivity extends Activity implements BtListener {
// Intent request codes
public static final long THREAD_REFRESH_PERIOD = 50;
private static final int REQUEST_CONNECT_DEVICE = 2;
private static final int REQUEST_ENABLE_BT = 3;
private BluetoothAdapter mBluetoothAdapter;
private GLSurfaceView mGlView;
private WakeLock mWakeLock;
private Vibrator mVibrator = null;
private BtHelper mBtHelper;
private VerticalSeekBar mAlphaBar;
private ToggleButton mBluetoothButton;
private ToggleButton mStartButton;
private DataHandler mDataHandler;
private Graph mGraph;
private boolean mRefreshThread = true;
private SteeringWheelView mSteeringWheelView;
private PospeskiView mPospeskiView;
private StevecView mStevecView;
private int mViewMode; // 0 normal 1 gl 2 graph
private GraphicalView mChartViewAll;
private GraphicalView mChartViewTurn;
private GraphicalView mChartViewRevs;
private GraphicalView mChartViewG;
private CarSurfaceViewRenderer mCarSurfaceView;
private RelativeLayout mGraphViewLayout;
private RelativeLayout mGlViewLayout;
private RelativeLayout mNormalViewLayout;
private ToggleButton mAvarageButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get wake lock:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Sandboc lock");
mWakeLock.acquire();
init();
}
/**
* Inits all the components of the application
*/
private void init() {
mViewMode = 0;
setGraphViews();
mAlphaBar = (VerticalSeekBar) findViewById(R.id.alphaBar);
mBluetoothButton = (ToggleButton) findViewById(R.id.bluetoothButton);
mGraphViewLayout = ((RelativeLayout) findViewById(R.id.graphViewLayou));
mGlViewLayout = ((RelativeLayout) findViewById(R.id.glViewLayou));
mNormalViewLayout = ((RelativeLayout) findViewById(R.id.normalViewLayou));
mPospeskiView = (PospeskiView) findViewById(R.id.pospeski);
mStartButton = (ToggleButton) findViewById(R.id.powerButton);
mSteeringWheelView = (SteeringWheelView) findViewById(R.id.steeringWheel);
mStevecView = (StevecView) findViewById(R.id.stevec);
mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mDataHandler = new DataHandler();
mBtHelper = new BtHelper(getApplicationContext(), this, mDataHandler);
mCarSurfaceView = new CarSurfaceViewRenderer(new ModelLoader(this));
mGlView = (GLSurfaceView) findViewById(R.id.glSurface);
if (mGlView == null) {
finish();
return;
}
mGlView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);
mGlView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
mGlView.setRenderer(mCarSurfaceView);
mGlView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
// add data handlers to each view or class
mDataHandler.registerListener(mCarSurfaceView.getCar());
mDataHandler.registerListener(mStevecView);
mDataHandler.registerListener(mSteeringWheelView);
mDataHandler.registerListener(mPospeskiView);
mDataHandler.registerListener(mGraph);
setButtonListeners();
}
/**
* Sends start and stop signals
*/
private void toggleStart() {
if (!mBluetoothButton.isChecked()) {
mStartButton.setChecked(false);
return;
}
if (mStartButton.isChecked()) {
mBtHelper.sendStart();
mVibrator.vibrate(200);
} else {
mBtHelper.sendStop();
mVibrator.vibrate(200);
}
}
/**
* Enables bluetooth if available
*/
private void enableBluetooth() {
if (mBluetoothButton.isChecked()) {
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),
"Bluetooth is not available", Toast.LENGTH_LONG).show();
mBluetoothButton.setChecked(false);
} else if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
Intent serverIntent = new Intent(getApplicationContext(),
DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
} else {
btUnaviable();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
D.dbgv("on result from : " + requestCode + " resultCode "
+ resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getExtras().getString(
DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
mBtHelper.connect(device, false);
startRepaintingThread();
} else {
Toast.makeText(getApplicationContext(),
"Bluetooth is not available", Toast.LENGTH_LONG).show();
mBluetoothButton.setChecked(false);
mBtHelper.stopCar();
}
break;
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
enableBluetooth();
} else {
Toast.makeText(getApplicationContext(),
"Bluetooth is not available", Toast.LENGTH_LONG).show();
mBluetoothButton.setChecked(false);
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
/**
* Switches from full screen opengl/graph views
* to the normal "all in one" view
*/
private void toNormalView() {
D.dbgv("switching to normal view");
switch (mViewMode) {
case 1:
mGlViewLayout.removeView(mGlView);
mNormalViewLayout.addView(mGlView);
findViewById(R.id.backGroundOkvir).bringToFront();
findViewById(R.id.expandGlButton).bringToFront();
findViewById(R.id.expandGraphButton).bringToFront();
findViewById(R.id.alphaBar).bringToFront();
findViewById(R.id.averageButton).bringToFront();
mPospeskiView.bringToFront();
mNormalViewLayout.setVisibility(View.VISIBLE);
mGlViewLayout.setVisibility(View.INVISIBLE);
RelativeLayout.LayoutParams l = new RelativeLayout.LayoutParams(
720, 400);
l.setMargins(530, 40, 0, 0);
mGlView.setLayoutParams(l);
break;
case 2:
mNormalViewLayout.setVisibility(View.VISIBLE);
mGlViewLayout.setVisibility(View.INVISIBLE);
break;
}
mGraphViewLayout.setVisibility(View.INVISIBLE);
mViewMode = 0;
}
/**
* Shows graphs in fullscreen
*/
private void toGraphView() {
D.dbgv("switching to graph view");
mNormalViewLayout.setVisibility(View.INVISIBLE);
mGraphViewLayout.setVisibility(View.VISIBLE);
mGlViewLayout.setVisibility(View.INVISIBLE);
mViewMode = 2;
if(!mBluetoothButton.isChecked()){
Toast.makeText(getApplicationContext(),
"Calculating history...", Toast.LENGTH_SHORT).show();
mDataHandler.setAlpha(mAlphaBar.getProgress());
mDataHandler.setSmoothMode(mAvarageButton.isChecked());
if(mAvarageButton.isChecked())
mGraph.insertWholeHistory(mDataHandler.getWholeHistoryRolingAvg());
else
mGraph.insertWholeHistory(mDataHandler.getWholeHistoryAlpha());
}
}
/**
* Shows opengl view in fullscreen
*/
private void toGLView() {
D.dbgv("switching to gl view " + mGlView.getHeight() + " "
+ mGlView.getWidth());
mGraphViewLayout.setVisibility(View.INVISIBLE);
mNormalViewLayout.removeView(mGlView);
mGlViewLayout.addView(mGlView);
findViewById(R.id.backGroundOkvirGl).bringToFront();
mPospeskiView.bringToFront();
findViewById(R.id.normalViewButton2).bringToFront();
findViewById(R.id.textM).bringToFront();
findViewById(R.id.textMS).bringToFront();
findViewById(R.id.textRPM).bringToFront();
findViewById(R.id.textMn).bringToFront();
findViewById(R.id.textMSn).bringToFront();
findViewById(R.id.textRPMn).bringToFront();
mNormalViewLayout.setVisibility(View.INVISIBLE);
mGlViewLayout.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams l = new RelativeLayout.LayoutParams(1170,
670);
l.setMargins(60, 40, 0, 0);
mGlView.setLayoutParams(l);
mViewMode = 1;
}
@Override
+ public boolean onKeyDown(int keyCode, KeyEvent event) {
+ if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
+ if(mViewMode != 0){
+ toNormalView();
+ return true;
+ }
+ }
+ return super.onKeyDown(keyCode, event);
+ }
+
+ @Override
protected void onStop() {
super.onStop();
btUnaviable();
}
/**
* Called when bluetooth connection is lost
*/
public void btUnaviable() {
mBluetoothButton.setChecked(false);
mBtHelper.reset();
mStartButton.setChecked(false);
mRefreshThread = false;
}
/**
* Adds the graph renderers to their views
*/
private void setGraphViews() {
mGraph = new Graph();
LinearLayout graphAll = (LinearLayout) findViewById(R.id.chart);
mChartViewAll = ChartFactory.getLineChartView(this,
mGraph.getDatasetAll(), mGraph.getRendererAll());
LinearLayout graphTurn = (LinearLayout) findViewById(R.id.chartGL2);
mChartViewTurn = ChartFactory.getLineChartView(this,
mGraph.getDatasetTurn(), mGraph.getRendererTurn());
LinearLayout graphRevs = (LinearLayout) findViewById(R.id.chartGL3);
mChartViewRevs = ChartFactory.getLineChartView(this,
mGraph.getDatasetRevs(), mGraph.getRendererRevs());
LinearLayout graphG = (LinearLayout) findViewById(R.id.chartGL4);
mChartViewG = ChartFactory.getLineChartView(this, mGraph.getDatasetG(),
mGraph.getRendererG());
graphAll.addView((View) mChartViewAll, new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
graphTurn.addView((View) mChartViewTurn, new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
graphRevs.addView((View) mChartViewRevs, new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
graphG.addView((View) mChartViewG, new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
}
/**
* Initializes all the button listeners
*/
private void setButtonListeners() {
mGlView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCarSurfaceView.setNextCameraPosition();
}
});
((Button) findViewById(R.id.expandGlButton))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
toGLView();
}
});
((Button) findViewById(R.id.expandGraphButton))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
toGraphView();
}
});
((Button) findViewById(R.id.normalViewButton))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
toNormalView();
}
});
((Button) findViewById(R.id.normalViewButton2))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
toNormalView();
}
});
mAvarageButton = ((ToggleButton) findViewById(R.id.averageButton));
mAvarageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mDataHandler.setSmoothMode(((ToggleButton) v).isChecked());
mChartViewAll.repaint();
}
});
mStartButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
toggleStart();
}
});
mBluetoothButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
enableBluetooth();
}
});
mAlphaBar
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
mDataHandler.setAlpha(progress);
mChartViewAll.repaint();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
/**
* Repaint thread repaints the pospeski, steeringWheel, stevec and chart
* views
*/
private void startRepaintingThread() {
mRefreshThread = true;
new Thread() {
public void run() {
while (mRefreshThread) {
try {
switch (mViewMode) {
case 0:
Thread.sleep(100);
mPospeskiView.postInvalidate();
mSteeringWheelView.postInvalidate();
mStevecView.postInvalidate();
mChartViewAll.repaint();
break;
case 1:
Thread.sleep(100);
break;
case 2:
Thread.sleep(50);
mChartViewRevs.repaint();
mChartViewTurn.repaint();
mChartViewG.repaint();
break;
default:
Thread.sleep(100);
}
} catch (InterruptedException e) {
}
}
};
}.start();
}
}
| false | false | null | null |
diff --git a/app/models/Rule.java b/app/models/Rule.java
index 71a9972..2a9a9e0 100644
--- a/app/models/Rule.java
+++ b/app/models/Rule.java
@@ -1,67 +1,71 @@
package models;
import java.util.*;
import javax.persistence.*;
import play.db.ebean.*;
import play.data.validation.*;
@Entity
public class Rule extends Model {
-
+
@Id
public Long id;
public Date start;
-
+
public Date finish;
-
+
public static Finder<Long, Rule> find = new Finder<Long, Rule>(Long.class, Rule.class);
-
+
public Rule() {
// TODO Auto-generated constructor stub
}
-
+
public Rule(Date start, Date finish) {
this.start = start;
this.finish = finish;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public Date getFinish() {
return finish;
}
public void setFinish(Date finish) {
this.finish = finish;
}
-
+
// Additional logic
public boolean canVote() {
Date now = new Date();
Date start = this.getStart();
Date finish = this.getFinish();
if (now.after(start) && now.before(finish)) {
return true;
}
else {
return false;
}
}
-
+
+ public String startString() {
+ return start.getDate() + "/" + start.getMonth() + "/" + (start.getYear() + 1900) + " at " + start.getHours() + ":" + start.getMinutes() + ":" + start.getSeconds();
+ }
+
}
\ No newline at end of file
| false | false | null | null |
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.html/src/org/eclipse/birt/report/engine/emitter/html/HTMLReportEmitter.java b/plugins/org.eclipse.birt.report.engine.emitter.html/src/org/eclipse/birt/report/engine/emitter/html/HTMLReportEmitter.java
index 81b96f4fb..83aaa11b0 100644
--- a/plugins/org.eclipse.birt.report.engine.emitter.html/src/org/eclipse/birt/report/engine/emitter/html/HTMLReportEmitter.java
+++ b/plugins/org.eclipse.birt.report.engine.emitter.html/src/org/eclipse/birt/report/engine/emitter/html/HTMLReportEmitter.java
@@ -1,3450 +1,3454 @@
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.emitter.html;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IHTMLActionHandler;
import org.eclipse.birt.report.engine.api.IHTMLImageHandler;
import org.eclipse.birt.report.engine.api.IImage;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.InstanceID;
import org.eclipse.birt.report.engine.api.RenderOptionBase;
import org.eclipse.birt.report.engine.api.impl.Action;
import org.eclipse.birt.report.engine.api.impl.Image;
import org.eclipse.birt.report.engine.api.script.IReportContext;
import org.eclipse.birt.report.engine.content.IBandContent;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IColumn;
import org.eclipse.birt.report.engine.content.IContainerContent;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.content.IDataContent;
import org.eclipse.birt.report.engine.content.IElement;
import org.eclipse.birt.report.engine.content.IForeignContent;
import org.eclipse.birt.report.engine.content.IGroupContent;
import org.eclipse.birt.report.engine.content.IHyperlinkAction;
import org.eclipse.birt.report.engine.content.IImageContent;
import org.eclipse.birt.report.engine.content.ILabelContent;
import org.eclipse.birt.report.engine.content.IListBandContent;
import org.eclipse.birt.report.engine.content.IListGroupContent;
import org.eclipse.birt.report.engine.content.IPageContent;
import org.eclipse.birt.report.engine.content.IReportContent;
import org.eclipse.birt.report.engine.content.IRowContent;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.content.ITableBandContent;
import org.eclipse.birt.report.engine.content.ITableContent;
import org.eclipse.birt.report.engine.content.ITableGroupContent;
import org.eclipse.birt.report.engine.content.ITextContent;
import org.eclipse.birt.report.engine.css.dom.CellMergedStyle;
import org.eclipse.birt.report.engine.css.engine.value.FloatValue;
import org.eclipse.birt.report.engine.css.engine.value.birt.BIRTConstants;
import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants;
import org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter;
import org.eclipse.birt.report.engine.emitter.IEmitterServices;
import org.eclipse.birt.report.engine.emitter.html.util.HTMLEmitterUtil;
import org.eclipse.birt.report.engine.executor.ExecutionContext.ElementExceptionInfo;
import org.eclipse.birt.report.engine.executor.css.HTMLProcessor;
import org.eclipse.birt.report.engine.i18n.EngineResourceHandle;
import org.eclipse.birt.report.engine.i18n.MessageConstants;
import org.eclipse.birt.report.engine.ir.DimensionType;
import org.eclipse.birt.report.engine.ir.EngineIRConstants;
import org.eclipse.birt.report.engine.ir.MasterPageDesign;
import org.eclipse.birt.report.engine.ir.Report;
import org.eclipse.birt.report.engine.ir.SimpleMasterPageDesign;
import org.eclipse.birt.report.engine.ir.TemplateDesign;
import org.eclipse.birt.report.engine.parser.TextParser;
import org.eclipse.birt.report.engine.presentation.ContentEmitterVisitor;
import org.eclipse.birt.report.model.api.IResourceLocator;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.core.IModuleModel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.css.CSSPrimitiveValue;
import org.w3c.dom.css.CSSValue;
import com.ibm.icu.util.ULocale;
/**
* <code>HTMLReportEmitter</code> is a subclass of
* <code>ContentEmitterAdapter</code> that implements IContentEmitter
* interface to output IARD Report ojbects to HTML file.
*
* <br>
* Metadata information:<br>
* <table border="solid;1px">
* <tr>
* <td rowspan="2">Item</td>
* <td colspan="2">Output position</td>
* </tr>
* <tr>
* <td>EnableMetadata=true</td>
* <td>EnableMetadata=false</td>
* </tr>
* <tr>
* <td>Container</td>
* <td>On self</td>
* <td>On self</td>
* <tr>
* <td>Table</td>
* <td>On self</td>
* <td>On self</td>
* </tr>
* <tr>
* <td>Image</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* <tr>
* <td>Chart</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* <tr>
* <td>Foreign</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* <tr>
* <td>Label</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* <tr>
* <td>Template Items( including template table, template label, etc.)</td>
* <td>On container( for select handle )</td>
* <td>Only bookmark is output on self</td>
* </tr>
* </table>
*
*/
public class HTMLReportEmitter extends ContentEmitterAdapter
{
/**
* the output format
*/
public static final String OUTPUT_FORMAT_HTML = "HTML"; //$NON-NLS-1$
/**
* the default target report file name
*/
public static final String REPORT_FILE = "report.html"; //$NON-NLS-1$
/**
* the default image folder
*/
public static final String IMAGE_FOLDER = "image"; //$NON-NLS-1$
/**
* output stream
*/
protected OutputStream out = null;
/**
* the report content
*/
protected IReportContent report;
/**
* the report runnable instance
*/
protected IReportRunnable runnable;
/**
* the render options
*/
protected IRenderOption renderOption;
/**
* should output the page header & footer
*/
protected boolean outputMasterPageContent = true;
/**
* specifies if the HTML output is embeddable
*/
protected boolean isEmbeddable = false;
/**
* the url encoding
*/
protected String urlEncoding = null;
/**
* should we output the report as Right To Left
*/
protected boolean htmlRtLFlag = false;
protected boolean pageFooterFloatFlag = true;
protected boolean enableMetadata = false;
protected List ouputInstanceIDs = null;
/**
* specified the current page number, starting from 0
*/
protected int pageNo = 0;
/**
* the <code>HTMLWriter<code> object that is used to output HTML content
*/
protected HTMLWriter writer;
/**
* the context used to execute the report
*/
protected IReportContext reportContext;
/**
* indicates that the styled element is hidden or not
*/
protected Stack stack = new Stack( );
/**
* An Log object that <code>HTMLReportEmitter</code> use to log the error,
* debug, information messages.
*/
protected static Logger logger = Logger.getLogger( HTMLReportEmitter.class
.getName( ) );
/**
* html image handler
*/
protected IHTMLImageHandler imageHandler;
/**
* html action handler
*/
protected IHTMLActionHandler actionHandler;
/**
* emitter services
*/
protected IEmitterServices services;
/**
* The <code>tagStack</code> that stores the tag names to be closed in
* <code>endContainer()</code>.
*/
private Stack tagStack = new Stack( );
/**
* display type of Block
*/
protected static final int DISPLAY_BLOCK = 1;
/**
* display type of Inline
*/
protected static final int DISPLAY_INLINE = 2;
/**
* display type of Inline-Block
*/
protected static final int DISPLAY_INLINE_BLOCK = 4;
/**
* display type of none
*/
protected static final int DISPLAY_NONE = 8;
/**
* display flag which contains all display types
*/
protected static final int DISPLAY_FLAG_ALL = 0xffff;
/**
* content visitor that is used to handle page header/footer
*/
protected ContentEmitterVisitor contentVisitor;
private MetadataEmitter metadataEmitter;
private IDGenerator idGenerator = new IDGenerator( );
static HashMap borderStyleMap = null;
static
{
borderStyleMap = new HashMap( );
borderStyleMap.put( CSSConstants.CSS_NONE_VALUE, new Integer( 0 ) );
borderStyleMap.put( CSSConstants.CSS_INSET_VALUE, new Integer( 1 ) );
borderStyleMap.put( CSSConstants.CSS_GROOVE_VALUE, new Integer( 2 ) );
borderStyleMap.put( CSSConstants.CSS_OUTSET_VALUE, new Integer( 3 ) );
borderStyleMap.put( CSSConstants.CSS_RIDGE_VALUE, new Integer( 4 ) );
borderStyleMap.put( CSSConstants.CSS_DOTTED_VALUE, new Integer( 5 ) );
borderStyleMap.put( CSSConstants.CSS_DASHED_VALUE, new Integer( 6 ) );
borderStyleMap.put( CSSConstants.CSS_SOLID_VALUE, new Integer( 7 ) );
borderStyleMap.put( CSSConstants.CSS_DOUBLE_VALUE, new Integer( 8 ) );
}
/**
* record the leaf cell
*/
private ICellContent leafCell;
/**
* record the leaf cell is filled or not.
*/
private boolean cellFilled = false;
/**
* the constructor
*/
public HTMLReportEmitter( )
{
contentVisitor = new ContentEmitterVisitor( this );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#initialize(org.eclipse.birt.report.engine.emitter.IEmitterServices)
*/
public void initialize( IEmitterServices services )
{
this.services = services;
Object fd = services.getOption( RenderOptionBase.OUTPUT_FILE_NAME );
File file = null;
try
{
if ( fd != null )
{
file = new File( fd.toString( ) );
File parent = file.getParentFile( );
if ( parent != null && !parent.exists( ) )
{
parent.mkdirs( );
}
out = new BufferedOutputStream( new FileOutputStream( file ) );
}
}
catch ( FileNotFoundException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
}
if ( out == null )
{
Object value = services.getOption( RenderOptionBase.OUTPUT_STREAM );
if ( value != null && value instanceof OutputStream )
{
out = (OutputStream) value;
}
else
{
try
{
// FIXME
file = new File( REPORT_FILE );
out = new BufferedOutputStream( new FileOutputStream( file ) );
}
catch ( FileNotFoundException e )
{
// FIXME
logger.log( Level.SEVERE, e.getMessage( ), e );
}
}
}
Object emitterConfig = services.getEmitterConfig( ).get( "html" ); //$NON-NLS-1$
if ( emitterConfig != null
&& emitterConfig instanceof HTMLEmitterConfig )
{
imageHandler = ( (HTMLEmitterConfig) emitterConfig )
.getImageHandler( );
actionHandler = ( (HTMLEmitterConfig) emitterConfig )
.getActionHandler( );
}
Object im = services.getOption( HTMLRenderOption.IMAGE_HANDLER );
if ( im != null && im instanceof IHTMLImageHandler )
{
imageHandler = (IHTMLImageHandler) im;
}
Object ac = services.getOption( HTMLRenderOption.ACTION_HANDLER );
if ( ac != null && ac instanceof IHTMLActionHandler )
{
actionHandler = (IHTMLActionHandler) ac;
}
reportContext = services.getReportContext( );
renderOption = services.getRenderOption( );
runnable = services.getReportRunnable( );
writer = new HTMLWriter( );
if ( renderOption != null )
{
HTMLRenderOption htmlOption = new HTMLRenderOption( renderOption );
isEmbeddable = htmlOption.getEmbeddable( );
HashMap options = renderOption.getOutputSetting( );
if ( options != null )
{
urlEncoding = (String) options
.get( HTMLRenderOption.URL_ENCODING );
}
outputMasterPageContent = htmlOption.getMasterPageContent( );
IHTMLActionHandler actHandler = htmlOption.getActionHandle( );
if ( ac != null )
{
actionHandler = actHandler;
}
pageFooterFloatFlag = htmlOption.getPageFooterFloatFlag( );
htmlRtLFlag = htmlOption.getHtmlRtLFlag( );
enableMetadata = htmlOption.getEnableMetadata( );
ouputInstanceIDs = htmlOption.getInstanceIDs( );
metadataEmitter = new MetadataEmitter( writer, htmlOption, idGenerator );
}
}
/**
* @return the <code>Report</code> object.
*/
public IReportContent getReport( )
{
return report;
}
/**
* Pushes the Boolean indicating whether or not the item is hidden according
* to the style
*
* @param style
*/
public void push( IStyle style )
{
stack.push( new Boolean( peek( style ) ) );
}
/**
* Pops the element of the stack
*
* @return the boolean indicating whether or not the item is hidden
*/
public boolean pop( )
{
return ( (Boolean) stack.pop( ) ).booleanValue( );
}
/**
* Peeks the element of stack
*
* @param style
* @return the boolean indicating whether or not the item is hidden
*/
public boolean peek( IStyle style )
{
boolean isHidden = false;
if ( !stack.empty( ) )
{
isHidden = ( (Boolean) stack.peek( ) ).booleanValue( );
}
if ( !isHidden )
{
String formats = style.getVisibleFormat( );
if ( formats != null
&& ( formats.indexOf( EngineIRConstants.FORMAT_TYPE_VIEWER ) >= 0 || formats
.indexOf( BIRTConstants.BIRT_ALL_VALUE ) >= 0 ) )
{
isHidden = true;
}
}
return isHidden;
}
/**
* Checks if the current item is hidden
*
* @return a boolean value
*/
public boolean isHidden( )
{
return ( (Boolean) stack.peek( ) ).booleanValue( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#getOutputFormat()
*/
public String getOutputFormat( )
{
return OUTPUT_FORMAT_HTML;
}
/**
* Fixes a PNG problem related to transparency. See
* http://homepage.ntlworld.com/bobosola/ for detail.
*/
protected void fixTransparentPNG( )
{
writer.writeCode( "<!--[if gte IE 5.5000]>" ); //$NON-NLS-1$
writer
.writeCode( " <script language=\"JavaScript\"> var ie55up = true </script>" ); //$NON-NLS-1$
writer.writeCode( "<![endif]-->" ); //$NON-NLS-1$
writer.writeCode( "<script language=\"JavaScript\">" ); //$NON-NLS-1$
writer
.writeCode( " function fixPNG(myImage) // correctly handle PNG transparency in Win IE 5.5 or higher." ); //$NON-NLS-1$
writer.writeCode( " {" ); //$NON-NLS-1$
writer.writeCode( " if (window.ie55up)" ); //$NON-NLS-1$
writer.writeCode( " {" ); //$NON-NLS-1$
writer
.writeCode( " var imgID = (myImage.id) ? \"id='\" + myImage.id + \"' \" : \"\"" ); //$NON-NLS-1$
writer
.writeCode( " var imgClass = (myImage.className) ? \"class='\" + myImage.className + \"' \" : \"\"" ); //$NON-NLS-1$
writer
.writeCode( " var imgTitle = (myImage.title) ? \"title='\" + myImage.title + \"' \" : \"title='\" + myImage.alt + \"' \"" ); //$NON-NLS-1$
writer
.writeCode( " var imgStyle = \"display:inline-block;\" + myImage.style.cssText" ); //$NON-NLS-1$
writer
.writeCode( " var strNewHTML = \"<span \" + imgID + imgClass + imgTitle" ); //$NON-NLS-1$
writer
.writeCode( " strNewHTML += \" style=\\\"\" + \"width:\" + myImage.width + \"px; height:\" + myImage.height + \"px;\" + imgStyle + \";\"" ); //$NON-NLS-1$
writer
.writeCode( " strNewHTML += \"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader\"" ); //$NON-NLS-1$
writer
.writeCode( " strNewHTML += \"(src=\\'\" + myImage.src + \"\\', sizingMethod='scale');\\\"></span>\"" ); //$NON-NLS-1$
writer.writeCode( " myImage.outerHTML = strNewHTML" ); //$NON-NLS-1$
writer.writeCode( " }" ); //$NON-NLS-1$
writer.writeCode( " }" ); //$NON-NLS-1$
writer.writeCode( "</script>" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#start(org.eclipse.birt.report.engine.content.IReportContent)
*/
public void start( IReportContent report )
{
logger.log( Level.FINE, "[HTMLReportEmitter] Start emitter." ); //$NON-NLS-1$
this.report = report;
writer.open( out, "UTF-8" ); //$NON-NLS-1$
// If it is the body style and htmlRtLFlag has been set true,
// remove the text-align included in the style.
if ( htmlRtLFlag )
{
String reportStyleName = report == null ? null : report.getDesign( )
.getRootStyleName( );
if ( reportStyleName != null )
{
IStyle style = report.findStyle( reportStyleName );
//style.removeProperty( "text-align" );
style.setTextAlign( "right" );
}
}
if ( isEmbeddable )
{
fixTransparentPNG( );
writer.openTag( HTMLTags.TAG_DIV );
String reportStyleName = report == null ? null : report.getDesign( )
.getRootStyleName( );
if ( reportStyleName != null )
{
IStyle style = report.findStyle( reportStyleName );
StringBuffer styleBuffer = new StringBuffer( );
AttributeBuilder.buildStyle( styleBuffer, style, this, false );
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
return;
}
writer.startWriter( );
writer.openTag( HTMLTags.TAG_HTML );
writer.openTag( HTMLTags.TAG_HEAD );
// write the title of the report in html.
Report reportDesign = null;
if ( report != null )
{
reportDesign = report.getDesign( );
ReportDesignHandle designHandle = reportDesign.getReportDesign( );
String title = designHandle.getStringProperty( IModuleModel.TITLE_PROP );
if ( title == null )
{
// set the default title
if ( renderOption != null )
{
HTMLRenderOption htmlOption = new HTMLRenderOption(
renderOption );
title = htmlOption.getHtmlTitle( );
}
}
if ( title != null )
{
writer.openTag( HTMLTags.TAG_TITLE );
writer.text( title );
writer.closeTag( HTMLTags.TAG_TITLE );
}
}
writer.openTag( HTMLTags.TAG_META );
writer.attribute( HTMLTags.ATTR_HTTP_EQUIV, "Content-Type" ); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_CONTENT, "text/html; charset=UTF-8" ); //$NON-NLS-1$
writer.closeNoEndTag( );
writer.openTag( HTMLTags.TAG_STYLE );
writer.attribute( HTMLTags.ATTR_TYPE, "text/css" ); //$NON-NLS-1$
IStyle style;
StringBuffer styleBuffer = new StringBuffer( );
if ( report == null )
{
logger.log( Level.WARNING,
"[HTMLReportEmitter] Report object is null." ); //$NON-NLS-1$
}
else
{
Map styles = reportDesign.getStyles( );
Iterator iter = styles.entrySet( ).iterator( );
while ( iter.hasNext( ) )
{
Map.Entry entry = (Map.Entry) iter.next( );
String styleName = (String) entry.getKey( );
style = (IStyle) entry.getValue( );
styleBuffer.setLength( 0 );
AttributeBuilder.buildStyle( styleBuffer, style, this, true );
writer.style( styleName, styleBuffer.toString( ), false );
}
}
writer.closeTag( HTMLTags.TAG_STYLE );
fixTransparentPNG( );
writer.closeTag( HTMLTags.TAG_HEAD );
String reportStyleName = report == null ? null : report.getDesign( )
.getRootStyleName( );
writer.openTag( HTMLTags.TAG_BODY );
if ( reportStyleName != null )
{
writer.attribute( HTMLTags.ATTR_CLASS, reportStyleName );
}
}
private void appendErrorMessage(EngineResourceHandle rc, int index, ElementExceptionInfo info )
{
writer.writeCode( " <div>" );
writer.writeCode( " <div id=\"error_title\" style=\"text-decoration:underline\">" );
String name = info.getName( );
if ( name != null )
{
writer.text( rc.getMessage( MessageConstants.REPORT_ERROR_MESSAGE,
new Object[]{info.getType( ), name } ), false );
}
else
{
writer.text( rc.getMessage( MessageConstants.REPORT_ERROR_MESSAGE_WITH_ID,
new Object[]{info.getType( ), info.getID( ) } ), false );
}
writer.writeCode( "</div>" );//$NON-NLS-1$
ArrayList errorList = info.getErrorList( );
ArrayList countList = info.getCountList( );
for ( int i = 0; i < errorList.size( ); i++ )
{
String errorId = "document.getElementById('error_detail" + index + "_" + i + "')";
String errorIcon = "document.getElementById('error_icon" + index + "_" + i + "')";
String onClick = "if (" + errorId + ".style.display == 'none') { "
+ errorIcon + ".innerHTML = '- '; " + errorId
+ ".style.display = 'block'; }" + "else { " + errorIcon
+ ".innerHTML = '+ '; " + errorId + ".style.display = 'none'; }";
writer.writeCode("<div>");
BirtException ex = (BirtException) errorList.get( i );
writer.writeCode( "<span id=\"error_icon" + index + "_" + i
+ "\" style=\"cursor:pointer\" onclick=\"" + onClick
+ "\" > + </span>" );
writer.text( ex.getLocalizedMessage( ) );
writer.writeCode( " <pre id=\"error_detail" + index + "_" + i //$NON-NLS-1$
+ "\" style=\"display:none;\" >" );//$NON-NLS-1$
String messageTitle = rc.getMessage(
MessageConstants.REPORT_ERROR_ID, new Object[]{
ex.getErrorCode( ) ,
countList.get( i )} );
String detailTag = rc
.getMessage( MessageConstants.REPORT_ERROR_DETAIL );
String messageBody = getDetailMessage( ex );
boolean indent = writer.isIndent( );
writer.setIndent( false );
writer.text( messageTitle, false );
writer.writeCode( "\r\n" );//$NON-NLS-1$
writer.text( detailTag, false );
writer.text( messageBody, false );
writer.setIndent( indent );
writer.writeCode( " </pre>" ); //$NON-NLS-1$
writer.writeCode("</div>");
}
writer.writeCode( "</div>" ); //$NON-NLS-1$
writer.writeCode( "<br>" ); //$NON-NLS-1$
}
private String getDetailMessage( Throwable t )
{
StringWriter out = new StringWriter( );
PrintWriter print = new PrintWriter( out );
try
{
t.printStackTrace( print );
}
catch ( Throwable ex )
{
}
print.flush( );
return out.getBuffer( ).toString( );
}
protected boolean outputErrors( List errors )
{
// Outputs the error message at the end of the report
if ( errors != null && !errors.isEmpty( ) )
{
writer.writeCode( " <hr style=\"color:red\"/>" );
writer.writeCode( " <div style=\"color:red\">" );
writer.writeCode( " <div>" );
Locale locale = reportContext.getLocale( );
if(locale==null)
{
locale = Locale.getDefault();
}
EngineResourceHandle rc = new EngineResourceHandle( ULocale.forLocale(locale) );
writer.text( rc.getMessage(
MessageConstants.ERRORS_ON_REPORT_PAGE ), false );
writer.writeCode( "</div>" );//$NON-NLS-1$
writer.writeCode( "<br>") ;//$NON-NLS-1$
Iterator it = errors.iterator( );
int index = 0;
while ( it.hasNext( ) )
{
appendErrorMessage(rc, index++, (ElementExceptionInfo) it.next( ) );
}
writer.writeCode( "</div>" );
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#end(org.eclipse.birt.report.engine.content.IReportContent)
*/
public void end( IReportContent report )
{
logger.log( Level.FINE, "[HTMLReportEmitter] End body." ); //$NON-NLS-1$
if ( report != null )
{
List errors = report.getErrors( );
if ( errors != null && !errors.isEmpty( ) )
{
outputErrors( errors );
}
}
if ( !isEmbeddable )
{
writer.closeTag( HTMLTags.TAG_BODY );
writer.closeTag( HTMLTags.TAG_HTML );
}
else
{
writer.closeTag( HTMLTags.TAG_DIV );
}
writer.endWriter( );
writer.close( );
if ( out != null )
{
try
{
out.close( );
}
catch ( IOException e )
{
logger.log( Level.WARNING, e.getMessage( ), e );
}
}
}
/***
* output the style of page header/footer/body.
* The background style will not be out put.
* @param styleName name of the style
* @param style style object
*/
public void buildPageStyle( String styleName, IStyle style, StringBuffer styleBuffer )
{
if ( isEmbeddable )
{
AttributeBuilder.buildPageStyle( styleBuffer, style, this );
}
else
{
IStyle classStyle = report.findStyle( styleName );
AttributeBuilder.buildPageStyle( styleBuffer, classStyle, this );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startPage(org.eclipse.birt.report.engine.content.IPageContent)
*/
public void startPage( IPageContent page )
{
pageNo++;
if ( pageNo > 1 && outputMasterPageContent == false )
{
writer.openTag( "hr" );
writer.closeTag( "hr" );
}
// out put the page tag
writer.openTag( HTMLTags.TAG_DIV );
// out put the background and width
if ( page != null )
{
Object genBy = page.getGenerateBy( );
if ( genBy instanceof MasterPageDesign )
{
MasterPageDesign masterPage = (MasterPageDesign) genBy;
String masterPageStyleName = masterPage.getStyleName( );
IStyle classStyle = report.findStyle( masterPageStyleName );
StringBuffer styleBuffer = new StringBuffer( );
// build the background
AttributeBuilder.buildBackgroundStyle( styleBuffer, classStyle, this );
// build the width
styleBuffer.append( " width:" + masterPage.getPageWidth( ).toString( ) + ";");
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
}
if ( htmlRtLFlag )
{
writer.attribute( HTMLTags.ATTR_HTML_DIR, "RTL" );
}
if ( pageNo > 1 )
{
writer.attribute( HTMLTags.ATTR_STYLE, "page-break-before: always;" );
}
//output page header
if ( page != null )
{
if ( outputMasterPageContent )
{
// output DIV for page header
boolean showHeader = true;
Object genBy = page.getGenerateBy( );
if ( genBy instanceof SimpleMasterPageDesign )
{
SimpleMasterPageDesign masterPage = (SimpleMasterPageDesign) genBy;
if ( !masterPage.isShowHeaderOnFirst( ) )
{
if ( page.getPageNumber( ) == 1 )
{
showHeader = false;
}
}
}
if ( showHeader )
{
writer.openTag( HTMLTags.TAG_DIV );
//build page header style
StringBuffer styleBuffer = new StringBuffer( );
buildPageStyle( page.getPageHeader( ).getStyleClass( ),
page.getPageHeader( ).getStyle( ),
styleBuffer);
// //build page header margin
// if( genBy instanceof SimpleMasterPageDesign )
// {
// SimpleMasterPageDesign SimpleMasterPage = (SimpleMasterPageDesign) genBy;
// if( null != SimpleMasterPage )
// {
// styleBuffer.append( "margin-left: " + SimpleMasterPage.getLeftMargin( ).toString( ) + ";");
// styleBuffer.append( "margin-top: " + SimpleMasterPage.getTopMargin( ).toString( ) + ";");
// styleBuffer.append( "margin-right: " + SimpleMasterPage.getRightMargin( ).toString( ) + ";");
// }
// }
// else if ( genBy instanceof MasterPageDesign )
// {
// MasterPageDesign masterPage = (MasterPageDesign) genBy;
// if( null != masterPage )
// {
// styleBuffer.append( "margin-left: " + masterPage.getLeftMargin( ).toString( ) + ";");
// styleBuffer.append( "margin-top: " + masterPage.getTopMargin( ).toString( ) + ";");
// styleBuffer.append( "margin-right: " + masterPage.getRightMargin( ).toString( ) + ";");
// }
// }
//output the page header attribute
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
contentVisitor.visitChildren( page.getPageHeader( ), null );
// close the page header
writer.closeTag( HTMLTags.TAG_DIV );
}
}
}
// start output the page body , with the body style
writer.openTag( HTMLTags.TAG_DIV );
if ( page != null )
{
IContent pageBody = page.getPageBody( );
IStyle bodyStyle = pageBody.getStyle( );
String bodyStyleName = pageBody.getStyleClass( );
Object genBy = page.getGenerateBy( );
if ( genBy instanceof MasterPageDesign )
{
MasterPageDesign masterPage = (MasterPageDesign) genBy;
StringBuffer styleBuffer = new StringBuffer( );
if ( isEmbeddable )
{
AttributeBuilder.buildPageStyle( styleBuffer, bodyStyle, this );
}
else
{
IStyle classStyle = report.findStyle( bodyStyleName );
AttributeBuilder.buildPageStyle( styleBuffer, classStyle, this );
}
if( !pageFooterFloatFlag )
{
AttributeBuilder.buildSize( styleBuffer,
HTMLTags.ATTR_MIN_HEIGHT,
masterPage.getPageHeight( ) );
}
// //output page body margin
// styleBuffer.append( "margin-left: " + masterPage.getLeftMargin( ).toString( ) + ";");
// styleBuffer.append( "margin-right: " + masterPage.getRightMargin( ).toString( ) + ";");
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endPage(org.eclipse.birt.report.engine.content.IPageContent)
*/
public void endPage( IPageContent page )
{
logger.log( Level.FINE, "[HTMLReportEmitter] End page." ); //$NON-NLS-1$
//close the page body (DIV)
writer.closeTag( HTMLTags.TAG_DIV );
//output page footer
if ( page != null )
{
if ( outputMasterPageContent )
{
boolean showFooter = true;
Object genBy = page.getGenerateBy( );
if ( genBy instanceof SimpleMasterPageDesign )
{
SimpleMasterPageDesign masterPage = (SimpleMasterPageDesign) genBy;
if ( !masterPage.isShowFooterOnLast( ) )
{
long totalPage = page.getPageNumber( );
IReportContent report = page.getReportContent( );
if ( report != null )
{
totalPage = report.getTotalPage( );
}
if ( page.getPageNumber( ) == totalPage)
{
showFooter = false;
}
}
}
if ( showFooter )
{
// start output the page footer
writer.openTag( HTMLTags.TAG_DIV );
//build page footer style
StringBuffer styleBuffer = new StringBuffer( );
buildPageStyle( page.getPageHeader( ).getStyleClass( ),
page.getPageHeader( ).getStyle( ),
styleBuffer);
// //build page footer margin
// if( genBy instanceof SimpleMasterPageDesign )
// {
// SimpleMasterPageDesign SimpleMasterPage = (SimpleMasterPageDesign) genBy;
// if( null != SimpleMasterPage )
// {
// styleBuffer.append( "margin-left: " + SimpleMasterPage.getLeftMargin( ).toString( ) + ";");
// styleBuffer.append( "margin-right: " + SimpleMasterPage.getRightMargin( ).toString( ) + ";");
// styleBuffer.append( "margin-bottom: " + SimpleMasterPage.getBottomMargin( ).toString( ) + ";");
// }
// }
// else if ( genBy instanceof MasterPageDesign )
// {
// MasterPageDesign masterPage = (MasterPageDesign) genBy;
// if( null != masterPage )
// {
// styleBuffer.append( "margin-left: " + masterPage.getLeftMargin( ).toString( ) + ";");
// styleBuffer.append( "margin-right: " + masterPage.getRightMargin( ).toString( ) + ";");
// styleBuffer.append( "margin-bottom: " + masterPage.getBottomMargin( ).toString( ) + ";");
// }
// }
//output the page footer attribute
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
contentVisitor.visitChildren( page.getPageFooter( ), null );
// close the page footer
writer.closeTag( HTMLTags.TAG_DIV );
}
}
}
// close the page tag ( DIV )
writer.closeTag( HTMLTags.TAG_DIV );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTable(org.eclipse.birt.report.engine.content.ITableContent)
*/
public void startTable( ITableContent table )
{
assert table != null;
if ( enableMetadata )
{
metadataEmitter.startWrapTable( table );
}
IStyle mergedStyle = table.getStyle( );
push( mergedStyle );
if ( isHidden( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLTableEmitter] Start table" ); //$NON-NLS-1$
DimensionType x = table.getX( );
DimensionType y = table.getY( );
StringBuffer styleBuffer = new StringBuffer( );
addDefaultTableStyles( styleBuffer );
writer.openTag( HTMLTags.TAG_TABLE );
// style string
setStyleName( table.getStyleClass( ) );
int display = checkElementType( x, y, mergedStyle, styleBuffer );
setDisplayProperty( display, DISPLAY_INLINE, styleBuffer );
handleShrink( DISPLAY_BLOCK, mergedStyle, table.getHeight( ), table
.getWidth( ), styleBuffer );
- //build the table-layout
- if( null != table.getWidth( ))
+ // build the table-layout
+ DimensionType tableWidth = table.getWidth( );
+ if ( null != tableWidth )
{
- styleBuffer.append( " table-layout:fixed;" );
+ if ( !DimensionType.UNITS_PERCENTAGE.equals( tableWidth.getUnits( ) ) )
+ {
+ styleBuffer.append( " table-layout:fixed;" );
+ }
}
handleStyle( table, styleBuffer );
// bookmark
String bookmark = table.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
table.setBookmark( bookmark );
}
HTMLEmitterUtil.setBookmark( writer, null, bookmark );
// Add it to active id list, and output type ��iid to html
HTMLEmitterUtil.setActiveIDTypeIID(writer, ouputInstanceIDs, table);
// table caption
String caption = table.getCaption( );
if ( caption != null && caption.length( ) > 0 )
{
writer.openTag( HTMLTags.TAG_CAPTION );
writer.text( caption );
writer.closeTag( HTMLTags.TAG_CAPTION );
}
// include select handle table
if ( enableMetadata )
{
metadataEmitter.startTable( table );
}
writeColumns( table );
}
protected void writeColumns( ITableContent table )
{
int widthArraySize = table.getColumnCount( );
DimensionType widthArray[] = new DimensionType[ widthArraySize ];
// put all the column width into the array.
for ( int i = 0; i < table.getColumnCount( ); i++ )
{
IColumn column = table.getColumn( i );
if ( isColumnHidden( column ) )
{
widthArray[ i ] = new DimensionType( 0, DimensionType.UNITS_IN );
continue;
}
DimensionType value = column.getWidth( );
if( null != value )
{
widthArray[ i ] = new DimensionType( value.getMeasure( ), value.getUnits( ) );
}
else
{
widthArray[ i ] = null ;
}
}
// resize the column width
resizeWidth( widthArray, widthArraySize );
//write the columns
for ( int i = 0; i < table.getColumnCount( ); i++ )
{
IColumn column = table.getColumn( i );
if ( isColumnHidden( column ) )
{
continue;
}
writer.openTag( HTMLTags.TAG_COL );
setStyleName( column.getStyleClass( ) );
// width
StringBuffer styleBuffer = new StringBuffer( );
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_WIDTH,
widthArray[ i ] );
if ( isEmbeddable )
{
// output in-line style
String styleName = column.getStyleClass( );
if ( styleName != null )
{
IStyle style = report.findStyle( styleName );
if ( style != null )
{
AttributeBuilder.buildStyle( styleBuffer, style, this );
}
}
}
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
if ( enableMetadata )
{
// Instance ID
InstanceID iid = column.getInstanceID( );
if ( iid != null )
{
writer.attribute( "iid", iid.toString( ) );
}
}
writer.closeNoEndTag( );
}
}
/**
* Resize the columns' width.
* All the fixed value won't be changed. All the null value will be reset to a percentage
* value. If the percentage value existing, the sum of all the percentage value will be 100%.
* @param widthArray: array to store the solumn width
* @param size: the size of the array widthArray
* @return
*/
private void resizeWidth( DimensionType widthArray[], int size )
{
double percentSum = 0;//the sum of the origin percentage values.
int NullNum = 0;//the number of the null values.
for ( int i = 0; i < size; i++ )
{
if( null == widthArray[ i ] )
{
NullNum++;
}
else if( DimensionType.UNITS_PERCENTAGE.equals( widthArray[ i ].getUnits( ) ) )
{
percentSum += widthArray[ i ].getMeasure( );
}
}
for ( int i = 0; i < size; i++ )
{
if( null == widthArray[ i ] )
{
if( percentSum >= 100 )
{
widthArray[ i ] = new DimensionType( 0, DimensionType.UNITS_PERCENTAGE );
}
else
{
widthArray[ i ] = new DimensionType( ((100 - percentSum) / NullNum), DimensionType.UNITS_PERCENTAGE );
}
}
else if( DimensionType.UNITS_PERCENTAGE.equals( widthArray[ i ].getUnits( ) ) )
{
if( ( percentSum > 100 ) || (( percentSum < 100 ) && ( 0 == NullNum )))
{
widthArray[ i ] = new DimensionType( ((widthArray[ i ].getMeasure( ) * 100)/percentSum), DimensionType.UNITS_PERCENTAGE );
}
}
}
}
/**
* Pushes the Boolean indicating whether or not the item is hidden according
* @param hidden
*/
public void push( boolean hidden )
{
boolean isHidden = false;
if ( !stack.empty( ) )
{
isHidden = ( (Boolean) stack.peek( ) ).booleanValue( );
}
if ( !isHidden )
{
isHidden = hidden;
}
stack.push( new Boolean( isHidden ) );
}
/**
* check whether to hide the column.
* @param column
* @return
*/
private boolean isColumnHidden( IColumn column )
{
String formats = column.getVisibleFormat( );
if ( formats != null
&& ( formats.indexOf( EngineIRConstants.FORMAT_TYPE_VIEWER ) >= 0 || formats
.indexOf( BIRTConstants.BIRT_ALL_VALUE ) >= 0 ) )
{
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTable(org.eclipse.birt.report.engine.content.ITableContent)
*/
public void endTable( ITableContent table )
{
if ( pop( ) )
{
return;
}
// include select handle table
if ( enableMetadata )
{
metadataEmitter.endTable( table );
}
writer.closeTag( HTMLTags.TAG_TABLE );
if ( enableMetadata )
{
metadataEmitter.endWrapTable( table );
}
logger.log( Level.FINE, "[HTMLTableEmitter] End table" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTableHeader(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableHeader( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_THEAD );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTableHeader(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableHeader( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.closeTag( HTMLTags.TAG_THEAD );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTableBody(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableBody( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_TBODY );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTableBody(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableBody( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.closeTag( HTMLTags.TAG_TBODY );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startTableFooter(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableFooter( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.openTag( HTMLTags.TAG_TFOOT );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endTableFooter(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableFooter( ITableBandContent band )
{
if ( isHidden( ) )
{
return;
}
writer.closeTag( HTMLTags.TAG_TFOOT );
}
boolean isRowInDetailBand(IRowContent row)
{
IElement parent = row.getParent( );
if ( !( parent instanceof IBandContent ) )
{
return false;
}
IBandContent band = (IBandContent)parent;
if (band.getBandType( ) == IBandContent.BAND_DETAIL)
{
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startRow(org.eclipse.birt.report.engine.content.IRowContent)
*/
public void startRow( IRowContent row )
{
assert row != null;
IStyle mergedStyle = row.getStyle( );
push( mergedStyle );
if ( isHidden( ) )
{
return;
}
if ( enableMetadata )
{
metadataEmitter.startRow( row );
}
writer.openTag( HTMLTags.TAG_TR );
setStyleName( row.getStyleClass( ) );
// bookmark
HTMLEmitterUtil.setBookmark( writer, null, row.getBookmark( ) );
StringBuffer styleBuffer = new StringBuffer( );
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, row
.getHeight( ) ); //$NON-NLS-1$
if ( enableMetadata )
{
outputRowMetaData( row );
}
handleStyle( row, styleBuffer );
}
protected IGroupContent getGroup(IBandContent bandContent)
{
IContent parent = (IContent)bandContent.getParent();
if (parent instanceof IGroupContent)
{
return (IGroupContent)parent;
}
return null;
}
protected void outputRowMetaData( IRowContent rowContent )
{
Object parent = rowContent.getParent( );
if ( parent instanceof ITableBandContent )
{
ITableBandContent bandContent = (ITableBandContent) parent;
IGroupContent group = rowContent.getGroup( );
String groupId = rowContent.getGroupId( );
if ( groupId != null )
{
writer.attribute( HTMLTags.ATTR_GOURP_ID, groupId );
}
String rowType = null;
String metaType = null;
int bandType = bandContent.getBandType( );
if ( bandType == ITableBandContent.BAND_HEADER )
{
metaType = "wrth";
rowType = "header";
}
else if ( bandType == ITableBandContent.BAND_FOOTER )
{
metaType = "wrtf";
rowType = "footer";
}
else if ( bandType == ITableBandContent.BAND_GROUP_HEADER )
{
rowType = "group-header";
if ( group != null )
{
metaType = "wrgh" + group.getGroupLevel( );
}
}
else if ( bandType == ITableBandContent.BAND_GROUP_FOOTER )
{
rowType = "group-footer";
if ( group != null )
{
metaType = "wrgf" + group.getGroupLevel( );
}
}
writer.attribute( HTMLTags.ATTR_TYPE, metaType );
writer.attribute( HTMLTags.ATTR_ROW_TYPE, rowType );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endRow(org.eclipse.birt.report.engine.content.IRowContent)
*/
public void endRow( IRowContent row )
{
if ( pop( ) )
{
return;
}
if ( enableMetadata )
{
metadataEmitter.endRow( row );
}
// assert currentData != null;
//
// currentData.adjustCols( );
writer.closeTag( HTMLTags.TAG_TR );
}
private boolean isCellInTableHead( ICellContent cell )
{
IElement row = cell.getParent( );
if ( row instanceof IRowContent )
{
IElement tableBand = row.getParent( );
if ( tableBand instanceof ITableBandContent )
{
int type = ( (ITableBandContent)tableBand ).getBandType( );
if ( type == ITableBandContent.BAND_HEADER )
{
return true;
}
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startCell(org.eclipse.birt.report.engine.content.ICellContent)
*/
public void startCell( ICellContent cell )
{
leafCell = cell;
cellFilled = false;
int colSpan = cell.getColSpan( );
push( false );
if ( isHidden( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLTableEmitter] Start cell." ); //$NON-NLS-1$
// output 'th' tag in table head, otherwise 'td' tag
boolean isInTableHead = isCellInTableHead( cell );
if ( isInTableHead )
{
writer.openTag( HTMLTags.TAG_TH ); //$NON-NLS-1$
}
else
{
writer.openTag( HTMLTags.TAG_TD ); //$NON-NLS-1$
}
// set the 'name' property
setStyleName( cell.getStyleClass( ) );
// colspan
if ( colSpan > 1 )
{
writer.attribute( HTMLTags.ATTR_COLSPAN, colSpan );
}
// rowspan
if ( ( cell.getRowSpan( ) ) > 1 )
{
writer.attribute( HTMLTags.ATTR_ROWSPAN, cell.getRowSpan( ) );
}
// vertical align can only be used with tabelCell/Inline Element
StringBuffer styleBuffer = new StringBuffer( );
handleColumnRelatedStyle( cell, styleBuffer );
handleVerticalAlign( cell, styleBuffer );
// set font weight to be normal if the cell use "th" tag while it is in table header.
if ( isInTableHead )
{
handleCellFont( cell, styleBuffer );
}
handleCellStyle( cell, styleBuffer );
writer.attribute( "align", cell.getComputedStyle( ).getTextAlign( ) ); //$NON-NLS-1$
if ( !startedGroups.isEmpty( ) )
{
Iterator iter = startedGroups.iterator( );
while (iter.hasNext( ))
{
IGroupContent group = (IGroupContent) iter.next( );
outputBookmark( group );
}
startedGroups.clear( );
}
if ( enableMetadata )
{
metadataEmitter.startCell( cell );
}
}
private void handleColumnRelatedStyle( ICellContent cell,
StringBuffer styleBuffer )
{
IStyle style = new CellMergedStyle( cell );
AttributeBuilder.buildStyle( styleBuffer, style, this, true );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endCell(org.eclipse.birt.report.engine.content.ICellContent)
*/
public void endCell( ICellContent cell )
{
if( (cell == leafCell) && (false == cellFilled) )
{
writer.text( " " );
}
leafCell = null;
cellFilled = false;
if ( pop( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] End cell." ); //$NON-NLS-1$
if ( enableMetadata )
{
metadataEmitter.endCell( cell );
}
if ( isCellInTableHead( cell ) )
{
writer.closeTag( HTMLTags.TAG_TH );
}
else
{
writer.closeTag( HTMLTags.TAG_TD );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startContainer(org.eclipse.birt.report.engine.content.IContainerContent)
*/
public void startContainer( IContainerContent container )
{
IStyle mergedStyle = container.getStyle( );
push( mergedStyle );
if ( isHidden( ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] Start container" ); //$NON-NLS-1$
String tagName;
StringBuffer styleBuffer = new StringBuffer( );
DimensionType x = container.getX( );
DimensionType y = container.getY( );
DimensionType width = container.getWidth( );
DimensionType height = container.getHeight( );
int display = checkElementType( x, y, width, height, mergedStyle,
styleBuffer );
if( ((display & HTMLEmitterUtil.DISPLAY_INLINE ) > 0)
|| ((display & HTMLEmitterUtil.DISPLAY_INLINE_BLOCK ) > 0) )
{
writer.openTag( HTMLTags.TAG_TABLE );
writer.attribute( HTMLTags.ATTR_STYLE, " display:-moz-inline-box !important; display:inline;" );
writer.openTag( HTMLTags.TAG_TR );
writer.openTag( HTMLTags.TAG_TD );
// this tag is pushed in Stack. The tag will be popped when close the container.
tagStack.push( "ImplementInlineBlock" );
}
else
{
// this tag is pushed in Stack. The tag will be popped when close the container.
tagStack.push( HTMLTags.TAG_DIV );
}
writer.openTag( HTMLTags.TAG_DIV );
tagName = HTMLTags.TAG_DIV;
// class
setStyleName( container.getStyleClass( ) );
// bookmark
String bookmark = container.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
container.setBookmark( bookmark );
}
HTMLEmitterUtil.setBookmark( writer, tagName, bookmark );
HTMLEmitterUtil
.setActiveIDTypeIID( writer, ouputInstanceIDs, container );
// output style
// if ( x == null && y == null )
// {
// styleBuffer.append( "position: relative;" ); //$NON-NLS-1$
// }
setDisplayProperty( display, DISPLAY_INLINE_BLOCK, styleBuffer );
handleShrink( display, mergedStyle, height, width, styleBuffer );
handleStyle( container, styleBuffer );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#endContainer(org.eclipse.birt.report.engine.content.IContainerContent)
*/
public void endContainer( IContainerContent container )
{
if ( pop( ) )
{
return;
}
String tag = (String) tagStack.pop( );
if( tag.equals( "ImplementInlineBlock" ))
{
writer.closeTag( HTMLTags.TAG_DIV );
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TABLE );
}
else
{
writer.closeTag( tag );
}
logger.log( Level.FINE, "[HTMLContainerEmitter] End container" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startText(org.eclipse.birt.report.engine.content.ITextContent)
*/
public void startText( ITextContent text )
{
IStyle mergedStyle = text.getStyle( );
if ( peek( mergedStyle ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] Start text" ); //$NON-NLS-1$
//Resize if the text generated by TemplateDesign
//resizeTemplateElement( text);
StringBuffer styleBuffer = new StringBuffer( );
DimensionType x = text.getX( );
DimensionType y = text.getY( );
DimensionType width = text.getWidth( );
DimensionType height = text.getHeight( );
String textValue = text.getText( );
if (textValue == null || textValue == "" ) //$NON-NLS-1$
{
textValue = " "; //$NON-NLS-1$
}
int display;
// If the item is multi-line, we should check if it can be inline-block
if ( textValue != null && textValue.indexOf( '\n' ) >= 0 )
{
display = checkElementType( x, y, width, height, mergedStyle,
styleBuffer );
}
else
{
display = checkElementType( x, y, mergedStyle, styleBuffer );
}
// action
String tagName;
String url = validate( text.getHyperlinkAction( ) );
boolean metadataOutput = false;
if ( url != null )
{
//output select class
if ( enableMetadata )
{
metadataOutput = metadataEmitter.startText( text,
HTMLTags.TAG_SPAN );
}
tagName = HTMLTags.TAG_A;
outputAction( text.getHyperlinkAction( ), url );
setDisplayProperty( display, DISPLAY_BLOCK | DISPLAY_INLINE_BLOCK,
styleBuffer );
AttributeBuilder.checkHyperlinkTextDecoration( mergedStyle,
styleBuffer );
}
else
{
if ( enableMetadata )
{
metadataOutput = metadataEmitter.startText( text, HTMLEmitterUtil.getTagByType(
display, DISPLAY_FLAG_ALL ) );
}
tagName = openTagByType( display, DISPLAY_FLAG_ALL );
setDisplayProperty( display, DISPLAY_INLINE_BLOCK, styleBuffer );
}
setStyleName( text.getStyleClass( ) );
// bookmark
if ( !metadataOutput )
{
outputBookmark( text, tagName );
}
// title
writer.attribute( HTMLTags.ATTR_TITLE, text.getHelpText( ) ); //$NON-NLS-1$
/*if( isTalbeTemplateElement( text ) )
{
//set lines to dotted lines
mergedStyle.setProperty( IStyle.STYLE_BORDER_TOP_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_BOTTOM_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_LEFT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_RIGHT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_FONT_FAMILY, IStyle.SANS_SERIF_VALUE );
}*/
// check 'can-shrink' property
handleShrink( display, mergedStyle, height, width, styleBuffer );
// export the text-align
String textAlign = text.getComputedStyle( ).getTextAlign( );
if ( textAlign != null )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( textAlign );
styleBuffer.append( ";" );
}
handleStyle( text, styleBuffer, false );
String verticalAlign = null;
String canShrink = "false";
if(mergedStyle!=null)
{
verticalAlign = mergedStyle.getVerticalAlign( );
canShrink = mergedStyle.getCanShrink( );
}
if ( !"baseline".equals( verticalAlign ) && height != null && !"true".equalsIgnoreCase( canShrink ) )
{
// implement vertical align.
writer.openTag( HTMLTags.TAG_TABLE );
writer.attribute( HTMLTags.ATTR_STYLE, " width:100%; height:100%;" );
writer.openTag( HTMLTags.TAG_TR );
writer.openTag( HTMLTags.TAG_TD );
StringBuffer textStyleBuffer = new StringBuffer( );
textStyleBuffer.append( " vertical-align:" );
textStyleBuffer.append( verticalAlign==null? "top":verticalAlign );
textStyleBuffer.append( ";" );
writer.attribute( HTMLTags.ATTR_STYLE, textStyleBuffer );
writer.text( textValue );
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TABLE );
}
else
{
writer.text( textValue );
}
writer.closeTag( tagName );
if ( enableMetadata )
{
metadataEmitter.endText( text );
}
cellFilled = true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startForeign(org.eclipse.birt.report.engine.content.IForeignContent)
*/
public void startForeign( IForeignContent foreign )
{
IStyle mergedStyle = foreign.getStyle( );
if ( peek( mergedStyle ) )
{
return;
}
logger.log( Level.FINE, "[HTMLReportEmitter] Start foreign" ); //$NON-NLS-1$
resizeTemplateElement( foreign);
StringBuffer styleBuffer = new StringBuffer( );
DimensionType x = foreign.getX( );
DimensionType y = foreign.getY( );
DimensionType width = foreign.getWidth( );
DimensionType height = foreign.getHeight( );
int display;
display = checkElementType( x, y, width, height, mergedStyle,
styleBuffer );
// create default bookmark if we need output metadata
if ( foreign.getGenerateBy( ) instanceof TemplateDesign )
{
//FIXME: actually, it should be birt-template-design
String bookmark = foreign.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
foreign.setBookmark( bookmark );
}
}
// action
String tagName;
String url = validate( foreign.getHyperlinkAction( ) );
boolean metadataOutput = false;
if ( url != null )
{
if ( enableMetadata )
{
metadataOutput = metadataEmitter.startForeign( foreign,
HTMLTags.TAG_SPAN );
}
tagName = HTMLTags.TAG_A;
outputAction( foreign.getHyperlinkAction( ), url );
setDisplayProperty( display, DISPLAY_BLOCK | DISPLAY_INLINE_BLOCK,
styleBuffer );
AttributeBuilder.checkHyperlinkTextDecoration( mergedStyle,
styleBuffer );
}
else
{
if ( enableMetadata )
{
metadataOutput = metadataEmitter.startForeign( foreign, HTMLEmitterUtil.getTagByType(
display, DISPLAY_FLAG_ALL ) );
}
tagName = openTagByType( display, DISPLAY_FLAG_ALL );
setDisplayProperty( display, DISPLAY_INLINE_BLOCK, styleBuffer );
}
setStyleName( foreign.getStyleClass( ) );
// bookmark
if ( !metadataOutput )
{
outputBookmark( foreign, tagName );
}
// title
writer.attribute( HTMLTags.ATTR_TITLE, foreign.getHelpText( ) );
if( isTalbeTemplateElement( foreign ) )
{
//set lines to dotted lines
mergedStyle.setProperty( IStyle.STYLE_BORDER_TOP_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_BOTTOM_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_LEFT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_BORDER_RIGHT_STYLE, IStyle.DOTTED_VALUE );
mergedStyle.setProperty( IStyle.STYLE_FONT_FAMILY, IStyle.SANS_SERIF_VALUE );
}
String textAlign = foreign.getComputedStyle( ).getTextAlign( );
if ( textAlign != null )
{
styleBuffer.append( " text-align:" );
styleBuffer.append( textAlign );
styleBuffer.append( ";" );
}
// check 'can-shrink' property
handleShrink( display, mergedStyle, height, width, styleBuffer );
handleStyle( foreign, styleBuffer, false );
String rawType = foreign.getRawType( );
boolean isHtml = IForeignContent.HTML_TYPE.equalsIgnoreCase( rawType );
if ( isHtml )
{
String verticalAlign = mergedStyle.getVerticalAlign( );
if ( !"baseline".equals( verticalAlign ) && height != null )
{
// implement vertical align.
writer.openTag( HTMLTags.TAG_TABLE );
writer.attribute( HTMLTags.ATTR_STYLE, " width:100%; height:100%;" );
writer.openTag( HTMLTags.TAG_TR );
writer.openTag( HTMLTags.TAG_TD );
StringBuffer textStyleBuffer = new StringBuffer( );
textStyleBuffer.append( " vertical-align:" );
textStyleBuffer.append( verticalAlign );
textStyleBuffer.append( ";" );
writer.attribute( HTMLTags.ATTR_STYLE, textStyleBuffer );
outputHtmlText(foreign);
writer.closeTag( HTMLTags.TAG_TD );
writer.closeTag( HTMLTags.TAG_TR );
writer.closeTag( HTMLTags.TAG_TABLE );
}
else
{
outputHtmlText( foreign);
}
}
// writer.text( text, !isHtml, !isHtml );
writer.closeTag( tagName );
if ( enableMetadata )
{
metadataEmitter.endForeign( foreign );
}
/**
* We suppose the foreign content will all occupy space now.
* In fact some foreign contents don't occupy space.
* For example: a empty html text will not occupy space in html.
* It needs to be solved in the future.
*/
cellFilled = true;
}
private void outputHtmlText(IForeignContent foreign)
{
Object rawValue = foreign.getRawValue( );
String text = rawValue == null ? null : rawValue.toString( );
Document doc = new TextParser( ).parse( text,
TextParser.TEXT_TYPE_HTML );
ReportDesignHandle design = (ReportDesignHandle) runnable
.getDesignHandle( );
HTMLProcessor htmlProcessor = new HTMLProcessor( design );
HashMap styleMap = new HashMap( );
Element body = null;
if ( doc != null )
{
NodeList bodys = doc.getElementsByTagName( "body" );
if ( bodys.getLength( ) > 0 )
{
body = (Element) bodys.item( 0 );
}
}
if ( body != null )
{
htmlProcessor.execute( body, styleMap );
processNodes( body, styleMap );
}
}
/**
* Visits the children nodes of the specific node
*
* @param visitor
* the ITextNodeVisitor instance
* @param ele
* the specific node
*/
private void processNodes( Element ele, HashMap cssStyles )
{
for ( Node node = ele.getFirstChild( ); node != null; node = node
.getNextSibling( ) )
{
// At present we only deal with the text and element nodes
if ( node.getNodeType( ) == Node.TEXT_NODE
|| node.getNodeType( ) == Node.ELEMENT_NODE )
{
if ( !node.getNodeName( ).equals( "#text" ) )
{
startNode( node, cssStyles );
}
if ( node.getNodeType( ) == Node.TEXT_NODE )
{
if ( isScriptText( node ) )
{
textForScript( node.getNodeValue( ) );
}
else
{
// bug132213 in text item should only deal with the
// escape special characters: < > &
// writer.text( node.getNodeValue( ), false, true );
writer.textForHtmlItem( node.getNodeValue( ) );
}
}
else
{
processNodes( (Element) node, cssStyles );
}
if ( !node.getNodeName( ).equals( "#text" ) )
{
endNode( node );
}
}
}
}
/**
* test if the text node is in the script
* @param node text node
* @return true if the text is a script, otherwise, false.
*/
private boolean isScriptText( Node node )
{
Node parent = node.getParentNode( );
if ( parent != null )
{
if ( parent.getNodeType( ) == Node.ELEMENT_NODE )
{
String tag = parent.getNodeName( );
if ( HTMLTags.TAG_SCRIPT.equalsIgnoreCase( tag ) )
{
return true;
}
}
}
return false;
}
/**
* the script is output directly.
* @param text
*/
private void textForScript( String text )
{
writer.text( text, false, false );
}
public void startNode( Node node, HashMap cssStyles )
{
String nodeName = node.getNodeName( );
HashMap cssStyle = (HashMap) cssStyles.get( node );
writer.openTag( nodeName );
NamedNodeMap attributes = node.getAttributes( );
if ( attributes != null )
{
for ( int i = 0; i < attributes.getLength( ); i++ )
{
Node attribute = attributes.item( i );
String attrName = attribute.getNodeName( );
String attrValue = attribute.getNodeValue( );
if ( attrValue != null )
{
if ( "img".equalsIgnoreCase( nodeName )
&& "src".equalsIgnoreCase( attrName ) )
{
String attrValueTrue = handleStyleImage( attrValue );
if ( attrValueTrue != null )
{
attrValue = attrValueTrue;
}
}
writer.attribute( attrName, attrValue );
}
}
}
if ( cssStyle != null )
{
StringBuffer buffer = new StringBuffer( );
Iterator ite = cssStyle.entrySet( ).iterator( );
while ( ite.hasNext( ) )
{
Map.Entry entry = (Map.Entry) ite.next( );
Object keyObj = entry.getKey( );
Object valueObj = entry.getValue( );
if ( keyObj == null || valueObj == null )
{
continue;
}
String key = keyObj.toString( );
String value = valueObj.toString( );
buffer.append( key );
buffer.append( ":" );
if ( "background-image".equalsIgnoreCase( key ) )
{
String valueTrue = handleStyleImage( value );
if ( valueTrue != null )
{
value = valueTrue;
}
buffer.append( "url(" );
buffer.append( value );
buffer.append( ")" );
}
else
{
buffer.append( value.replaceAll( " ", "" ) );
}
buffer.append( ";" );
}
if ( buffer.length( ) != 0 )
{
writer.attribute( "style", buffer.toString( ) );
}
}
}
public void endNode( Node node )
{
writer.closeTag( node.getNodeName( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startLabel(org.eclipse.birt.report.engine.content.ILabelContent)
*/
public void startLabel( ILabelContent label )
{
String bookmark = label.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
label.setBookmark( bookmark );
}
startText( label );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startData(org.eclipse.birt.report.engine.content.IDataContent)
*/
public void startData( IDataContent data )
{
startText( data );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.emitter.IContentEmitter#startImage(org.eclipse.birt.report.engine.content.IImageContent)
*/
public void startImage( IImageContent image )
{
assert image != null;
IStyle mergedStyle = image.getStyle( );
if ( peek( mergedStyle ) )
{
return;
}
logger.log( Level.FINE, "[HTMLImageEmitter] Start image" ); //$NON-NLS-1$
StringBuffer styleBuffer = new StringBuffer( );
int display = checkElementType( image.getX( ), image.getY( ),
mergedStyle, styleBuffer );
boolean isSelectHandleTableChart = false;
if ( enableMetadata )
{
isSelectHandleTableChart = metadataEmitter.startImage( image );
}
String tag = openTagByType( display, DISPLAY_BLOCK );
// action
boolean hasAction = handleAction( image.getHyperlinkAction( ) );
String imgUri = getImageURI( image );
boolean useSVG = (( image.getMIMEType( ) != null )
&& image.getMIMEType( ).equalsIgnoreCase( "image/svg+xml" )) //$NON-NLS-1$
|| (( image.getExtension( ) != null )
&& image.getExtension( ).equalsIgnoreCase( ".svg" )) //$NON-NLS-1$
|| (( image.getURI( ) != null )
&& image.getURI( ).toLowerCase( ).endsWith( ".svg" )); //$NON-NLS-1$
if ( useSVG )
{ // use svg
writer.openTag( HTMLTags.TAG_EMBED );
// bookmark
String bookmark = image.getBookmark( );
if ( !isSelectHandleTableChart )
{
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
image.setBookmark( bookmark );
}
outputBookmark( image, HTMLTags.ATTR_IMAGE ); //$NON-NLS-1$
}
// onresize gives the SVG a change to change its content
writer.attribute( "onresize", bookmark+".reload()"); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_TYPE, "image/svg+xml" ); //$NON-NLS-1$
writer.attribute( HTMLTags.ATTR_SRC, imgUri );
// alternative text
String altText = image.getAltText( );
if ( altText == null )
{
writer.attributeAllowEmpty( HTMLTags.ATTR_ALT, "" );
}
else
{
writer.attribute( HTMLTags.ATTR_ALT, altText );
}
setStyleName( image.getStyleClass( ) );
setDisplayProperty( display, 0, styleBuffer );
// build size
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, image
.getWidth( ) ); //$NON-NLS-1$
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT, image
.getHeight( ) ); //$NON-NLS-1$
// handle inline style
handleStyle( image, styleBuffer, false );
writer.closeNoEndTag( );
}
else
{ // use img
// write image map if necessary
Object imageMapObject = image.getImageMap( );
// use imgUri as the image ID. As we know only the CHART can have
// image maps and each chart
// will have differnt URI, so it is safe for CHART. (If the named
// image also support image
// map, then we must use another way to get the image ID.
String imageMapId = imgUri;
boolean hasImageMap = ( imageMapObject != null )
&& ( imageMapObject instanceof String )
&& ( ( (String) imageMapObject ).length( ) > 0 );
if ( hasImageMap )
{
writer.openTag( HTMLTags.TAG_MAP );
writer.attribute( HTMLTags.ATTR_NAME, imageMapId );
writer.text( (String) imageMapObject, true, false );
writer.closeTag( HTMLTags.TAG_MAP );
}
writer.openTag( HTMLTags.TAG_IMAGE ); //$NON-NLS-1$
setStyleName( image.getStyleClass( ) );
setDisplayProperty( display, 0, styleBuffer );
// bookmark
String bookmark = image.getBookmark( );
if ( !isSelectHandleTableChart )
{
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
image.setBookmark( bookmark );
}
outputBookmark( image, HTMLTags.ATTR_IMAGE ); //$NON-NLS-1$
}
String ext = image.getExtension( );
// FIXME special process, such as encoding etc
writer.attribute( HTMLTags.ATTR_SRC, imgUri );
if ( hasImageMap )
{
// BUGZILLA 119245 request chart (without hyperlink) can't have
// borders, the BROWSER add blue-solid border to the image with
// maps.
if ( !hasAction )
{
// disable the border, if the user defines border with the
// image, it will be overided by the following style setting
IStyle style = image.getStyle( );
if ( style.getBorderTopStyle( ) == null )
{
// user doesn't define the border, remove it.
styleBuffer.append( "border-top-style:none;" );
}
else
{
// use define the border-style, but not define the
// border color, use the default
// color.
if ( style.getBorderTopColor( ) == null )
{
styleBuffer.append( "border-top-color:black" );
}
}
if ( style.getBorderBottomStyle( ) == null )
{
styleBuffer.append( "border-bottom-style:none;" );
}
else
{
if ( style.getBorderBottomColor( ) == null )
{
styleBuffer.append( "border-bottom-color:black" );
}
}
if ( style.getBorderLeftStyle( ) == null )
{
styleBuffer.append( "border-left-style:none;" );
}
else
{
if ( style.getBorderLeftColor( ) == null )
{
styleBuffer.append( "border-left-color:black" );
}
}
if ( style.getBorderRightStyle( ) == null )
{
styleBuffer.append( "border-right-style:none;" );
}
else
{
if ( style.getBorderRightColor( ) == null )
{
styleBuffer.append( "border-right-color:black" );
}
}
}
writer.attribute( HTMLTags.ATTR_USEMAP, "#" + imageMapId ); //$NON-NLS-1$ //$NON-NLS-2$
}
// alternative text
String altText = image.getAltText( );
if ( altText == null )
{
writer.attributeAllowEmpty( HTMLTags.ATTR_ALT, "" );
}
else
{
writer.attribute( HTMLTags.ATTR_ALT, altText );
}
// help text
writer.attribute( HTMLTags.ATTR_TITLE, image.getHelpText( ) );
// image size
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, image
.getWidth( ) ); //$NON-NLS-1$
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT,
image.getHeight( ) ); //$NON-NLS-1$
// handle style
handleStyle( image, styleBuffer, false );
if ( ".PNG".equalsIgnoreCase( ext ) && imageHandler != null ) //$NON-NLS-1$
{
writer.attribute( HTMLTags.ATTR_ONLOAD, "fixPNG(this)" ); //$NON-NLS-1$
}
writer.closeNoEndTag( );
}
if ( hasAction )
{
writer.closeTag( HTMLTags.TAG_A );
}
writer.closeTag( tag );
// include select handle chart
if ( enableMetadata )
{
metadataEmitter.endImage( image );
}
cellFilled = true;
}
/**
* gets the image's URI
*
* @param image
* the image content
* @return image's URI
*/
protected String getImageURI( IImageContent image )
{
String imgUri = null;
if ( imageHandler != null )
{
Image img = new Image( image );
img.setRenderOption( renderOption );
img.setReportRunnable( runnable );
switch ( img.getSource( ) )
{
case IImage.DESIGN_IMAGE :
imgUri = imageHandler.onDesignImage( img, reportContext );
break;
case IImage.URL_IMAGE :
imgUri = imageHandler.onURLImage( img, reportContext );
break;
case IImage.REPORTDOC_IMAGE :
imgUri = imageHandler.onDocImage( img, reportContext );
break;
case IImage.CUSTOM_IMAGE :
imgUri = imageHandler.onCustomImage( img, reportContext );
break;
case IImage.FILE_IMAGE :
imgUri = imageHandler.onFileImage( img, reportContext );
break;
case IImage.INVALID_IMAGE :
break;
}
}
return imgUri;
}
/**
* Sets the <code>'class'</code> property and stores the style to styleMap
* object.
*
* @param styleName
* the style name
*/
protected void setStyleName( String styleName )
{
if ( isEmbeddable )
{
return;
}
if ( styleName != null )
{
writer.attribute( HTMLTags.ATTR_CLASS, styleName );
}
}
/**
* Checks the 'CanShrink' property and sets the width and height according
* to the table below:
* <p>
* <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing
* symbol, location, localized, and meaning.">
* <tr bgcolor="#ccccff">
* <th align=left>CanShrink</th>
* <th align=left>Element Type</th>
* <th align=left>Width</th>
* <th align=left>Height</th>
* </tr>
* <tr valign=middle>
* <td rowspan="2"><code>true(by default)</code></td>
* <td>in-line</td>
* <td>ignor</td>
* <td>set</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>block</code></td>
* <td>set</td>
* <td>ignor</td>
* </tr>
* <tr valign=middle>
* <td rowspan="2" bgcolor="#eeeeff"><code>false</code></td>
* <td>in-line</td>
* <td>replaced by 'min-width' property</td>
* <td>set</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td><code>block</code></td>
* <td>set</td>
* <td>replaced by 'min-height' property</td>
* </tr>
* </table>
*
* @param type
* The display type of the element.
* @param style
* The style of an element.
* @param height
* The height property.
* @param width
* The width property.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
* @return A <code>boolean</code> value indicating 'Can-Shrink' property
* is set to <code>true</code> or not.
*/
protected boolean handleShrink( int type, IStyle style,
DimensionType height, DimensionType width, StringBuffer styleBuffer )
{
boolean canShrink = style != null
&& "true".equalsIgnoreCase( style.getCanShrink( ) ); //$NON-NLS-1$
if ( ( type & DISPLAY_BLOCK ) > 0 )
{
AttributeBuilder
.buildSize( styleBuffer, HTMLTags.ATTR_WIDTH, width );
if ( !canShrink )
{
AttributeBuilder.buildSize( styleBuffer,
HTMLTags.ATTR_MIN_HEIGHT, height );
}
}
else if ( ( type & DISPLAY_INLINE ) > 0 )
{
AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_HEIGHT,
height );
if ( !canShrink )
{
AttributeBuilder.buildSize( styleBuffer,
HTMLTags.ATTR_MIN_WIDTH, width );
}
}
else
{
assert false;
}
return canShrink;
}
protected void outputBookmark( IContent content, String tagName )
{
String bookmark = content.getBookmark( );
HTMLEmitterUtil.setBookmark( writer, tagName, bookmark );
}
/**
* Checks whether the element is block, inline or inline-block level. In
* BIRT, the absolute positioning model is used and a box is explicitly
* offset with respect to its containing block. When an element's x or y is
* set, it will be treated as a block level element regardless of the
* 'Display' property set in style. When designating width or height value
* to an inline element, it will be treated as inline-block.
*
* @param x
* Specifies how far a box's left margin edge is offset to the
* right of the left edge of the box's containing block.
* @param y
* Specifies how far an absolutely positioned box's top margin
* edge is offset below the top edge of the box's containing
* block.
* @param width
* The width of the element.
* @param height
* The height of the element.
* @param style
* The <code>IStyle</code> object.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
* @return The display type of the element.
*/
protected int checkElementType( DimensionType x, DimensionType y,
IStyle style, StringBuffer styleBuffer )
{
return checkElementType( x, y, null, null, style, styleBuffer );
}
protected int checkElementType( DimensionType x, DimensionType y,
DimensionType width, DimensionType height, IStyle style,
StringBuffer styleBuffer )
{
//if ( x != null || y != null )
//{
// styleBuffer.append( "position: absolute;" ); //$NON-NLS-1$
// AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_LEFT, x );
// AttributeBuilder.buildSize( styleBuffer, HTMLTags.ATTR_TOP, y );
//}
return getElementType( x, y, width, height, style);
}
public int getElementType( DimensionType x, DimensionType y,
DimensionType width, DimensionType height, IStyle style )
{
int type = 0;
String display = null;
if ( style != null )
{
display = style.getDisplay( );
}
if ( EngineIRConstants.DISPLAY_NONE.equalsIgnoreCase( display ) )
{
type |= DISPLAY_NONE;
}
if ( x != null || y != null )
{
return type | DISPLAY_BLOCK;
}
else if ( EngineIRConstants.DISPLAY_INLINE.equalsIgnoreCase( display ) )
{
type |= DISPLAY_INLINE;
if ( width != null || height != null )
{
type |= DISPLAY_INLINE_BLOCK;
}
return type;
}
return type | DISPLAY_BLOCK;
}
/**
* Open a tag according to the display type of the element. Here is the
* mapping table:
* <p>
* <table border=0 cellspacing=3 cellpadding=0 summary="Chart showing
* symbol, location, localized, and meaning.">
* <tr bgcolor="#ccccff">
* <th align=left>Display Type</th>
* <th align=left>Tag name</th>
* </tr>
* <tr valign=middle>
* <td>DISPLAY_BLOCK</td>
* <td>DIV</td>
* </tr>
* <tr valign=top bgcolor="#eeeeff">
* <td>DISPLAY_INLINE</td>
* <td>SPAN</td>
* </tr>
* </table>
*
* @param display
* The display type.
* @param mask
* The mask value.
* @return Tag name.
*/
protected String openTagByType( int display, int mask )
{
String tag = HTMLEmitterUtil.getTagByType( display, mask );
if ( tag != null)
{
writer.openTag( tag );
}
return tag;
}
/**
* Set the display property to style.
*
* @param display
* The display type.
* @param mask
* The mask.
* @param styleBuffer
* The <code>StringBuffer</code> object that returns 'style'
* content.
*/
protected void setDisplayProperty( int display, int mask,
StringBuffer styleBuffer )
{
int flag = display & mask;
if ( ( display & DISPLAY_NONE ) > 0 )
{
styleBuffer.append( "display: none;" ); //$NON-NLS-1$
}
else if ( flag > 0 )
{
if ( ( flag & DISPLAY_BLOCK ) > 0 )
{
styleBuffer.append( "display: block;" ); //$NON-NLS-1$
}
else if ( ( flag & DISPLAY_INLINE_BLOCK ) > 0 )
{
styleBuffer.append( "display: inline-block;" ); //$NON-NLS-1$
}
else if ( ( flag & DISPLAY_INLINE ) > 0 )
{
styleBuffer.append( "display: inline;" ); //$NON-NLS-1$
}
}
}
/**
* Checks the Action object and then output corresponding tag and property.
*
* @param action
* The <code>IHyperlinkAction</code> object.
* @return A <code>boolean</code> value indicating whether the Action
* object is valid or not.
*/
protected boolean handleAction( IHyperlinkAction action )
{
String url = validate( action );
if ( url != null )
{
outputAction( action, url );
}
return url != null;
}
/**
* Outputs an hyperlink action.
*
* @param action
* the hyperlink action.
*/
protected void outputAction( IHyperlinkAction action, String url )
{
writer.openTag( HTMLTags.TAG_A );
writer.attribute( HTMLTags.ATTR_HREF, url );
writer.attribute( HTMLTags.ATTR_TARGET, action.getTargetWindow( ) );
}
/**
* Judges if a hyperlink is valid.
*
* @param action
* the hyperlink action
* @return
*/
private String validate( IHyperlinkAction action )
{
if ( action == null )
{
return null;
}
String systemId = runnable == null ? null : runnable.getReportName( );
Action act = new Action( systemId, action );
if ( actionHandler == null )
{
return null;
}
String link = actionHandler.getURL( act, reportContext );
if ( link != null && !link.equals( "" ) )//$NON-NLS-1$
{
return link;
}
return null;
}
/**
* handle style image
*
* @param uri
* uri in style image
* @return
*/
public String handleStyleImage( String uri )
{
ReportDesignHandle design = (ReportDesignHandle) runnable
.getDesignHandle( );
URL url = design.findResource( uri, IResourceLocator.IMAGE );
if ( url == null )
{
return uri;
}
uri = url.toExternalForm( );
Image image = new Image( uri );
image.setReportRunnable( runnable );
image.setRenderOption( renderOption );
String imgUri = null;
if ( imageHandler != null )
{
switch ( image.getSource( ) )
{
case IImage.URL_IMAGE :
imgUri = imageHandler.onURLImage( image, reportContext );
break;
case IImage.FILE_IMAGE :
imgUri = imageHandler.onFileImage( image, reportContext );
break;
case IImage.INVALID_IMAGE :
break;
default :
assert ( false );
}
// imgUri = imgUri.replace( File.separatorChar, '/' );
}
return imgUri;
}
/**
* Handles the style of the styled element content
*
* @param element
* the styled element content
* @param styleBuffer
* the StringBuffer instance
*/
protected void handleStyle( IContent element, StringBuffer styleBuffer,
boolean bContainer )
{
IStyle style;
if ( isEmbeddable )
{
style = element.getStyle( );
}
else
{
style = element.getInlineStyle( );
}
AttributeBuilder.buildStyle( styleBuffer, style, this, bContainer );
if ( !bContainer )
{
AttributeBuilder.buildComputedTextStyle( styleBuffer, element.getComputedStyle( ),this , bContainer );
}
// output in-line style
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
/**
* Handles the style of a cell
* @param cell: the cell content
* @param styleBuffer: the buffer to store the tyle building result.
*/
protected void handleCellStyle( ICellContent cell, StringBuffer styleBuffer )
{
IStyle style = null;
if ( isEmbeddable )
{
style = cell.getStyle( );
}
else
{
style = cell.getInlineStyle( );
}
// build the cell's style except border
AttributeBuilder.buildCellStyle( styleBuffer, style, this, true );
//prepare build the cell's border
int columnCount = -1;
IStyle cellStyle = null, cellComputedStyle = null;
IStyle rowStyle = null, rowComputedStyle = null;
cellStyle = cell.getStyle( );
cellComputedStyle = cell.getComputedStyle( );
IRowContent row = (IRowContent) cell.getParent( );
if( null != row )
{
rowStyle = row.getStyle( );
rowComputedStyle = row.getComputedStyle( );
ITableContent table = row.getTable( );
if( null != table )
{
columnCount = table.getColumnCount( );
}
}
//build the cell's border
if( null == rowStyle || cell.getColumn( )< 0 || columnCount < 1 )
{
if( null != cellStyle )
{
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_TOP,
cellStyle.getBorderTopWidth( ), cellStyle.getBorderTopStyle( ),
cellStyle.getBorderTopColor( ), 0, null, null, null, 0 );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_RIGHT,
cellStyle.getBorderRightWidth( ), cellStyle.getBorderRightStyle( ),
cellStyle.getBorderRightColor( ), 0, null, null, null, 0 );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_BOTTOM,
cellStyle.getBorderBottomWidth( ), cellStyle.getBorderBottomStyle( ),
cellStyle.getBorderBottomColor( ), 0, null, null, null, 0 );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_LEFT,
cellStyle.getBorderLeftWidth( ), cellStyle.getBorderLeftStyle( ),
cellStyle.getBorderLeftColor( ), 0, null, null, null, 0 );
}
}
else if( null == cellStyle )
{
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_TOP, null, null, null, 0,
rowStyle.getBorderTopWidth( ), rowStyle.getBorderTopStyle( ),
rowStyle.getBorderTopColor( ), 0 );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_RIGHT, null, null, null, 0,
rowStyle.getBorderRightWidth( ), rowStyle.getBorderRightStyle( ),
rowStyle.getBorderRightColor( ), 0 );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_BOTTOM, null, null, null, 0,
rowStyle.getBorderBottomWidth( ), rowStyle.getBorderBottomStyle( ),
rowStyle.getBorderBottomColor( ), 0 );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_LEFT, null, null, null, 0,
rowStyle.getBorderLeftWidth( ), rowStyle.getBorderLeftStyle( ),
rowStyle.getBorderLeftColor( ), 0 );
}
else
{
//We have treat the column span. But we haven't treat the row span.
//It need to be solved in the future.
int cellWidthValue = getBorderWidthValue( cellComputedStyle, IStyle.STYLE_BORDER_TOP_WIDTH );
int rowWidthValue = getBorderWidthValue( rowComputedStyle, IStyle.STYLE_BORDER_TOP_WIDTH );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_TOP,
cellStyle.getBorderTopWidth( ), cellStyle.getBorderTopStyle( ),
cellStyle.getBorderTopColor( ), cellWidthValue,
rowStyle.getBorderTopWidth( ), rowStyle.getBorderTopStyle( ),
rowStyle.getBorderTopColor( ), rowWidthValue );
if( (cell.getColumn( ) + cell.getColSpan( )) == columnCount )
{
cellWidthValue = getBorderWidthValue( cellComputedStyle, IStyle.STYLE_BORDER_RIGHT_WIDTH );
rowWidthValue = getBorderWidthValue( rowComputedStyle, IStyle.STYLE_BORDER_RIGHT_WIDTH );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_RIGHT,
cellStyle.getBorderRightWidth( ), cellStyle.getBorderRightStyle( ),
cellStyle.getBorderRightColor( ), cellWidthValue,
rowStyle.getBorderRightWidth( ), rowStyle.getBorderRightStyle( ),
rowStyle.getBorderRightColor( ), rowWidthValue );
}
else
{
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_RIGHT,
cellStyle.getBorderRightWidth( ), cellStyle.getBorderRightStyle( ),
cellStyle.getBorderRightColor( ), 0, null, null, null, 0 );
}
cellWidthValue = getBorderWidthValue( cellComputedStyle, IStyle.STYLE_BORDER_BOTTOM_WIDTH );
rowWidthValue = getBorderWidthValue( rowComputedStyle, IStyle.STYLE_BORDER_BOTTOM_WIDTH );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_BOTTOM,
cellStyle.getBorderBottomWidth( ), cellStyle.getBorderBottomStyle( ),
cellStyle.getBorderBottomColor( ), cellWidthValue,
rowStyle.getBorderBottomWidth( ), rowStyle.getBorderBottomStyle( ),
rowStyle.getBorderBottomColor( ), rowWidthValue );
if( cell.getColumn( ) == 0 )
{
cellWidthValue = getBorderWidthValue( cellComputedStyle, IStyle.STYLE_BORDER_LEFT_WIDTH );
rowWidthValue = getBorderWidthValue( rowComputedStyle, IStyle.STYLE_BORDER_LEFT_WIDTH );
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_LEFT,
cellStyle.getBorderLeftWidth( ), cellStyle.getBorderLeftStyle( ),
cellStyle.getBorderLeftColor( ), cellWidthValue,
rowStyle.getBorderLeftWidth( ), rowStyle.getBorderLeftStyle( ),
rowStyle.getBorderLeftColor( ), rowWidthValue );
}
else
{
buildCellRowBorder( styleBuffer, HTMLTags.ATTR_BORDER_LEFT,
cellStyle.getBorderLeftWidth( ), cellStyle.getBorderLeftStyle( ),
cellStyle.getBorderLeftColor( ), 0, null, null, null, 0 );
}
}
// output in-line style
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
/**
* Get the border width from a style. It don't support '%'.
* @param style
* @param borderNum
* @return
*/
private int getBorderWidthValue( IStyle style, int borderNum )
{
if( null == style )
{
return 0;
}
if( IStyle.STYLE_BORDER_TOP_WIDTH != borderNum
&& IStyle.STYLE_BORDER_RIGHT_WIDTH != borderNum
&& IStyle.STYLE_BORDER_BOTTOM_WIDTH != borderNum
&& IStyle.STYLE_BORDER_LEFT_WIDTH != borderNum )
{
return 0;
}
CSSValue value = style.getProperty( borderNum );
if ( value != null && ( value instanceof FloatValue ) )
{
FloatValue fv = (FloatValue) value;
float v = fv.getFloatValue( );
switch ( fv.getPrimitiveType( ) )
{
case CSSPrimitiveValue.CSS_CM :
return (int) ( v * 72000 / 2.54 );
case CSSPrimitiveValue.CSS_IN :
return (int) ( v * 72000 );
case CSSPrimitiveValue.CSS_MM :
return (int) ( v * 7200 / 2.54 );
case CSSPrimitiveValue.CSS_PT :
return (int) ( v * 1000 );
case CSSPrimitiveValue.CSS_NUMBER :
return (int) v;
}
}
return 0;
}
/**
* Treat the conflict of cell border and row border
* @param content
* @param borderName
* @param cellBorderWidth
* @param cellBorderStyle
* @param cellBorderColor
* @param cellWidthValue
* @param rowBorderWidth
* @param rowBorderStyle
* @param rowBorderColor
* @param rowWidthValue
*/
private void buildCellRowBorder( StringBuffer content, String borderName,
String cellBorderWidth, String cellBorderStyle, String cellBorderColor, int cellWidthValue,
String rowBorderWidth, String rowBorderStyle, String rowBorderColor, int rowWidthValue)
{
boolean bUseCellBorder = true;//true means choose cell's border; false means choose row's border
if( null == rowBorderStyle )
{
}
else if( null == cellBorderStyle )
{
bUseCellBorder = false;
}
else if( cellBorderStyle.matches( "hidden" ) )
{
}
else if( rowBorderStyle.matches( "hidden" ) )
{
bUseCellBorder = false;
}
else if( rowBorderStyle.matches( CSSConstants.CSS_NONE_VALUE ) )
{
}
else if( cellBorderStyle.matches( CSSConstants.CSS_NONE_VALUE ) )
{
bUseCellBorder = false;
}
else if( rowWidthValue < cellWidthValue )
{
}
else if( rowWidthValue > cellWidthValue )
{
bUseCellBorder = false;
}
else if( !cellBorderStyle.matches( rowBorderStyle ) )
{
Integer iCellBorderLevel = ( (Integer) borderStyleMap.get( cellBorderStyle ) );
Integer iRowBorderLevel = ( (Integer) borderStyleMap.get( rowBorderStyle ) );
if( null == iCellBorderLevel )
{
iCellBorderLevel = new Integer( -1 );
}
if( null == iRowBorderLevel )
{
iRowBorderLevel = new Integer( -1 );
}
if( iRowBorderLevel.intValue( ) > iCellBorderLevel.intValue( ) )
{
bUseCellBorder = false;
}
}
if( bUseCellBorder )
{
AttributeBuilder.buildBorder( content, borderName, cellBorderWidth, cellBorderStyle, cellBorderColor );
}
else
{
AttributeBuilder.buildBorder( content, borderName, rowBorderWidth, rowBorderStyle, rowBorderColor );
}
}
protected void handleStyle( IContent element, StringBuffer styleBuffer )
{
IStyle style;
if ( isEmbeddable )
{
style = element.getStyle( );
}
else
{
style = element.getInlineStyle( );
}
AttributeBuilder.buildStyle( styleBuffer, style, this, true );
// output in-line style
writer.attribute( HTMLTags.ATTR_STYLE, styleBuffer.toString( ) );
}
/**
* Handles the Vertical-Align property of the element content
*
* @param element
* the styled element content
* @param styleBuffer
* the StringBuffer instance
*/
protected void handleVerticalAlign( ICellContent element,
StringBuffer styleBuffer )
{
IStyle style = element.getComputedStyle( );
String verticalAlign = style.getVerticalAlign( );
if ( verticalAlign == null || verticalAlign.equals( "baseline" ) )
{
verticalAlign = "top";
}
if ( verticalAlign != null )
{
styleBuffer.append( "vertical-align: " );
styleBuffer.append( verticalAlign );
styleBuffer.append( ";" );
}
}
/**
* Handles the font-weight property of the cell content
* while the cell is in table header
*
* @param element
* the styled element content
* @param styleBuffer
* the StringBuffer instance
*/
protected void handleCellFont( ICellContent element,
StringBuffer styleBuffer )
{
IStyle style = element.getInlineStyle( );
String fontWeight = style.getFontWeight( );
if ( fontWeight == null )
{
style = element.getComputedStyle( );
fontWeight = style.getFontWeight( );
if ( fontWeight == null )
{
fontWeight = "normal";
}
styleBuffer.append( "font-weight: " );
styleBuffer.append( fontWeight );
styleBuffer.append( ";" );
}
}
/**
* adds the default table styles
*
* @param styleBuffer
*/
protected void addDefaultTableStyles( StringBuffer styleBuffer )
{
styleBuffer
.append( "border-collapse: collapse; empty-cells: show;" ); //$NON-NLS-1$
}
/**
* Resize chart template and table template element.
*
* @param content
* the styled element content
*/
private void resizeTemplateElement( IContent content )
{
Object genBy = content.getGenerateBy( );
if( genBy instanceof TemplateDesign )
{
TemplateDesign template = (TemplateDesign) genBy;
String allowedType = template.getAllowedType( );
if ( "ExtendedItem".equals(allowedType ) )
{
// Resize chart template element
IStyle style = content.getStyle( );
style.setProperty( IStyle.STYLE_CAN_SHRINK, IStyle.FALSE_VALUE );
content.setWidth( new DimensionType( 3, DimensionType.UNITS_IN ) );
content.setHeight( new DimensionType( 3, DimensionType.UNITS_IN ) );
}
else if ( "Table".equals(allowedType) )
{
// Resize table template element
IStyle style = content.getStyle( );
style.setProperty( IStyle.STYLE_CAN_SHRINK, IStyle.FALSE_VALUE );
content.setWidth( new DimensionType( 5, DimensionType.UNITS_IN ) );
}
}
}
/**
* judge the content is belong table template element or not.
*
* @param content
* the styled element content
*/
private boolean isTalbeTemplateElement( IContent content )
{
Object genBy = content.getGenerateBy( );
if( genBy instanceof TemplateDesign )
{
TemplateDesign template = (TemplateDesign) genBy;
String allowedType = template.getAllowedType( );
if ( "Table".equals(allowedType) )
{
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endGroup(org.eclipse.birt.report.engine.content.IGroupContent)
*/
public void endGroup( IGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endListBand(org.eclipse.birt.report.engine.content.IListBandContent)
*/
public void endListBand( IListBandContent listBand )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endListGroup(org.eclipse.birt.report.engine.content.IListGroupContent)
*/
public void endListGroup( IListGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endTableBand(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void endTableBand( ITableBandContent band )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#endTableGroup(org.eclipse.birt.report.engine.content.ITableGroupContent)
*/
public void endTableGroup( ITableGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startGroup(org.eclipse.birt.report.engine.content.IGroupContent)
*/
public void startGroup( IGroupContent group )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startListBand(org.eclipse.birt.report.engine.content.IListBandContent)
*/
public void startListBand( IListBandContent listBand )
{
}
/**
* used to control the output of group bookmarks.
* @see {@link #startTableGroup(ITableGroupContent)}
* @see {@link #startListGroup(IListGroupContent)}
*/
protected Stack startedGroups = new Stack();
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startListGroup(org.eclipse.birt.report.engine.content.IListGroupContent)
*/
public void startListGroup( IListGroupContent group )
{
outputBookmark( group );
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startTableBand(org.eclipse.birt.report.engine.content.ITableBandContent)
*/
public void startTableBand( ITableBandContent band )
{
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.engine.emitter.ContentEmitterAdapter#startTableGroup(org.eclipse.birt.report.engine.content.ITableGroupContent)
*/
public void startTableGroup( ITableGroupContent group )
{
startedGroups.push( group );
}
private void outputBookmark( IGroupContent group )
{
String bookmark = group.getBookmark( );
if ( bookmark == null )
{
bookmark = idGenerator.generateUniqueID( );
group.setBookmark( bookmark );
}
writer.openTag( HTMLTags.TAG_SPAN );
writer.attribute( HTMLTags.ATTR_ID, group.getBookmark( ) );
writer.closeTag( HTMLTags.TAG_SPAN );
}
}
class IDGenerator
{
protected int bookmarkId = 0;
IDGenerator( )
{
this.bookmarkId = 0;
}
protected String generateUniqueID( )
{
bookmarkId ++;
return "AUTOGENBOOKMARK_" + bookmarkId;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/com/ichi2/anki/AnkiDroidWidget.java b/src/com/ichi2/anki/AnkiDroidWidget.java
index ce240ae9..c3af6932 100644
--- a/src/com/ichi2/anki/AnkiDroidWidget.java
+++ b/src/com/ichi2/anki/AnkiDroidWidget.java
@@ -1,351 +1,340 @@
/***************************************************************************************
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki;
import com.tomgibara.android.veecheck.util.PrefSettings;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.IBinder;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import com.tomgibara.android.veecheck.util.PrefSettings;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;
public class AnkiDroidWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.i(AnkiDroidApp.TAG, "onUpdate");
WidgetStatus.update(context);
}
public static class UpdateService extends Service {
/** If this action is used when starting the service, it will move to the next due deck. */
private static final String ACTION_NEXT = "org.ichi2.anki.AnkiDroidWidget.NEXT";
/**
* If this action is used when starting the service, it will move to the previous due
* deck.
*/
private static final String ACTION_PREV = "org.ichi2.anki.AnkiDroidWidget.PREV";
/**
* When received, this action is ignored by the service.
* <p>
* It is used to associate with elements that at some point need to have a pending intent
* associated with them, but want to clear it off afterwards.
*/
private static final String ACTION_IGNORE = "org.ichi2.anki.AnkiDroidWidget.IGNORE";
/**
* If this action is used when starting the service, it will open the current due deck.
*/
private static final String ACTION_OPEN = "org.ichi2.anki.AnkiDroidWidget.OPEN";
/**
* Update the state of the widget.
*/
public static final String ACTION_UPDATE = "org.ichi2.anki.AnkiDroidWidget.UPDATE";
/**
* The current due deck that is shown in the widget.
*
* <p>This value is kept around until as long as the service is running and it is shared
* by all instances of the widget.
*/
private int currentDueDeck = 0;
/** The cached information about the decks with due cards. */
private List<DeckStatus> dueDecks;
/** The cached number of total due cards. */
private int dueCardsCount;
private CharSequence getDeckStatusString(DeckStatus deck) {
SpannableStringBuilder sb = new SpannableStringBuilder();
SpannableString red = new SpannableString(Integer.toString(deck.mFailedCards));
red.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
SpannableString black = new SpannableString(Integer.toString(deck.mDueCards));
black.setSpan(new ForegroundColorSpan(Color.BLACK), 0, black.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
SpannableString blue = new SpannableString(Integer.toString(deck.mNewCards));
blue.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blue.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.append(red);
sb.append(" ");
sb.append(black);
sb.append(" ");
sb.append(blue);
return sb;
}
@Override
public void onStart(Intent intent, int startId) {
Log.i(AnkiDroidApp.TAG, "OnStart");
boolean updateDueDecksNow = true;
if (intent != null) {
// Bound checks will be done when updating the widget below.
if (ACTION_NEXT.equals(intent.getAction())) {
currentDueDeck++;
// Do not update the due decks on next action.
// This causes latency.
updateDueDecksNow = false;
} else if (ACTION_PREV.equals(intent.getAction())) {
currentDueDeck--;
// Do not update the due decks on prev action.
// This causes latency.
updateDueDecksNow = false;
} else if (ACTION_IGNORE.equals(intent.getAction())) {
updateDueDecksNow = false;
} else if (ACTION_OPEN.equals(intent.getAction())) {
Intent loadDeckIntent =
new Intent(Intent.ACTION_VIEW, intent.getData(), this, StudyOptions.class);
loadDeckIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(loadDeckIntent);
updateDueDecksNow = false;
} else if (ACTION_UPDATE.equals(intent.getAction())) {
// Updating the widget is done below for all actions.
Log.d(AnkiDroidApp.TAG, "AnkiDroidWidget.UpdateService: UPDATE");
}
}
RemoteViews updateViews = buildUpdate(this, updateDueDecksNow);
ComponentName thisWidget = new ComponentName(this, AnkiDroidWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, updateViews);
}
private RemoteViews buildUpdate(Context context, boolean updateDueDecksNow) {
Log.i(AnkiDroidApp.TAG, "buildUpdate");
// Resources res = context.getResources();
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);
// Add a click listener to open Anki from the icon.
// This should be always there, whether there are due cards or not.
Intent ankiDroidIntent = new Intent(context, StudyOptions.class);
ankiDroidIntent.setAction(Intent.ACTION_MAIN);
ankiDroidIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingAnkiDroidIntent =
PendingIntent.getActivity(context, 0, ankiDroidIntent, 0);
updateViews.setOnClickPendingIntent(R.id.anki_droid_logo,
pendingAnkiDroidIntent);
if (!AnkiDroidApp.isSdCardMounted()) {
updateViews.setTextViewText(R.id.anki_droid_title,
context.getText(R.string.sdcard_missing_message));
updateViews.setTextViewText(R.id.anki_droid_name, "");
updateViews.setTextViewText(R.id.anki_droid_status, "");
return updateViews;
}
// If we do not have a cached version, always update.
if (dueDecks == null || updateDueDecksNow) {
// Build a list of decks with due cards.
// Also compute the total number of cards due.
updateDueDecks();
}
if (dueCardsCount > 0) {
Resources resources = getResources();
String decksText = resources.getQuantityString(
R.plurals.widget_decks, dueDecks.size(), dueDecks.size());
String text = resources.getQuantityString(
R.plurals.widget_cards_in_decks_due, dueCardsCount, dueCardsCount, decksText);
updateViews.setTextViewText(R.id.anki_droid_title, text);
// If the current due deck is out of bound, go back to the first one.
if (currentDueDeck < 0 || currentDueDeck > dueDecks.size() - 1) {
currentDueDeck = 0;
}
// Show the name and info from the current due deck.
DeckStatus deckStatus = dueDecks.get(currentDueDeck);
updateViews.setTextViewText(R.id.anki_droid_name, deckStatus.mDeckName);
updateViews.setTextViewText(R.id.anki_droid_status,
getDeckStatusString(deckStatus));
PendingIntent openPendingIntent = getOpenPendingIntent(context,
deckStatus.mDeckPath);
updateViews.setOnClickPendingIntent(R.id.anki_droid_name, openPendingIntent);
updateViews.setOnClickPendingIntent(R.id.anki_droid_status, openPendingIntent);
// Enable or disable the prev and next buttons.
if (currentDueDeck > 0) {
updateViews.setImageViewResource(R.id.anki_droid_prev, R.drawable.widget_left_arrow);
updateViews.setOnClickPendingIntent(R.id.anki_droid_prev, getPrevPendingIntent(context));
} else {
updateViews.setImageViewResource(R.id.anki_droid_prev, R.drawable.widget_left_arrow_disabled);
updateViews.setOnClickPendingIntent(R.id.anki_droid_prev, getIgnoredPendingIntent(context));
}
if (currentDueDeck < dueDecks.size() - 1) {
updateViews.setImageViewResource(R.id.anki_droid_next, R.drawable.widget_right_arrow);
updateViews.setOnClickPendingIntent(R.id.anki_droid_next, getNextPendingIntent(context));
} else {
updateViews.setImageViewResource(R.id.anki_droid_next, R.drawable.widget_right_arrow_disabled);
updateViews.setOnClickPendingIntent(R.id.anki_droid_next, getIgnoredPendingIntent(context));
}
updateViews.setViewVisibility(R.id.anki_droid_name, View.VISIBLE);
updateViews.setViewVisibility(R.id.anki_droid_status, View.VISIBLE);
updateViews.setViewVisibility(R.id.anki_droid_next, View.VISIBLE);
updateViews.setViewVisibility(R.id.anki_droid_prev, View.VISIBLE);
} else {
// No card is currently due.
updateViews.setTextViewText(R.id.anki_droid_title,
context.getString(R.string.widget_no_cards_due));
updateViews.setTextViewText(R.id.anki_droid_name, "");
updateViews.setTextViewText(R.id.anki_droid_status, "");
updateViews.setViewVisibility(R.id.anki_droid_name, View.INVISIBLE);
updateViews.setViewVisibility(R.id.anki_droid_status, View.INVISIBLE);
updateViews.setViewVisibility(R.id.anki_droid_next, View.INVISIBLE);
updateViews.setViewVisibility(R.id.anki_droid_prev, View.INVISIBLE);
}
SharedPreferences preferences = PrefSettings.getSharedPrefs(context);
int minimumCardsDueForNotification = Integer.parseInt(preferences.getString(
"minimumCardsDueForNotification", "25"));
if (dueCardsCount >= minimumCardsDueForNotification) {
// Raise a notification
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.anki;
CharSequence tickerText = String.format(
getString(R.string.widget_minimum_cards_due_notification_ticker_text), dueCardsCount);
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
if (preferences.getBoolean("widgetVibrate", false)) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
if (preferences.getBoolean("widgetBlink", false)) {
notification.defaults |= Notification.DEFAULT_LIGHTS;
}
Context appContext = getApplicationContext();
CharSequence contentTitle = getText(R.string.widget_minimum_cards_due_notification_ticker_title);
notification.setLatestEventInfo(appContext, contentTitle, tickerText, pendingAnkiDroidIntent);
final int WIDGET_NOTIFY_ID = 1;
mNotificationManager.notify(WIDGET_NOTIFY_ID, notification);
}
return updateViews;
}
private void updateDueDecks() {
- Deck currentDeck = AnkiDroidApp.deck();
- if (currentDeck != null) {
- // Close the current deck, otherwise we'll have problems
- currentDeck.closeDeck();
- }
-
// Fetch the deck information, sorted by due cards
DeckStatus[] decks = WidgetStatus.fetch(getBaseContext());
- if (currentDeck != null) {
- AnkiDroidApp.setDeck(currentDeck);
- Deck.openDeck(currentDeck.getDeckPath());
- }
-
if (dueDecks == null) {
dueDecks = new ArrayList<DeckStatus>();
} else {
dueDecks.clear();
}
dueCardsCount = 0;
for (DeckStatus deck : decks) {
if (deck.mDueCards > 0) {
dueCardsCount += deck.mDueCards;
dueDecks.add(deck);
}
}
}
/**
* Returns a pending intent that updates the widget to show the next deck.
*/
private PendingIntent getNextPendingIntent(Context context) {
Intent ankiDroidIntent = new Intent(context, UpdateService.class);
ankiDroidIntent.setAction(ACTION_NEXT);
return PendingIntent.getService(context, 0, ankiDroidIntent, 0);
}
/**
* Returns a pending intent that updates the widget to show the previous deck.
*/
private PendingIntent getPrevPendingIntent(Context context) {
Intent ankiDroidIntent = new Intent(context, UpdateService.class);
ankiDroidIntent.setAction(ACTION_PREV);
return PendingIntent.getService(context, 0, ankiDroidIntent, 0);
}
/**
* Returns a pending intent that is ignored by the service.
*/
private PendingIntent getIgnoredPendingIntent(Context context) {
Intent ankiDroidIntent = new Intent(context, UpdateService.class);
ankiDroidIntent.setAction(ACTION_IGNORE);
return PendingIntent.getService(context, 0, ankiDroidIntent, 0);
}
/**
* Returns a pending intent that opens the current deck.
*/
private PendingIntent getOpenPendingIntent(Context context, String deckPath) {
Intent ankiDroidIntent = new Intent(context, UpdateService.class);
ankiDroidIntent.setAction(ACTION_OPEN);
ankiDroidIntent.setData(Uri.parse("file://" + deckPath));
return PendingIntent.getService(context, 0, ankiDroidIntent, 0);
}
@Override
public IBinder onBind(Intent arg0) {
Log.i(AnkiDroidApp.TAG, "onBind");
return null;
}
}
}
diff --git a/src/com/ichi2/anki/WidgetStatus.java b/src/com/ichi2/anki/WidgetStatus.java
index 065eb1dd..266b7878 100644
--- a/src/com/ichi2/anki/WidgetStatus.java
+++ b/src/com/ichi2/anki/WidgetStatus.java
@@ -1,139 +1,144 @@
/***************************************************************************************
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki;
import com.tomgibara.android.veecheck.util.PrefSettings;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.os.AsyncTask;
import android.util.Log;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
/**
* The status of the widget.
* <p>
* It contains the status of each of the decks.
*/
public final class WidgetStatus {
/** This class should not be instantiated. */
private WidgetStatus() {}
/** Request the widget to update its status. */
public static void update(Context context) {
Log.d(AnkiDroidApp.TAG, "WidgetStatus.update()");
AsyncTask<Context,Void,Context> updateDeckStatusAsyncTask = new UpdateDeckStatusAsyncTask();
updateDeckStatusAsyncTask.execute(context);
}
/** Returns the status of each of the decks. */
public static DeckStatus[] fetch(Context context) {
return MetaDB.getWidgetStatus(context);
}
private static class UpdateDeckStatusAsyncTask extends AsyncTask<Context, Void, Context> {
private static final DeckStatus[] EMPTY_DECK_STATUS = new DeckStatus[0];
private static DeckStatus[] mDecks = EMPTY_DECK_STATUS;
@Override
protected Context doInBackground(Context... params) {
Log.d(AnkiDroidApp.TAG, "WidgetStatus.UpdateDeckStatusAsyncTask.doInBackground()");
Context context = params[0];
SharedPreferences preferences = PrefSettings.getSharedPrefs(context);
String deckPath = preferences.getString("deckPath",
AnkiDroidApp.getStorageDirectory() + "/AnkiDroid");
File dir = new File(deckPath);
File[] fileList = dir.listFiles(new AnkiFileFilter());
if (fileList == null || fileList.length == 0) {
mDecks = EMPTY_DECK_STATUS;
return context;
}
// For the deck information
ArrayList<DeckStatus> decks = new ArrayList<DeckStatus>(fileList.length);
for (File file : fileList) {
try {
// Run through the decks and get the information
String absPath = file.getAbsolutePath();
String deckName = file.getName().replaceAll(".anki", "");
Log.i(AnkiDroidApp.TAG, "Found deck: " + absPath);
- Deck deck = Deck.openDeck(absPath);
+ Deck deck = Deck.openDeck(absPath, false);
int dueCards = deck.getDueCount();
int newCards = deck.getNewCountToday();
int failedCards = deck.getFailedSoonCount();
- deck.closeDeck();
+ // Close the database connection, but only if this is not the current database.
+ // Probably we need to make this atomic to be sure it will not cause a failure.
+ Deck currentDeck = AnkiDroidApp.deck();
+ if (currentDeck != null && currentDeck.getDB() != deck.getDB()) {
+ deck.closeDeck();
+ }
// Add the information about the deck
decks.add(new DeckStatus(absPath, deckName, newCards, dueCards, failedCards));
} catch (SQLException e) {
Log.i(AnkiDroidApp.TAG, "Could not open deck");
Log.e(AnkiDroidApp.TAG, e.toString());
}
}
if (!decks.isEmpty() && decks.size() > 1) {
// Sort and reverse the list if there are decks
Log.i(AnkiDroidApp.TAG, "Sorting deck");
// Ordered by reverse due cards number
Collections.sort(decks, new ByDueComparator());
}
mDecks = decks.toArray(EMPTY_DECK_STATUS);
return context;
}
@Override
protected void onPostExecute(Context context) {
Log.d(AnkiDroidApp.TAG, "WidgetStatus.UpdateDeckStatusAsyncTask.onPostExecute()");
MetaDB.storeWidgetStatus(context, mDecks);
Intent intent = new Intent(context, AnkiDroidWidget.UpdateService.class);
intent.setAction(AnkiDroidWidget.UpdateService.ACTION_UPDATE);
context.startService(intent);
}
/** Comparator that sorts instances of {@link DeckStatus} based on number of due cards. */
private static class ByDueComparator implements java.util.Comparator<DeckStatus> {
@Override
public int compare(DeckStatus deck1, DeckStatus deck2) {
// Reverse due cards number order
return deck2.mDueCards - deck1.mDueCards;
}
}
/** Filter for Anki files. */
private static final class AnkiFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".anki");
}
}
}
}
| false | false | null | null |
diff --git a/app/controllers/TMController.java b/app/controllers/TMController.java
index d3d87ed..8caf98b 100644
--- a/app/controllers/TMController.java
+++ b/app/controllers/TMController.java
@@ -1,304 +1,302 @@
package controllers;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import controllers.deadbolt.Deadbolt;
import models.account.Account;
import models.account.AccountEntity;
import models.account.User;
import models.tm.Project;
import models.tm.TMUser;
import models.tm.test.Tag;
import org.hibernate.Session;
import play.cache.Cache;
import play.db.jpa.JPA;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.Util;
import play.mvc.With;
import play.templates.JavaExtensions;
import util.Logger;
/**
* Parent controller for the TM application.
* Sets common view template data such as username, visible menu elements, ...
* Contains common utility methods.
*
* @author Manuel Bernhardt <[email protected]>
*/
@With(Deadbolt.class)
public class TMController extends Controller {
- public static final String USER_KEY = session.getId() + "_user";
-
/**
* Set Hibernate filters for multi-tenancy and so on.
*/
@Before(priority = 0)
public static void setFilters() {
if (Security.isConnected()) {
// account filter
Long accountId = getConnectedUser().account.getId();
((Session) JPA.em().getDelegate()).enableFilter("account").setParameter("account_id", accountId);
// active users filter
((Session) JPA.em().getDelegate()).enableFilter("activeUser").setParameter("active", true);
((Session) JPA.em().getDelegate()).enableFilter("activeTMUser").setParameter("active", true);
// we need to do the lookup for an active project here first, otherwise we enable the filter before passing the parameter.
if (controllerHasActiveProject()) {
Project p = getActiveProject();
if (p != null) {
((Session) JPA.em().getDelegate()).enableFilter("project").setParameter("project_id", p.getId());
} else {
getConnectedUser().<TMUser>merge().initializeActiveProject();
}
}
}
}
/**
* Load user details for rendering, and update the session expiration timestamp.
*/
@Before(priority = 1)
public static void loadConnectedUser() {
if (Security.isConnected()) {
User user = getConnectedUser().user;
renderArgs.put("firstName", user.firstName);
renderArgs.put("lastName", user.lastName);
if (controllerHasActiveProject()) {
renderArgs.put("activeProject", getActiveProject());
renderArgs.put("projects", getConnectedUser().getProjects());
}
// TODO write a job that goes over this time every 5 minutes and flushes the time to the database
// TODO but only if it is more recent than the time in the database
// TODO also disconnect users for which the session is not active any longer.
Cache.set(session.getId() + "_session_expiration", Security.getSessionExpirationTimestamp());
}
}
public static TMUser getConnectedUser() {
// TODO cache this better
if (Security.isConnected()) {
// temporary
- TMUser u = (TMUser) Cache.get(USER_KEY);
+ TMUser u = (TMUser) Cache.get(session.getId() + "_user");
if (u == null) {
// TODO FIXME search by user account as well - we can only do this once we know the account from the URL
u = TMUser.find("from TMUser u where u.user.email = ?", Security.connected()).<TMUser>first();
- Cache.set(USER_KEY, u);
+ Cache.set(session.getId() + "_user", u);
}
return u;
} else {
// TODO test this!
flash.put("url", "GET".equals(request.method) ? request.url : "/");
try {
Secure.login();
} catch (Throwable throwable) {
Logger.error(Logger.LogType.TECHNICAL, throwable, "Error while logging in user upon connected user query through getConnectedUser()");
}
}
return null;
}
public static Account getConnectedUserAccount() {
return getConnectedUser().user.account;
}
/**
* Gets the active project for the connected user, <code>null</code> if none is set
*
* @return the active {@see Project}
*/
public static Project getActiveProject() {
if (!controllerHasActiveProject()) {
throw new RuntimeException("Active project can't be fetched in the admin area");
}
return getConnectedUser().activeProject;
}
/**
* Does this controller have the concept of active project
*
* @return <code>true</code> if this is not an admin controller
*/
private static boolean controllerHasActiveProject() {
return !request.controller.startsWith("admin");
}
/**
* Switches the user to a different project
*
* @param projectId the id of the project to switch to
*/
public static void switchActiveProject(Long projectId) {
if (!controllerHasActiveProject()) {
// ???
Logger.error(Logger.LogType.TECHNICAL, "Attempt to switch to a different active project from the admin area, project ID %s, controller %s", projectId, request.controllerClass.getName());
error("Cannot switch to a different project from the administration area");
}
checkAuthenticity();
Project project = Lookups.getProject(projectId);
if (project == null) {
Logger.error(Logger.LogType.SECURITY, "Trying to switch to non-existing project with ID %s", projectId);
notFound("Can't find project with ID " + projectId);
}
TMUser connectedUser = getConnectedUser();
connectedUser = connectedUser.merge();
if (connectedUser.getProjects().contains(project)) {
// check if there is enough place on the project we want to switch to
// effectively switch the user to the project
Logger.info(Logger.LogType.USER, "Switching to project '%s'", project.name);
connectedUser.activeProject = project;
connectedUser.save();
// invalidate roles caches and others
- Cache.set(USER_KEY, connectedUser);
+ Cache.set(session.getId() + "_user", connectedUser);
// figure out a way to switch to the current view
System.out.println();
System.out.println();
System.out.println();
System.out.println(request.controller);
System.out.println();
System.out.println();
System.out.println();
System.out.println();
redirect(request.controller + ".index");
} else {
Logger.error(Logger.LogType.SECURITY, "Attempt to switch to project without membership! Project: '%s'", project.name);
forbidden("You are not a member of this project.");
}
}
@Util
public static void checkInAccount(AccountEntity accountEntity) {
if (!accountEntity.isInAccount(getConnectedUserAccount())) {
Logger.fatal(Logger.LogType.SECURITY, "Entity %s with ID %s is not in account %s of user %s", accountEntity.getClass(), accountEntity.getId(), getConnectedUserAccount().name, Security.connected());
forbidden();
}
}
/**
* Returns a list of Tag instances given a comma-separated list of strings (tag names)
*
* @param tags a comma-separated list of strings
* @param type the type of tags
* @return a list of {@link Tag} instances
*/
@Util
public static List<Tag> getTags(String tags, Tag.TagType type) {
List<Tag> tagList = new ArrayList<Tag>();
if (tags != null) {
for (String name : tags.split(",")) {
Tag t = Tag.find("from Tag t where t.name = ? and t.type = '" + type.name() + "' and t.project = ?", name.trim(), getActiveProject()).first();
if (t == null && name.trim().length() > 0) {
t = new Tag(getActiveProject());
t.name = name.trim();
t.type = type;
t.create();
}
if (!tagList.contains(t)) {
tagList.add(t);
}
}
}
return tagList;
}
/////////////////////////////////////////////////////////////
// The following code is used by the ox.form implementation /
/////////////////////////////////////////////////////////////
private final static DateFormat df = new SimpleDateFormat(play.Play.configuration.getProperty("date.format"));
/**
* Renders the values of given fields of a base object as JSON string. Values in the JSON object are prefixed with "value_".
*
* @param base the base object
* @param fields the fields (paths) to render
*/
@Util
public static void renderFields(Object base, String[] fields) {
Map<String, Object> values = new HashMap<String, Object>();
List<String> toResolve = new ArrayList<String>();
// merge required field paths, sorted by length and alphabetical order
List<String> sortedFields = Arrays.asList(fields);
Collections.sort(sortedFields);
for (String f : sortedFields) {
String[] path = f.split("\\.");
String resolve = path[0];
for (int i = 1; i < path.length + 1; i++) {
if (!toResolve.contains(resolve)) {
toResolve.add(resolve);
}
if (i < path.length) {
resolve = resolve + "." + path[i];
}
}
}
// here we do two assumptions: that we only have one kind of baseObject, and that the sorting works so that it will be first
// in the future we may want to add support for more than one baseObject
values.put(toResolve.get(0), base);
for (String s : toResolve) {
if (!values.containsKey(s)) {
if (s.indexOf(".") == -1) {
values.put(s, getValue(base, s));
} else {
// since we did resolve the required field paths beforehand, we can safely rely on our parent being already resolved
String parent = s.substring(0, s.lastIndexOf("."));
Object parentValue = values.get(parent);
if (parentValue != null) {
values.put(s, getValue(parentValue, s.substring(parent.length() + 1, s.length())));
} else {
// "nullable pointer"... we just ignore it in this case
values.put(s, null);
}
}
}
}
Map<String, Object> result = new HashMap<String, Object>();
for (String r : sortedFields) {
Object val = values.get(r);
// Gson doesn't help here, for some reason it ignores the data format setting in lists...
if (val instanceof Date) {
val = df.format((Date) val);
}
result.put("value_" + r.replaceAll("\\.", "_"), val == null ? "" : val);
}
renderJSON(result);
}
@Util
private static Object getValue(Object base, String s) {
Method getter = null;
try {
getter = base.getClass().getMethod("get" + JavaExtensions.capFirst(s));
return getter.invoke(base, new Object[0]);
} catch (Throwable t) {
// do nothing for now, but let the console know
t.printStackTrace();
}
return null;
}
}
| false | false | null | null |
diff --git a/server-integ/src/test/java/org/apache/directory/server/operations/modify/ModifyReplaceIT.java b/server-integ/src/test/java/org/apache/directory/server/operations/modify/ModifyReplaceIT.java
index 8c3f9763d0..d43c158ede 100644
--- a/server-integ/src/test/java/org/apache/directory/server/operations/modify/ModifyReplaceIT.java
+++ b/server-integ/src/test/java/org/apache/directory/server/operations/modify/ModifyReplaceIT.java
@@ -1,373 +1,373 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.server.operations.modify;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.apache.directory.server.core.DefaultDirectoryService;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.entry.ServerEntry;
import org.apache.directory.server.core.integ.IntegrationUtils;
import org.apache.directory.server.core.integ.Level;
import org.apache.directory.server.core.integ.annotations.ApplyLdifs;
import org.apache.directory.server.core.integ.annotations.CleanupLevel;
import org.apache.directory.server.core.integ.annotations.Factory;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmIndex;
import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition;
import org.apache.directory.server.integ.LdapServerFactory;
import org.apache.directory.server.integ.SiRunner;
import static org.apache.directory.server.integ.ServerIntegrationUtils.getWiredContext;
import org.apache.directory.server.ldap.LdapService;
import org.apache.directory.server.ldap.handlers.bind.MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.SimpleMechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.cramMD5.CramMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.digestMD5.DigestMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.gssapi.GssapiMechanismHandler;
import org.apache.directory.server.ldap.handlers.bind.ntlm.NtlmMechanismHandler;
import org.apache.directory.server.ldap.handlers.extended.StartTlsHandler;
import org.apache.directory.server.ldap.handlers.extended.StoredProcedureExtendedOperationHandler;
import org.apache.directory.server.protocol.shared.transport.TcpTransport;
import org.apache.directory.server.xdbm.Index;
import org.apache.directory.shared.ldap.constants.SchemaConstants;
import org.apache.directory.shared.ldap.constants.SupportedSaslMechanisms;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.util.AvailablePortFinder;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertEquals;
/**
* Test case for all modify replace operations.
*
* Demonstrates DIRSERVER-646 ("Replacing an unknown attribute with
* no values (deletion) causes an error").
*/
@RunWith ( SiRunner.class )
@CleanupLevel ( Level.SUITE )
@Factory ( ModifyReplaceIT.Factory.class )
@ApplyLdifs( {
// Entry # 1
"dn: cn=Kate Bush,ou=system\n" +
"objectClass: top\n" +
"objectClass: person\n" +
"sn: Bush\n" +
"cn: Kate Bush\n\n" +
// Entry # 2
"dn: cn=Kim Wilde,ou=system\n" +
"objectClass: top\n" +
"objectClass: person\n" +
"objectClass: organizationalPerson \n" +
"objectClass: inetOrgPerson \n" +
"sn: Wilde\n" +
"cn: Kim Wilde\n\n"
}
)
public class ModifyReplaceIT
{
private static final String BASE = "ou=system";
public static LdapService ldapService;
public static class Factory implements LdapServerFactory
{
public LdapService newInstance() throws Exception
{
DirectoryService service = new DefaultDirectoryService();
IntegrationUtils.doDelete( service.getWorkingDirectory() );
service.getChangeLog().setEnabled( true );
service.setShutdownHookEnabled( false );
JdbmPartition system = new JdbmPartition();
system.setId( "system" );
// @TODO need to make this configurable for the system partition
system.setCacheSize( 500 );
system.setSuffix( "ou=system" );
// Add indexed attributes for system partition
Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OBJECT_CLASS_AT ) );
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OU_AT ) );
system.setIndexedAttributes( indexedAttrs );
service.setSystemPartition( system );
// change the working directory to something that is unique
// on the system and somewhere either under target directory
// or somewhere in a temp area of the machine.
LdapService ldapService = new LdapService();
ldapService.setDirectoryService( service );
- ldapService.setSocketAcceptor( new NioSocketAcceptor() );
int port = AvailablePortFinder.getNextAvailable( 1024 );
ldapService.setTcpTransport( new TcpTransport( port ) );
+ ldapService.setSocketAcceptor( new NioSocketAcceptor() );
ldapService.getTcpTransport().setNbThreads( 3 );
ldapService.addExtendedOperationHandler( new StartTlsHandler() );
ldapService.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );
// Setup SASL Mechanisms
Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new SimpleMechanismHandler() );
CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );
DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );
GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );
NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );
ldapService.setSaslMechanismHandlers( mechanismHandlerMap );
return ldapService;
}
}
/**
* Create a person entry and try to remove a not present attribute
*/
@Test
public void testReplaceToRemoveNotPresentAttribute() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
Attribute attr = new BasicAttribute( "description" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
sysRoot.modifyAttributes( rdn, new ModificationItem[] { item } );
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Bush)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = ( SearchResult ) enm.next();
Attribute cn = sr.getAttributes().get( "cn" );
assertNotNull( cn );
assertTrue( cn.contains( "Kate Bush") );
Attribute desc = sr.getAttributes().get( "description" );
assertNull( desc );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry and try to add a not present attribute via a REPLACE
*/
@Test
public void testReplaceToAddNotPresentAttribute() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
Attribute attr = new BasicAttribute( "description", "added description" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
sysRoot.modifyAttributes( rdn, new ModificationItem[] { item } );
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Bush)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = ( SearchResult ) enm.next();
Attribute cn = sr.getAttributes().get( "cn" );
assertNotNull( cn );
assertTrue( cn.contains( "Kate Bush") );
Attribute desc = sr.getAttributes().get( "description" );
assertNotNull( desc );
assertTrue( desc.contains( "added description") );
assertEquals( 1, desc.size() );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry and try to remove a non existing attribute
*/
@Test
public void testReplaceNonExistingAttribute() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
Attribute attr = new BasicAttribute( "numberOfOctaves" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
sysRoot.modifyAttributes( rdn, new ModificationItem[] { item } );
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Bush)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = enm.next();
Attribute cn = sr.getAttributes().get( "cn" );
assertNotNull( cn );
assertTrue( cn.contains( "Kate Bush" ) );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry and try to remove a non existing attribute
*/
@Test
public void testReplaceNonExistingAttributeManyMods() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
Attribute attr = new BasicAttribute( "numberOfOctaves" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
Attribute attr2 = new BasicAttribute( "description", "blah blah blah" );
ModificationItem item2 = new ModificationItem( DirContext.ADD_ATTRIBUTE, attr2 );
sysRoot.modifyAttributes(rdn, new ModificationItem[] { item, item2 });
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Bush)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = enm.next();
Attribute cn = sr.getAttributes().get( "cn" );
assertNotNull( cn );
assertTrue( cn.contains( "Kate Bush" ) );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry and try to replace a non existing indexed attribute
*/
@Test
public void testReplaceNonExistingIndexedAttribute() throws Exception
{
DirContext sysRoot = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kim Wilde";
//ldapService.getDirectoryService().getPartitions();
Attribute attr = new BasicAttribute( "ou", "test" );
ModificationItem item = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, attr );
sysRoot.modifyAttributes(rdn, new ModificationItem[] { item });
SearchControls sctls = new SearchControls();
sctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String filter = "(sn=Wilde)";
String base = "";
NamingEnumeration<SearchResult> enm = sysRoot.search( base, filter, sctls );
while ( enm.hasMore() )
{
SearchResult sr = enm.next();
Attribute ou = sr.getAttributes().get( "ou" );
assertNotNull( ou );
assertTrue( ou.contains( "test" ) );
}
sysRoot.destroySubcontext( rdn );
}
/**
* Create a person entry, replace telephoneNumber, verify the
* case of the attribute description attribute.
*/
@Test
public void testReplaceCaseOfAttributeDescription() throws Exception
{
DirContext ctx = ( DirContext ) getWiredContext( ldapService ).lookup( BASE );
String rdn = "cn=Kate Bush";
// Replace telephoneNumber
String newValue = "2345678901";
Attributes attrs = new BasicAttributes( "telephoneNumber", newValue, false );
ctx.modifyAttributes( rdn, DirContext.REPLACE_ATTRIBUTE, attrs );
// Verify, that
// - case of attribute description is correct
// - attribute value is added
attrs = ctx.getAttributes( rdn );
Attribute attr = attrs.get( "telephoneNumber" );
assertNotNull( attr );
assertEquals( "telephoneNumber", attr.getID() );
assertTrue( attr.contains( newValue ) );
assertEquals( 1, attr.size() );
}
}
| false | true | public LdapService newInstance() throws Exception
{
DirectoryService service = new DefaultDirectoryService();
IntegrationUtils.doDelete( service.getWorkingDirectory() );
service.getChangeLog().setEnabled( true );
service.setShutdownHookEnabled( false );
JdbmPartition system = new JdbmPartition();
system.setId( "system" );
// @TODO need to make this configurable for the system partition
system.setCacheSize( 500 );
system.setSuffix( "ou=system" );
// Add indexed attributes for system partition
Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OBJECT_CLASS_AT ) );
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OU_AT ) );
system.setIndexedAttributes( indexedAttrs );
service.setSystemPartition( system );
// change the working directory to something that is unique
// on the system and somewhere either under target directory
// or somewhere in a temp area of the machine.
LdapService ldapService = new LdapService();
ldapService.setDirectoryService( service );
ldapService.setSocketAcceptor( new NioSocketAcceptor() );
int port = AvailablePortFinder.getNextAvailable( 1024 );
ldapService.setTcpTransport( new TcpTransport( port ) );
ldapService.getTcpTransport().setNbThreads( 3 );
ldapService.addExtendedOperationHandler( new StartTlsHandler() );
ldapService.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );
// Setup SASL Mechanisms
Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new SimpleMechanismHandler() );
CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );
DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );
GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );
NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );
ldapService.setSaslMechanismHandlers( mechanismHandlerMap );
return ldapService;
}
| public LdapService newInstance() throws Exception
{
DirectoryService service = new DefaultDirectoryService();
IntegrationUtils.doDelete( service.getWorkingDirectory() );
service.getChangeLog().setEnabled( true );
service.setShutdownHookEnabled( false );
JdbmPartition system = new JdbmPartition();
system.setId( "system" );
// @TODO need to make this configurable for the system partition
system.setCacheSize( 500 );
system.setSuffix( "ou=system" );
// Add indexed attributes for system partition
Set<Index<?,ServerEntry>> indexedAttrs = new HashSet<Index<?,ServerEntry>>();
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OBJECT_CLASS_AT ) );
indexedAttrs.add( new JdbmIndex<String,ServerEntry>( SchemaConstants.OU_AT ) );
system.setIndexedAttributes( indexedAttrs );
service.setSystemPartition( system );
// change the working directory to something that is unique
// on the system and somewhere either under target directory
// or somewhere in a temp area of the machine.
LdapService ldapService = new LdapService();
ldapService.setDirectoryService( service );
int port = AvailablePortFinder.getNextAvailable( 1024 );
ldapService.setTcpTransport( new TcpTransport( port ) );
ldapService.setSocketAcceptor( new NioSocketAcceptor() );
ldapService.getTcpTransport().setNbThreads( 3 );
ldapService.addExtendedOperationHandler( new StartTlsHandler() );
ldapService.addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );
// Setup SASL Mechanisms
Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String,MechanismHandler>();
mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new SimpleMechanismHandler() );
CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );
DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );
GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );
NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );
ldapService.setSaslMechanismHandlers( mechanismHandlerMap );
return ldapService;
}
|
diff --git a/src/org/apache/xalan/xsltc/dom/DOMImpl.java b/src/org/apache/xalan/xsltc/dom/DOMImpl.java
index ac1dd725..dabb6c67 100644
--- a/src/org/apache/xalan/xsltc/dom/DOMImpl.java
+++ b/src/org/apache/xalan/xsltc/dom/DOMImpl.java
@@ -1,3253 +1,3252 @@
/*
* @(#)$Id$
*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 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 "Xalan" 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) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
* @author Morten Jorgensen
*
*/
/* Issues to resolve:
o) All stacks in the DOMBuilder class have hardcoded length
o) There are no namespace nodes (but namespace are handled correctly).
*/
package org.apache.xalan.xsltc.dom;
import java.io.Externalizable;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Stack;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Document;
import org.xml.sax.*;
import org.xml.sax.ext.*;
import org.apache.xalan.xsltc.*;
import org.apache.xalan.xsltc.util.IntegerArray;
import org.apache.xalan.xsltc.runtime.BasisLibrary;
import org.apache.xalan.xsltc.runtime.SAXAdapter;
import org.apache.xalan.xsltc.runtime.Hashtable;
public final class DOMImpl implements DOM, Externalizable {
// empty String for null attribute values
private final static String EMPTYSTRING = "";
// empty iterator to be returned when there are no children
private final static NodeIterator EMPTYITERATOR = new NodeIterator() {
public NodeIterator reset() { return this; }
public NodeIterator setStartNode(int node) { return this; }
public int next() { return NULL; }
public void setMark() {}
public void gotoMark() {}
public int getLast() { return 0; }
public int getPosition() { return 0; }
public NodeIterator cloneIterator() { return this; }
public boolean isReverse() { return false; }
public NodeIterator resetOnce() { return this; }
};
// Contains the number of nodes and attribute nodes in the tree
private int _treeNodeLimit;
private int _firstAttributeNode;
// Node-to-type, type-to-name, and name-to-type mappings
private short[] _type;
private Hashtable _types = null;
private String[] _namesArray;
// Tree navigation arrays
private int[] _parent;
private int[] _nextSibling;
private int[] _offsetOrChild; // Serves two purposes !!!
private int[] _lengthOrAttr; // Serves two purposes !!!
// Holds contents of text/comment nodes and attribute values
private char[] _text;
// Namespace related stuff
private String[] _uriArray;
private String[] _prefixArray;
private short[] _namespace;
private short[] _prefix;
private Hashtable _nsIndex = new Hashtable();
// Tracks which textnodes are whitespaces and which are not
private BitArray _whitespace; // takes xml:space into acc.
// The URI to this document
private String _documentURI;
// Support for access/navigation through org.w3c.dom API
private Node[] _nodes;
private NodeList[] _nodeLists;
private static NodeList EmptyNodeList;
private static NamedNodeMap EmptyNamedNodeMap;
/**
* Define the origin of the document from which the tree was built
*/
public void setDocumentURI(String uri) {
_documentURI = uri;
}
/**
* Returns the origin of the document from which the tree was built
*/
public String getDocumentURI() {
return(_documentURI);
}
public String getDocumentURI(int node) {
return(_documentURI);
}
public void setupMapping(String[] names, String[] namespaces) {
// This method only has a function in DOM adapters
}
/**
* Returns 'true' if a specific node is an element (of any type)
*/
private boolean isElement(final int node) {
return ((node < _firstAttributeNode) && (_type[node] >= NTYPES));
}
/**
* Returns the number of nodes in the tree (used for indexing)
*/
public int getSize() {
return(_type.length);
}
/**
* Part of the DOM interface - no function here.
*/
public void setFilter(StripFilter filter) { }
/**
* Returns true if node1 comes before node2 in document order
*/
public boolean lessThan(int node1, int node2) {
if ((node2 < _treeNodeLimit) && (node1 < node2))
return(true);
else
return(false);
}
/**
* Create an org.w3c.dom.Node from a node in the tree
*/
public Node makeNode(int index) {
if (_nodes == null) {
_nodes = new Node[_type.length];
}
return _nodes[index] != null
? _nodes[index]
: (_nodes[index] = new NodeImpl(index));
}
/**
* Create an org.w3c.dom.Node from a node in an iterator
* The iterator most be started before this method is called
*/
public Node makeNode(NodeIterator iter) {
return makeNode(iter.next());
}
/**
* Create an org.w3c.dom.NodeList from a node in the tree
*/
public NodeList makeNodeList(int index) {
if (_nodeLists == null) {
_nodeLists = new NodeList[_type.length];
}
return _nodeLists[index] != null
? _nodeLists[index]
: (_nodeLists[index] = new NodeListImpl(index));
}
/**
* Create an org.w3c.dom.NodeList from a node iterator
* The iterator most be started before this method is called
*/
public NodeList makeNodeList(NodeIterator iter) {
return new NodeListImpl(iter);
}
/**
* Create an empty org.w3c.dom.NodeList
*/
private NodeList getEmptyNodeList() {
return EmptyNodeList != null
? EmptyNodeList
: (EmptyNodeList = new NodeListImpl(new int[0]));
}
/**
* Create an empty org.w3c.dom.NamedNodeMap
*/
private NamedNodeMap getEmptyNamedNodeMap() {
return EmptyNamedNodeMap != null
? EmptyNamedNodeMap
: (EmptyNamedNodeMap = new NamedNodeMapImpl(new int[0]));
}
/**
* Exception thrown by methods in inner classes implementing
* various org.w3c.dom interfaces (below)
*/
private final class NotSupportedException extends DOMException {
public NotSupportedException() {
super(NOT_SUPPORTED_ERR, "modification not supported");
}
}
/**************************************************************
* Implementation of org.w3c.dom.NodeList
*/
private final class NodeListImpl implements NodeList {
private final int[] _nodes;
public NodeListImpl(int node) {
_nodes = new int[1];
_nodes[0] = node;
}
public NodeListImpl(int[] nodes) {
_nodes = nodes;
}
public NodeListImpl(NodeIterator iter) {
final IntegerArray list = new IntegerArray();
int node;
while ((node = iter.next()) != NodeIterator.END) {
list.add(node);
}
_nodes = list.toIntArray();
}
public int getLength() {
return _nodes.length;
}
public Node item(int index) {
return makeNode(_nodes[index]);
}
}
/**************************************************************
* Implementation of org.w3c.dom.NamedNodeMap
*/
private final class NamedNodeMapImpl implements NamedNodeMap {
private final int[] _nodes;
public NamedNodeMapImpl(int[] nodes) {
_nodes = nodes;
}
public int getLength() {
return _nodes.length;
}
public Node getNamedItem(String name) {
for (int i = 0; i < _nodes.length; i++) {
if (name.equals(getNodeName(_nodes[i]))) {
return makeNode(_nodes[i]);
}
}
return null;
}
public Node item(int index) {
return makeNode(_nodes[index]);
}
public Node removeNamedItem(String name) {
throw new NotSupportedException();
}
public Node setNamedItem(Node node) {
throw new NotSupportedException();
}
public Node getNamedItemNS(String uri, String local) {
return(getNamedItem(uri+':'+local));
}
public Node setNamedItemNS(Node node) {
throw new NotSupportedException();
}
public Node removeNamedItemNS(String uri, String local) {
throw new NotSupportedException();
}
}
/**************************************************************
* Implementation of org.w3c.dom.Node
*/
private final class NodeImpl implements Node {
private final int _index;
public NodeImpl(int index) {
_index = index;
}
public short getNodeType() {
switch (_type[_index]) {
case ROOT:
return Node.DOCUMENT_NODE;
case TEXT:
return Node.TEXT_NODE;
case PROCESSING_INSTRUCTION:
return Node.PROCESSING_INSTRUCTION_NODE;
case COMMENT:
return Node.COMMENT_NODE;
default:
return _index < _firstAttributeNode
? Node.ELEMENT_NODE : Node.ATTRIBUTE_NODE;
}
}
public Node getParentNode() {
final int parent = getParent(_index);
return parent > NULL ? makeNode(parent) : null;
}
public Node appendChild(Node node) throws DOMException {
throw new NotSupportedException();
}
public Node cloneNode(boolean deep) {
throw new NotSupportedException();
}
public NamedNodeMap getAttributes() {
if (getNodeType() == Node.ELEMENT_NODE) {
int attribute = _lengthOrAttr[_index];
if (attribute != NULL) {
final IntegerArray attributes = new IntegerArray(4);
do {
attributes.add(attribute);
}
while ((attribute = _nextSibling[attribute]) != 0);
return new NamedNodeMapImpl(attributes.toIntArray());
}
else {
return getEmptyNamedNodeMap();
}
}
else {
return null;
}
}
public NodeList getChildNodes() {
if (hasChildNodes()) {
final IntegerArray children = new IntegerArray(8);
int child = _offsetOrChild[_index];
do {
children.add(child);
}
while ((child = _nextSibling[child]) != 0);
return new NodeListImpl(children.toIntArray());
}
else {
return getEmptyNodeList();
}
}
public Node getFirstChild() {
return hasChildNodes()
? makeNode(_offsetOrChild[_index])
: null;
}
public Node getLastChild() {
return hasChildNodes()
? makeNode(lastChild(_index))
: null;
}
public Node getNextSibling() {
final int next = _nextSibling[_index];
return next != 0 ? makeNode(next) : null;
}
public String getNodeName() {
switch (_type[_index]) {
case ROOT:
return "#document";
case TEXT:
return "#text";
case PROCESSING_INSTRUCTION:
return "#pi";
case COMMENT:
return "#comment";
default:
return DOMImpl.this.getNodeName(_index);
}
}
public String getNodeValue() throws DOMException {
return DOMImpl.this.getNodeValue(_index);
}
public Document getOwnerDocument() {
return null;
}
//??? how does it work with attributes
public Node getPreviousSibling() {
int node = _parent[_index];
if (node > NULL) {
int prev = -1;
node = _offsetOrChild[node];
while (node != _index) {
node = _nextSibling[prev = node];
}
if (prev != -1) {
return makeNode(prev);
}
}
return null;
}
public boolean hasChildNodes() {
switch (getNodeType()) {
case Node.ELEMENT_NODE:
case Node.DOCUMENT_NODE:
return _offsetOrChild[_index] != 0;
default:
return false;
}
}
public Node insertBefore(Node n1, Node n2) throws DOMException {
throw new NotSupportedException();
}
public Node removeChild(Node n) throws DOMException {
throw new NotSupportedException();
}
public Node replaceChild(Node n1, Node n2) throws DOMException {
throw new NotSupportedException();
}
public void setNodeValue(String s) throws DOMException {
throw new NotSupportedException();
}
public void normalize() {
throw new NotSupportedException();
}
public boolean isSupported(String feature, String version) {
return false;
}
public String getNamespaceURI() {
return _uriArray[_namespace[_type[_index] - NTYPES]];
}
public String getPrefix() {
return _prefixArray[_prefix[_index]];
}
public void setPrefix(String prefix) {
throw new NotSupportedException();
}
public String getLocalName() {
return DOMImpl.this.getLocalName(_index);
}
public boolean hasAttributes() {
return (_lengthOrAttr[_index] != NULL);
}
}
// A single copy (cache) of ElementFilter
private Filter _elementFilter;
/**
* Returns a filter that lets only element nodes through
*/
private Filter getElementFilter() {
if (_elementFilter == null) {
_elementFilter = new Filter() {
public boolean test(int node) {
return isElement(node);
}
};
}
return _elementFilter;
}
/**
* Implementation of a filter that only returns nodes of a
* certain type (instanciate through getTypeFilter()).
*/
private final class TypeFilter implements Filter {
private final int _nodeType;
public TypeFilter(int type) {
_nodeType = type;
}
public boolean test(int node) {
return _type[node] == _nodeType;
}
}
/**
* Returns a node type filter (implementation of Filter)
*/
public Filter getTypeFilter(int type) {
return new TypeFilter(type);
}
/**************************************************************
* Iterator that returns all children of a given node
*/
private final class ChildrenIterator extends NodeIteratorBase {
// child to return next
private int _currentChild;
private int _last = -1;
public NodeIterator setStartNode(final int node) {
_last = -1;
if (_isRestartable) {
_currentChild = hasChildren(node)
? _offsetOrChild[_startNode = node] : END;
return resetPosition();
}
return this;
}
public int next() {
final int node = _currentChild;
_currentChild = _nextSibling[node];
return returnNode(node);
}
public void setMark() {
_markedNode = _currentChild;
}
public void gotoMark() {
_currentChild = _markedNode;
}
public int getLast() {
if (_last == -1) {
+ _last = 1;
int node = _offsetOrChild[_startNode];
- do {
- ++_last;
- } while ((node = _nextSibling[node]) != END);
+ while ((node = _nextSibling[node]) != END) _last++;
}
return(_last);
}
} // end of ChildrenIterator
/**************************************************************
* Iterator that returns the parent of a given node
*/
private final class ParentIterator extends NodeIteratorBase {
// candidate parent node
private int _node;
private int _nodeType = -1;
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
_node = _parent[_startNode = node];
return resetPosition();
}
return this;
}
public NodeIterator setNodeType(final int type) {
_nodeType = type;
return this;
}
public int next() {
int result = _node;
if ((_nodeType != -1) && (_type[_node] != _nodeType))
result = END;
else
result = _node;
_node = END;
return returnNode(result);
}
public void setMark() {
_markedNode = _node;
}
public void gotoMark() {
_node = _markedNode;
}
} // end of ParentIterator
/**************************************************************
* Iterator that returns children of a given type for a given node.
* The functionality chould be achieved by putting a filter on top
* of a basic child iterator, but a specialised iterator is used
* for efficiency (both speed and size of translet).
*/
private final class TypedChildrenIterator extends NodeIteratorBase {
private final int _nodeType;
// node to consider next
private int _currentChild;
public TypedChildrenIterator(int nodeType) {
_nodeType = nodeType;
}
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
_currentChild = hasChildren(node)
? _offsetOrChild[_startNode = node] : END;
return resetPosition();
}
return this;
}
public NodeIterator reset() {
if (hasChildren(_startNode))
_currentChild = _offsetOrChild[_startNode];
else
_currentChild = END;
return this;
}
public int next() {
for (int node = _currentChild; node != END;
node = _nextSibling[node]) {
if (_type[node] == _nodeType) {
_currentChild = _nextSibling[node];
return returnNode(node);
}
}
return END;
}
public void setMark() {
_markedNode = _currentChild;
}
public void gotoMark() {
_currentChild = _markedNode;
}
} // end of TypedChildrenIterator
/**************************************************************
* Iterator that returns children within a given namespace for a
* given node. The functionality chould be achieved by putting a
* filter on top of a basic child iterator, but a specialised
* iterator is used for efficiency (both speed and size of translet).
*/
private final class NamespaceChildrenIterator extends NodeIteratorBase {
private final int _nsType;
private int _currentChild;
public NamespaceChildrenIterator(final int type) {
_nsType = type;
}
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
_currentChild = hasChildren(node)
? _offsetOrChild[_startNode = node] : END;
return resetPosition();
}
return this;
}
public int next() {
for (int node = _currentChild; node != END;
node = _nextSibling[node]) {
if (getNamespaceType(node) == _nsType) {
_currentChild = _nextSibling[node];
return returnNode(node);
}
}
return END;
}
public void setMark() {
_markedNode = _currentChild;
}
public void gotoMark() {
_currentChild = _markedNode;
}
} // end of TypedChildrenIterator
/**************************************************************
* Iterator that returns attributes within a given namespace for a node.
*/
private final class NamespaceAttributeIterator extends NodeIteratorBase {
private final int _nsType;
private int _attribute;
public NamespaceAttributeIterator(int nsType) {
super();
_nsType = nsType;
}
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
for (node = _lengthOrAttr[_startNode = node];
node != NULL && getNamespaceType(node) != _nsType;
node = _nextSibling[node]);
_attribute = node;
return resetPosition();
}
return this;
}
public int next() {
final int save = _attribute;
int node = save;
_attribute = _nextSibling[_attribute];
for (node = _lengthOrAttr[_startNode = node];
node != NULL && getNamespaceType(node) != _nsType;
node = _nextSibling[node]);
_attribute = node;
return returnNode(save);
}
public void setMark() {
_markedNode = _attribute;
}
public void gotoMark() {
_attribute = _markedNode;
}
} // end of TypedChildrenIterator
/**************************************************************
* Iterator that returns all siblings of a given node.
*/
private class FollowingSiblingIterator extends NodeIteratorBase {
private int _node;
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
_node = _startNode = node;
return resetPosition();
}
return this;
}
public int next() {
return returnNode(_node = _nextSibling[_node]);
}
public void setMark() {
_markedNode = _node;
}
public void gotoMark() {
_node = _markedNode;
}
} // end of FollowingSiblingIterator
/**************************************************************
* Iterator that returns all following siblings of a given node.
*/
private final class TypedFollowingSiblingIterator
extends FollowingSiblingIterator {
private final int _nodeType;
public TypedFollowingSiblingIterator(int type) {
_nodeType = type;
}
public int next() {
int node;
while ((node = super.next()) != NULL) {
if (_type[node] == _nodeType) return node;
}
return END;
}
} // end of TypedFollowingSiblingIterator
/**************************************************************
* Iterator that returns attribute nodes (of what nodes?)
*/
private final class AttributeIterator extends NodeIteratorBase {
private int _attribute;
// assumes caller will pass element nodes
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
_attribute = isElement(node)
? _lengthOrAttr[_startNode = node]
: NULL;
return resetPosition();
}
return this;
}
public int next() {
final int node = _attribute;
_attribute = _nextSibling[_attribute];
return returnNode(node);
}
public void setMark() {
_markedNode = _attribute;
}
public void gotoMark() {
_attribute = _markedNode;
}
} // end of AttributeIterator
/**************************************************************
* Iterator that returns attribute nodes of a given type
*/
private final class TypedAttributeIterator extends NodeIteratorBase {
private final int _nodeType;
private int _attribute;
public TypedAttributeIterator(int nodeType) {
_nodeType = nodeType;
}
// assumes caller will pass element nodes
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
for (node = _lengthOrAttr[_startNode = node];
node != NULL && _type[node] != _nodeType;
node = _nextSibling[node]);
_attribute = node;
return resetPosition();
}
return this;
}
public int next() {
final int node = _attribute;
_attribute = NULL; // singleton iterator
return returnNode(node);
}
public void setMark() {
_markedNode = _attribute;
}
public void gotoMark() {
_attribute = _markedNode;
}
} // end of TypedAttributeIterator
/**************************************************************
* Iterator that returns preceding siblings of a given node
*/
private class PrecedingSiblingIterator extends NodeIteratorBase {
private int _start;
private int _node;
public boolean isReverse() {
return true;
}
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
_node = _offsetOrChild[_parent[_startNode = _start = node]];
return resetPosition();
}
return this;
}
public int next() {
if (_node == _start) {
return NULL;
}
else {
final int node = _node;
_node = _nextSibling[node];
return returnNode(node);
}
}
public void setMark() {
_markedNode = _node;
}
public void gotoMark() {
_node = _markedNode;
}
} // end of PrecedingSiblingIterator
/**************************************************************
* Iterator that returns preceding siblings of a given type for
* a given node
*/
private final class TypedPrecedingSiblingIterator
extends PrecedingSiblingIterator {
private final int _nodeType;
public TypedPrecedingSiblingIterator(int type) {
_nodeType = type;
}
public int next() {
int node;
while ((node = super.next()) != NULL && _type[node] != _nodeType) {
}
return returnNode(node);
}
} // end of PrecedingSiblingIterator
/**************************************************************
* Iterator that returns preceding nodes of a given node.
* This includes the node set {root+1, start-1}, but excludes
* all ancestors.
*/
private class PrecedingIterator extends NodeIteratorBase {
private int _node = 0;
private int[] _stack = new int[8];
private int _sp = 0;
private int _spStart = 0;
private int _spMark = 0;
public boolean isReverse() {
return true;
}
public NodeIterator cloneIterator() {
try {
_isRestartable = false;
final PrecedingIterator clone =
(PrecedingIterator)super.clone();
return clone.reset();
}
catch (CloneNotSupportedException e) {
BasisLibrary.runTimeError("Iterator clone not supported.");
return null;
}
}
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
_startNode = node;
_node = ROOTNODE;
int parent = node;
while ((parent = _parent[parent]) > ROOTNODE) {
if (_sp == _stack.length) {
final int[] stack = new int[_sp + 4];
System.arraycopy(_stack, 0, stack, 0, _sp);
_stack = stack;
}
_stack[_sp++] = parent;
}
_sp--;
_spStart = _sp;
return resetPosition();
}
return this;
}
public int next() {
// Advance node index and check if all nodes have been returned.
while (++_node < _startNode) {
// Check if we reached one of the base node's ancestors
if ((_sp < 0) || (_node < _stack[_sp])) return(_node);
// Anvance past the next ancestor node
_sp--;
}
return(NULL);
}
// redefine NodeIteratorBase's reset
public NodeIterator reset() {
_node = ROOTNODE;
_spStart = _sp;
return resetPosition();
}
public void setMark() {
_markedNode = _node;
_spMark = _sp;
}
public void gotoMark() {
_node = _markedNode;
_sp = _spMark;
}
} // end of PrecedingIterator
/**************************************************************
* Iterator that returns preceding nodes of agiven type for a
* given node. This includes the node set {root+1, start-1}, but
* excludes all ancestors.
*/
private final class TypedPrecedingIterator extends PrecedingIterator {
private final int _nodeType;
public TypedPrecedingIterator(int type) {
_nodeType = type;
}
public int next() {
int node;
while ((node = super.next()) != NULL && _type[node] != _nodeType) {
}
return node;
}
} // end of TypedPrecedingIterator
/**************************************************************
* Iterator that returns following nodes of for a given node.
*/
private class FollowingIterator extends NodeIteratorBase {
// _node precedes search for next
protected int _node;
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
_startNode = node;
// find rightmost descendant (or self)
int current;
while ((node = lastChild(current = node)) != NULL) {
}
_node = current;
// _node precedes possible following(node) nodes
return resetPosition();
}
return this;
}
public int next() {
final int node = _node + 1;
return node < _treeNodeLimit ? returnNode(_node = node) : NULL;
}
public void setMark() {
_markedNode = _node;
}
public void gotoMark() {
_node = _markedNode;
}
} // end of FollowingIterator
/**************************************************************
* Iterator that returns following nodes of a given type for a given node.
*/
private final class TypedFollowingIterator extends FollowingIterator {
private final int _nodeType;
public TypedFollowingIterator(int type) {
_nodeType = type;
}
public int next() {
int node;
while ((node = super.next()) != NULL) {
if (_type[node] == _nodeType) return node;
}
return END;
}
} // end of TypedFollowingIterator
/**************************************************************
* Iterator that returns the ancestors of a given node.
* The nodes are returned in reverse document order, so you
* get the context node (or its parent node) first, and the
* root node in the very, very end.
*/
private class AncestorIterator extends NodeIteratorBase {
protected int _index;
public final boolean isReverse() {
return true;
}
public int getLast() {
return(ROOT);
}
public NodeIterator cloneIterator() {
_isRestartable = false; // must set to false for any clone
try {
final AncestorIterator clone = (AncestorIterator)super.clone();
clone._startNode = _startNode;
return clone.reset();
} catch (CloneNotSupportedException e) {
BasisLibrary.runTimeError("Iterator clone not supported.");
return null;
}
}
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
if (_includeSelf)
_startNode = node;
else
_startNode = _parent[node];
_index = _startNode;
return resetPosition();
}
return this;
}
public NodeIterator reset() {
_index = _startNode;
return resetPosition();
}
public int next() {
if (_index >= 0) {
int bob = _index;
if (_index == 0)
_index = -1;
else
_index = _parent[_index];
return returnNode(bob);
}
return(NULL);
}
public void setMark() {
_markedNode = _index;
}
public void gotoMark() {
_index = _markedNode;
}
} // end of AncestorIterator
/**************************************************************
* Typed iterator that returns the ancestors of a given node.
*/
private final class TypedAncestorIterator extends AncestorIterator {
private final int _nodeType;
public TypedAncestorIterator(int type) {
_nodeType = type;
}
public int next() {
int node;
while ((node = super.next()) != NULL) {
if (_type[node] == _nodeType)
return returnNode(node);
}
return(NULL);
}
public int getLast() {
int last = _index;
int curr = _index;
while (curr >= 0) {
if (curr == 0)
curr = -1;
else {
curr = _parent[curr];
if (_type[curr] == _nodeType)
last = curr;
}
}
return(last);
}
} // end of TypedAncestorIterator
/**************************************************************
* Iterator that returns the descendants of a given node.
*/
private class DescendantIterator extends NodeIteratorBase {
// _node precedes search for next
protected int _node;
// first node outside descendant range
protected int _limit;
public NodeIterator setStartNode(int node) {
_startNode = node;
if (_isRestartable) {
_node = _startNode = _includeSelf ? node - 1 : node;
// no descendents if no children
if (hasChildren(node) == false) {
// set _limit to match next()'s criteria for end
_limit = node + 1;
}
// find leftmost descendant of next sibling
else if ((node = _nextSibling[node]) == 0) {
// no next sibling, array end is the limit
_limit = _treeNodeLimit;
}
else {
_limit = leftmostDescendant(node);
}
return resetPosition();
}
return this;
}
public int next() {
if (++_node >= (_limit))
return(NULL);
else
return(returnNode(_node));
}
public void setMark() {
_markedNode = _node;
}
public void gotoMark() {
_node = _markedNode;
}
} // end of DescendantIterator
/**************************************************************
* Typed iterator that returns the descendants of a given node.
*/
private final class TypedDescendantIterator extends DescendantIterator {
private final int _nodeType;
public TypedDescendantIterator(int nodeType) {
_nodeType = nodeType;
}
public int next() {
final int limit = _limit;
final int type = _nodeType;
int node = _node + 1; // start search w/ next
// while condition == which nodes to skip
// iteration stops when at end or node w/ desired type
while (node < limit && _type[node] != type) {
++node;
}
return node < limit ? returnNode(_node = node) : NULL;
}
} // end of TypedDescendantIterator
/**************************************************************
* Iterator that returns the descendants of a given node.
*/
private class NthDescendantIterator extends DescendantIterator {
int _pos;
public NthDescendantIterator(int pos) {
_pos = pos;
_limit = _treeNodeLimit;
}
// The start node of this iterator is always the root!!!
public NodeIterator setStartNode(int node) {
NodeIterator iterator = super.setStartNode(1);
_limit = _treeNodeLimit;
return iterator;
}
public int next() {
int node;
while ((node = super.next()) != END) {
int parent = _parent[node];
int child = _offsetOrChild[parent];
int pos = 0;
do {
if (isElement(child)) pos++;
} while ((pos < _pos) && (child = _nextSibling[child]) != 0);
if (node == child) return node;
}
return(END);
}
} // end of NthDescendantIterator
/**************************************************************
* Iterator that returns a given node only if it is of a given type.
*/
private final class TypedSingletonIterator extends SingletonIterator {
private final int _nodeType;
public TypedSingletonIterator(int nodeType) {
_nodeType = nodeType;
}
public int next() {
final int result = super.next();
return _type[result] == _nodeType ? result : NULL;
}
} // end of TypedSingletonIterator
/**************************************************************
* Iterator to put on top of other iterators. It will take the
* nodes from the underlaying iterator and return all but
* whitespace text nodes. The iterator needs to be a supplied
* with a filter that tells it what nodes are WS text.
*/
private final class StrippingIterator extends NodeIteratorBase {
private static final int USE_PREDICATE = 0;
private static final int STRIP_SPACE = 1;
private static final int PRESERVE_SPACE = 2;
private StripFilter _filter = null;
private short[] _mapping = null;
private final NodeIterator _source;
private boolean _children = false;
private int _action = USE_PREDICATE;
private int _last = -1;
public StrippingIterator(NodeIterator source,
short[] mapping,
StripFilter filter) {
_filter = filter;
_mapping = mapping;
_source = source;
if (_source instanceof ChildrenIterator ||
_source instanceof TypedChildrenIterator) {
_children = true;
}
}
public NodeIterator setStartNode(int node) {
if (_children) {
if (_filter.stripSpace((DOM)DOMImpl.this, node,
_mapping[_type[node]]))
_action = STRIP_SPACE;
else
_action = PRESERVE_SPACE;
}
_source.setStartNode(node);
//return resetPosition();
return(this);
}
public int next() {
int node;
while ((node = _source.next()) != END) {
switch(_action) {
case STRIP_SPACE:
if (_whitespace.getBit(node)) continue;
// fall through...
case PRESERVE_SPACE:
return returnNode(node);
case USE_PREDICATE:
default:
if (_whitespace.getBit(node) &&
_filter.stripSpace((DOM)DOMImpl.this, node,
_mapping[_type[_parent[node]]]))
continue;
return returnNode(node);
}
}
return END;
}
public NodeIterator reset() {
_source.reset();
return this;
}
public void setMark() {
_source.setMark();
}
public void gotoMark() {
_source.gotoMark();
}
public int getLast() {
// Return chached value (if we have it)
if (_last != -1) return _last;
int count = getPosition();
int node;
_source.setMark();
while ((node = _source.next()) != END) {
switch(_action) {
case STRIP_SPACE:
if (_whitespace.getBit(node))
continue;
// fall through...
case PRESERVE_SPACE:
count++;
break;
case USE_PREDICATE:
default:
if (_whitespace.getBit(node) &&
_filter.stripSpace((DOM)DOMImpl.this, node,
_mapping[_type[_parent[node]]]))
continue;
else
count++;
}
}
_source.gotoMark();
_last = count;
return(count);
}
} // end of StrippingIterator
public NodeIterator strippingIterator(NodeIterator iterator,
short[] mapping,
StripFilter filter) {
return(new StrippingIterator(iterator, mapping, filter));
}
/**************************************************************
* This is a specialised iterator for predicates comparing node or
* attribute values to variable or parameter values.
*/
private final class NodeValueIterator extends NodeIteratorBase {
private NodeIterator _source;
private String _value;
private boolean _op;
private final boolean _isReverse;
private int _returnType = RETURN_PARENT;
public NodeValueIterator(NodeIterator source, int returnType,
String value, boolean op) {
_source = source;
_returnType = returnType;
_value = value;
_op = op;
_isReverse = source.isReverse();
}
public boolean isReverse() {
return _isReverse;
}
public NodeIterator cloneIterator() {
try {
NodeValueIterator clone = (NodeValueIterator)super.clone();
clone._isRestartable = false;
clone._source = _source.cloneIterator();
clone._value = _value;
clone._op = _op;
return clone.reset();
}
catch (CloneNotSupportedException e) {
BasisLibrary.runTimeError("Iterator clone not supported.");
return null;
}
}
public NodeIterator reset() {
_source.reset();
return resetPosition();
}
public int next() {
int node;
while ((node = _source.next()) != END) {
String val = getNodeValue(node);
if (_value.equals(val) == _op) {
if (_returnType == RETURN_CURRENT)
return returnNode(node);
else
return returnNode(_parent[node]);
}
}
return END;
}
public NodeIterator setStartNode(int node) {
if (_isRestartable) {
_source.setStartNode(_startNode = node);
return resetPosition();
}
return this;
}
public void setMark() {
_source.setMark();
}
public void gotoMark() {
_source.gotoMark();
}
}
public NodeIterator getNodeValueIterator(NodeIterator iterator, int type,
String value, boolean op) {
return(new NodeValueIterator(iterator, type, value, op));
}
/**************************************************************
* Iterator that assured that a single node is only returned once
* and that the nodes are returned in document order.
*/
private final class OrderedIterator extends NodeIteratorBase {
private BitArray _nodes = null;
private int _save = 0;
private int _mark = 0;
private int _start = 0;
private int _node = -1;
private int _last = 0;
public OrderedIterator(NodeIterator source, int node) {
_nodes = new BitArray(_treeNodeLimit);
source.setStartNode(node);
while ((_node = source.next()) != END) {
if (_start == -1) _start = _node;
_last = _node;
_nodes.setBit(_node);
}
_node = -1;
}
public int next() {
while ((_node < _treeNodeLimit) && (!_nodes.getBit(++_node))) ;
if (_node >= _treeNodeLimit) return(END);
return returnNode(_node);
}
public NodeIterator reset() {
_node = _start - 1;
return(this);
}
public int getLast() {
return(_last);
}
public void setMark() {
_save = _node;
}
public void gotoMark() {
_node = _save;
}
public NodeIterator setStartNode(int start) {
_start = start;
return((NodeIterator)this);
}
public boolean isReverse() {
return(false);
}
public NodeIterator cloneIterator() {
return((NodeIterator)this);
}
} // end of OrderedIterator
/**
* Encapsulates an iterator in an OrderedIterator to ensure node order
*/
public NodeIterator orderNodes(NodeIterator source, int node) {
return new OrderedIterator(source, node);
}
/**
* Returns the leftmost descendant of a node (bottom left in sub-tree)
*/
private int leftmostDescendant(int node) {
int current;
while (_type[current = node] >= NTYPES
&& (node = _offsetOrChild[node]) != NULL) {
}
return current;
}
/**
* Returns index of last child or 0 if no children
*/
private int lastChild(int node) {
if (isElement(node) || node == ROOTNODE) {
int child;
if ((child = _offsetOrChild[node]) != NULL) {
while ((child = _nextSibling[node = child]) != NULL) {
}
return node;
}
}
return 0;
}
/**
* Returns the parent of a node
*/
public int getParent(final int node) {
return _parent[node];
}
/**
* Returns a node's position amongst other nodes of the same type
*/
public int getTypedPosition(int type, int node) {
// Just return the basic position if no type is specified
if (type == -1) type = _type[node];
// Initialize with the first sbiling of the current node
int match = 0;
int curr = _offsetOrChild[_parent[node]];
if (_type[curr] == type) match++;
// Then traverse all other siblings up until the current node
while (curr != node) {
curr = _nextSibling[curr];
if (_type[curr] == type) match++;
}
// And finally return number of matches
return match;
}
/**
* Returns an iterator's last node of a given type
*/
public int getTypedLast(int type, int node) {
// Just return the basic position if no type is specified
if (type == -1) type = _type[node];
// Initialize with the first sbiling of the current node
int match = 0;
int curr = _offsetOrChild[_parent[node]];
if (_type[curr] == type) match++;
// Then traverse all other siblings up until the very last one
while (curr != NULL) {
curr = _nextSibling[curr];
if (_type[curr] == type) match++;
}
return match;
}
/**
* Returns singleton iterator containg the document root
* Works for them main document (mark == 0)
*/
public NodeIterator getIterator() {
return new SingletonIterator(ROOTNODE);
}
/**
* Returns the type of a specific node
*/
public int getType(final int node) {
if (node >= _type.length)
return(0);
else
return _type[node];
}
/**
* Returns the namespace type of a specific node
*/
public int getNamespaceType(final int node) {
final int type = _type[node];
if (type >= NTYPES)
return(_namespace[type-NTYPES]);
else
return(0); // default namespace
}
/**
* Returns the node-to-type mapping array
*/
public short[] getTypeArray() {
return _type;
}
/**
* Returns the (String) value of any node in the tree
*/
public String getNodeValue(final int node) {
if ((node == NULL) || (node > _treeNodeLimit)) return EMPTYSTRING;
switch(_type[node]) {
case ROOT:
return getNodeValue(_offsetOrChild[node]);
case TEXT:
case COMMENT:
case PROCESSING_INSTRUCTION:
return makeStringValue(node);
default:
if (node < _firstAttributeNode)
return getElementValue(node); // element string value
else
return makeStringValue(node); // attribute value
}
}
private String getLocalName(int node) {
final int type = _type[node] - NTYPES;
final String qname = _namesArray[type];
final String uri = _uriArray[_namespace[type]];
if (uri != null) {
final int len = uri.length();
if (len > 0) return qname.substring(len+1);
}
return qname;
}
/**
* Sets up a translet-to-dom type mapping table
*/
private Hashtable setupMapping(String[] namesArray) {
final int nNames = namesArray.length;
final Hashtable types = new Hashtable(nNames);
for (int i = 0; i < nNames; i++) {
types.put(namesArray[i], new Integer(i + NTYPES));
}
return types;
}
/**
* Returns the internal type associated with an expaneded QName
*/
public int getGeneralizedType(final String name) {
final Integer type = (Integer)_types.get(name);
if (type == null) {
// memorize default type
final int code = name.charAt(0) == '@' ? ATTRIBUTE : ELEMENT;
_types.put(name, new Integer(code));
return code;
}
else {
return type.intValue();
}
}
/**
* Get mapping from DOM element/attribute types to external types
*/
public short[] getMapping(String[] names) {
int i;
final int namesLength = names.length;
final int mappingLength = _namesArray.length + NTYPES;
final short[] result = new short[mappingLength];
// primitive types map to themselves
for (i = 0; i < NTYPES; i++)
result[i] = (short)i;
// extended types initialized to "beyond caller's types"
// unknown element or Attr
for (i = NTYPES; i < mappingLength; i++) {
final int type = i - NTYPES;
final String name = _namesArray[type];
final String uri = _uriArray[_namespace[type]];
int len = 0;
if (uri != null) {
len = uri.length();
if (len > 0) len++;
}
if (name.charAt(len) == '@')
result[i] = (short)ATTRIBUTE;
else
result[i] = (short)ELEMENT;
}
// actual mapping of caller requested names
for (i = 0; i < namesLength; i++) {
result[getGeneralizedType(names[i])] = (short)(i + NTYPES);
}
return(result);
}
/**
* Get mapping from external element/attribute types to DOM types
*/
public short[] getReverseMapping(String[] names) {
int i;
final short[] result = new short[names.length + NTYPES];
// primitive types map to themselves
for (i = 0; i < NTYPES; i++) {
result[i] = (short)i;
}
// caller's types map into appropriate dom types
for (i = 0; i < names.length; i++) {
result[i + NTYPES] = (short)getGeneralizedType(names[i]);
if (result[i + NTYPES] == ELEMENT)
result[i + NTYPES] = NO_TYPE;
}
return(result);
}
/**
* Get mapping from DOM namespace types to external namespace types
*/
public short[] getNamespaceMapping(String[] namespaces) {
int i;
final int nsLength = namespaces.length;
final int mappingLength = _uriArray.length;
final short[] result = new short[mappingLength];
// Initialize all entries to -1
for (i=0; i<mappingLength; i++)
result[i] = (-1);
for (i=0; i<nsLength; i++) {
Integer type = (Integer)_nsIndex.get(namespaces[i]);
if (type != null) {
result[type.intValue()] = (short)i;
}
}
return(result);
}
/**
* Get mapping from external namespace types to DOM namespace types
*/
public short[] getReverseNamespaceMapping(String[] namespaces) {
int i;
final int length = namespaces.length;
final short[] result = new short[length];
for (i=0; i<length; i++) {
Integer type = (Integer)_nsIndex.get(namespaces[i]);
if (type == null)
result[i] = -1;
else
result[i] = type.shortValue();
}
return(result);
}
/**
* Dump the whole tree to a file (serialized)
*/
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(_treeNodeLimit);
out.writeObject(_type);
out.writeObject(_namespace);
out.writeObject(_parent);
out.writeObject(_nextSibling);
out.writeObject(_offsetOrChild);
out.writeObject(_lengthOrAttr);
out.writeObject(_text);
out.writeObject(_namesArray);
out.writeObject(_uriArray);
out.writeObject(_whitespace);
out.writeObject(_prefix);
out.flush();
}
/**
* Read the whole tree from a file (serialized)
*/
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
_treeNodeLimit = in.readInt();
_type = (short[])in.readObject();
_namespace = (short[])in.readObject();
_parent = (int[])in.readObject();
_nextSibling = (int[])in.readObject();
_offsetOrChild = (int[])in.readObject();
_lengthOrAttr = (int[])in.readObject();
_text = (char[])in.readObject();
_namesArray = (String[])in.readObject();
_uriArray = (String[])in.readObject();
_whitespace = (BitArray)in.readObject();
_prefix = (short[])in.readObject();
_types = setupMapping(_namesArray);
}
/**
* Constructor - defaults to 32K nodes
*/
public DOMImpl() {
this(32*1024);
}
/**
* Constructor - defines initial size
*/
public DOMImpl(int size) {
_type = new short[size];
_parent = new int[size];
_nextSibling = new int[size];
_offsetOrChild = new int[size];
_lengthOrAttr = new int[size];
_text = new char[size * 10];
_whitespace = new BitArray(size);
_prefix = new short[size];
// _namesArray[] and _uriArray are allocated in endDocument
}
/**
* Prints the whole tree to standard output
*/
public void print(int node, int level) {
switch(_type[node]) {
case ROOT:
print(_offsetOrChild[node], level);
break;
case TEXT:
case COMMENT:
case PROCESSING_INSTRUCTION:
System.out.print(makeStringValue(node));
break;
default: // element
final String name = getNodeName(node);
System.out.print("<" + name);
for (int a = _lengthOrAttr[node]; a != NULL; a = _nextSibling[a]) {
System.out.print("\n" + getNodeName(a) +
"=\"" + makeStringValue(a) + "\"");
}
System.out.print('>');
for (int child = _offsetOrChild[node]; child != NULL;
child = _nextSibling[child]) {
print(child, level + 1);
}
System.out.println("</" + name + '>');
break;
}
}
/**
* Returns the name of a node (attribute or element).
*/
public String getNodeName(final int node) {
// Get the node type and make sure that it is within limits
final short type = _type[node];
switch(type) {
case DOM.ROOT:
case DOM.TEXT:
case DOM.UNUSED:
case DOM.ELEMENT:
case DOM.ATTRIBUTE:
case DOM.COMMENT:
return EMPTYSTRING;
case DOM.PROCESSING_INSTRUCTION:
return "a-pi";
default:
// Construct the local part (omit '@' for attributes)
String name = getLocalName(node);
if (node >= _firstAttributeNode)
name = name.substring(1);
final int pi = _prefix[node];
if (pi > 0) {
final String prefix = _prefixArray[pi];
if (prefix != EMPTYSTRING)
name = prefix+':'+name;
}
return name;
}
}
/**
* Returns the namespace URI to which a node belongs
*/
public String getNamespaceName(final int node) {
final int type = getNamespaceType(node);
final String name = _uriArray[type];
if (name == null)
return(EMPTYSTRING);
else
return(name);
}
/**
* Returns the string value of a single text/comment node or
* attribute value (they are all stored in the same array).
*/
private String makeStringValue(final int node) {
return new String(_text, _offsetOrChild[node], _lengthOrAttr[node]);
}
/**
* Returns the attribute node of a given type (if any) for an element
*/
public int getAttributeNode(final int type, final int element) {
for (int attr = _lengthOrAttr[element];
attr != NULL;
attr = _nextSibling[attr]) {
if (_type[attr] == type) return attr;
}
return NULL;
}
/**
* Returns the value of a given attribute type of a given element
*/
public String getAttributeValue(final int type, final int element) {
final int attr = getAttributeNode(type, element);
if (attr != NULL)
return makeStringValue(attr);
else
return EMPTYSTRING;
}
/**
* Returns true if a given element has an attribute of a given type
*/
public boolean hasAttribute(final int type, final int node) {
if (getAttributeNode(type, node) != NULL)
return true;
else
return false;
}
/**
* This method is for testing/debugging only
*/
public String getAttributeValue(final String name, final int element) {
return getAttributeValue(getGeneralizedType(name), element);
}
/**
* Returns true if the given element has any children
*/
private boolean hasChildren(final int node) {
if (node < _firstAttributeNode) {
final int type = _type[node];
return(((type >= NTYPES) || (type == ROOT)) &&
(_offsetOrChild[node] != 0));
}
return(false);
}
/**
* Returns an iterator with all the children of a given node
*/
public NodeIterator getChildren(final int node) {
if (hasChildren(node))
return(new ChildrenIterator());
else
return(EMPTYITERATOR);
}
/**
* Returns an iterator with all children of a specific type
* for a given node (element)
*/
public NodeIterator getTypedChildren(final int type) {
return(new TypedChildrenIterator(type));
}
/**
* This is a shortcut to the iterators that implement the
* supported XPath axes (only namespace::) is not supported.
* Returns a bare-bones iterator that must be initialized
* with a start node (using iterator.setStartNode()).
*/
public NodeIterator getAxisIterator(final int axis) {
NodeIterator iterator = null;
switch (axis) {
case Axis.SELF:
iterator = new SingletonIterator();
break;
case Axis.CHILD:
iterator = new ChildrenIterator();
break;
case Axis.PARENT:
return(new ParentIterator());
case Axis.ANCESTOR:
return(new AncestorIterator());
case Axis.ANCESTORORSELF:
return((new AncestorIterator()).includeSelf());
case Axis.ATTRIBUTE:
return(new AttributeIterator());
case Axis.DESCENDANT:
iterator = new DescendantIterator();
break;
case Axis.DESCENDANTORSELF:
iterator = (new DescendantIterator()).includeSelf();
break;
case Axis.FOLLOWING:
iterator = new FollowingIterator();
break;
case Axis.PRECEDING:
iterator = new PrecedingIterator();
break;
case Axis.FOLLOWINGSIBLING:
iterator = new FollowingSiblingIterator();
break;
case Axis.PRECEDINGSIBLING:
iterator = new PrecedingSiblingIterator();
break;
case Axis.NAMESPACE:
return(new TypedAttributeIterator(getGeneralizedType("xmlns")));
default:
BasisLibrary.runTimeError("Error: iterator for axis '" +
Axis.names[axis] + "' not implemented");
System.exit(1);
}
return(iterator);
}
/**
* Similar to getAxisIterator, but this one returns an iterator
* containing nodes of a typed axis (ex.: child::foo)
*/
public NodeIterator getTypedAxisIterator(int axis, int type) {
NodeIterator iterator = null;
/* This causes an error when using patterns for elements that
do not exist in the DOM (translet types which do not correspond
to a DOM type are mapped to the DOM.ELEMENT type).
*/
if (type == NO_TYPE) {
return(EMPTYITERATOR);
}
else if (type == ELEMENT) {
iterator = new FilterIterator(getAxisIterator(axis),
getElementFilter());
}
else {
switch (axis) {
case Axis.SELF:
iterator = new TypedSingletonIterator(type);
break;
case Axis.CHILD:
iterator = new TypedChildrenIterator(type);
break;
case Axis.PARENT:
return(new ParentIterator().setNodeType(type));
case Axis.ANCESTOR:
return(new TypedAncestorIterator(type));
case Axis.ANCESTORORSELF:
return((new TypedAncestorIterator(type)).includeSelf());
case Axis.ATTRIBUTE:
return(new TypedAttributeIterator(type));
case Axis.DESCENDANT:
iterator = new TypedDescendantIterator(type);
break;
case Axis.DESCENDANTORSELF:
iterator = (new TypedDescendantIterator(type)).includeSelf();
break;
case Axis.FOLLOWING:
iterator = new TypedFollowingIterator(type);
break;
case Axis.PRECEDING:
iterator = new TypedPrecedingIterator(type);
break;
case Axis.FOLLOWINGSIBLING:
iterator = new TypedFollowingSiblingIterator(type);
break;
case Axis.PRECEDINGSIBLING:
iterator = new TypedPrecedingSiblingIterator(type);
break;
default:
BasisLibrary.runTimeError("Error: typed iterator for axis " +
Axis.names[axis]+"not implemented");
}
}
return(iterator);
}
/**
* Do not thing that this returns an iterator for the namespace axis.
* It returns an iterator with nodes that belong in a certain namespace,
* such as with <xsl:apply-templates select="blob/foo:*"/>
* The 'axis' specifies the axis for the base iterator from which the
* nodes are taken, while 'ns' specifies the namespace URI type.
*/
public NodeIterator getNamespaceAxisIterator(int axis, int ns) {
NodeIterator iterator = null;
if (ns == NO_TYPE) {
return(EMPTYITERATOR);
}
else {
switch (axis) {
case Axis.CHILD:
iterator = new NamespaceChildrenIterator(ns);
break;
case Axis.ATTRIBUTE:
iterator = new NamespaceAttributeIterator(ns);
break;
default:
BasisLibrary.runTimeError("Error: typed iterator for axis " +
Axis.names[axis]+"not implemented");
}
}
return(iterator);
}
/**
* Returns an iterator with all descendants of a node that are of
* a given type.
*/
public NodeIterator getTypedDescendantIterator(int type) {
NodeIterator iterator = new TypedDescendantIterator(type);
iterator.setStartNode(1);
return(iterator);
}
/**
* Returns the nth descendant of a node (1 = parent, 2 = gramps)
*/
public NodeIterator getNthDescendant(int node, int n) {
return (new NthDescendantIterator(n));
}
/**
* Copy the contents of a text-node to an output handler
*/
public void characters(final int textNode, TransletOutputHandler handler)
throws TransletException {
handler.characters(_text,
_offsetOrChild[textNode],
_lengthOrAttr[textNode]);
}
/**
* Copy a node-set to an output handler
*/
public void copy(NodeIterator nodes, TransletOutputHandler handler)
throws TransletException {
int node;
while ((node = nodes.next()) != NULL) {
copy(node, handler);
}
}
/**
* Copy the whole tree to an output handler
*/
public void copy(TransletOutputHandler handler) throws TransletException {
copy(ROOTNODE, handler);
}
/**
* Performs a deep copy (ref. XSLs copy-of())
*
* TODO: Copy namespace declarations. Can't be done until we
* add namespace nodes and keep track of NS prefixes
* TODO: Copy comment nodes
*/
public void copy(final int node, TransletOutputHandler handler)
throws TransletException {
final int type = _type[node];
switch(type) {
case ROOT:
for (int c=_offsetOrChild[node]; c!=NULL; c=_nextSibling[c])
copy(c, handler);
break;
case PROCESSING_INSTRUCTION:
copyPI(node, handler);
break;
case COMMENT:
case TEXT:
handler.characters(_text,
_offsetOrChild[node],
_lengthOrAttr[node]);
break;
case ATTRIBUTE:
shallowCopy(node, handler);
break;
default:
if (isElement(node)) {
// Start element definition
final String name = copyElement(node, type, handler);
// Copy element attribute
for (int a=_lengthOrAttr[node]; a!=NULL; a=_nextSibling[a]) {
final String uri = getNamespaceName(a);
if (uri != EMPTYSTRING) {
final String prefix = _prefixArray[_prefix[a]];
handler.namespace(prefix, uri);
}
handler.attribute(getNodeName(a), makeStringValue(a));
}
// Copy element children
for (int c=_offsetOrChild[node]; c!=NULL; c=_nextSibling[c])
copy(c, handler);
// Close element definition
handler.endElement(name);
}
// Shallow copy of attribute to output handler
else {
final String uri = getNamespaceName(node);
if (uri != EMPTYSTRING) {
final String prefix = _prefixArray[_prefix[node]];
handler.namespace(prefix, uri);
}
handler.attribute(getNodeName(node), makeStringValue(node));
}
break;
}
}
/**
* Copies a processing instruction node to an output handler
*/
private void copyPI(final int node, TransletOutputHandler handler)
throws TransletException {
final char[] text = _text;
final int start = _offsetOrChild[node];
final int length = _lengthOrAttr[node];
// Target and Value are separated by a whitespace - find it!
int i = start;
while (text[i] != ' ') i++;
final int len = i - start;
final String target = new String(text, start, len);
final String value = new String(text, i + 1, length - len);
handler.processingInstruction(target, value);
}
/**
* Performs a shallow copy (ref. XSLs copy())
*
* TODO: Copy namespace declarations. Can't be done until we
* add namespace nodes and keep track of NS prefixes
* TODO: Copy comment nodes
*/
public String shallowCopy(final int node, TransletOutputHandler handler)
throws TransletException {
final int type = _type[node];
switch(type) {
case ROOT: // do nothing
return EMPTYSTRING;
case TEXT:
handler.characters(_text,
_offsetOrChild[node],
_lengthOrAttr[node]);
return null;
case PROCESSING_INSTRUCTION:
copyPI(node, handler);
return null;
case COMMENT:
return null;
default:
if (isElement(node)) {
return(copyElement(node, type, handler));
}
else {
final String uri = getNamespaceName(node);
if (uri != EMPTYSTRING) {
final String prefix = _prefixArray[_prefix[node]];
handler.namespace(prefix, uri);
}
handler.attribute(getNodeName(node), makeStringValue(node));
return null;
}
}
}
private String copyElement(int node, int type,
TransletOutputHandler handler)
throws TransletException {
type = type - NTYPES;
String name = _namesArray[type];
final int pi = _prefix[node];
if (pi > 0) {
final String prefix = _prefixArray[pi];
final String uri = _uriArray[_namespace[type]];
final String local = getLocalName(node);
if (prefix.equals(EMPTYSTRING))
name = local;
else
name = prefix+':'+local;
handler.startElement(name);
handler.namespace(prefix, uri);
}
else {
handler.startElement(name);
}
return name;
}
/**
* Returns the string value of the entire tree
*/
public String getStringValue() {
return getElementValue(ROOTNODE);
}
/**
* Returns the string value of any element
*/
public String getElementValue(final int element) {
// optimization: only create StringBuffer if > 1 child
final int child = _offsetOrChild[element];
return child != NULL
? (_type[child] == TEXT && _nextSibling[child] == NULL
? makeStringValue(child)
: stringValueAux(new StringBuffer(), element).toString())
: EMPTYSTRING;
}
/**
* Helper to getElementValue() above
*/
private StringBuffer stringValueAux(StringBuffer buffer, final int element) {
for (int child = _offsetOrChild[element];
child != NULL;
child = _nextSibling[child]) {
switch (_type[child]) {
case COMMENT:
break;
case TEXT:
buffer.append(_text,
_offsetOrChild[child],
_lengthOrAttr[child]);
break;
case PROCESSING_INSTRUCTION:
break;
// !!! at the moment default can only be an element???
default:
stringValueAux(buffer, child);
}
}
return buffer;
}
/**
* Returns a node' defined language for a node (if any)
*/
public String getLanguage(int node) {
final Integer langType = (Integer)_types.get("xml:@lang");
if (langType != null) {
final int type = langType.intValue();
while (node != DOM.NULL) {
int attr = _lengthOrAttr[node];
while (attr != DOM.NULL) {
if (_type[attr] == type)
return(getNodeValue(attr));
attr = _nextSibling[attr];
}
node = getParent(node);
}
}
return(null);
}
/**
* Returns an instance of the DOMBuilder inner class
* This class will consume the input document through a SAX2
* interface and populate the tree.
*/
public DOMBuilder getBuilder() {
return new DOMBuilderImpl();
}
/**
* Returns a DOMBuilder class wrapped in a SAX adapter.
* I am not sure if we need this one anymore now that the
* DOM builder's interface is pure SAX2 (must investigate)
*/
public TransletOutputHandler getOutputDomBuilder() {
return new SAXAdapter(getBuilder());
}
/**
* Returns true if a character is an XML whitespace character.
* Order of tests is important for performance ([space] first).
*/
private static final boolean isWhitespaceChar(char c) {
return c == 0x20 || c == 0x0A || c == 0x0D || c == 0x09;
}
/****************************************************************/
/* DOM builder class definition */
/****************************************************************/
private final class DOMBuilderImpl implements DOMBuilder {
private final static int ATTR_ARRAY_SIZE = 32;
private final static int REUSABLE_TEXT_SIZE = 32;
private Hashtable _shortTexts = null;
private Hashtable _names = null;
private int _nextNameCode = NTYPES;
private int[] _parentStack = new int[64];
private int[] _previousSiblingStack = new int[64];
private int _sp;
private int _baseOffset = 0;
private int _currentOffset = 0;
private int _currentNode = 0;
// Temporary structures for attribute nodes
private int _currentAttributeNode = 0;
private short[] _type2 = new short[ATTR_ARRAY_SIZE];
private short[] _prefix2 = new short[ATTR_ARRAY_SIZE];
private int[] _parent2 = new int[ATTR_ARRAY_SIZE];
private int[] _nextSibling2 = new int[ATTR_ARRAY_SIZE];
private int[] _offset = new int[ATTR_ARRAY_SIZE];
private int[] _length = new int[ATTR_ARRAY_SIZE];
// Namespace prefix-to-uri mapping stuff
private Hashtable _nsPrefixes = new Hashtable();
private int _uriCount = 0;
private int _prefixCount = 0;
// Stack used to keep track of what whitespace text nodes are protected
// by xml:space="preserve" attributes and which nodes that are not.
private int[] _xmlSpaceStack = new int[64];
private int _idx = 1;
private boolean _preserve = false;
private static final String XML_STRING = "xml:";
private static final String XMLSPACE_STRING = "xml:space";
private static final String PRESERVE_STRING = "preserve";
/**
* Default constructor for the DOMBuiler class
*/
public DOMBuilderImpl() {
_xmlSpaceStack[0] = DOM.ROOTNODE;
}
/**
* Returns the namespace URI that a prefix currentl maps to
*/
private String getNamespaceURI(String prefix) {
// Get the stack associated with this namespace prefix
final Stack stack = (Stack)_nsPrefixes.get(prefix);
if ((stack != null) && (!stack.empty())) {
return((String)stack.peek());
}
else
return(EMPTYSTRING);
}
/**
* Call this when an xml:space attribute is encountered to
* define the whitespace strip/preserve settings.
*/
private void xmlSpaceDefine(String val, final int node) {
final boolean setting = val.equals(PRESERVE_STRING);
if (setting != _preserve) {
_xmlSpaceStack[_idx++] = node;
_preserve = setting;
}
}
/**
* Call this from endElement() to revert strip/preserve setting
* to whatever it was before the corresponding startElement()
*/
private void xmlSpaceRevert(final int node) {
if (node == _xmlSpaceStack[_idx - 1]) {
_idx--;
_preserve = !_preserve;
}
}
/**
* Returns the next available node. Increases the various arrays
* that constitute the node if necessary.
*/
private int nextNode() {
final int index = _currentNode++;
if (index == _type.length) {
resizeArrays(_type.length * 2, index);
}
return index;
}
/**
* Returns the next available attribute node. Increases the
* various arrays that constitute the attribute if necessary
*/
private int nextAttributeNode() {
final int index = _currentAttributeNode++;
if (index == _type2.length) {
resizeArrays2(_type2.length * 2, index);
}
return index;
}
/**
* Resize the character array that holds the contents of
* all text nodes, comments and attribute values
*/
private void resizeTextArray(final int newSize) {
final char[] newText = new char[newSize];
System.arraycopy(_text, 0, newText, 0, _currentOffset);
_text = newText;
}
/**
* Links together the children of a node. Child nodes are linked
* through the _nextSibling array
*/
private void linkChildren(final int node) {
_parent[node] = _parentStack[_sp];
if (_previousSiblingStack[_sp] != 0) { // current not first child
_nextSibling[_previousSiblingStack[_sp]] = node;
}
else {
_offsetOrChild[_parentStack[_sp]] = node;
}
_previousSiblingStack[_sp] = node;
}
/**
* Generate the internal type for an element's expanded QName
*/
private short makeElementNode(String uri, String localname)
throws SAXException {
final String name;
if (uri != EMPTYSTRING)
name = uri + ':' + localname;
else
name = localname;
// Stuff the QName into the names vector & hashtable
Integer obj = (Integer)_names.get(name);
if (obj == null) {
_names.put(name, obj = new Integer(_nextNameCode++));
}
return (short)obj.intValue();
}
/**
* Generate the internal type for an element's expanded QName
*/
private short makeElementNode(String name, int col)
throws SAXException {
// Expand prefix:localname to full QName
if (col > -1) {
final String uri = getNamespaceURI(name.substring(0, col));
name = uri + name.substring(col);
}
// Append default namespace with the name has no prefix
else {
final String uri = getNamespaceURI(EMPTYSTRING);
if (!uri.equals(EMPTYSTRING)) name = uri + ':' + name;
}
// Stuff the QName into the names vector & hashtable
Integer obj = (Integer)_names.get(name);
if (obj == null) {
_names.put(name, obj = new Integer(_nextNameCode++));
}
return (short)obj.intValue();
}
/**
*
*/
private short registerPrefix(String prefix) {
Stack stack = (Stack)_nsPrefixes.get(prefix);
if (stack != null) {
Integer obj = (Integer)stack.elementAt(0);
return (short)obj.intValue();
}
return 0;
}
/*
* This method will check if the current text node contains text that
* is already in the text array. If the text is found in the array
* then this method returns the offset of the previous instance of the
* string. Otherwise the text is inserted in the array, and the
* offset of the new instance is inserted.
* Updates the globals _baseOffset and _currentOffset
*/
private int maybeReuseText(final int length) {
final int base = _baseOffset;
if (length <= REUSABLE_TEXT_SIZE) {
// Use a char array instead of string for performance benefit
char[] chars = new char[length];
System.arraycopy(_text, base, chars, 0, length);
final Integer offsetObj = (Integer)_shortTexts.get(chars);
if (offsetObj != null) {
_currentOffset = base; // step back current
return offsetObj.intValue(); // reuse previous string
}
else {
_shortTexts.put(chars, new Integer(base));
}
}
_baseOffset = _currentOffset; // advance base to current
return base;
}
/**
* Links a text reference (an occurance of a sequence of characters
* in the _text[] array) to a specific node index.
*/
private void storeTextRef(final int node) {
final int length = _currentOffset - _baseOffset;
_offsetOrChild[node] = maybeReuseText(length);
_lengthOrAttr[node] = length;
}
/**
* Creates a text-node and checks if it is a whitespace node.
*/
private int makeTextNode(boolean isWhitespace) {
if (_currentOffset > _baseOffset) {
final int node = nextNode();
final int limit = _currentOffset;
// Tag as whitespace node if the parser tells us that it is...
if (isWhitespace) {
_whitespace.setBit(node);
}
// ...otherwise we check if this is a whitespace node, unless
// the node is protected by an xml:space="preserve" attribute.
else if (!_preserve) {
int i = _baseOffset;
while (isWhitespaceChar(_text[i++]) && i < limit) ;
if ((i == limit) && isWhitespaceChar(_text[i-1])) {
_whitespace.setBit(node);
}
}
_type[node] = TEXT;
linkChildren(node);
storeTextRef(node);
return node;
}
return -1;
}
/**
* Links an attribute value (an occurance of a sequence of characters
* in the _text[] array) to a specific attribute node index.
*/
private void storeAttrValRef(final int attributeNode) {
final int length = _currentOffset - _baseOffset;
_offset[attributeNode] = maybeReuseText(length);
_length[attributeNode] = length;
}
/**
* Creates an attribute node
*/
private int makeAttributeNode(int parent, Attributes attList, int i)
throws SAXException {
final int node = nextAttributeNode();
final String qname = attList.getQName(i);
final String localname = attList.getLocalName(i);
final String value = attList.getValue(i);
StringBuffer namebuf = new StringBuffer(EMPTYSTRING);
// Create the internal attribute node name (uri+@+localname)
if (qname.startsWith(XML_STRING)) {
if (qname.startsWith(XMLSPACE_STRING))
xmlSpaceDefine(attList.getValue(i), parent);
namebuf.append("xml:");
}
else {
final String uri = attList.getURI(i);
if ((uri != null) && (!uri.equals(EMPTYSTRING))) {
namebuf.append(uri);
namebuf.append(':');
}
}
namebuf.append('@');
namebuf.append(localname);
String name = namebuf.toString();
// Get the index of the attribute node name (create new if non-ex).
Integer obj = (Integer)_names.get(name);
if (obj == null) {
_type2[node] = (short)_nextNameCode;
_names.put(name, obj = new Integer(_nextNameCode++));
}
else {
_type2[node] = (short)obj.intValue();
}
_parent2[node] = parent;
final int col = qname.lastIndexOf(':');
if (col > 0) {
_prefix2[node] = registerPrefix(qname.substring(0, col));
}
characters(attList.getValue(i));
storeAttrValRef(node);
return node;
}
/****************************************************************/
/* SAX Interface Starts Here */
/****************************************************************/
/**
* SAX2: Receive notification of character data.
*/
public void characters(char[] ch, int start, int length) {
if (_currentOffset + length > _text.length) {
resizeTextArray(_text.length * 2);
}
System.arraycopy(ch, start, _text, _currentOffset, length);
_currentOffset += length;
}
/**
* SAX2: Receive notification of the beginning of a document.
*/
public void startDocument() {
_shortTexts = new Hashtable();
_names = new Hashtable();
_sp = 0;
_parentStack[0] = ROOTNODE; // root
_currentNode = ROOTNODE + 1;
_currentAttributeNode = 0;
startPrefixMapping(EMPTYSTRING, EMPTYSTRING);
}
/**
* SAX2: Receive notification of the end of a document.
*/
public void endDocument() {
makeTextNode(false);
_shortTexts = null;
final int namesSize = _nextNameCode - NTYPES;
// Fill the _namesArray[] array
_namesArray = new String[namesSize];
Enumeration keys = _names.keys();
while (keys.hasMoreElements()) {
final String name = (String)keys.nextElement();
final Integer idx = (Integer)_names.get(name);
_namesArray[idx.intValue() - NTYPES] = name;
}
_names = null;
_types = setupMapping(_namesArray);
// trim arrays' sizes
resizeTextArray(_currentOffset);
_firstAttributeNode = _currentNode;
shiftAttributes(_currentNode);
resizeArrays(_currentNode + _currentAttributeNode, _currentNode);
appendAttributes();
_treeNodeLimit = _currentNode + _currentAttributeNode;
// Fill the _namespace[] and _uriArray[] array
_namespace = new short[namesSize];
_uriArray = new String[_uriCount];
for (int i = 0; i<namesSize; i++) {
final String qname = _namesArray[i];
final int col = _namesArray[i].lastIndexOf(':');
// Elements/attributes with the xml prefix are not in a NS
if ((!qname.startsWith(XML_STRING)) && (col > -1)) {
final String uri = _namesArray[i].substring(0, col);
final Integer idx = (Integer)_nsIndex.get(uri);
_namespace[i] = idx.shortValue();
_uriArray[idx.intValue()] = uri;
}
}
_prefixArray = new String[_prefixCount];
Enumeration p = _nsPrefixes.keys();
while (p.hasMoreElements()) {
final String prefix = (String)p.nextElement();
final Stack stack = (Stack)_nsPrefixes.get(prefix);
final Integer I = (Integer)stack.elementAt(0);
_prefixArray[I.shortValue()] = prefix;
}
}
/**
* SAX2: Receive notification of the beginning of an element.
*/
public void startElement(String uri, String localName,
String qname, Attributes attributes)
throws SAXException {
makeTextNode(false);
// Get node index and setup parent/child references
final int node = nextNode();
linkChildren(node);
_parentStack[++_sp] = node;
final int count = attributes.getLength();
// Process attribute list and create attr nodes
if (count > 0) {
int attr = _currentAttributeNode + 1;
_lengthOrAttr[node] = attr;
for (int i = 0; i<count; i++) {
attr = makeAttributeNode(node, attributes, i);
_nextSibling2[attr] = attr + 1;
}
_nextSibling2[attr] = DOM.NULL;
}
// The element has no attributes
else {
_lengthOrAttr[node] = DOM.NULL;
}
final int col = qname.lastIndexOf(':');
// Assign an internal type to this element (may exist)
if ((uri != null) && (localName.length() > 0))
_type[node] = makeElementNode(uri, localName);
else
_type[node] = makeElementNode(qname, col);
// Assign an internal type to the element's prefix (may exist)
if (col > -1) {
_prefix[node] = registerPrefix(qname.substring(0, col));
}
}
/**
* SAX2: Receive notification of the end of an element.
*/
public void endElement(String namespaceURI, String localName,
String qname) {
makeTextNode(false);
// Revert to strip/preserve-space setting from before this element
xmlSpaceRevert(_parentStack[_sp]);
_previousSiblingStack[_sp--] = 0;
}
/**
* SAX2: Receive notification of a processing instruction.
*/
public void processingInstruction(String target, String data)
throws SAXException {
makeTextNode(false);
final int node = nextNode();
_type[node] = PROCESSING_INSTRUCTION;
linkChildren(node);
characters(target);
characters(" ");
characters(data);
storeTextRef(node);
}
/**
* SAX2: Receive notification of ignorable whitespace in element
* content. Similar to characters(char[], int, int).
*/
public void ignorableWhitespace(char[] ch, int start, int length) {
if (_currentOffset + length > _text.length) {
resizeTextArray(_text.length * 2);
}
System.arraycopy(ch, start, _text, _currentOffset, length);
_currentOffset += length;
makeTextNode(true);
}
/**
* SAX2: Receive an object for locating the origin of SAX document
* events.
*/
public void setDocumentLocator(Locator locator) {
// Not handled
}
/**
* SAX2: Receive notification of a skipped entity.
*/
public void skippedEntity(String name) {
// Not handled
}
/**
* SAX2: Begin the scope of a prefix-URI Namespace mapping.
*/
public void startPrefixMapping(String prefix, String uri) {
// Get the stack associated with this namespace prefix
Stack stack = (Stack)_nsPrefixes.get(prefix);
if (stack == null) {
stack = new Stack();
stack.push(new Integer(_prefixCount++));
_nsPrefixes.put(prefix, stack);
}
// Check if the URI already exists before pushing on stack
if (_nsIndex.get(uri) == null) {
_nsIndex.put(uri, new Integer(_uriCount++));
}
stack.push(uri);
}
/**
* SAX2: End the scope of a prefix-URI Namespace mapping.
*/
public void endPrefixMapping(String prefix) {
// Get the stack associated with this namespace prefix
final Stack stack = (Stack)_nsPrefixes.get(prefix);
if ((stack != null) && (!stack.empty())) stack.pop();
}
/**
* SAX2: Report an XML comment anywhere in the document.
*/
public void comment(char[] ch, int start, int length) {
makeTextNode(false);
if (_currentOffset + length > _text.length) {
resizeTextArray(_text.length * 2);
}
System.arraycopy(ch, start, _text, _currentOffset, length);
_currentOffset += length;
final int node = makeTextNode(false);
_type[node] = COMMENT;
}
/**
* SAX2: Ignored events
*/
public void startCDATA() {}
public void endCDATA() {}
public void startDTD(String name, String publicId, String systemId) {}
public void endDTD() {}
public void startEntity(String name) {}
public void endEntity(String name) {}
/**
* Similar to the SAX2 method character(char[], int, int), but this
* method takes a string as its only parameter. The effect is the same.
*/
private void characters(final String string) {
final int length = string.length();
if (_currentOffset + length > _text.length) {
resizeTextArray(_text.length * 2);
}
string.getChars(0, length, _text, _currentOffset);
_currentOffset += length;
}
private void resizeArrays(final int newSize, final int length) {
if (newSize > length) {
// Resize the '_type' array
final short[] newType = new short[newSize];
System.arraycopy(_type, 0, newType, 0, length);
_type = newType;
// Resize the '_parent' array
final int[] newParent = new int[newSize];
System.arraycopy(_parent, 0, newParent, 0, length);
_parent = newParent;
// Resize the '_nextSibling' array
final int[] newNextSibling = new int[newSize];
System.arraycopy(_nextSibling, 0, newNextSibling, 0, length);
_nextSibling = newNextSibling;
// Resize the '_offsetOrChild' array
final int[] newOffsetOrChild = new int[newSize];
System.arraycopy(_offsetOrChild, 0, newOffsetOrChild, 0,length);
_offsetOrChild = newOffsetOrChild;
// Resize the '_lengthOrAttr' array
final int[] newLengthOrAttr = new int[newSize];
System.arraycopy(_lengthOrAttr, 0, newLengthOrAttr, 0, length);
_lengthOrAttr = newLengthOrAttr;
// Resize the '_whitespace' array (a BitArray instance)
_whitespace.resize(newSize);
// Resize the '_prefix' array
final short[] newPrefix = new short[newSize];
System.arraycopy(_prefix, 0, newPrefix, 0, length);
_prefix = newPrefix;
}
}
private void resizeArrays2(final int newSize, final int length) {
if (newSize > length) {
// Resize the '_type2' array (attribute types)
final short[] newType = new short[newSize];
System.arraycopy(_type2, 0, newType, 0, length);
_type2 = newType;
// Resize the '_parent2' array (attribute parent elements)
final int[] newParent = new int[newSize];
System.arraycopy(_parent2, 0, newParent, 0, length);
_parent2 = newParent;
// Resize the '_nextSibling2' array (you get the idea...)
final int[] newNextSibling = new int[newSize];
System.arraycopy(_nextSibling2, 0, newNextSibling, 0, length);
_nextSibling2 = newNextSibling;
// Resize the '_offset' array (attribute value start)
final int[] newOffset = new int[newSize];
System.arraycopy(_offset, 0, newOffset, 0, length);
_offset = newOffset;
// Resize the 'length' array (attribute value length)
final int[] newLength = new int[newSize];
System.arraycopy(_length, 0, newLength, 0, length);
_length = newLength;
// Resize the '_prefix2' array
final short[] newPrefix = new short[newSize];
System.arraycopy(_prefix2, 0, newPrefix, 0, length);
_prefix2 = newPrefix;
}
}
private void shiftAttributes(final int shift) {
int i = 0;
int next = 0;
final int limit = _currentAttributeNode;
int lastParent = -1;
for (i = 0; i < limit; i++) {
if (_parent2[i] != lastParent) {
lastParent = _parent2[i];
_lengthOrAttr[lastParent] = i + shift;
}
next = _nextSibling2[i];
_nextSibling2[i] = next != 0 ? next + shift : 0;
}
}
private void appendAttributes() {
final int len = _currentAttributeNode;
if (len > 0) {
final int dst = _currentNode;
System.arraycopy(_type2, 0, _type, dst, len);
System.arraycopy(_prefix2, 0, _prefix, dst, len);
System.arraycopy(_parent2, 0, _parent, dst, len);
System.arraycopy(_nextSibling2, 0, _nextSibling, dst, len);
System.arraycopy(_offset, 0, _offsetOrChild, dst, len);
System.arraycopy(_length, 0, _lengthOrAttr, dst, len);
}
}
} // end of DOMBuilder
}
| false | false | null | null |
diff --git a/src/iitb/Model/ConcatRegexFeatures.java b/src/iitb/Model/ConcatRegexFeatures.java
index 1b06f72..5d04386 100644
--- a/src/iitb/Model/ConcatRegexFeatures.java
+++ b/src/iitb/Model/ConcatRegexFeatures.java
@@ -1,320 +1,320 @@
package iitb.Model;
import iitb.CRF.*;
import java.util.regex.*;
import java.util.*;
import java.io.*;
/**
* ConcatRegexFeatures generates features by matching the token with the character patterns.
* Character patterns are regular expressions for checking whether the token is capitalized word,
* a number, small case word, whether the token contains any special characters and like.
* It uses regular expression to match a sequence of character pattern and generates features
* accordingly.
* <P>
* The feature generated here is whether a sequence of tokens has a particular sequence of given pattern or not.
* For example, if a pattern is to mathc a capital word, then for two token context window, various features
* generated are weither two token (bigram) sequence is having any of the following pattern or not:
* (1) Capital, Capital
* (2) Capital, Non-Capital
* (3) Non-capital, Capital.
*
* You can use any window around the current token (segment) for creating regular expression based features.
* Also, you can define your own patterns, by writing down the regular expression in a file,
* whose format is specified below.
* </p>
* <p>
* The object of this class should be wrap around {@link FeatureTypesEachLabel} as follows:
* <pre>
* new FeatureTypesEachLabel(model, new ConcreteConcatRegexFeatures(model,relSegmentStart, relSegmentEnd, maxMemory, patternFile));
* </pre>
* </p>
* A token in a token sequence has a index relative to the current token index, which is described below:
* <pre>
x0 x1 x2 x3 x4 x5 x6 x7 .... xn
-4 -3 -2 -1 0 0 0 1 2 ...
* </pre>
* <p>
* In above example, the current segment is from postion 4 to 6 with value of pos = 6 and prevPos = 3 in
* startScanFeaturesAt() call of FeatureGenerator.
* You can refer to any of the token relative to current position by using the index below the token sequence.
* Thus, you can create a pattern concat features for any token sequence in the neighbourhood of the current token,
* using relSegmentStart and relSegmentEnd.
* For, example to create pattern for two tokens to the left of the current token, following is the parameters
* to be passed to the constructor of the class:
* </p>
* <pre>
* new FeatureTypesEachLabel(model, new ConcreteConcatRegexFeatures(model,-2, -1, maxMemory, patternFile));
* </pre>
*
* @author Imran Mansuri
*/
public class ConcatRegexFeatures extends FeatureTypes {
/**
* Various patterns are defined here.
* First dimension of this two dimensional array is feature name and second value is the
* regular expression pattern to be matched against a token. You can add your own patterns
* in this array.
*/
String patternString[][] = {
{"isWord", "[a-zA-Z][a-zA-Z]+" },
{"singleCapLetterWithDot", "[A-Z]\\." },
{"singleCapLetter", "[A-Z]" },
{"isDigits", "\\d+" },
{"singleDot", "[.]" },
{"singleComma", "[,]" },
{"isSpecialCharacter", "[#;:\\-/<>'\"()&]"},
{"containsSpecialCharacters",".*[#;:\\-/<>'\"()&].*"},
{"isInitCapital", "[A-Z][a-z]+" },
{"isAllCapital", "[A-Z]+" },
{"isAllSmallCase", "[a-z]+" },
{"isAlpha", "[a-zA-Z]+" },
{"isAlphaNumeric", "[a-zA-Z0-9]+" },
{"endsWithDot", "\\p{Alnum}+\\." },
{"endsWithComma", "\\w+[,]" },
{"endsWithPunctuation", "\\w+[;:,.?!]" },
{"singlePunctuation", "\\p{Punct}" },
{"singleAmp", "[&]" },
{"containsDigit", ".*\\d+.*" },
{"singleDigit", "\\s*\\d\\s*" },
{"twoDigits", "\\s*\\d{2}\\s*" },
{"threeDigits", "\\s*\\d{3}\\s*" },
{"fourDigits", "\\s*\\(*\\d{4}\\)*\\s*" },
{"isNumberRange", "\\d+\\s*([-]{1,2}\\s*\\d+)?"},
{"isDashSeparatedWords", "(\\w[-])+\\w"},
{"isDashSeparatedSeq", "((\\p{Alpha}+|\\p{Digit}+)[-])+(\\p{Alpha}+|\\p{Digit}+)"},
{"isURL", "\\p{Alpha}+://(\\w+\\.)\\w+(:(\\d{2}|\\d{4}))?(/\\w+)*(/|(/\\w+\\.\\w+))?" },
{"isEmailId", "\\w+@(\\w+\\.)+\\w+" },
{"containsDashes", ".*--.*"}
};
Pattern p[];
transient protected DataSequence data;
protected int index, idbase, curId, window;
protected int relSegmentStart, relSegmentEnd;
protected int maxMemory;
protected int left, right;
/**
* @param relSegmentStart2
* @param relSegmentEnd2
* @return
*/
private int getWindowSize(int relSegmentStart, int relSegmentEnd) {
if((sign(relSegmentEnd) == sign(relSegmentStart)) && relSegmentStart != 0)
return relSegmentEnd - relSegmentStart + 1;
else
return relSegmentEnd - relSegmentStart + maxMemory;
}
/**
* Constructs an object of ConcatRegexFeatures to be used to generate features for the token
* sequence as specified.
* You can specify the sequence of tokens on which the pattern has to be applied using relSegmentStart
* and relSegmentEnd, which denotes segment boundries.
* The maxMemory denotes the maximum segment size, for normal CRF the value of maxMemory is 1.
* There are certain default patterns defined in the class. You can specify your own pattern in a file, and pass
* the name of the file in this constructor. The file should begin with integer value for number of pattern in the
* file. This should be follwoed by one pattern definition on each line. The first word is the name of the pattern
* and second word is regular expression for the pattern.
*
* @param fgen a {@link Model} object
* @param relSegmentStart index of the reltive position for left boundary
* @param relSegmentEnd index of the reltive position for right boundary
* @param maxMemory maximum size of a segment
* @param patternFile file which contains the pattern definition
*/
public ConcatRegexFeatures(FeatureGenImpl fgen, int relSegmentStart, int relSegmentEnd, int maxMemory, String patternFile){
super(fgen);
assert(relSegmentEnd >= relSegmentStart);
this.relSegmentStart = relSegmentStart;
this.relSegmentEnd = relSegmentEnd;
this.maxMemory = maxMemory;
window = getWindowSize(relSegmentStart, relSegmentEnd);
idbase = (int) Math.pow(2, window-1);
if (patternFile != null) getPatterns(patternFile);
assert(patternString != null);
p = new Pattern[patternString.length];
for(int i = 0; i < patternString.length; i++){
//System.out.println("i"+ i +" " + patternString[i][1]);
p[i] = Pattern.compile(patternString[i][1]);
}
cache=true;
}
/**
* Constructs an object of ConcatRegexFeatures to be used to generate features for current token.
* @param m a {@link Model} object
* @param relSegmentStart index of the reltive position for left boundary
* @param relSegmentEnd index of the reltive position for right boundary
* @param maxMemory maximum size of a segment
*/
public ConcatRegexFeatures(FeatureGenImpl m, int relSegmentStart, int relSegmentEnd, int maxMemory){
this(m,relSegmentStart,relSegmentEnd,maxMemory,null);
}
/**
* Constructs an object of ConcatRegexFeatures to be used to generate features for current token.
* @param m a {@link Model} object
* @param relSegmentStart index of the reltive position for left boundary
* @param relSegmentEnd index of the reltive position for right boundary
*/
public ConcatRegexFeatures(FeatureGenImpl m, int relSegmentStart, int relSegmentEnd){
this(m, relSegmentStart, relSegmentEnd, 1);
}
public ConcatRegexFeatures(FeatureGenImpl m){
this(m, 0,0,1);
}
/**
* Constructs an object of ConcatRegexFeatures to be used to generate features for current token.
* @param m a {@link Model} object
* @param relSegmentStart index of the reltive position for left boundary
* @param relSegmentEnd index of the reltive position for right boundary
* @param patternFile file which contains the pattern definition
*/
public ConcatRegexFeatures(FeatureGenImpl m, int relSegmentStart, int relSegmentEnd, String patternFile){
this(m, relSegmentStart, relSegmentEnd, 1, patternFile);
}
private int sign(int boundary){
if(boundary == 0)
return 0;
else if(boundary < 0)
return -1;
else
return 1;
}
/**
* Reads patterns to be matched from the file.
* The format of the file is as follows:
* The first line of the file is number of patterns, followed by a list of patterns one per line.
* Each line describes a pattern's name and pattern string itself.
*
* @param patternFile name of the pattern file
*/
void getPatterns(String patternFile){
String line;
String patterns[][];
try {
BufferedReader in = new BufferedReader(new FileReader(patternFile));
int len = Integer.parseInt(in.readLine());
patterns = new String[len][2];
for(int k = 0; k < len; k++){
StringTokenizer strTokenizer = new StringTokenizer(in.readLine());
patterns[k][0] = strTokenizer.nextToken();
patterns[k][1] = strTokenizer.nextToken();
//System.out.println(patterns[k][0] + " " + patterns[k][1]);
}
}catch(IOException ioe){
System.err.println("Could not read pattern file : " + patternFile);
ioe.printStackTrace();
return;
}
patternString = patterns;
return;
}
/**
* Initaites scanning of features in a sequence at specified position.
*
* @param data a training sequence
* @param prevPos the previous label postion
* @param pos Current token postion
*/
public boolean startScanFeaturesAt(DataSequence data, int prevPos, int pos){
assert(patternString != null);
this.data = data;
index = 0;
if (relSegmentStart <= 0) {
left = prevPos + 1 + relSegmentStart;
} else {
left = pos + relSegmentStart;
}
if (relSegmentEnd < 0) {
right = prevPos + 1 + relSegmentEnd;
} else {
right = pos + relSegmentEnd;
}
if(!(left >= 0 && left < data.length() && right >= 0 && right < data.length()))
index = patternString.length;
//System.out.println("DataLength:" + data.length() + " segment(" + (prevPos+1) + "," + pos + ") rs(" +relSegmentStart + "," + relSegmentEnd + ") window(" + left + "," + right + ") idbase:" + idbase);
advance();
return true;
}
/**
* Returns true if there are any more feature(s) for the current scan.
*
*/
public boolean hasNext() {
return index < patternString.length;
}
/**
* Generates the next feature for the current scan.
*
* @param f Copies the feature generated to the argument
*/
public void next(FeatureImpl f) {
if(featureCollectMode()){
//This is a feature collection mode, so return id and name
f.strId.name = "R_" + patternString[index][0];
if ((window > 1) && (curId > 0)) {
f.strId.name = f.strId.name + ("_" + window + "_" + Integer.toBinaryString(curId));
}
}
/*//Return feature on token window
int base = 1;
f.strId.id = 0;
for(int k = left; k <= right; k++){
boolean match = p[index].matcher((String)data.x(k)).matches();
f.strId.id += base * (match? 1:0);
base = base * 2;
}
f.val = (f.strId.id > 0) ? 1:0; //In case of no match return 0 as feature value
f.ystart = -1;
f.strId.id += idbase * index++;*/
f.val = 1;
f.strId.id = curId + idbase * index++;
f.ystart = -1;
advance();
}
private void advance(){
curId = 0;
while(curId <= 0 && index < patternString.length){
int base = 1;
for(int k = left; k <= right; k++){
- boolean match = p[index].matcher((String)data.x(k)).matches();
+ boolean match = p[index].matcher(data.x(k).toString()).matches();
curId += base * (match? 1:0);
base = base * 2;
}
if(curId > 0)
break;
index++;
}
}
public int maxFeatureId(){
return idbase * patternString.length; //(maximum base i.e. most significat bits + maximum offset)
}
int offsetLabelIndependentId(FeatureImpl f) {
return f.strId.id;
}
};
| true | false | null | null |
diff --git a/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/RubyUILanguageToolkit.java b/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/RubyUILanguageToolkit.java
index 98c5cc79..d002e4c3 100644
--- a/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/RubyUILanguageToolkit.java
+++ b/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/RubyUILanguageToolkit.java
@@ -1,123 +1,123 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.ruby.internal.ui;
import org.eclipse.dltk.core.IDLTKLanguageToolkit;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.IType;
import org.eclipse.dltk.ruby.core.RubyConstants;
import org.eclipse.dltk.ruby.core.RubyLanguageToolkit;
import org.eclipse.dltk.ruby.internal.ui.editor.RubyEditor;
import org.eclipse.dltk.ruby.internal.ui.preferences.SimpleRubySourceViewerConfiguration;
import org.eclipse.dltk.ui.IDLTKUILanguageToolkit;
import org.eclipse.dltk.ui.ScriptElementLabels;
import org.eclipse.dltk.ui.text.ScriptSourceViewerConfiguration;
import org.eclipse.dltk.ui.text.ScriptTextTools;
import org.eclipse.dltk.ui.viewsupport.ScriptUILabelProvider;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.preference.IPreferenceStore;
public class RubyUILanguageToolkit implements IDLTKUILanguageToolkit {
private static ScriptElementLabels sInstance = new ScriptElementLabels() {
public void getElementLabel(IModelElement element, long flags,
StringBuffer buf) {
StringBuffer buffer = new StringBuffer(60);
super.getElementLabel(element, flags, buffer);
String s = buffer.toString();
if (s != null && !s.startsWith(element.getElementName())) {
if (s.indexOf('$') != -1) {
s = s.replaceAll("\\$", ".");
}
}
buf.append(s);
}
protected void getTypeLabel(IType type, long flags, StringBuffer buf) {
StringBuffer buffer = new StringBuffer(60);
super.getTypeLabel(type, flags, buffer);
String s = buffer.toString();
if (s.indexOf('$') != -1) {
s = s.replaceAll("\\$", "::");
}
buf.append(s);
}
protected char getTypeDelimiter() {
return '$';
}
};
private static RubyUILanguageToolkit sToolkit = null;
public static IDLTKUILanguageToolkit getInstance() {
if (sToolkit == null) {
sToolkit = new RubyUILanguageToolkit();
}
return sToolkit;
}
public ScriptElementLabels getScriptElementLabels() {
return sInstance;
}
public IPreferenceStore getPreferenceStore() {
return RubyUI.getDefault().getPreferenceStore();
}
public IDLTKLanguageToolkit getCoreToolkit() {
return RubyLanguageToolkit.getDefault();
}
public IDialogSettings getDialogSettings() {
return RubyUI.getDefault().getDialogSettings();
}
public String getPartitioningId() {
return RubyConstants.RUBY_PARTITIONING;
}
public String getEditorId(Object inputElement) {
return RubyEditor.EDITOR_ID;
}
public String getInterpreterContainerId() {
return "org.eclipse.dltk.ruby.launching.INTERPRETER_CONTAINER";
}
- public ScriptUILabelProvider createScripUILabelProvider() {
+ public ScriptUILabelProvider createScriptUILabelProvider() {
return null;
}
public boolean getProvideMembers(ISourceModule element) {
return true;
}
public ScriptTextTools getTextTools() {
return RubyUI.getDefault().getTextTools();
}
public ScriptSourceViewerConfiguration createSourceViewerConfiguration() {
return new SimpleRubySourceViewerConfiguration(getTextTools()
.getColorManager(), getPreferenceStore(), null,
getPartitioningId(), false);
}
private static final String INTERPRETERS_PREFERENCE_PAGE_ID = "org.eclipse.dltk.ruby.preferences.interpreters";
private static final String DEBUG_PREFERENCE_PAGE_ID = "org.eclipse.dltk.ruby.preferences.debug";
public String getInterpreterPreferencePage() {
return INTERPRETERS_PREFERENCE_PAGE_ID;
}
public String getDebugPreferencePage() {
return DEBUG_PREFERENCE_PAGE_ID;
}
}
diff --git a/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/preferences/RubyBuildPathsBlock.java b/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/preferences/RubyBuildPathsBlock.java
index 7ddcecfc..b7973d1e 100644
--- a/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/preferences/RubyBuildPathsBlock.java
+++ b/plugins/org.eclipse.dltk.ruby.ui/src/org/eclipse/dltk/ruby/internal/ui/preferences/RubyBuildPathsBlock.java
@@ -1,33 +1,33 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.ruby.internal.ui.preferences;
import org.eclipse.dltk.ruby.internal.ui.RubyUI;
import org.eclipse.dltk.ui.util.IStatusChangeListener;
import org.eclipse.dltk.ui.wizards.BuildpathsBlock;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.preferences.IWorkbenchPreferenceContainer;
public class RubyBuildPathsBlock extends BuildpathsBlock {
public RubyBuildPathsBlock(IRunnableContext runnableContext,
IStatusChangeListener context, int pageToShow, boolean useNewPage,
IWorkbenchPreferenceContainer pageContainer) {
super(runnableContext, context, pageToShow, useNewPage, pageContainer);
}
protected IPreferenceStore getPreferenceStore() {
return RubyUI.getDefault().getPreferenceStore();
}
protected boolean supportZips() {
- return true;
+ return false;
}
}
| false | false | null | null |
diff --git a/python-checks/src/test/java/org/sonar/python/checks/CheckListTest.java b/python-checks/src/test/java/org/sonar/python/checks/CheckListTest.java
index 85b5bfe9..82d744ac 100644
--- a/python-checks/src/test/java/org/sonar/python/checks/CheckListTest.java
+++ b/python-checks/src/test/java/org/sonar/python/checks/CheckListTest.java
@@ -1,95 +1,95 @@
/*
* Sonar Python Plugin
* Copyright (C) 2011 SonarSource and Waleri Enns
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.python.checks;
import com.google.common.collect.Sets;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.sonar.api.rules.AnnotationRuleParser;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleParam;
import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
import static org.fest.assertions.Assertions.assertThat;
public class CheckListTest {
/**
* Enforces that each check declared in list.
*/
@Test
public void count() {
int count = 0;
List<File> files = (List<File>) FileUtils.listFiles(new File("src/main/java/org/sonar/python/checks/"), new String[] {"java"}, false);
for (File file : files) {
if (file.getName().endsWith("Check.java")) {
count++;
}
}
assertThat(CheckList.getChecks().size()).isEqualTo(count);
}
/**
* Enforces that each check has test, name and description.
*/
@Test
public void test() {
List<Class> checks = CheckList.getChecks();
for (Class cls : checks) {
String testName = '/' + cls.getName().replace('.', '/') + "Test.class";
assertThat(getClass().getResource(testName))
.overridingErrorMessage("No test for " + cls.getSimpleName())
.isNotNull();
}
ResourceBundle resourceBundle = ResourceBundle.getBundle("org.sonar.l10n.python", Locale.ENGLISH);
Set<String> keys = Sets.newHashSet();
List<Rule> rules = new AnnotationRuleParser().parse("repositoryKey", checks);
for (Rule rule : rules) {
assertThat(keys).as("Duplicate key " + rule.getKey()).excludes(rule.getKey());
keys.add(rule.getKey());
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".name");
assertThat(getClass().getResource("/org/sonar/l10n/python/rules/python/" + rule.getKey() + ".html"))
.overridingErrorMessage("No description for " + rule.getKey())
.isNotNull();
assertThat(rule.getDescription())
.overridingErrorMessage("Description of " + rule.getKey() + " should be in separate file")
- .isEmpty();
+ .isNull();
for (RuleParam param : rule.getParams()) {
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".param." + param.getKey());
assertThat(param.getDescription())
.overridingErrorMessage("Description for param " + param.getKey() + " of " + rule.getKey() + " should be in separate file")
.isEmpty();
}
}
}
}
| true | true | public void test() {
List<Class> checks = CheckList.getChecks();
for (Class cls : checks) {
String testName = '/' + cls.getName().replace('.', '/') + "Test.class";
assertThat(getClass().getResource(testName))
.overridingErrorMessage("No test for " + cls.getSimpleName())
.isNotNull();
}
ResourceBundle resourceBundle = ResourceBundle.getBundle("org.sonar.l10n.python", Locale.ENGLISH);
Set<String> keys = Sets.newHashSet();
List<Rule> rules = new AnnotationRuleParser().parse("repositoryKey", checks);
for (Rule rule : rules) {
assertThat(keys).as("Duplicate key " + rule.getKey()).excludes(rule.getKey());
keys.add(rule.getKey());
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".name");
assertThat(getClass().getResource("/org/sonar/l10n/python/rules/python/" + rule.getKey() + ".html"))
.overridingErrorMessage("No description for " + rule.getKey())
.isNotNull();
assertThat(rule.getDescription())
.overridingErrorMessage("Description of " + rule.getKey() + " should be in separate file")
.isEmpty();
for (RuleParam param : rule.getParams()) {
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".param." + param.getKey());
assertThat(param.getDescription())
.overridingErrorMessage("Description for param " + param.getKey() + " of " + rule.getKey() + " should be in separate file")
.isEmpty();
}
}
}
| public void test() {
List<Class> checks = CheckList.getChecks();
for (Class cls : checks) {
String testName = '/' + cls.getName().replace('.', '/') + "Test.class";
assertThat(getClass().getResource(testName))
.overridingErrorMessage("No test for " + cls.getSimpleName())
.isNotNull();
}
ResourceBundle resourceBundle = ResourceBundle.getBundle("org.sonar.l10n.python", Locale.ENGLISH);
Set<String> keys = Sets.newHashSet();
List<Rule> rules = new AnnotationRuleParser().parse("repositoryKey", checks);
for (Rule rule : rules) {
assertThat(keys).as("Duplicate key " + rule.getKey()).excludes(rule.getKey());
keys.add(rule.getKey());
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".name");
assertThat(getClass().getResource("/org/sonar/l10n/python/rules/python/" + rule.getKey() + ".html"))
.overridingErrorMessage("No description for " + rule.getKey())
.isNotNull();
assertThat(rule.getDescription())
.overridingErrorMessage("Description of " + rule.getKey() + " should be in separate file")
.isNull();
for (RuleParam param : rule.getParams()) {
resourceBundle.getString("rule." + CheckList.REPOSITORY_KEY + "." + rule.getKey() + ".param." + param.getKey());
assertThat(param.getDescription())
.overridingErrorMessage("Description for param " + param.getKey() + " of " + rule.getKey() + " should be in separate file")
.isEmpty();
}
}
}
|
diff --git a/src/main/java/com/stuzzhosting/totallylogical/TotallyLogicalGenerator.java b/src/main/java/com/stuzzhosting/totallylogical/TotallyLogicalGenerator.java
index f43d618..6ff6e4e 100644
--- a/src/main/java/com/stuzzhosting/totallylogical/TotallyLogicalGenerator.java
+++ b/src/main/java/com/stuzzhosting/totallylogical/TotallyLogicalGenerator.java
@@ -1,59 +1,62 @@
package com.stuzzhosting.totallylogical;
import java.util.Random;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.util.noise.SimplexNoiseGenerator;
class TotallyLogicalGenerator extends ChunkGenerator {
private static final byte BEDROCK = (byte) Material.BEDROCK.getId();
private static final byte STONE = (byte) Material.MONSTER_EGGS.getId();
@Override
public byte[][] generateBlockSections( World world, Random random, int chunkX, int chunkZ, BiomeGrid biomes ) {
byte[][] result = new byte[world.getMaxHeight() >> 4][];
Random seed = new Random(world.getSeed());
SimplexNoiseGenerator exists = new SimplexNoiseGenerator( seed );
SimplexNoiseGenerator tall = new SimplexNoiseGenerator( seed );
for ( int _x = 0; _x < 16; _x++ ) {
for ( int _z = 0; _z < 16; _z++ ) {
biomes.setBiome( _x, _z, Biome.EXTREME_HILLS );
int x = _x + ( chunkX << 4 ), z = _z + ( chunkZ << 4 );
if ( exists.noise( x / 100.0, z / 100.0 ) < 0.2 ) {
boolean isTall = Math.abs( tall.noise( x / 20.0, z / 20.0 ) ) < 0.2;
for (int y = 0; y < world.getMaxHeight() / (isTall ? 1 : 4); y++) {
if (y <= random.nextInt(6)) {
setBlock( result, x, y, z, BEDROCK );
continue;
}
setBlock( result, x, y, z, STONE );
}
}
}
}
return result;
}
private static void setBlock( byte[][] result, int x, int y, int z, byte blkid ) {
if ( result[y >> 4] == null && blkid != 0 ) {
result[y >> 4] = new byte[16 * 16 * 16];
}
result[y >> 4][( ( y & 0xF ) << 8 ) | ( ( z & 0xF ) << 4 ) | ( x & 0xF )] = blkid;
}
private static byte getBlock( byte[][] result, int x, int y, int z ) {
if ( result[y >> 4] == null ) {
return (byte) 0;
}
return result[y >> 4][( ( y & 0xF ) << 8 ) | ( ( z & 0xF ) << 4 ) | ( x & 0xF )];
}
-
+ @Override
+ public boolean canSpawn( World world, int x, int z ) {
+ return world.getHighestBlockYAt( x, z ) < 128;
+ }
}
| true | false | null | null |
diff --git a/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java b/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java
index 0cba267..92a0fd7 100644
--- a/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java
+++ b/src/java/com/android/internal/telephony/cdma/CdmaLteServiceStateTracker.java
@@ -1,578 +1,581 @@
/*
* Copyright (C) 2012 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.internal.telephony.cdma;
import com.android.internal.telephony.TelephonyProperties;
import com.android.internal.telephony.MccTable;
import com.android.internal.telephony.EventLogTags;
import com.android.internal.telephony.uicc.RuimRecords;
import com.android.internal.telephony.uicc.IccCardApplicationStatus.AppState;
import android.telephony.CellInfo;
import android.telephony.CellInfoLte;
import android.telephony.CellSignalStrengthLte;
import android.telephony.CellIdentityLte;
import android.telephony.SignalStrength;
import android.telephony.ServiceState;
import android.telephony.cdma.CdmaCellLocation;
import android.text.TextUtils;
import android.os.AsyncResult;
import android.os.Message;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.telephony.Rlog;
import android.util.EventLog;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class CdmaLteServiceStateTracker extends CdmaServiceStateTracker {
private CDMALTEPhone mCdmaLtePhone;
private final CellInfoLte mCellInfoLte;
private CellIdentityLte mNewCellIdentityLte = new CellIdentityLte();
private CellIdentityLte mLasteCellIdentityLte = new CellIdentityLte();
public CdmaLteServiceStateTracker(CDMALTEPhone phone) {
super(phone, new CellInfoLte());
mCdmaLtePhone = phone;
mCellInfoLte = (CellInfoLte) mCellInfo;
((CellInfoLte)mCellInfo).setCellSignalStrength(new CellSignalStrengthLte());
((CellInfoLte)mCellInfo).setCellIdentity(new CellIdentityLte());
if (DBG) log("CdmaLteServiceStateTracker Constructors");
}
@Override
public void handleMessage(Message msg) {
AsyncResult ar;
int[] ints;
String[] strings;
switch (msg.what) {
case EVENT_POLL_STATE_GPRS:
if (DBG) log("handleMessage EVENT_POLL_STATE_GPRS");
ar = (AsyncResult)msg.obj;
handlePollStateResult(msg.what, ar);
break;
case EVENT_RUIM_RECORDS_LOADED:
RuimRecords ruim = (RuimRecords)mIccRecords;
if ((ruim != null) && ruim.isProvisioned()) {
mMdn = ruim.getMdn();
mMin = ruim.getMin();
parseSidNid(ruim.getSid(), ruim.getNid());
mPrlVersion = ruim.getPrlVersion();
mIsMinInfoReady = true;
updateOtaspState();
}
// SID/NID/PRL is loaded. Poll service state
// again to update to the roaming state with
// the latest variables.
pollState();
break;
default:
super.handleMessage(msg);
}
}
/**
* Handle the result of one of the pollState()-related requests
*/
@Override
protected void handlePollStateResultMessage(int what, AsyncResult ar) {
if (what == EVENT_POLL_STATE_GPRS) {
String states[] = (String[])ar.result;
if (DBG) {
log("handlePollStateResultMessage: EVENT_POLL_STATE_GPRS states.length=" +
states.length + " states=" + states);
}
int type = 0;
int regState = -1;
if (states.length > 0) {
try {
regState = Integer.parseInt(states[0]);
// states[3] (if present) is the current radio technology
if (states.length >= 4 && states[3] != null) {
type = Integer.parseInt(states[3]);
}
} catch (NumberFormatException ex) {
loge("handlePollStateResultMessage: error parsing GprsRegistrationState: "
+ ex);
}
if (states.length >= 10) {
int mcc;
int mnc;
int tac;
int pci;
int eci;
int csgid;
String operatorNumeric = null;
try {
operatorNumeric = mNewSS.getOperatorNumeric();
mcc = Integer.parseInt(operatorNumeric.substring(0,3));
} catch (Exception e) {
try {
operatorNumeric = mSS.getOperatorNumeric();
mcc = Integer.parseInt(operatorNumeric.substring(0,3));
} catch (Exception ex) {
loge("handlePollStateResultMessage: bad mcc operatorNumeric=" +
operatorNumeric + " ex=" + ex);
operatorNumeric = "";
mcc = Integer.MAX_VALUE;
}
}
try {
mnc = Integer.parseInt(operatorNumeric.substring(3));
} catch (Exception e) {
loge("handlePollStateResultMessage: bad mnc operatorNumeric=" +
operatorNumeric + " e=" + e);
mnc = Integer.MAX_VALUE;
}
// Use Integer#decode to be generous in what we receive and allow
// decimal, hex or octal values.
try {
tac = Integer.decode(states[6]);
} catch (Exception e) {
loge("handlePollStateResultMessage: bad tac states[6]=" +
states[6] + " e=" + e);
tac = Integer.MAX_VALUE;
}
try {
pci = Integer.decode(states[7]);
} catch (Exception e) {
loge("handlePollStateResultMessage: bad pci states[7]=" +
states[7] + " e=" + e);
pci = Integer.MAX_VALUE;
}
try {
eci = Integer.decode(states[8]);
} catch (Exception e) {
loge("handlePollStateResultMessage: bad eci states[8]=" +
states[8] + " e=" + e);
eci = Integer.MAX_VALUE;
}
try {
csgid = Integer.decode(states[9]);
} catch (Exception e) {
// FIX: Always bad so don't pollute the logs
// loge("handlePollStateResultMessage: bad csgid states[9]=" +
// states[9] + " e=" + e);
csgid = Integer.MAX_VALUE;
}
mNewCellIdentityLte = new CellIdentityLte(mcc, mnc, eci, pci, tac);
if (DBG) {
log("handlePollStateResultMessage: mNewLteCellIdentity=" +
mNewCellIdentityLte);
}
}
}
mNewSS.setRilDataRadioTechnology(type);
int dataRegState = regCodeToServiceState(regState);
mNewSS.setDataRegState(dataRegState);
if (DBG) {
log("handlPollStateResultMessage: CdmaLteSST setDataRegState=" + dataRegState
+ " regState=" + regState
+ " dataRadioTechnology=" + type);
}
} else {
super.handlePollStateResultMessage(what, ar);
}
}
@Override
protected void pollState() {
mPollingContext = new int[1];
mPollingContext[0] = 0;
switch (mCi.getRadioState()) {
case RADIO_UNAVAILABLE:
mNewSS.setStateOutOfService();
mNewCellLoc.setStateInvalid();
setSignalStrengthDefaultValues();
mGotCountryCode = false;
pollStateDone();
break;
case RADIO_OFF:
mNewSS.setStateOff();
mNewCellLoc.setStateInvalid();
setSignalStrengthDefaultValues();
mGotCountryCode = false;
pollStateDone();
break;
default:
// Issue all poll-related commands at once, then count
// down the responses which are allowed to arrive
// out-of-order.
mPollingContext[0]++;
// RIL_REQUEST_OPERATOR is necessary for CDMA
mCi.getOperator(obtainMessage(EVENT_POLL_STATE_OPERATOR_CDMA, mPollingContext));
mPollingContext[0]++;
// RIL_REQUEST_VOICE_REGISTRATION_STATE is necessary for CDMA
mCi.getVoiceRegistrationState(obtainMessage(EVENT_POLL_STATE_REGISTRATION_CDMA,
mPollingContext));
mPollingContext[0]++;
// RIL_REQUEST_DATA_REGISTRATION_STATE
mCi.getDataRegistrationState(obtainMessage(EVENT_POLL_STATE_GPRS,
mPollingContext));
break;
}
}
@Override
protected void pollStateDone() {
log("pollStateDone: lte 1 ss=[" + mSS + "] newSS=[" + mNewSS + "]");
useDataRegStateForDataOnlyDevices();
boolean hasRegistered = mSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE
&& mNewSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE
&& mNewSS.getVoiceRegState() != ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionAttached =
mSS.getDataRegState() != ServiceState.STATE_IN_SERVICE
&& mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionDetached =
mSS.getDataRegState() == ServiceState.STATE_IN_SERVICE
&& mNewSS.getDataRegState() != ServiceState.STATE_IN_SERVICE;
boolean hasCdmaDataConnectionChanged =
mSS.getDataRegState() != mNewSS.getDataRegState();
boolean hasVoiceRadioTechnologyChanged = mSS.getRilVoiceRadioTechnology()
!= mNewSS.getRilVoiceRadioTechnology();
boolean hasDataRadioTechnologyChanged = mSS.getRilDataRadioTechnology()
!= mNewSS.getRilDataRadioTechnology();
boolean hasChanged = !mNewSS.equals(mSS);
boolean hasRoamingOn = !mSS.getRoaming() && mNewSS.getRoaming();
boolean hasRoamingOff = mSS.getRoaming() && !mNewSS.getRoaming();
boolean hasLocationChanged = !mNewCellLoc.equals(mCellLoc);
boolean has4gHandoff =
mNewSS.getDataRegState() == ServiceState.STATE_IN_SERVICE &&
(((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) &&
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) ||
((mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD) &&
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE)));
boolean hasMultiApnSupport =
(((mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) ||
(mNewSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)) &&
((mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_LTE) &&
(mSS.getRilDataRadioTechnology() != ServiceState.RIL_RADIO_TECHNOLOGY_EHRPD)));
boolean hasLostMultiApnSupport =
((mNewSS.getRilDataRadioTechnology() >= ServiceState.RIL_RADIO_TECHNOLOGY_IS95A) &&
(mNewSS.getRilDataRadioTechnology() <= ServiceState.RIL_RADIO_TECHNOLOGY_EVDO_A));
if (DBG) {
log("pollStateDone:"
+ " hasRegistered=" + hasRegistered
+ " hasDeegistered=" + hasDeregistered
+ " hasCdmaDataConnectionAttached=" + hasCdmaDataConnectionAttached
+ " hasCdmaDataConnectionDetached=" + hasCdmaDataConnectionDetached
+ " hasCdmaDataConnectionChanged=" + hasCdmaDataConnectionChanged
+ " hasVoiceRadioTechnologyChanged= " + hasVoiceRadioTechnologyChanged
+ " hasDataRadioTechnologyChanged=" + hasDataRadioTechnologyChanged
+ " hasChanged=" + hasChanged
+ " hasRoamingOn=" + hasRoamingOn
+ " hasRoamingOff=" + hasRoamingOff
+ " hasLocationChanged=" + hasLocationChanged
+ " has4gHandoff = " + has4gHandoff
+ " hasMultiApnSupport=" + hasMultiApnSupport
+ " hasLostMultiApnSupport=" + hasLostMultiApnSupport);
}
// Add an event log when connection state changes
if (mSS.getVoiceRegState() != mNewSS.getVoiceRegState()
|| mSS.getDataRegState() != mNewSS.getDataRegState()) {
EventLog.writeEvent(EventLogTags.CDMA_SERVICE_STATE_CHANGE, mSS.getVoiceRegState(),
mSS.getDataRegState(), mNewSS.getVoiceRegState(), mNewSS.getDataRegState());
}
ServiceState tss;
tss = mSS;
mSS = mNewSS;
mNewSS = tss;
// clean slate for next time
mNewSS.setStateOutOfService();
CdmaCellLocation tcl = mCellLoc;
mCellLoc = mNewCellLoc;
mNewCellLoc = tcl;
mNewSS.setStateOutOfService(); // clean slate for next time
if (hasDataRadioTechnologyChanged) {
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mSS.getRilDataRadioTechnology()));
+
+ // Query Signalstrength when there is a change in PS RAT.
+ sendMessage(obtainMessage(EVENT_POLL_SIGNAL_STRENGTH));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
}
if (hasChanged) {
if (mPhone.isEriFileLoaded()) {
String eriText;
// Now the CDMAPhone sees the new ServiceState so it can get the
// new ERI text
if (mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE) {
eriText = mPhone.getCdmaEriText();
} else if (mSS.getVoiceRegState() == ServiceState.STATE_POWER_OFF) {
eriText = (mIccRecords != null) ? mIccRecords.getServiceProviderName() : null;
if (TextUtils.isEmpty(eriText)) {
// Sets operator alpha property by retrieving from
// build-time system property
eriText = SystemProperties.get("ro.cdma.home.operator.alpha");
}
} else {
// Note that ServiceState.STATE_OUT_OF_SERVICE is valid used
// for mRegistrationState 0,2,3 and 4
eriText = mPhone.getContext()
.getText(com.android.internal.R.string.roamingTextSearching).toString();
}
mSS.setOperatorAlphaLong(eriText);
}
if (mUiccApplcation != null && mUiccApplcation.getState() == AppState.APPSTATE_READY &&
mIccRecords != null) {
// SIM is found on the device. If ERI roaming is OFF, and SID/NID matches
// one configured in SIM, use operator name from CSIM record.
boolean showSpn =
((RuimRecords)mIccRecords).getCsimSpnDisplayCondition();
int iconIndex = mSS.getCdmaEriIconIndex();
if (showSpn && (iconIndex == EriInfo.ROAMING_INDICATOR_OFF) &&
isInHomeSidNid(mSS.getSystemId(), mSS.getNetworkId()) &&
mIccRecords != null) {
mSS.setOperatorAlphaLong(mIccRecords.getServiceProviderName());
}
}
String operatorNumeric;
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
mSS.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = mSS.getOperatorNumeric();
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
} else {
String isoCountryCode = "";
String mcc = operatorNumeric.substring(0, 3);
try {
isoCountryCode = MccTable.countryCodeForMcc(Integer.parseInt(operatorNumeric
.substring(0, 3)));
} catch (NumberFormatException ex) {
loge("countryCodeForMcc error" + ex);
} catch (StringIndexOutOfBoundsException ex) {
loge("countryCodeForMcc error" + ex);
}
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY,
isoCountryCode);
mGotCountryCode = true;
if (shouldFixTimeZoneNow(mPhone, operatorNumeric, prevOperatorNumeric,
mNeedFixZone)) {
fixTimeZone(isoCountryCode);
}
}
mPhone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
mSS.getRoaming() ? "true" : "false");
updateSpnDisplay();
mPhone.notifyServiceStateChanged(mSS);
}
if (hasCdmaDataConnectionAttached || has4gHandoff) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasCdmaDataConnectionDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if ((hasCdmaDataConnectionChanged || hasDataRadioTechnologyChanged)) {
log("pollStateDone: call notifyDataConnection");
mPhone.notifyDataConnection(null);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
mPhone.notifyLocationChanged();
}
ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>();
synchronized(mCellInfo) {
CellInfoLte cil = (CellInfoLte)mCellInfo;
boolean cidChanged = ! mNewCellIdentityLte.equals(mLasteCellIdentityLte);
if (hasRegistered || hasDeregistered || cidChanged) {
// TODO: Handle the absence of LteCellIdentity
long timeStamp = SystemClock.elapsedRealtime() * 1000;
boolean registered = mSS.getVoiceRegState() == ServiceState.STATE_IN_SERVICE;
mLasteCellIdentityLte = mNewCellIdentityLte;
cil.setRegisterd(registered);
cil.setCellIdentity(mLasteCellIdentityLte);
if (DBG) {
log("pollStateDone: hasRegistered=" + hasRegistered +
" hasDeregistered=" + hasDeregistered +
" cidChanged=" + cidChanged +
" mCellInfo=" + mCellInfo);
}
arrayCi.add(mCellInfo);
}
mPhoneBase.notifyCellInfo(arrayCi);
}
}
@Override
protected boolean onSignalStrengthResult(AsyncResult ar, boolean isGsm) {
if (mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) {
isGsm = true;
}
boolean ssChanged = super.onSignalStrengthResult(ar, isGsm);
synchronized (mCellInfo) {
if (mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) {
mCellInfoLte.setTimeStamp(SystemClock.elapsedRealtime() * 1000);
mCellInfoLte.setTimeStampType(CellInfo.TIMESTAMP_TYPE_JAVA_RIL);
mCellInfoLte.getCellSignalStrength()
.initialize(mSignalStrength,SignalStrength.INVALID);
}
if (mCellInfoLte.getCellIdentity() != null) {
ArrayList<CellInfo> arrayCi = new ArrayList<CellInfo>();
arrayCi.add(mCellInfoLte);
mPhoneBase.notifyCellInfo(arrayCi);
}
}
return ssChanged;
}
@Override
public boolean isConcurrentVoiceAndDataAllowed() {
// For non-LTE, look at the CSS indicator to check on Concurrent V & D capability
if (mSS.getRilDataRadioTechnology() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE) {
return true;
} else {
return mSS.getCssIndicator() == 1;
}
}
/**
* Check whether the specified SID and NID pair appears in the HOME SID/NID list
* read from NV or SIM.
*
* @return true if provided sid/nid pair belongs to operator's home network.
*/
private boolean isInHomeSidNid(int sid, int nid) {
// if SID/NID is not available, assume this is home network.
if (isSidsAllZeros()) return true;
// length of SID/NID shold be same
if (mHomeSystemId.length != mHomeNetworkId.length) return true;
if (sid == 0) return true;
for (int i = 0; i < mHomeSystemId.length; i++) {
// Use SID only if NID is a reserved value.
// SID 0 and NID 0 and 65535 are reserved. (C.0005 2.6.5.2)
if ((mHomeSystemId[i] == sid) &&
((mHomeNetworkId[i] == 0) || (mHomeNetworkId[i] == 65535) ||
(nid == 0) || (nid == 65535) || (mHomeNetworkId[i] == nid))) {
return true;
}
}
// SID/NID are not in the list. So device is not in home network
return false;
}
/**
* TODO: Remove when we get new ril/modem for Galaxy Nexus.
*
* @return all available cell information, the returned List maybe empty but never null.
*/
@Override
public List<CellInfo> getAllCellInfo() {
if (mCi.getRilVersion() >= 8) {
return super.getAllCellInfo();
} else {
ArrayList<CellInfo> arrayList = new ArrayList<CellInfo>();
CellInfo ci;
synchronized(mCellInfo) {
arrayList.add(mCellInfoLte);
}
if (DBG) log ("getAllCellInfo: arrayList=" + arrayList);
return arrayList;
}
}
@Override
protected void log(String s) {
Rlog.d(LOG_TAG, "[CdmaLteSST] " + s);
}
@Override
protected void loge(String s) {
Rlog.e(LOG_TAG, "[CdmaLteSST] " + s);
}
@Override
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println("CdmaLteServiceStateTracker extends:");
super.dump(fd, pw, args);
pw.println(" mCdmaLtePhone=" + mCdmaLtePhone);
}
}
| true | false | null | null |
diff --git a/oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/index/SolrIndexUpdate.java b/oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/index/SolrIndexUpdate.java
index 2289117ec7..3cdc05cf5b 100644
--- a/oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/index/SolrIndexUpdate.java
+++ b/oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/index/SolrIndexUpdate.java
@@ -1,178 +1,178 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.index.solr.index;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.annotation.Nonnull;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.index.solr.OakSolrConfiguration;
import org.apache.jackrabbit.oak.plugins.index.solr.OakSolrUtils;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import com.google.common.base.Preconditions;
/**
* A Solr index update
*/
public class SolrIndexUpdate implements Closeable {
private final String path;
private final NodeBuilder index;
private OakSolrConfiguration configuration;
private final Map<String, NodeState> insert = new TreeMap<String, NodeState>();
private final Set<String> remove = new TreeSet<String>();
public SolrIndexUpdate(String path, NodeBuilder index, OakSolrConfiguration configuration) {
this.path = path;
this.index = index;
this.configuration = configuration;
}
public void insert(String path, NodeBuilder value) {
Preconditions.checkArgument(path.startsWith(this.path));
- if (!insert.containsKey(path)) {
- String key = path.substring(this.path.length());
+ String key = path.substring(this.path.length());
+ if (!insert.containsKey(key)) {
if ("".equals(key)) {
key = "/";
}
if (value != null) {
insert.put(key, value.getNodeState());
}
}
}
public void remove(String path) {
Preconditions.checkArgument(path.startsWith(this.path));
remove.add(path.substring(this.path.length()));
}
boolean getAndResetReindexFlag() {
boolean reindex = index.getProperty("reindex") != null
&& index.getProperty("reindex").getValue(
Type.BOOLEAN);
index.setProperty("reindex", false);
return reindex;
}
public void apply(SolrServer solrServer) throws CommitFailedException {
if (remove.isEmpty() && insert.isEmpty()) {
return;
}
try {
for (String p : remove) {
deleteSubtreeWriter(solrServer, p);
}
for (String p : insert.keySet()) {
NodeState ns = insert.get(p);
addSubtreeWriter(solrServer, p, ns);
}
OakSolrUtils.commitByPolicy(solrServer, configuration.getCommitPolicy());
} catch (IOException e) {
throw new CommitFailedException(
"Failed to update the full text search index", e);
} catch (SolrServerException e) {
throw new CommitFailedException(
"Failed to update the full text search index", e);
} finally {
remove.clear();
insert.clear();
}
}
private Collection<SolrInputDocument> docsFromState(String path, @Nonnull NodeState state) {
List<SolrInputDocument> solrInputDocuments = new LinkedList<SolrInputDocument>();
SolrInputDocument inputDocument = docFromState(path, state);
solrInputDocuments.add(inputDocument);
for (ChildNodeEntry childNodeEntry : state.getChildNodeEntries()) {
solrInputDocuments.addAll(docsFromState(new StringBuilder(path).append('/').
append(childNodeEntry.getName()).toString(), childNodeEntry.getNodeState()));
}
return solrInputDocuments;
}
private SolrInputDocument docFromState(String path, NodeState state) {
SolrInputDocument inputDocument = new SolrInputDocument();
inputDocument.addField(configuration.getPathField(), path);
for (PropertyState propertyState : state.getProperties()) {
// try to get the field to use for this property from configuration
String fieldName = configuration.getFieldNameFor(propertyState.getType());
if (fieldName != null) {
inputDocument.addField(fieldName, propertyState.getValue(propertyState.getType()));
} else {
// or fallback to adding propertyName:stringValue(s)
if (propertyState.isArray()) {
for (String s : propertyState.getValue(Type.STRINGS)) {
inputDocument.addField(propertyState.getName(), s);
}
} else {
inputDocument.addField(propertyState.getName(), propertyState.getValue(Type.STRING));
}
}
}
return inputDocument;
}
private void deleteSubtreeWriter(SolrServer solrServer, String path)
throws IOException, SolrServerException {
// TODO verify the removal of the entire sub-hierarchy
if (!path.startsWith("/")) {
path = "/" + path;
}
solrServer.deleteByQuery(new StringBuilder(configuration.getPathField())
.append(':').append(path).append("*").toString());
}
private void addSubtreeWriter(SolrServer solrServer, String path,
NodeState state) throws IOException, SolrServerException {
if (!path.startsWith("/")) {
path = "/" + path;
}
solrServer.add(docFromState(path, state));
}
@Override
public void close() throws IOException {
remove.clear();
insert.clear();
}
@Override
public String toString() {
return "SolrIndexUpdate [path=" + path + ", insert=" + insert
+ ", remove=" + remove + "]";
}
}
diff --git a/oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrQueryIndex.java b/oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrQueryIndex.java
index 080e6ccc7d..3437814959 100644
--- a/oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrQueryIndex.java
+++ b/oak-solr-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrQueryIndex.java
@@ -1,250 +1,255 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.index.solr.query;
import java.util.Collection;
import org.apache.jackrabbit.oak.api.PropertyValue;
import org.apache.jackrabbit.oak.plugins.index.IndexDefinition;
import org.apache.jackrabbit.oak.plugins.index.solr.OakSolrConfiguration;
import org.apache.jackrabbit.oak.spi.query.Cursor;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.jackrabbit.oak.spi.query.IndexRow;
import org.apache.jackrabbit.oak.spi.query.PropertyValues;
import org.apache.jackrabbit.oak.spi.query.QueryIndex;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Solr based {@link QueryIndex}
*/
public class SolrQueryIndex implements QueryIndex {
private static final Logger log = LoggerFactory.getLogger(SolrQueryIndex.class);
public static final String TYPE = "solr";
private final IndexDefinition index;
private final SolrServer solrServer;
private final OakSolrConfiguration configuration;
public SolrQueryIndex(IndexDefinition indexDefinition, SolrServer solrServer, OakSolrConfiguration configuration) {
this.index = indexDefinition;
this.solrServer = solrServer;
this.configuration = configuration;
}
@Override
public String getIndexName() {
return index.getName();
}
@Override
public double getCost(Filter filter, NodeState root) {
// TODO : estimate no of returned values and 0 is not good for no restrictions
return (filter.getPropertyRestrictions() != null ? filter.getPropertyRestrictions().size() * 0.1 : 0)
+ (filter.getFulltextConditions() != null ? filter.getFulltextConditions().size() * 0.01 : 0)
+ (filter.getPathRestriction() != null ? 0.2 : 0);
}
@Override
public String getPlan(Filter filter, NodeState nodeState) {
return getQuery(filter).toString();
}
private SolrQuery getQuery(Filter filter) {
SolrQuery solrQuery = new SolrQuery();
solrQuery.setParam("q.op", "AND");
solrQuery.setParam("df", "catch_all");
// TODO : can we handle this better?
solrQuery.setParam("rows", String.valueOf(Integer.MAX_VALUE));
StringBuilder queryBuilder = new StringBuilder();
// TODO : handle node type restriction
Filter.PathRestriction pathRestriction = filter.getPathRestriction();
if (pathRestriction != null) {
String path = purgePath(filter);
String fieldName = configuration.getFieldForPathRestriction(pathRestriction);
if (fieldName != null) {
queryBuilder.append(fieldName);
queryBuilder.append(':');
// TODO : remove this hack for all descendants of root node
if (path.equals("\\/") && pathRestriction.equals(Filter.PathRestriction.ALL_CHILDREN)) {
queryBuilder.append("*");
} else {
-// queryBuilder.append("\"");
+ queryBuilder.append("\"");
queryBuilder.append(path);
-// queryBuilder.append("\"");
+ queryBuilder.append("\"");
}
queryBuilder.append(" ");
}
}
Collection<Filter.PropertyRestriction> propertyRestrictions = filter.getPropertyRestrictions();
if (propertyRestrictions != null && !propertyRestrictions.isEmpty()) {
for (Filter.PropertyRestriction pr : propertyRestrictions) {
-
+ if (pr.propertyName.contains("/")) {
+ // lucene cannot handle child-level property restrictions
+ continue;
+ }
String first = null;
if (pr.first != null) {
first = partialEscape(String.valueOf(pr.first.getValue(pr.first.getType()))).toString();
}
String last = null;
if (pr.last != null) {
last = partialEscape(String.valueOf(pr.last.getValue(pr.last.getType()))).toString();
}
String prField = configuration.getFieldForPropertyRestriction(pr);
CharSequence fieldName = partialEscape(prField != null ?
prField : pr.propertyName);
if ("jcr\\:path".equals(fieldName.toString())) {
queryBuilder.append(configuration.getPathField());
queryBuilder.append(':');
queryBuilder.append(first);
} else {
queryBuilder.append(fieldName).append(':');
if (pr.first != null && pr.last != null && pr.first.equals(pr.last)) {
queryBuilder.append(first);
} else if (pr.first == null && pr.last == null) {
queryBuilder.append('*');
} else if ((pr.first != null && pr.last == null) || (pr.last != null && pr.first == null) || (!pr.first.equals(pr.last))) {
// TODO : need to check if this works for all field types (most likely not!)
queryBuilder.append(createRangeQuery(first, last, pr.firstIncluding, pr.lastIncluding));
} else if (pr.isLike) {
// TODO : the current parameter substitution is not expected to work well
queryBuilder.append(partialEscape(String.valueOf(pr.first.getValue(pr.first.getType())).replace('%', '*').replace('_', '?')));
} else {
throw new RuntimeException("[unexpected!] not handled case");
}
}
queryBuilder.append(" ");
}
}
Collection<String> fulltextConditions = filter.getFulltextConditions();
for (String fulltextCondition : fulltextConditions) {
queryBuilder.append(fulltextCondition).append(" ");
}
-
+ if(queryBuilder.length() == 0) {
+ queryBuilder.append("*:*");
+ }
String escapedQuery = queryBuilder.toString();
solrQuery.setQuery(escapedQuery);
if (log.isDebugEnabled()) {
log.debug(new StringBuilder("JCR query: \n" + filter.getQueryStatement() + " \nhas been converted to Solr query: \n").
append(solrQuery.toString()).toString());
}
return solrQuery;
}
private String createRangeQuery(String first, String last, boolean firstIncluding, boolean lastIncluding) {
// TODO : handle inclusion / exclusion of bounds
StringBuilder rangeQueryBuilder = new StringBuilder("[");
rangeQueryBuilder.append(first != null ? first : "*");
rangeQueryBuilder.append(" TO ");
rangeQueryBuilder.append(last != null ? last : "*");
rangeQueryBuilder.append("]");
return rangeQueryBuilder.toString();
}
private String purgePath(Filter filter) {
return partialEscape(filter.getPath()).toString();
}
// partially borrowed from SolrPluginUtils#partialEscape
private CharSequence partialEscape(CharSequence s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\\' || c == '!' || c == '(' || c == ')' ||
c == ':' || c == '^' || c == '[' || c == ']' || c == '/' ||
c == '{' || c == '}' || c == '~' || c == '*' || c == '?' ||
c == '-'
) {
sb.append('\\');
}
sb.append(c);
}
return sb;
}
@Override
public Cursor query(Filter filter, NodeState root) {
Cursor cursor;
try {
SolrQuery query = getQuery(filter);
QueryResponse queryResponse = solrServer.query(query);
cursor = new SolrCursor(queryResponse);
} catch (Exception e) {
throw new RuntimeException(e);
}
return cursor;
}
private class SolrCursor implements Cursor {
private final SolrDocumentList results;
private int i;
public SolrCursor(QueryResponse queryResponse) {
this.results = queryResponse.getResults();
i = 0;
}
@Override
public boolean hasNext() {
return results != null && i < results.size();
}
@Override
public void remove() {
results.remove(i);
}
public IndexRow next() {
if (i < results.size()) {
final SolrDocument doc = results.get(i);
i++;
return new IndexRow() {
@Override
public String getPath() {
return String.valueOf(doc.getFieldValue(configuration.getPathField()));
}
@Override
public PropertyValue getValue(String columnName) {
String s = doc.getFieldValue(columnName).toString();
return PropertyValues.newString(s);
}
};
} else {
return null;
}
}
}
}
diff --git a/oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrIndexQueryTest.java b/oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrIndexQueryTest.java
index a585612df7..512acb93fd 100644
--- a/oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrIndexQueryTest.java
+++ b/oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrIndexQueryTest.java
@@ -1,146 +1,144 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.index.solr.query;
import java.util.Iterator;
import org.apache.jackrabbit.oak.Oak;
import org.apache.jackrabbit.oak.api.ContentRepository;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.plugins.index.solr.OakSolrConfiguration;
import org.apache.jackrabbit.oak.plugins.index.solr.TestUtils;
-import org.apache.jackrabbit.oak.plugins.index.solr.server.OakSolrNodeStateConfiguration;
-import org.apache.jackrabbit.oak.plugins.memory.PropertyStates;
import org.apache.jackrabbit.oak.plugins.nodetype.write.InitialContent;
import org.apache.jackrabbit.oak.query.AbstractQueryTest;
import org.apache.jackrabbit.oak.query.JsopUtil;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.solr.client.solrj.SolrServer;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
- * General query extensive testcase for {@link org.apache.jackrabbit.oak.plugins.index.solr.query.SolrQueryIndex} and {@link org.apache.jackrabbit.oak.plugins.index.solr.index.SolrIndexDiff}
+ * General query extensive testcase for {@link SolrQueryIndex} and {@link
+ * org.apache.jackrabbit.oak.plugins.index.solr.index.SolrIndexDiff}
*/
public class SolrIndexQueryTest extends AbstractQueryTest {
private SolrServer solrServer;
@After
public void tearDown() throws Exception {
solrServer.deleteByQuery("*:*");
solrServer.commit();
}
@Override
protected void createTestIndexNode() throws Exception {
Tree index = root.getTree("/");
createTestIndexNode(index, SolrQueryIndex.TYPE);
root.commit();
}
@Override
protected ContentRepository createRepository() {
NodeState mockedNodeState = createMockedConfigurationNodeState();
OakSolrConfiguration testConfiguration = TestUtils.getTestConfiguration(mockedNodeState);
try {
solrServer = TestUtils.createSolrServer();
return new Oak().with(new InitialContent())
.with(TestUtils.getTestQueryIndexProvider(solrServer, testConfiguration))
.with(TestUtils.getTestIndexHookProvider(solrServer, testConfiguration))
.createContentRepository();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private NodeState createMockedConfigurationNodeState() {
NodeState mockedNodeState = mock(NodeState.class);
when(mockedNodeState.getProperty(anyString())).thenReturn(null); // this triggers defaults
return mockedNodeState;
}
@Test
- @Ignore("failing")
public void sql2() throws Exception {
test("sql2.txt");
}
@Test
@Ignore("OAK-420")
public void sql2Measure() throws Exception {
test("sql2_measure.txt");
}
@Test
public void descendantTest() throws Exception {
JsopUtil.apply(root, "/ + \"test\": { \"a\": {}, \"b\": {} }");
root.commit();
Iterator<String> result = executeQuery(
"select * from [nt:base] where isdescendantnode('/test')",
"JCR-SQL2").iterator();
assertTrue(result.hasNext());
assertEquals("/test/a", result.next());
assertEquals("/test/b", result.next());
assertFalse(result.hasNext());
}
@Test
public void descendantTest2() throws Exception {
JsopUtil.apply(
root,
"/ + \"test\": { \"a\": { \"name\": [\"Hello\", \"World\" ] }, \"b\": { \"name\" : \"Hello\" }}");
root.commit();
Iterator<String> result = executeQuery(
"select * from [nt:base] where isdescendantnode('/test') and name='World'",
"JCR-SQL2").iterator();
assertTrue(result.hasNext());
assertEquals("/test/a", result.next());
assertFalse(result.hasNext());
}
@Test
public void ischildnodeTest() throws Exception {
JsopUtil.apply(
root,
"/ + \"parents\": { \"p0\": {\"id\": \"0\"}, \"p1\": {\"id\": \"1\"}, \"p2\": {\"id\": \"2\"}}");
JsopUtil.apply(
root,
"/ + \"children\": { \"c1\": {\"p\": \"1\"}, \"c2\": {\"p\": \"1\"}, \"c3\": {\"p\": \"2\"}, \"c4\": {\"p\": \"3\"}}");
root.commit();
Iterator<String> result = executeQuery(
"select * from [nt:base] as p inner join [nt:base] as p2 on ischildnode(p2, p) where p.[jcr:path] = '/'",
"JCR-SQL2").iterator();
assertTrue(result.hasNext());
assertEquals("/, /children", result.next());
assertEquals("/, /jcr:system", result.next());
assertEquals("/, /oak:index", result.next());
assertEquals("/, /parents", result.next());
assertFalse(result.hasNext());
}
}
| false | false | null | null |
diff --git a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeSourceViewer.java b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeSourceViewer.java
index a06dc4767..d716ef1ed 100644
--- a/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeSourceViewer.java
+++ b/bundles/org.eclipse.compare/compare/org/eclipse/compare/internal/MergeSourceViewer.java
@@ -1,1043 +1,1043 @@
/*******************************************************************************
* Copyright (c) 2000, 2013 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
* Max Weninger ([email protected]) - Bug 131895 [Edit] Undo in compare
* Max Weninger ([email protected]) - Bug 72936 [Viewers] Show line numbers in comparision
*******************************************************************************/
package org.eclipse.compare.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import org.eclipse.compare.ICompareContainer;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.operations.IOperationHistory;
import org.eclipse.core.commands.operations.IOperationHistoryListener;
import org.eclipse.core.commands.operations.IUndoContext;
import org.eclipse.core.commands.operations.OperationHistoryEvent;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.IUndoManager;
import org.eclipse.jface.text.IUndoManagerExtension;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.CommandContributionItemParameter;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.ChangeEncodingAction;
import org.eclipse.ui.texteditor.FindReplaceAction;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IElementStateListener;
import org.eclipse.ui.texteditor.ITextEditor;
/**
* Wraps a JFace SourceViewer and add some convenience methods.
*/
public class MergeSourceViewer implements ISelectionChangedListener,
ITextListener, IMenuListener, IOperationHistoryListener, IAdaptable {
public static final String UNDO_ID= "undo"; //$NON-NLS-1$
public static final String REDO_ID= "redo"; //$NON-NLS-1$
public static final String CUT_ID= "cut"; //$NON-NLS-1$
public static final String COPY_ID= "copy"; //$NON-NLS-1$
public static final String PASTE_ID= "paste"; //$NON-NLS-1$
public static final String DELETE_ID= "delete"; //$NON-NLS-1$
public static final String SELECT_ALL_ID= "selectAll"; //$NON-NLS-1$
public static final String FIND_ID= "find"; //$NON-NLS-1$
public static final String GOTO_LINE_ID= "gotoLine"; //$NON-NLS-1$
public static final String CHANGE_ENCODING_ID= "changeEncoding"; //$NON-NLS-1$
class TextOperationAction extends MergeViewerAction {
private int fOperationCode;
TextOperationAction(int operationCode, boolean mutable, boolean selection, boolean content) {
this(operationCode, null, mutable, selection, content);
}
public TextOperationAction(int operationCode, String actionDefinitionId, boolean mutable, boolean selection, boolean content) {
super(mutable, selection, content);
if (actionDefinitionId != null)
setActionDefinitionId(actionDefinitionId);
fOperationCode= operationCode;
update();
}
public void run() {
if (isEnabled())
getSourceViewer().doOperation(fOperationCode);
}
public boolean isEnabled() {
return fOperationCode != -1 && getSourceViewer().canDoOperation(fOperationCode);
}
public void update() {
- this.setEnabled(isEnabled());
+ super.setEnabled(isEnabled());
}
}
/**
* TODO: The only purpose of this class is to provide "Go to Line" action in
* TextMergeViewer. The adapter should be removed as soon as we implement
* embedded TextEditor in a similar way JDT has it done for Java compare.
*/
class TextEditorAdapter implements ITextEditor {
public void close(boolean save) {
// defining interface method
}
public void doRevertToSaved() {
// defining interface method
}
public IAction getAction(String actionId) {
// defining interface method
return null;
}
public IDocumentProvider getDocumentProvider() {
return new IDocumentProvider(){
public void aboutToChange(Object element) {
// defining interface method
}
public void addElementStateListener(
IElementStateListener listener) {
// defining interface method
}
public boolean canSaveDocument(Object element) {
// defining interface method
return false;
}
public void changed(Object element) {
// defining interface method
}
public void connect(Object element) throws CoreException {
// defining interface method
}
public void disconnect(Object element) {
// defining interface method
}
public IAnnotationModel getAnnotationModel(Object element) {
// defining interface method
return null;
}
public IDocument getDocument(Object element) {
return MergeSourceViewer.this.getSourceViewer().getDocument();
}
public long getModificationStamp(Object element) {
// defining interface method
return 0;
}
public long getSynchronizationStamp(Object element) {
// defining interface method
return 0;
}
public boolean isDeleted(Object element) {
// defining interface method
return false;
}
public boolean mustSaveDocument(Object element) {
// defining interface method
return false;
}
public void removeElementStateListener(
IElementStateListener listener) {
// defining interface method
}
public void resetDocument(Object element) throws CoreException {
// defining interface method
}
public void saveDocument(IProgressMonitor monitor,
Object element, IDocument document, boolean overwrite)
throws CoreException {
// defining interface method
}};
}
public IRegion getHighlightRange() {
// defining interface method
return null;
}
public ISelectionProvider getSelectionProvider() {
return MergeSourceViewer.this.getSourceViewer().getSelectionProvider();
}
public boolean isEditable() {
// defining interface method
return false;
}
public void removeActionActivationCode(String actionId) {
// defining interface method
}
public void resetHighlightRange() {
// defining interface method
}
public void selectAndReveal(int start, int length) {
selectAndReveal(start, length, start, length);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#selectAndReveal(int, int, int, int)
*/
private void selectAndReveal(int selectionStart, int selectionLength, int revealStart, int revealLength) {
ISelection selection = getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
StyledText widget= MergeSourceViewer.this.getSourceViewer().getTextWidget();
widget.setRedraw(false);
{
adjustHighlightRange(revealStart, revealLength);
MergeSourceViewer.this.getSourceViewer().revealRange(revealStart, revealLength);
MergeSourceViewer.this.getSourceViewer().setSelectedRange(selectionStart, selectionLength);
markInNavigationHistory();
}
widget.setRedraw(true);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#markInNavigationHistory()
*/
private void markInNavigationHistory() {
getSite().getPage().getNavigationHistory().markLocation(this);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#adjustHighlightRange(int, int)
*/
private void adjustHighlightRange(int offset, int length) {
if (MergeSourceViewer.this instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) MergeSourceViewer.this;
extension.exposeModelRange(new Region(offset, length));
} else if (!isVisible(MergeSourceViewer.this.getSourceViewer(), offset, length)) {
MergeSourceViewer.this.getSourceViewer().resetVisibleRegion();
}
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#isVisible(ISourceViewer, int, int)
*/
private /*static*/ final boolean isVisible(ITextViewer viewer, int offset, int length) {
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion overlap= extension.modelRange2WidgetRange(new Region(offset, length));
return overlap != null;
}
return viewer.overlapsWithVisibleRegion(offset, length);
}
public void setAction(String actionID, IAction action) {
// defining interface method
}
public void setActionActivationCode(String actionId,
char activationCharacter, int activationKeyCode,
int activationStateMask) {
// defining interface method
}
public void setHighlightRange(int offset, int length, boolean moveCursor) {
// defining interface method
}
public void showHighlightRangeOnly(boolean showHighlightRangeOnly) {
// defining interface method
}
public boolean showsHighlightRangeOnly() {
// defining interface method
return false;
}
public IEditorInput getEditorInput() {
if (MergeSourceViewer.this.fContainer.getWorkbenchPart() instanceof IEditorPart)
return ((IEditorPart) MergeSourceViewer.this.fContainer.getWorkbenchPart()).getEditorInput();
return null;
}
public IEditorSite getEditorSite() {
// defining interface method
return null;
}
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
// defining interface method
}
public void addPropertyListener(IPropertyListener listener) {
// defining interface method
}
public void createPartControl(Composite parent) {
// defining interface method
}
public void dispose() {
// defining interface method
}
public IWorkbenchPartSite getSite() {
return MergeSourceViewer.this.fContainer.getWorkbenchPart().getSite();
}
public String getTitle() {
// defining interface method
return null;
}
public Image getTitleImage() {
// defining interface method
return null;
}
public String getTitleToolTip() {
// defining interface method
return null;
}
public void removePropertyListener(IPropertyListener listener) {
// defining interface method
}
public void setFocus() {
// defining interface method
}
public Object getAdapter(Class adapter) {
// defining interface method
return null;
}
public void doSave(IProgressMonitor monitor) {
// defining interface method
}
public void doSaveAs() {
// defining interface method
}
public boolean isDirty() {
// defining interface method
return false;
}
public boolean isSaveAsAllowed() {
// defining interface method
return false;
}
public boolean isSaveOnCloseNeeded() {
// defining interface method
return false;
}
}
private ResourceBundle fResourceBundle;
private ICompareContainer fContainer;
private SourceViewer fSourceViewer;
private Position fRegion;
private boolean fEnabled= true;
private HashMap fActions= new HashMap();
private IDocument fRememberedDocument;
private boolean fAddSaveAction= true;
private boolean isConfigured = false;
// line number ruler support
private IPropertyChangeListener fPreferenceChangeListener;
private boolean fShowLineNumber=false;
private LineNumberRulerColumn fLineNumberColumn;
private List textActions = new ArrayList();
private CommandContributionItem fSaveContributionItem;
public MergeSourceViewer(SourceViewer sourceViewer, ResourceBundle bundle, ICompareContainer container) {
Assert.isNotNull(sourceViewer);
fSourceViewer= sourceViewer;
fResourceBundle= bundle;
fContainer = container;
MenuManager menu= new MenuManager();
menu.setRemoveAllWhenShown(true);
menu.addMenuListener(this);
StyledText te= getSourceViewer().getTextWidget();
te.setMenu(menu.createContextMenu(te));
fContainer.registerContextMenu(menu, getSourceViewer());
// for listening to editor show/hide line number preference value
fPreferenceChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
MergeSourceViewer.this.handlePropertyChangeEvent(event);
}
};
EditorsUI.getPreferenceStore().addPropertyChangeListener(fPreferenceChangeListener);
fShowLineNumber= EditorsUI.getPreferenceStore().getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER);
if(fShowLineNumber){
updateLineNumberRuler();
}
IOperationHistory history = getHistory();
if (history != null)
history.addOperationHistoryListener(this);
// don't add save when in a dialog, IWorkbenchPart is null in dialog containers
fAddSaveAction = fContainer.getWorkbenchPart() != null;
}
public void rememberDocument(IDocument doc) {
// if (doc != null && fRememberedDocument != null) {
// System.err.println("MergeSourceViewer.rememberDocument: fRememberedDocument != null: shouldn't happen"); //$NON-NLS-1$
// }
fRememberedDocument= doc;
}
public IDocument getRememberedDocument() {
return fRememberedDocument;
}
public void hideSaveAction() {
fAddSaveAction= false;
}
public void setFont(Font font) {
StyledText te= getSourceViewer().getTextWidget();
if (te != null)
te.setFont(font);
if (fLineNumberColumn != null) {
fLineNumberColumn.setFont(font);
layoutViewer();
}
}
public void setBackgroundColor(Color color) {
StyledText te= getSourceViewer().getTextWidget();
if (te != null)
te.setBackground(color);
if (fLineNumberColumn != null)
fLineNumberColumn.setBackground(color);
}
public void setForegroundColor(Color color) {
StyledText te= getSourceViewer().getTextWidget();
if (te != null)
te.setForeground(color);
}
public void setEnabled(boolean enabled) {
if (enabled != fEnabled) {
fEnabled= enabled;
StyledText c= getSourceViewer().getTextWidget();
if (c != null) {
c.setEnabled(enabled);
Display d= c.getDisplay();
c.setBackground(enabled ? d.getSystemColor(SWT.COLOR_LIST_BACKGROUND) : null);
}
}
}
public boolean getEnabled() {
return fEnabled;
}
public void setRegion(Position region) {
fRegion= region;
}
public Position getRegion() {
return fRegion;
}
public boolean isControlOkToUse() {
StyledText t= getSourceViewer().getTextWidget();
return t != null && !t.isDisposed();
}
public void setSelection(Position position) {
if (position != null)
getSourceViewer().setSelectedRange(position.getOffset(), position.getLength());
}
public void setLineBackground(Position position, Color c) {
StyledText t= getSourceViewer().getTextWidget();
if (t != null && !t.isDisposed()) {
Point region= new Point(0, 0);
getLineRange(position, region);
region.x-= getDocumentRegionOffset();
try {
t.setLineBackground(region.x, region.y, c);
} catch (IllegalArgumentException ex) {
// silently ignored
}
}
}
public void resetLineBackground() {
StyledText t= getSourceViewer().getTextWidget();
if (t != null && !t.isDisposed()) {
int lines= getLineCount();
t.setLineBackground(0, lines, null);
}
}
/*
* Returns number of lines in document region.
*/
public int getLineCount() {
IRegion region= getSourceViewer().getVisibleRegion();
int length= region.getLength();
if (length == 0)
return 0;
IDocument doc= getSourceViewer().getDocument();
int startLine= 0;
int endLine= 0;
int start= region.getOffset();
try {
startLine= doc.getLineOfOffset(start);
} catch(BadLocationException ex) {
// silently ignored
}
try {
endLine= doc.getLineOfOffset(start+length);
} catch(BadLocationException ex) {
// silently ignored
}
return endLine-startLine+1;
}
public int getViewportLines() {
StyledText te= getSourceViewer().getTextWidget();
Rectangle clArea= te.getClientArea();
if (!clArea.isEmpty())
return clArea.height / te.getLineHeight();
return 0;
}
public int getViewportHeight() {
StyledText te= getSourceViewer().getTextWidget();
Rectangle clArea= te.getClientArea();
if (!clArea.isEmpty())
return clArea.height;
return 0;
}
/*
* Returns lines
*/
public int getDocumentRegionOffset() {
int start= getSourceViewer().getVisibleRegion().getOffset();
IDocument doc= getSourceViewer().getDocument();
if (doc != null) {
try {
return doc.getLineOfOffset(start);
} catch(BadLocationException ex) {
// silently ignored
}
}
return 0;
}
public int getVerticalScrollOffset() {
StyledText st= getSourceViewer().getTextWidget();
int lineHeight= st.getLineHeight();
return getSourceViewer().getTopInset() - ((getDocumentRegionOffset()*lineHeight) + st.getTopPixel());
}
/*
* Returns the start line and the number of lines which correspond to the given position.
* Starting line number is 0 based.
*/
public Point getLineRange(Position p, Point region) {
IDocument doc= getSourceViewer().getDocument();
if (p == null || doc == null) {
region.x= 0;
region.y= 0;
return region;
}
int start= p.getOffset();
int length= p.getLength();
int startLine= 0;
try {
startLine= doc.getLineOfOffset(start);
} catch (BadLocationException e) {
// silently ignored
}
int lineCount= 0;
if (length == 0) {
// // if range length is 0 and if range starts a new line
// try {
// if (start == doc.getLineStartOffset(startLine)) {
// lines--;
// }
// } catch (BadLocationException e) {
// lines--;
// }
} else {
int endLine= 0;
try {
endLine= doc.getLineOfOffset(start + length - 1); // why -1?
} catch (BadLocationException e) {
// silently ignored
}
lineCount= endLine-startLine+1;
}
region.x= startLine;
region.y= lineCount;
return region;
}
/*
* Scroll TextPart to the given line.
*/
public void vscroll(int line) {
int srcViewSize= getLineCount();
int srcExtentSize= getViewportLines();
if (srcViewSize > srcExtentSize) {
if (line < 0)
line= 0;
int cp= getSourceViewer().getTopIndex();
if (cp != line)
getSourceViewer().setTopIndex(line + getDocumentRegionOffset());
}
}
public void addAction(String actionId, MergeViewerAction action) {
fActions.put(actionId, action);
}
public IAction getAction(String actionId) {
IAction action= (IAction) fActions.get(actionId);
if (action == null) {
action= createAction(actionId);
if (action == null)
return null;
if (action instanceof MergeViewerAction) {
MergeViewerAction mva = (MergeViewerAction) action;
if (mva.isContentDependent())
getSourceViewer().addTextListener(this);
if (mva.isSelectionDependent())
getSourceViewer().addSelectionChangedListener(this);
Utilities.initAction(action, fResourceBundle, "action." + actionId + "."); //$NON-NLS-1$ //$NON-NLS-2$
}
addAction(actionId, action);
}
if (action instanceof MergeViewerAction) {
MergeViewerAction mva = (MergeViewerAction) action;
if (mva.isEditableDependent() && !getSourceViewer().isEditable())
return null;
}
return action;
}
protected IAction createAction(String actionId) {
if (UNDO_ID.equals(actionId))
return new TextOperationAction(ITextOperationTarget.UNDO, IWorkbenchCommandConstants.EDIT_UNDO, true, false, true);
if (REDO_ID.equals(actionId))
return new TextOperationAction(ITextOperationTarget.REDO, IWorkbenchCommandConstants.EDIT_REDO, true, false, true);
if (CUT_ID.equals(actionId))
return new TextOperationAction(ITextOperationTarget.CUT, IWorkbenchCommandConstants.EDIT_CUT, true, true, false);
if (COPY_ID.equals(actionId))
return new TextOperationAction(ITextOperationTarget.COPY, IWorkbenchCommandConstants.EDIT_COPY, false, true, false);
if (PASTE_ID.equals(actionId))
return new TextOperationAction(ITextOperationTarget.PASTE, IWorkbenchCommandConstants.EDIT_PASTE, true, false, false);
if (DELETE_ID.equals(actionId))
return new TextOperationAction(ITextOperationTarget.DELETE, IWorkbenchCommandConstants.EDIT_DELETE, true, false, false);
if (SELECT_ALL_ID.equals(actionId))
return new TextOperationAction(ITextOperationTarget.SELECT_ALL, IWorkbenchCommandConstants.EDIT_SELECT_ALL, false, false, false);
return null;
}
public void selectionChanged(SelectionChangedEvent event) {
Iterator e= fActions.values().iterator();
while (e.hasNext()) {
Object next = e.next();
if (next instanceof MergeViewerAction) {
MergeViewerAction action = (MergeViewerAction) next;
if (action.isSelectionDependent())
action.update();
}
}
}
public void textChanged(TextEvent event) {
updateContentDependantActions();
}
void updateContentDependantActions() {
Iterator e= fActions.values().iterator();
while (e.hasNext()) {
Object next = e.next();
if (next instanceof MergeViewerAction) {
MergeViewerAction action = (MergeViewerAction) next;
if (action.isContentDependent())
action.update();
}
}
}
/*
* Allows the viewer to add menus and/or tools to the context menu.
*/
public void menuAboutToShow(IMenuManager menu) {
menu.add(new Separator("undo")); //$NON-NLS-1$
addMenu(menu, UNDO_ID);
addMenu(menu, REDO_ID);
menu.add(new GroupMarker("save")); //$NON-NLS-1$
if (fAddSaveAction)
addSave(menu);
menu.add(new Separator("file")); //$NON-NLS-1$
menu.add(new Separator("ccp")); //$NON-NLS-1$
addMenu(menu, CUT_ID);
addMenu(menu, COPY_ID);
addMenu(menu, PASTE_ID);
addMenu(menu, DELETE_ID);
addMenu(menu, SELECT_ALL_ID);
menu.add(new Separator("edit")); //$NON-NLS-1$
addMenu(menu, CHANGE_ENCODING_ID);
menu.add(new Separator("find")); //$NON-NLS-1$
addMenu(menu, FIND_ID);
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator("text")); //$NON-NLS-1$
for (Iterator iterator = textActions.iterator(); iterator.hasNext();) {
IAction action = (IAction) iterator.next();
menu.add(action);
}
menu.add(new Separator("rest")); //$NON-NLS-1$
// update all actions
// to get undo redo right
updateActions();
}
private void addMenu(IMenuManager menu, String actionId) {
IAction action= getAction(actionId);
if (action != null)
menu.add(action);
}
private void addSave(IMenuManager menu) {
ICommandService commandService = (ICommandService) fContainer.getWorkbenchPart().getSite().getService(ICommandService.class);
final Command command= commandService.getCommand(IWorkbenchCommandConstants.FILE_SAVE);
final IHandler handler = command.getHandler();
if (handler != null) {
if (fSaveContributionItem == null) {
fSaveContributionItem = new CommandContributionItem(
new CommandContributionItemParameter(fContainer
.getWorkbenchPart().getSite(), null, command
.getId(), CommandContributionItem.STYLE_PUSH));
}
// save is an editable dependent action, ie add only when edit
// is possible
if (handler.isHandled() && getSourceViewer().isEditable())
menu.add(fSaveContributionItem);
}
}
/**
* The viewer is no longer part of the UI, it's a wrapper only. The disposal
* doesn't take place while releasing the editor pane's children. The method
* have to be called it manually. The wrapped viewer is disposed as a
* regular viewer, while disposing the UI.
*/
public void dispose() {
getSourceViewer().removeTextListener(this);
getSourceViewer().removeSelectionChangedListener(this);
EditorsUI.getPreferenceStore().removePropertyChangeListener(fPreferenceChangeListener);
IOperationHistory history = getHistory();
if (history != null)
history.removeOperationHistoryListener(this);
}
/**
* update all actions independent of their type
*
*/
public void updateActions() {
Iterator e= fActions.values().iterator();
while (e.hasNext()) {
Object next = e.next();
if (next instanceof MergeViewerAction) {
MergeViewerAction action = (MergeViewerAction) next;
action.update();
} else if (next instanceof FindReplaceAction) {
FindReplaceAction action = (FindReplaceAction) next;
action.update();
} else if (next instanceof ChangeEncodingAction) {
ChangeEncodingAction action = (ChangeEncodingAction) next;
action.update();
}
}
}
public void configure(SourceViewerConfiguration configuration) {
if (isConfigured )
getSourceViewer().unconfigure();
isConfigured = true;
getSourceViewer().configure(configuration);
}
/**
* specific implementation to support a vertical ruler
* @param x
* @param y
* @param width
* @param height
*/
public void setBounds (int x, int y, int width, int height) {
if(getSourceViewer().getControl() instanceof Composite){
((Composite)getSourceViewer().getControl()).setBounds(x, y, width, height);
} else {
getSourceViewer().getTextWidget().setBounds(x, y, width, height);
}
}
/**
* handle show/hide line numbers from editor preferences
* @param event
*/
protected void handlePropertyChangeEvent(PropertyChangeEvent event) {
String key= event.getProperty();
if(key.equals(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER)){
boolean b= EditorsUI.getPreferenceStore().getBoolean(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER);
if (b != fShowLineNumber){
toggleLineNumberRuler();
}
} else if (key.equals(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR)) {
updateLineNumberColumnPresentation(true);
}
}
/**
* Hides or shows line number ruler column based of preference setting
*/
private void updateLineNumberRuler() {
if (!fShowLineNumber) {
if (fLineNumberColumn != null) {
getSourceViewer().removeVerticalRulerColumn(fLineNumberColumn);
}
} else {
if (fLineNumberColumn == null) {
fLineNumberColumn = new LineNumberRulerColumn();
updateLineNumberColumnPresentation(false);
}
getSourceViewer().addVerticalRulerColumn(fLineNumberColumn);
}
}
private void updateLineNumberColumnPresentation(boolean refresh) {
if (fLineNumberColumn == null)
return;
RGB rgb= getColorFromStore(EditorsUI.getPreferenceStore(), AbstractDecoratedTextEditorPreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR);
if (rgb == null)
rgb= new RGB(0, 0, 0);
ISharedTextColors sharedColors= getSharedColors();
fLineNumberColumn.setForeground(sharedColors.getColor(rgb));
if (refresh) {
fLineNumberColumn.redraw();
}
}
private void layoutViewer() {
Control parent= getSourceViewer().getControl();
if (parent instanceof Composite && !parent.isDisposed())
((Composite) parent).layout(true);
}
private ISharedTextColors getSharedColors() {
return EditorsUI.getSharedTextColors();
}
private RGB getColorFromStore(IPreferenceStore store, String key) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
}
return rgb;
}
/**
* Toggles line number ruler column.
*/
private void toggleLineNumberRuler()
{
fShowLineNumber=!fShowLineNumber;
updateLineNumberRuler();
}
public void addTextAction(IAction textEditorPropertyAction) {
textActions.add(textEditorPropertyAction);
}
public boolean removeTextAction(IAction textEditorPropertyAction) {
return textActions.remove(textEditorPropertyAction);
}
public void addAction(String id, IAction action) {
fActions.put(id, action);
}
private IOperationHistory getHistory() {
if (PlatformUI.getWorkbench() == null) {
return null;
}
return PlatformUI.getWorkbench().getOperationSupport()
.getOperationHistory();
}
public void historyNotification(OperationHistoryEvent event) {
// This method updates the enablement of all content operations
// when the undo history changes. It could be localized to UNDO and REDO.
IUndoContext context = getUndoContext();
if (context != null && event.getOperation().hasContext(context)) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
updateContentDependantActions();
}
});
}
}
private IUndoContext getUndoContext() {
IUndoManager undoManager = getSourceViewer().getUndoManager();
if (undoManager instanceof IUndoManagerExtension)
return ((IUndoManagerExtension)undoManager).getUndoContext();
return null;
}
/**
* @return the wrapped viewer
*/
public SourceViewer getSourceViewer() {
return fSourceViewer;
}
public Object getAdapter(Class adapter) {
if (adapter == ITextEditor.class) {
return new TextEditorAdapter();
}
return null;
}
}
| true | false | null | null |
diff --git a/src/biz/bokhorst/xprivacy/ActivityMain.java b/src/biz/bokhorst/xprivacy/ActivityMain.java
index d0bb8085..bf4cf0f3 100644
--- a/src/biz/bokhorst/xprivacy/ActivityMain.java
+++ b/src/biz/bokhorst/xprivacy/ActivityMain.java
@@ -1,1871 +1,1864 @@
package biz.bokhorst.xprivacy;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InterfaceAddress;
import java.security.InvalidParameterException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlSerializer;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
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.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityMain extends Activity implements OnItemSelectedListener, CompoundButton.OnCheckedChangeListener {
private int mThemeId;
private Spinner spRestriction = null;
private AppListAdapter mAppAdapter = null;
private boolean mUsed = false;
private boolean mInternet = false;
private boolean mPro = false;
private static final int ACTIVITY_LICENSE = 0;
private static final int ACTIVITY_IMPORT = 1;
private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
new PriorityThreadFactor());
private static class PriorityThreadFactor implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
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);
// Salt should be the same when exporting/importing
String salt = PrivacyManager.getSetting(null, this, PrivacyManager.cSettingSalt, null, false);
if (salt == null) {
salt = Build.SERIAL;
if (salt == null)
salt = "";
PrivacyManager.setSetting(null, this, PrivacyManager.cSettingSalt, salt);
}
// Set theme
String themeName = PrivacyManager.getSetting(null, this, PrivacyManager.cSettingTheme, "", false);
mThemeId = (themeName.equals("Dark") ? R.style.CustomTheme : R.style.CustomTheme_Light);
setTheme(mThemeId);
// Set layout
setContentView(R.layout.mainlist);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
// Get localized restriction name
List<String> listRestriction = PrivacyManager.getRestrictions(true);
List<String> listLocalizedRestriction = new ArrayList<String>();
for (String restrictionName : listRestriction)
listLocalizedRestriction.add(PrivacyManager.getLocalizedName(this, restrictionName));
listLocalizedRestriction.add(0, getString(R.string.menu_all));
// Build spinner adapter
SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item);
spAdapter.addAll(listLocalizedRestriction);
// 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 title = (position == 0 ? "XPrivacy" : PrivacyManager.getRestrictions(true).get(position - 1));
String url = String.format("http://wiki.faircode.eu/index.php?title=%s", title);
Intent infoIntent = new Intent(Intent.ACTION_VIEW);
infoIntent.setData(Uri.parse(url));
startActivity(infoIntent);
}
}
});
// Setup spinner
spRestriction = (Spinner) findViewById(R.id.spRestriction);
spRestriction.setAdapter(spAdapter);
spRestriction.setOnItemSelectedListener(this);
// Handle help
ImageView ivHelp = (ImageView) findViewById(R.id.ivHelp);
ivHelp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog dialog = new Dialog(ActivityMain.this);
dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dialog.setTitle(getString(R.string.help_application));
dialog.setContentView(R.layout.help);
dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, getThemed(R.attr.icon_launcher));
dialog.setCancelable(true);
dialog.show();
}
});
ImageView imgEdit = (ImageView) findViewById(R.id.imgEdit);
imgEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast toast = Toast.makeText(ActivityMain.this, getString(R.string.msg_edit), Toast.LENGTH_LONG);
toast.show();
}
});
// Setup used filter
final ImageView imgUsed = (ImageView) findViewById(R.id.imgUsed);
if (savedInstanceState != null && savedInstanceState.containsKey("Used")) {
mUsed = savedInstanceState.getBoolean("Used");
imgUsed.setImageDrawable(getResources().getDrawable(
getThemed(mUsed ? R.attr.icon_used : R.attr.icon_used_grayed)));
}
imgUsed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mUsed = !mUsed;
imgUsed.setImageDrawable(getResources().getDrawable(
getThemed(mUsed ? R.attr.icon_used : R.attr.icon_used_grayed)));
applyFilter();
}
});
// Setup internet filter
final ImageView imgInternet = (ImageView) findViewById(R.id.imgInternet);
if (savedInstanceState != null && savedInstanceState.containsKey("Internet")) {
mInternet = savedInstanceState.getBoolean("Internet");
imgInternet.setImageDrawable(getResources().getDrawable(
getThemed(mInternet ? R.attr.icon_internet : R.attr.icon_internet_grayed)));
}
imgInternet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mInternet = !mInternet;
imgInternet.setImageDrawable(getResources().getDrawable(
getThemed(mInternet ? R.attr.icon_internet : R.attr.icon_internet_grayed)));
applyFilter();
}
});
// 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("");
}
});
// Setup restriction filter
CheckBox cbFilter = (CheckBox) findViewById(R.id.cbFilter);
cbFilter.setOnCheckedChangeListener(this);
// Start task to get app list
AppListTask appListTask = new AppListTask();
appListTask.executeOnExecutor(mExecutor, (Object) null);
// Check environment
checkRequirements();
// 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);
// First run
if (PrivacyManager.getSettingBool(null, this, PrivacyManager.cSettingFirstRun, true, false)) {
optionAbout();
PrivacyManager.setSetting(null, this, PrivacyManager.cSettingFirstRun, Boolean.FALSE.toString());
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("Used", mUsed);
outState.putBoolean("Internet", mInternet);
super.onSaveInstanceState(outState);
}
@Override
protected void onResume() {
super.onResume();
if (mAppAdapter != null)
mAppAdapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mPackageChangeReceiver != null)
unregisterReceiver(mPackageChangeReceiver);
}
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;
private void checkLicense() {
if (Util.hasProLicense(this) == null) {
if (Util.isProInstalled(this))
try {
int uid = getPackageManager().getApplicationInfo("biz.bokhorst.xprivacy.pro", 0).uid;
PrivacyManager.deleteRestrictions(this, uid);
Util.log(null, Log.INFO, "Licensing: check");
startActivityForResult(new Intent("biz.bokhorst.xprivacy.pro.CHECK"), ACTIVITY_LICENSE);
} catch (Throwable ex) {
Util.bug(null, ex);
}
} else {
Toast toast = Toast.makeText(this, getString(R.string.menu_pro), Toast.LENGTH_LONG);
toast.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTIVITY_LICENSE) {
// Result for license check
if (data != null) {
int code = data.getIntExtra("Code", -1);
int reason = data.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.INFO, "Licensing: code=" + code + " reason=" + sReason);
if (code > 0) {
mPro = true;
invalidateOptionsMenu();
Toast toast = Toast.makeText(this, getString(R.string.menu_pro), Toast.LENGTH_LONG);
toast.show();
} else if (reason == RETRY) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
checkLicense();
}
}, 60 * 1000);
}
}
} else if (requestCode == ACTIVITY_IMPORT) {
// Result for import file choice
if (data != null) {
String fileName = data.getData().getPath();
ImportTask importTask = new ImportTask();
importTask.executeOnExecutor(mExecutor, new File(fileName));
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean pro = (mPro || Util.hasProLicense(this) != null);
boolean mounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
menu.findItem(R.id.menu_export).setEnabled(pro && mounted);
menu.findItem(R.id.menu_import).setEnabled(pro && mounted);
menu.findItem(R.id.menu_pro).setVisible(!pro);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
try {
switch (item.getItemId()) {
case R.id.menu_all:
optionAll();
return true;
case R.id.menu_usage:
optionUsage();
return true;
case R.id.menu_settings:
optionSettings();
return true;
case R.id.menu_template:
optionTemplate();
return true;
case R.id.menu_update:
optionCheckUpdate();
return true;
case R.id.menu_report:
optionReportIssue();
return true;
case R.id.menu_export:
optionExport();
return true;
case R.id.menu_import:
optionImport();
return true;
case R.id.menu_theme:
optionSwitchTheme();
return true;
case R.id.menu_pro:
optionPro();
return true;
case R.id.menu_about:
optionAbout();
return true;
default:
return super.onOptionsItemSelected(item);
}
} catch (Throwable ex) {
Util.bug(null, ex);
return true;
}
}
// Spinner
@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) {
String restrictionName = (pos == 0 ? null : PrivacyManager.getRestrictions(true).get(pos - 1));
mAppAdapter.setRestrictionName(restrictionName);
applyFilter();
}
}
private class SpinnerAdapter extends ArrayAdapter<String> {
public SpinnerAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
row.setBackgroundColor(getBackgroundColor(position));
return row;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View row = super.getDropDownView(position, convertView, parent);
row.setBackgroundColor(getBackgroundColor(position));
return row;
}
private int getBackgroundColor(int position) {
String restrictionName = (position == 0 ? null : PrivacyManager.getRestrictions(true).get(position - 1));
if (PrivacyManager.isDangerousRestriction(restrictionName))
return getResources().getColor(getThemed(R.attr.color_dangerous));
else
return Color.TRANSPARENT;
}
}
// Filtering
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox cbFilter = (CheckBox) findViewById(R.id.cbFilter);
if (buttonView == cbFilter)
applyFilter();
}
private void applyFilter() {
if (mAppAdapter != null) {
EditText etFilter = (EditText) findViewById(R.id.etFilter);
CheckBox cbFilter = (CheckBox) findViewById(R.id.cbFilter);
String filter = String.format("%b\n%b\n%s\n%b", mUsed, mInternet, etFilter.getText().toString(),
cbFilter.isChecked());
mAppAdapter.getFilter().filter(filter);
}
}
private void checkRequirements() {
// Check Android version
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.ICE_CREAM_SANDWICH
&& Build.VERSION.SDK_INT != Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
&& Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN
&& Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN_MR1
&& Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN_MR2) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(getString(R.string.app_name));
alertDialogBuilder.setMessage(getString(R.string.app_wrongandroid));
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) {
Intent xposedIntent = new Intent(Intent.ACTION_VIEW);
xposedIntent.setData(Uri.parse("https://github.com/M66B/XPrivacy#installation"));
startActivity(xposedIntent);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
// Check Xposed version
int xVersion = Util.getXposedVersion();
if (xVersion < PrivacyManager.cXposedMinVersion) {
String msg = String.format(getString(R.string.app_notxposed), PrivacyManager.cXposedMinVersion);
Util.log(null, Log.WARN, msg);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(getString(R.string.app_name));
alertDialogBuilder.setMessage(msg);
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) {
Intent xposedIntent = new Intent(Intent.ACTION_VIEW);
xposedIntent.setData(Uri.parse("http://forum.xda-developers.com/showthread.php?t=1574401"));
startActivity(xposedIntent);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
// Check if XPrivacy is enabled
if (!Util.isXposedEnabled()) {
String msg = getString(R.string.app_notenabled);
Util.log(null, Log.WARN, msg);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(getString(R.string.app_name));
alertDialogBuilder.setMessage(msg);
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) {
Intent xInstallerIntent = getPackageManager().getLaunchIntentForPackage(
"de.robv.android.xposed.installer");
if (xInstallerIntent != null) {
xInstallerIntent.putExtra("opentab", 1);
startActivity(xInstallerIntent);
}
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
// Check activity manager
if (!checkField(getSystemService(Context.ACTIVITY_SERVICE), "mContext", Context.class))
reportClass(getSystemService(Context.ACTIVITY_SERVICE).getClass());
// Check activity thread
try {
Class<?> clazz = Class.forName("android.app.ActivityThread");
try {
clazz.getDeclaredMethod("unscheduleGcIdler");
} catch (NoSuchMethodException ex) {
reportClass(clazz);
}
} catch (Throwable ex) {
sendSupportInfo(ex.toString());
}
// Check activity thread receiver data
try {
Class<?> clazz = Class.forName("android.app.ActivityThread$ReceiverData");
if (!checkField(clazz, "intent"))
reportClass(clazz);
} catch (Throwable ex) {
try {
reportClass(Class.forName("android.app.ActivityThread"));
} catch (Throwable exex) {
sendSupportInfo(exex.toString());
}
}
// Check clipboard manager
if (!checkField(getSystemService(Context.CLIPBOARD_SERVICE), "mContext", Context.class))
reportClass(getSystemService(Context.CLIPBOARD_SERVICE).getClass());
// Check content resolver
if (!checkField(getContentResolver(), "mContext", Context.class))
reportClass(getContentResolver().getClass());
// Check interface address
if (!checkField(InterfaceAddress.class, "address") || !checkField(InterfaceAddress.class, "broadcastAddress")
|| PrivacyManager.getDefacedProp("InetAddress") == null)
reportClass(InterfaceAddress.class);
// Check package manager
if (!checkField(getPackageManager(), "mContext", Context.class))
reportClass(getPackageManager().getClass());
// Check package manager service
try {
Class<?> clazz = Class.forName("com.android.server.pm.PackageManagerService");
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
clazz.getDeclaredMethod("getPackageUid", String.class, int.class);
else
clazz.getDeclaredMethod("getPackageUid", String.class);
} catch (NoSuchMethodException ex) {
reportClass(clazz);
}
} catch (Throwable ex) {
sendSupportInfo(ex.toString());
}
// Check runtime
try {
Runtime.class.getDeclaredMethod("load", String.class, ClassLoader.class);
Runtime.class.getDeclaredMethod("loadLibrary", String.class, ClassLoader.class);
} catch (NoSuchMethodException ex) {
reportClass(Runtime.class);
}
// Check telephony manager
if (!checkField(getSystemService(Context.TELEPHONY_SERVICE), "sContext", Context.class)
&& !checkField(getSystemService(Context.TELEPHONY_SERVICE), "mContext", Context.class)
&& !checkField(getSystemService(Context.TELEPHONY_SERVICE), "sContextDuos", Context.class))
reportClass(getSystemService(Context.TELEPHONY_SERVICE).getClass());
// Check wifi info
if (!checkField(WifiInfo.class, "mSupplicantState") || !checkField(WifiInfo.class, "mBSSID")
|| !checkField(WifiInfo.class, "mIpAddress") || !checkField(WifiInfo.class, "mMacAddress")
|| !(checkField(WifiInfo.class, "mSSID") || checkField(WifiInfo.class, "mWifiSsid")))
reportClass(WifiInfo.class);
// Check mWifiSsid.octets
if (checkField(WifiInfo.class, "mWifiSsid"))
try {
Class<?> clazz = Class.forName("android.net.wifi.WifiSsid");
if (!checkField(clazz, "octets"))
reportClass(clazz);
} catch (Throwable ex) {
sendSupportInfo(ex.toString());
}
}
private boolean checkField(Object obj, String fieldName, Class<?> expectedClass) {
try {
// Find field
Field field = null;
Class<?> superClass = (obj == null ? null : obj.getClass());
while (superClass != null)
try {
field = superClass.getDeclaredField(fieldName);
field.setAccessible(true);
break;
} catch (Throwable ex) {
superClass = superClass.getSuperclass();
}
// Check field
if (field != null) {
Object value = field.get(obj);
if (value != null && expectedClass.isAssignableFrom(value.getClass()))
return true;
}
} catch (Throwable ex) {
}
return false;
}
private boolean checkField(Class<?> clazz, String fieldName) {
try {
clazz.getDeclaredField(fieldName);
return true;
} catch (Throwable ex) {
return false;
}
}
private void optionAll() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(getString(R.string.app_name));
alertDialogBuilder.setMessage(getString(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) {
if (mAppAdapter != null) {
// Check if some restricted
boolean someRestricted = false;
for (int pos = 0; pos < mAppAdapter.getCount(); pos++) {
ApplicationInfoEx xAppInfo = mAppAdapter.getItem(pos);
if (mAppAdapter.getRestrictionName() == null) {
for (boolean restricted : PrivacyManager.getRestricted(getApplicationContext(),
xAppInfo.getUid(), false))
if (restricted) {
someRestricted = true;
break;
}
} else if (PrivacyManager.getRestricted(null, ActivityMain.this, xAppInfo.getUid(),
mAppAdapter.getRestrictionName(), null, false, false))
someRestricted = true;
if (someRestricted)
break;
}
// Invert selection
for (int pos = 0; pos < mAppAdapter.getCount(); pos++) {
ApplicationInfoEx xAppInfo = mAppAdapter.getItem(pos);
if (mAppAdapter.getRestrictionName() == null) {
for (String restrictionName : PrivacyManager.getRestrictions(false))
PrivacyManager.setRestricted(null, ActivityMain.this, xAppInfo.getUid(),
restrictionName, null, !someRestricted);
} else
PrivacyManager.setRestricted(null, ActivityMain.this, xAppInfo.getUid(),
mAppAdapter.getRestrictionName(), null, !someRestricted);
}
// Refresh
mAppAdapter.notifyDataSetChanged();
}
}
});
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 optionUsage() {
Intent intent = new Intent(this, ActivityUsage.class);
startActivity(intent);
}
private void optionSettings() {
// Build dialog
final Dialog dlgSettings = new Dialog(this);
dlgSettings.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dlgSettings.setTitle(getString(R.string.app_name));
dlgSettings.setContentView(R.layout.settings);
dlgSettings.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, getThemed(R.attr.icon_launcher));
// Reference controls
final EditText etSerial = (EditText) dlgSettings.findViewById(R.id.etSerial);
final EditText etLat = (EditText) dlgSettings.findViewById(R.id.etLat);
final EditText etLon = (EditText) dlgSettings.findViewById(R.id.etLon);
final EditText etSearch = (EditText) dlgSettings.findViewById(R.id.etSearch);
Button btnSearch = (Button) dlgSettings.findViewById(R.id.btnSearch);
final EditText etMac = (EditText) dlgSettings.findViewById(R.id.etMac);
final EditText etImei = (EditText) dlgSettings.findViewById(R.id.etImei);
final EditText etPhone = (EditText) dlgSettings.findViewById(R.id.etPhone);
final EditText etId = (EditText) dlgSettings.findViewById(R.id.etId);
final EditText etGsfId = (EditText) dlgSettings.findViewById(R.id.etGsfId);
final EditText etMcc = (EditText) dlgSettings.findViewById(R.id.etMcc);
final EditText etMnc = (EditText) dlgSettings.findViewById(R.id.etMnc);
final EditText etCountry = (EditText) dlgSettings.findViewById(R.id.etCountry);
final EditText etIccId = (EditText) dlgSettings.findViewById(R.id.etIccId);
final EditText etSubscriber = (EditText) dlgSettings.findViewById(R.id.etSubscriber);
final CheckBox cbFPermission = (CheckBox) dlgSettings.findViewById(R.id.cbFPermission);
final CheckBox cbFSystem = (CheckBox) dlgSettings.findViewById(R.id.cbFSystem);
Button btnOk = (Button) dlgSettings.findViewById(R.id.btnOk);
// Set current values
final boolean fPermission = PrivacyManager.getSettingBool(null, ActivityMain.this,
PrivacyManager.cSettingFPermission, true, false);
final boolean fSystem = PrivacyManager.getSettingBool(null, ActivityMain.this, PrivacyManager.cSettingFSystem,
true, false);
etSerial.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingSerial, "", false));
etLat.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingLatitude, "", false));
etLon.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingLongitude, "", false));
etMac.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingMac, "", false));
etImei.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingImei, "", false));
etPhone.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingPhone, "", false));
etId.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingId, "", false));
etGsfId.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingGsfId, "", false));
etMcc.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingMcc, "", false));
etMnc.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingMnc, "", false));
etCountry
.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingCountry, "", false));
etIccId.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingIccId, "", false));
etSubscriber.setText(PrivacyManager.getSetting(null, ActivityMain.this, PrivacyManager.cSettingSubscriber, "",
false));
cbFPermission.setChecked(fPermission);
cbFSystem.setChecked(fSystem);
// Handle search
etSearch.setEnabled(Geocoder.isPresent());
btnSearch.setEnabled(Geocoder.isPresent());
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
etLat.setText("");
etLon.setText("");
String search = etSearch.getText().toString();
final List<Address> listAddress = new Geocoder(ActivityMain.this).getFromLocationName(search, 1);
if (listAddress.size() > 0) {
Address address = listAddress.get(0);
// Get coordinates
if (address.hasLatitude())
etLat.setText(Double.toString(address.getLatitude()));
if (address.hasLongitude())
etLon.setText(Double.toString(address.getLongitude()));
// Get address
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
if (i != 0)
sb.append(", ");
sb.append(address.getAddressLine(i));
}
etSearch.setText(sb.toString());
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
});
// Wait for OK
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Serial#
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingSerial, etSerial.getText()
.toString());
// Set location
try {
float lat = Float.parseFloat(etLat.getText().toString().replace(',', '.'));
float lon = Float.parseFloat(etLon.getText().toString().replace(',', '.'));
if (lat < -90 || lat > 90 || lon < -180 || lon > 180)
throw new InvalidParameterException();
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingLatitude,
Float.toString(lat));
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingLongitude,
Float.toString(lon));
} catch (Throwable ex) {
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingLatitude, "");
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingLongitude, "");
}
// Other settings
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingMac, etMac.getText()
.toString());
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingImei, etImei.getText()
.toString());
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingPhone, etPhone.getText()
.toString());
PrivacyManager
.setSetting(null, ActivityMain.this, PrivacyManager.cSettingId, etId.getText().toString());
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingGsfId, etGsfId.getText()
.toString());
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingMcc, etMcc.getText()
.toString());
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingMnc, etMnc.getText()
.toString());
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingCountry, etCountry.getText()
.toString());
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingIccId, etIccId.getText()
.toString());
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingSubscriber, etSubscriber
.getText().toString());
// Set filter by permission
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingFPermission,
Boolean.toString(cbFPermission.isChecked()));
// Set filter by system
PrivacyManager.setSetting(null, ActivityMain.this, PrivacyManager.cSettingFSystem,
Boolean.toString(cbFSystem.isChecked()));
// Refresh if needed
if (fPermission != cbFPermission.isChecked() || fSystem != cbFSystem.isChecked()) {
AppListTask appListTask = new AppListTask();
appListTask.executeOnExecutor(mExecutor, (Object) null);
}
// Done
dlgSettings.dismiss();
}
});
dlgSettings.setCancelable(true);
dlgSettings.show();
}
private void optionTemplate() {
// Get restriction categories
final List<String> listRestriction = PrivacyManager.getRestrictions(false);
CharSequence[] options = new CharSequence[listRestriction.size()];
boolean[] selection = new boolean[listRestriction.size()];
for (int i = 0; i < listRestriction.size(); i++) {
options[i] = PrivacyManager.getLocalizedName(this, listRestriction.get(i));
selection[i] = PrivacyManager.getSettingBool(null, this,
String.format("Template.%s", listRestriction.get(i)), true, false);
}
// Build dialog
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(getString(R.string.menu_template));
alertDialogBuilder.setIcon(getThemed(R.attr.icon_launcher));
alertDialogBuilder.setMultiChoiceItems(options, selection, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
PrivacyManager.setSetting(null, ActivityMain.this,
String.format("Template.%s", listRestriction.get(whichButton)), Boolean.toString(isChecked));
}
});
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 optionCheckUpdate() {
new UpdateTask().executeOnExecutor(mExecutor, "http://goo.im/json2&path=/devs/M66B/xprivacy");
}
private void optionReportIssue() {
// Report issue
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/M66B/XPrivacy/issues"));
startActivity(browserIntent);
}
private void optionPro() {
// Redirect to pro page
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.faircode.eu/xprivacy/"));
startActivity(browserIntent);
}
private void optionExport() {
boolean multiple = Util.isIntentAvailable(ActivityMain.this, Intent.ACTION_GET_CONTENT);
ExportTask exportTask = new ExportTask();
exportTask.executeOnExecutor(mExecutor, getExportFile(multiple));
}
private void optionImport() {
if (Util.isIntentAvailable(ActivityMain.this, Intent.ACTION_GET_CONTENT)) {
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/.xprivacy/");
chooseFile.setDataAndType(uri, "text/xml");
Intent intent = Intent.createChooser(chooseFile, getString(R.string.app_name));
startActivityForResult(intent, ACTIVITY_IMPORT);
} else {
ImportTask importTask = new ImportTask();
importTask.executeOnExecutor(mExecutor, getExportFile(false));
}
}
private void optionSwitchTheme() {
String themeName = PrivacyManager.getSetting(null, this, PrivacyManager.cSettingTheme, "", false);
themeName = (themeName.equals("Dark") ? "Light" : "Dark");
PrivacyManager.setSetting(null, this, PrivacyManager.cSettingTheme, themeName);
this.recreate();
}
private void optionAbout() {
// About
Dialog dlgAbout = new Dialog(this);
dlgAbout.requestWindowFeature(Window.FEATURE_LEFT_ICON);
dlgAbout.setTitle(getString(R.string.app_name));
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.getXposedVersion();
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.setVisibility(View.GONE);
else
tvLicensed.setText(String.format(getString(R.string.msg_licensed), licensed));
dlgAbout.setCancelable(true);
dlgAbout.show();
}
private File getExportFile(boolean multiple) {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator
+ ".xprivacy");
folder.mkdir();
String fileName;
if (multiple) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmm", Locale.ROOT);
fileName = String.format("XPrivacy_%s.xml", format.format(new Date()));
} else
fileName = "XPrivacy.xml";
return new File(folder + File.separator + fileName);
}
private String fetchUpdateJson(String... uri) {
try {
// Request downloads
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
// Succeeded
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
return out.toString("ISO-8859-1");
} else {
// Failed
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Throwable ex) {
Util.bug(null, ex);
return ex.toString();
}
}
private void processUpdateJson(String json) {
try {
// Parse result
String version = null;
String url = null;
if (json != null)
if (json.startsWith("{")) {
long newest = 0;
String prefix = "XPrivacy_";
JSONObject jRoot = new JSONObject(json);
JSONArray jArray = jRoot.getJSONArray("list");
for (int i = 0; jArray != null && i < jArray.length(); i++) {
// File
JSONObject jEntry = jArray.getJSONObject(i);
String filename = jEntry.getString("filename");
if (filename.startsWith(prefix)) {
// Check if newer
long modified = jEntry.getLong("modified");
if (modified > newest) {
newest = modified;
version = filename.substring(prefix.length()).replace(".apk", "");
url = "http://goo.im" + jEntry.getString("path");
}
}
}
} else {
Toast toast = Toast.makeText(ActivityMain.this, json, Toast.LENGTH_LONG);
toast.show();
}
if (url == null || version == null) {
// Assume no update
String msg = getString(R.string.msg_noupdate);
Toast toast = Toast.makeText(ActivityMain.this, msg, Toast.LENGTH_LONG);
toast.show();
} else {
// Compare versions
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
Version ourVersion = new Version(pInfo.versionName);
Version latestVersion = new Version(version);
if (ourVersion.compareTo(latestVersion) < 0) {
// Update available
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
} else {
// No update available
String msg = getString(R.string.msg_noupdate);
Toast toast = Toast.makeText(ActivityMain.this, msg, Toast.LENGTH_LONG);
toast.show();
}
}
} catch (Throwable ex) {
Toast toast = Toast.makeText(ActivityMain.this, ex.toString(), Toast.LENGTH_LONG);
toast.show();
Util.bug(null, ex);
}
}
private void reportClass(final Class<?> clazz) {
String msg = String.format("Incompatible %s", clazz.getName());
Util.log(null, Log.WARN, msg);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(getString(R.string.app_name));
alertDialogBuilder.setMessage(msg);
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) {
sendClassInfo(clazz);
}
});
alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private void sendClassInfo(Class<?> clazz) {
StringBuilder sb = new StringBuilder();
sb.append(clazz.getName());
sb.append("\r\n");
sb.append("\r\n");
for (Constructor<?> constructor : clazz.getConstructors()) {
sb.append(constructor.toString());
sb.append("\r\n");
}
sb.append("\r\n");
for (Method method : clazz.getDeclaredMethods()) {
sb.append(method.toString());
sb.append("\r\n");
}
sb.append("\r\n");
for (Field field : clazz.getDeclaredFields()) {
sb.append(field.toString());
sb.append("\r\n");
}
sb.append("\r\n");
sendSupportInfo(sb.toString());
}
private void sendSupportInfo(String text) {
String xversion = null;
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
xversion = pInfo.versionName;
} catch (Throwable ex) {
}
StringBuilder sb = new StringBuilder(text);
sb.insert(0, String.format("Android SDK %d\r\n", Build.VERSION.SDK_INT));
sb.insert(0, String.format("XPrivacy %s\r\n", xversion));
sb.append("\r\n");
Intent sendEmail = new Intent(Intent.ACTION_SEND);
sendEmail.setType("message/rfc822");
sendEmail.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" });
sendEmail.putExtra(Intent.EXTRA_SUBJECT, "XPrivacy support info");
sendEmail.putExtra(Intent.EXTRA_TEXT, sb.toString());
try {
startActivity(sendEmail);
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private class UpdateTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... uri) {
return fetchUpdateJson(uri);
}
@Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
if (json != null)
processUpdateJson(json);
}
}
private class ExportTask extends AsyncTask<File, String, String> {
private File mFile;
private final static int NOTIFY_ID = 1;
@Override
protected String doInBackground(File... params) {
mFile = params[0];
try {
// Serialize
Util.log(null, Log.INFO, "Exporting " + mFile);
FileOutputStream fos = new FileOutputStream(mFile);
try {
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(fos, "UTF-8");
serializer.startDocument(null, Boolean.valueOf(true));
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "XPrivacy");
// Process settings
publishProgress(getString(R.string.menu_settings));
Util.log(null, Log.INFO, "Exporting settings");
Map<String, String> mapSetting = PrivacyManager.getSettings(ActivityMain.this);
for (String setting : mapSetting.keySet())
if (!setting.startsWith("Account.") && !setting.startsWith("Contact.")
&& !setting.startsWith("RawContact.")) {
// Serialize setting
String value = mapSetting.get(setting);
serializer.startTag(null, "Setting");
serializer.attribute(null, "Name", setting);
serializer.attribute(null, "Value", value);
serializer.endTag(null, "Setting");
}
// Process restrictions
List<PrivacyManager.RestrictionDesc> listRestriction = PrivacyManager
.getRestricted(ActivityMain.this);
Map<String, List<PrivacyManager.RestrictionDesc>> mapRestriction = new HashMap<String, List<PrivacyManager.RestrictionDesc>>();
for (PrivacyManager.RestrictionDesc restriction : listRestriction) {
String[] packages = getPackageManager().getPackagesForUid(restriction.uid);
if (packages == null)
Util.log(null, Log.WARN, "No packages for uid=" + restriction.uid);
else
for (String packageName : packages) {
if (!mapRestriction.containsKey(packageName))
mapRestriction.put(packageName, new ArrayList<PrivacyManager.RestrictionDesc>());
mapRestriction.get(packageName).add(restriction);
}
}
// Process result
for (String packageName : mapRestriction.keySet()) {
publishProgress(packageName);
Util.log(null, Log.INFO, "Exporting " + packageName);
for (PrivacyManager.RestrictionDesc restrictionDesc : mapRestriction.get(packageName)) {
serializer.startTag(null, "Package");
serializer.attribute(null, "Name", packageName);
serializer.attribute(null, "Restriction", restrictionDesc.restrictionName);
if (restrictionDesc.methodName != null)
serializer.attribute(null, "Method", restrictionDesc.methodName);
serializer.attribute(null, "Restricted", Boolean.toString(restrictionDesc.restricted));
serializer.endTag(null, "Package");
}
}
// End serialization
serializer.endTag(null, "XPrivacy");
serializer.endDocument();
serializer.flush();
} finally {
fos.close();
}
// Send share intent
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/xml");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + mFile));
startActivity(Intent.createChooser(intent, getString(R.string.app_name)));
// Display message
Util.log(null, Log.INFO, "Exporting finished");
return getString(R.string.msg_done);
} catch (Throwable ex) {
Util.bug(null, ex);
return ex.toString();
}
}
@Override
protected void onProgressUpdate(String... values) {
notify(values[0], true);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
notify(result, false);
super.onPostExecute(result);
}
private void notify(String text, boolean ongoing) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ActivityMain.this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
notificationBuilder.setContentTitle(getString(R.string.menu_export));
notificationBuilder.setContentText(text);
notificationBuilder.setWhen(System.currentTimeMillis());
if (ongoing)
notificationBuilder.setOngoing(true);
else {
// Build result intent
Intent resultIntent = new Intent(ActivityMain.this, ActivityMain.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Build pending intent
PendingIntent pendingIntent = PendingIntent.getActivity(ActivityMain.this, NOTIFY_ID, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
}
Notification notification = notificationBuilder.build();
NotificationManager notificationManager = (NotificationManager) ActivityMain.this
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFY_ID, notification);
}
}
private class ImportTask extends AsyncTask<File, String, String> {
private File mFile;
private final static int NOTIFY_ID = 2;
@Override
protected String doInBackground(File... params) {
mFile = params[0];
try {
// Parse XML
Util.log(null, Log.INFO, "Importing " + mFile);
FileInputStream fis = null;
Map<String, Map<String, List<String>>> mapPackage;
try {
fis = new FileInputStream(mFile);
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
ImportHandler importHandler = new ImportHandler();
xmlReader.setContentHandler(importHandler);
xmlReader.parse(new InputSource(fis));
mapPackage = importHandler.getPackageMap();
} finally {
if (fis != null)
fis.close();
}
// Process result
for (String packageName : mapPackage.keySet()) {
try {
publishProgress(packageName);
Util.log(null, Log.INFO, "Importing " + packageName);
// Get uid
int uid = getPackageManager().getPackageInfo(packageName, 0).applicationInfo.uid;
// Reset existing restrictions
PrivacyManager.deleteRestrictions(ActivityMain.this, uid);
// Set imported restrictions
for (String restrictionName : mapPackage.get(packageName).keySet()) {
PrivacyManager.setRestricted(null, ActivityMain.this, uid, restrictionName, null, true);
for (String methodName : mapPackage.get(packageName).get(restrictionName))
PrivacyManager.setRestricted(null, ActivityMain.this, uid, restrictionName, methodName,
false);
}
} catch (NameNotFoundException ex) {
Util.log(null, Log.WARN, "Not found package=" + packageName);
}
}
// Display message
Util.log(null, Log.INFO, "Importing finished");
return getString(R.string.msg_done);
} catch (Throwable ex) {
Util.bug(null, ex);
return ex.toString();
}
}
@Override
protected void onProgressUpdate(String... values) {
notify(values[0], true);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
notify(result, false);
ActivityMain.this.recreate();
super.onPostExecute(result);
}
private void notify(String text, boolean ongoing) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ActivityMain.this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
notificationBuilder.setContentTitle(getString(R.string.menu_import));
notificationBuilder.setContentText(text);
notificationBuilder.setWhen(System.currentTimeMillis());
if (ongoing)
notificationBuilder.setOngoing(true);
else {
// Build result intent
Intent resultIntent = new Intent(ActivityMain.this, ActivityMain.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Build pending intent
PendingIntent pendingIntent = PendingIntent.getActivity(ActivityMain.this, NOTIFY_ID, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
}
Notification notification = notificationBuilder.build();
NotificationManager notificationManager = (NotificationManager) ActivityMain.this
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFY_ID, notification);
}
}
private class ImportHandler extends DefaultHandler {
private Map<String, Map<String, List<String>>> mMapPackage = new HashMap<String, Map<String, List<String>>>();
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("Setting")) {
// Setting
String name = attributes.getValue("Name");
String value = attributes.getValue("Value");
PrivacyManager.setSetting(null, ActivityMain.this, name, value);
} else if (qName.equals("Package")) {
// Restriction
String packageName = attributes.getValue("Name");
String restrictionName = attributes.getValue("Restriction");
String methodName = attributes.getValue("Method");
// Map package restriction
if (!mMapPackage.containsKey(packageName))
mMapPackage.put(packageName, new HashMap<String, List<String>>());
if (!mMapPackage.get(packageName).containsKey(restrictionName))
mMapPackage.get(packageName).put(restrictionName, new ArrayList<String>());
if (methodName != null)
mMapPackage.get(packageName).get(restrictionName).add(methodName);
}
}
public Map<String, Map<String, List<String>>> getPackageMap() {
return mMapPackage;
}
}
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();
// Reset spinner
spRestriction.setEnabled(false);
// Reset filters
final ImageView imgUsed = (ImageView) findViewById(R.id.imgUsed);
imgUsed.setEnabled(false);
final ImageView imgInternet = (ImageView) findViewById(R.id.imgInternet);
imgInternet.setEnabled(false);
EditText etFilter = (EditText) findViewById(R.id.etFilter);
etFilter.setEnabled(false);
CheckBox cbFilter = (CheckBox) findViewById(R.id.cbFilter);
cbFilter.setEnabled(false);
// Show progress dialog
ListView lvApp = (ListView) findViewById(R.id.lvApp);
mProgressDialog = new ProgressDialog(lvApp.getContext());
mProgressDialog.setMessage(getString(R.string.msg_loading));
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
@Override
protected void onPostExecute(List<ApplicationInfoEx> listApp) {
super.onPostExecute(listApp);
// 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
try {
mProgressDialog.dismiss();
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Enable filters
final ImageView imgUsed = (ImageView) findViewById(R.id.imgUsed);
imgUsed.setEnabled(true);
final ImageView imgInternet = (ImageView) findViewById(R.id.imgInternet);
imgInternet.setEnabled(true);
EditText etFilter = (EditText) findViewById(R.id.etFilter);
etFilter.setEnabled(true);
CheckBox cbFilter = (CheckBox) findViewById(R.id.cbFilter);
cbFilter.setEnabled(true);
// Enable spinner
Spinner spRestriction = (Spinner) findViewById(R.id.spRestriction);
spRestriction.setEnabled(true);
// Restore state
ActivityMain.this.selectRestriction(spRestriction.getSelectedItemPosition());
}
}
@SuppressLint("DefaultLocale")
private class AppListAdapter extends ArrayAdapter<ApplicationInfoEx> {
private Context mContext;
private List<ApplicationInfoEx> mListAppAll;
private List<ApplicationInfoEx> mListAppSelected;
private String mRestrictionName;
private LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
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;
selectApps();
}
public void setRestrictionName(String restrictionName) {
mRestrictionName = restrictionName;
selectApps();
notifyDataSetChanged();
}
public String getRestrictionName() {
return mRestrictionName;
}
private void selectApps() {
mListAppSelected = new ArrayList<ApplicationInfoEx>();
if (PrivacyManager.getSettingBool(null, ActivityMain.this, PrivacyManager.cSettingFPermission, true, false)) {
for (ApplicationInfoEx appInfo : mListAppAll)
if (mRestrictionName == null)
mListAppSelected.add(appInfo);
else if (PrivacyManager.hasPermission(mContext, appInfo.getPackageName(), mRestrictionName)
|| PrivacyManager.getUsed(mContext, appInfo.getUid(), mRestrictionName, null) > 0)
mListAppSelected.add(appInfo);
} else
mListAppSelected.addAll(mListAppAll);
}
@Override
public Filter getFilter() {
return new AppFilter();
}
private class AppFilter extends Filter {
public AppFilter() {
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// Get arguments
String[] components = ((String) constraint).split("\\n");
boolean fUsed = Boolean.parseBoolean(components[0]);
boolean fInternet = Boolean.parseBoolean(components[1]);
String fName = components[2];
boolean fRestricted = Boolean.parseBoolean(components[3]);
// Match applications
List<ApplicationInfoEx> lstApp = new ArrayList<ApplicationInfoEx>();
for (ApplicationInfoEx xAppInfo : AppListAdapter.this.mListAppSelected) {
// Get if used
boolean used = false;
if (fUsed)
used = (PrivacyManager.getUsed(getApplicationContext(), xAppInfo.getUid(), mRestrictionName,
null) != 0);
// Get if internet
boolean internet = false;
if (fInternet)
internet = xAppInfo.hasInternet();
// Get if name contains
boolean contains = false;
if (!fName.equals(""))
contains = (xAppInfo.toString().toLowerCase().contains(((String) fName).toLowerCase()));
// Get some restricted
boolean someRestricted = false;
if (fRestricted)
if (mRestrictionName == null) {
for (boolean restricted : PrivacyManager.getRestricted(getApplicationContext(),
xAppInfo.getUid(), false))
if (restricted) {
someRestricted = true;
break;
}
} else
someRestricted = PrivacyManager.getRestricted(null, getApplicationContext(),
xAppInfo.getUid(), mRestrictionName, null, false, false);
// Match application
if ((fUsed ? used : true) && (fInternet ? internet : true) && (fName.equals("") ? true : contains)
&& (fRestricted ? someRestricted : true))
lstApp.add(xAppInfo);
}
synchronized (this) {
results.values = lstApp;
results.count = lstApp.size();
}
return results;
}
@Override
@SuppressWarnings("unchecked")
protected void publishResults(CharSequence constraint, FilterResults results) {
clear();
if (results.values == null)
notifyDataSetInvalidated();
else {
addAll((ArrayList<ApplicationInfoEx>) results.values);
notifyDataSetChanged();
}
}
}
private class ViewHolder {
private View row;
private int position;
public ImageView imgIcon;
public ImageView imgUsed;
public ImageView imgGranted;
public ImageView imgInternet;
public ImageView imgFrozen;
public CheckedTextView ctvApp;
public ViewHolder(View theRow, int thePosition) {
row = theRow;
position = thePosition;
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);
ctvApp = (CheckedTextView) row.findViewById(R.id.ctvName);
}
}
private class HolderTask extends AsyncTask<Object, Object, Object> {
private int position;
private ViewHolder holder;
private ApplicationInfoEx xAppInfo = null;
private boolean used;
private boolean granted = true;
private List<String> listRestriction;
private boolean allRestricted = true;
private boolean someRestricted = false;
- public HolderTask(int thePosition, ViewHolder theHolder) {
+ public HolderTask(int thePosition, ViewHolder theHolder, ApplicationInfoEx theAppInfo) {
position = thePosition;
holder = theHolder;
+ xAppInfo = theAppInfo;
}
@Override
protected Object doInBackground(Object... params) {
if (holder.position == position) {
- // Get info
- try {
- xAppInfo = getItem(holder.position);
- } catch (IndexOutOfBoundsException ex) {
- // Can happen when filtering
- return null;
- }
-
// Get if used
used = (PrivacyManager.getUsed(holder.row.getContext(), xAppInfo.getUid(), mRestrictionName, null) != 0);
// Get if granted
if (mRestrictionName != null)
if (!PrivacyManager.hasPermission(holder.row.getContext(), xAppInfo.getPackageName(),
mRestrictionName))
granted = false;
// Get restrictions
if (mRestrictionName == null)
listRestriction = PrivacyManager.getRestrictions(false);
else {
listRestriction = new ArrayList<String>();
listRestriction.add(mRestrictionName);
}
// Get all/some restricted
if (mRestrictionName == null)
for (boolean restricted : PrivacyManager.getRestricted(holder.row.getContext(),
xAppInfo.getUid(), false)) {
allRestricted = allRestricted && restricted;
someRestricted = someRestricted || restricted;
}
else {
boolean restricted = PrivacyManager.getRestricted(null, holder.row.getContext(),
xAppInfo.getUid(), mRestrictionName, null, false, false);
allRestricted = restricted;
someRestricted = restricted;
}
}
return null;
}
@Override
protected void onPostExecute(Object result) {
if (holder.position == position && xAppInfo != null) {
// Check if used
holder.ctvApp.setTypeface(null, used ? Typeface.BOLD_ITALIC : Typeface.NORMAL);
holder.imgUsed.setVisibility(used ? View.VISIBLE : View.INVISIBLE);
// Check if permission
holder.imgGranted.setVisibility(granted ? View.VISIBLE : View.INVISIBLE);
// Check if internet access
holder.imgInternet.setVisibility(xAppInfo.hasInternet() ? View.VISIBLE : View.INVISIBLE);
// Check if frozen
holder.imgFrozen.setVisibility(xAppInfo.isFrozen() ? View.VISIBLE : View.INVISIBLE);
// Display restriction
holder.ctvApp.setChecked(allRestricted);
holder.ctvApp.setEnabled(mRestrictionName == null && someRestricted ? allRestricted : true);
// Listen for restriction changes
holder.ctvApp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Get all/some restricted
boolean allRestricted = true;
if (mRestrictionName == null)
for (boolean restricted : PrivacyManager.getRestricted(view.getContext(),
xAppInfo.getUid(), false))
allRestricted = allRestricted && restricted;
else {
boolean restricted = PrivacyManager.getRestricted(null, view.getContext(),
xAppInfo.getUid(), mRestrictionName, null, false, false);
allRestricted = restricted;
}
// Process click
allRestricted = !allRestricted;
for (String restrictionName : listRestriction)
PrivacyManager.setRestricted(null, view.getContext(), xAppInfo.getUid(),
restrictionName, null, allRestricted);
holder.ctvApp.setChecked(allRestricted);
}
});
}
}
}
@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);
// Set background color
if (xAppInfo.getIsSystem())
holder.row.setBackgroundColor(getResources().getColor(getThemed(R.attr.color_dangerous)));
else
holder.row.setBackgroundColor(Color.TRANSPARENT);
// Set icon
holder.imgIcon.setImageDrawable(xAppInfo.getIcon());
holder.imgIcon.setVisibility(View.VISIBLE);
// Handle details click
holder.imgIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intentSettings = new Intent(view.getContext(), ActivityApp.class);
intentSettings.putExtra(ActivityApp.cPackageName, xAppInfo.getPackageName());
intentSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(intentSettings);
}
});
// Set data
holder.ctvApp.setText(xAppInfo.toString());
holder.ctvApp.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.ctvApp.setChecked(false);
holder.ctvApp.setEnabled(false);
holder.ctvApp.setClickable(false);
// Async update
- new HolderTask(position, holder).executeOnExecutor(mExecutor, (Object) null);
+ new HolderTask(position, holder, xAppInfo).executeOnExecutor(mExecutor, (Object) null);
return convertView;
}
}
public int getThemed(int attr) {
TypedValue typedvalueattr = new TypedValue();
getTheme().resolveAttribute(attr, typedvalueattr, true);
return typedvalueattr.resourceId;
}
}
| false | false | null | null |
diff --git a/asta4d-sample/src/main/java/com/astamuse/asta4d/sample/snippet/SimpleSnippet.java b/asta4d-sample/src/main/java/com/astamuse/asta4d/sample/snippet/SimpleSnippet.java
index ae760013..f07c6188 100644
--- a/asta4d-sample/src/main/java/com/astamuse/asta4d/sample/snippet/SimpleSnippet.java
+++ b/asta4d-sample/src/main/java/com/astamuse/asta4d/sample/snippet/SimpleSnippet.java
@@ -1,68 +1,68 @@
/*
* Copyright 2012 astamuse company,Ltd.
*
* 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.astamuse.asta4d.sample.snippet;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Element;
import com.astamuse.asta4d.render.GoThroughRenderer;
import com.astamuse.asta4d.render.Renderer;
import com.astamuse.asta4d.util.ElementUtil;
public class SimpleSnippet {
// @ShowCode:showSnippetStart
// @ShowCode:showVariableinjectionStart
public Renderer render(String name) {
if (StringUtils.isEmpty(name)) {
name = "Asta4D";
}
Element element = ElementUtil.parseAsSingle("<span>Hello " + name + "!</span>");
return Renderer.create("*", element);
}
// @ShowCode:showVariableinjectionEnd
public Renderer setProfile() {
Renderer render = new GoThroughRenderer();
render.add("p#name span", "asta4d");
render.add("p#age span", 20);
return render;
}
// @ShowCode:showSnippetEnd
// @ShowCode:showVariableinjectionStart
public Renderer setProfileByVariableInjection(String name, int age) {
Renderer render = new GoThroughRenderer();
render.add("p#name span", name);
render.add("p#age span", age);
return render;
}
// @ShowCode:showVariableinjectionEnd
// @ShowCode:showAttributevaluesStart
public Renderer manipulateAttrValues() {
Renderer render = new GoThroughRenderer();
render.add("input#yes", "checked", "checked");
- render.add("button#delete", "disabled", null);
+ render.add("button#delete", "disabled", (Object) null);
render.add("li#plus", "+class", "red");
render.add("li#minus", "-class", "bold");
return render;
}
// @ShowCode:showAttributevaluesEnd
}
| true | true | public Renderer manipulateAttrValues() {
Renderer render = new GoThroughRenderer();
render.add("input#yes", "checked", "checked");
render.add("button#delete", "disabled", null);
render.add("li#plus", "+class", "red");
render.add("li#minus", "-class", "bold");
return render;
}
| public Renderer manipulateAttrValues() {
Renderer render = new GoThroughRenderer();
render.add("input#yes", "checked", "checked");
render.add("button#delete", "disabled", (Object) null);
render.add("li#plus", "+class", "red");
render.add("li#minus", "-class", "bold");
return render;
}
|
diff --git a/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java b/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java
index d7ee5b0..8e60789 100644
--- a/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java
+++ b/src/org/geometerplus/zlibrary/core/network/ZLNetworkManager.java
@@ -1,225 +1,225 @@
/*
* Copyright (C) 2010 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.core.network;
import java.util.*;
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.GeneralSecurityException;
import java.security.cert.*;
import org.geometerplus.zlibrary.core.util.ZLNetworkUtil;
import org.geometerplus.zlibrary.core.filesystem.ZLResourceFile;
public class ZLNetworkManager {
private static ZLNetworkManager ourManager;
public static ZLNetworkManager Instance() {
if (ourManager == null) {
ourManager = new ZLNetworkManager();
}
return ourManager;
}
private String doBeforeRequest(ZLNetworkRequest request) {
final String err = request.doBefore();
if (err != null) {
return err;
}
/*if (request.isInstanceOf(ZLNetworkPostRequest::TYPE_ID)) {
return doBeforePostRequest((ZLNetworkPostRequest &) request);
}*/
return null;
}
private String setCommonHTTPOptions(ZLNetworkRequest request, HttpURLConnection httpConnection) {
httpConnection.setInstanceFollowRedirects(request.FollowRedirects);
httpConnection.setConnectTimeout(15000); // FIXME: hardcoded timeout value!!!
httpConnection.setReadTimeout(30000); // FIXME: hardcoded timeout value!!!
//httpConnection.setRequestProperty("Connection", "Close");
httpConnection.setRequestProperty("User-Agent", ZLNetworkUtil.getUserAgent());
httpConnection.setAllowUserInteraction(false);
if (httpConnection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
if (request.SSLCertificate != null) {
InputStream stream;
try {
ZLResourceFile file = ZLResourceFile.createResourceFile(request.SSLCertificate);
stream = file.getInputStream();
} catch (IOException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_FILE, request.SSLCertificate);
}
try {
TrustManager[] managers = new TrustManager[] { new ZLX509TrustManager(stream) };
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, managers, null);
httpsConnection.setSSLSocketFactory(context.getSocketFactory());
} catch (CertificateExpiredException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_EXPIRED, request.SSLCertificate);
} catch (CertificateNotYetValidException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_NOT_YET_VALID, request.SSLCertificate);
} catch (CertificateException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_FILE, request.SSLCertificate);
} catch (GeneralSecurityException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM);
} finally {
try {
stream.close();
} catch (IOException ex) {
}
}
}
}
// TODO: handle Authentication
return null;
}
public String perform(ZLNetworkRequest request) {
- boolean sucess = false;
+ boolean success = false;
try {
final String error = doBeforeRequest(request);
if (error != null) {
return error;
}
HttpURLConnection httpConnection = null;
int response = -1;
for (int retryCounter = 0; retryCounter < 3 && response == -1; ++retryCounter) {
final URL url = new URL(request.URL);
final URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_UNSUPPORTED_PROTOCOL);
}
httpConnection = (HttpURLConnection) connection;
String err = setCommonHTTPOptions(request, httpConnection);
if (err != null) {
return err;
}
httpConnection.connect();
response = httpConnection.getResponseCode();
}
if (response == HttpURLConnection.HTTP_OK) {
InputStream stream = httpConnection.getInputStream();
try {
final String err = request.doHandleStream(httpConnection, stream);
if (err != null) {
return err;
}
} finally {
stream.close();
}
- sucess = true;
+ success = true;
} else {
if (response == HttpURLConnection.HTTP_UNAUTHORIZED) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED);
} else {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
}
}
} catch (SSLHandshakeException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_CONNECT, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLKeyException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_KEY, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLPeerUnverifiedException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PEER_UNVERIFIED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLProtocolException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PROTOCOL_ERROR);
} catch (SSLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM);
} catch (ConnectException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CONNECTION_REFUSED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (NoRouteToHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_HOST_CANNOT_BE_REACHED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (UnknownHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_RESOLVE_HOST, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (MalformedURLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_INVALID_URL);
} catch (SocketTimeoutException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_TIMEOUT);
} catch (IOException ex) {
ex.printStackTrace();
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
} finally {
- final String err = request.doAfter(sucess);
- if (sucess && err != null) {
+ final String err = request.doAfter(success);
+ if (success && err != null) {
return err;
}
}
return null;
}
public String perform(List<ZLNetworkRequest> requests) {
if (requests.size() == 0) {
return "";
}
if (requests.size() == 1) {
return perform(requests.get(0));
}
HashSet<String> errors = new HashSet<String>();
// TODO: implement concurrent execution !!!
for (ZLNetworkRequest r: requests) {
final String e = perform(r);
if (e != null && !errors.contains(e)) {
errors.add(e);
}
}
if (errors.size() == 0) {
return null;
}
StringBuilder message = new StringBuilder();
for (String e: errors) {
if (message.length() != 0) {
message.append(", ");
}
message.append(e);
}
return message.toString();
}
public final String downloadToFile(String url, final File outFile) {
return downloadToFile(url, outFile, 8192);
}
public final String downloadToFile(String url, final File outFile, final int bufferSize) {
return perform(new ZLNetworkRequest(url) {
public String handleStream(URLConnection connection, InputStream inputStream) throws IOException {
OutputStream outStream = new FileOutputStream(outFile);
try {
final byte[] buffer = new byte[bufferSize];
while (true) {
final int size = inputStream.read(buffer);
if (size <= 0) {
break;
}
outStream.write(buffer, 0, size);
}
} finally {
outStream.close();
}
return null;
}
});
}
}
| false | true | public String perform(ZLNetworkRequest request) {
boolean sucess = false;
try {
final String error = doBeforeRequest(request);
if (error != null) {
return error;
}
HttpURLConnection httpConnection = null;
int response = -1;
for (int retryCounter = 0; retryCounter < 3 && response == -1; ++retryCounter) {
final URL url = new URL(request.URL);
final URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_UNSUPPORTED_PROTOCOL);
}
httpConnection = (HttpURLConnection) connection;
String err = setCommonHTTPOptions(request, httpConnection);
if (err != null) {
return err;
}
httpConnection.connect();
response = httpConnection.getResponseCode();
}
if (response == HttpURLConnection.HTTP_OK) {
InputStream stream = httpConnection.getInputStream();
try {
final String err = request.doHandleStream(httpConnection, stream);
if (err != null) {
return err;
}
} finally {
stream.close();
}
sucess = true;
} else {
if (response == HttpURLConnection.HTTP_UNAUTHORIZED) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED);
} else {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
}
}
} catch (SSLHandshakeException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_CONNECT, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLKeyException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_KEY, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLPeerUnverifiedException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PEER_UNVERIFIED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLProtocolException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PROTOCOL_ERROR);
} catch (SSLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM);
} catch (ConnectException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CONNECTION_REFUSED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (NoRouteToHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_HOST_CANNOT_BE_REACHED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (UnknownHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_RESOLVE_HOST, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (MalformedURLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_INVALID_URL);
} catch (SocketTimeoutException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_TIMEOUT);
} catch (IOException ex) {
ex.printStackTrace();
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
} finally {
final String err = request.doAfter(sucess);
if (sucess && err != null) {
return err;
}
}
return null;
}
| public String perform(ZLNetworkRequest request) {
boolean success = false;
try {
final String error = doBeforeRequest(request);
if (error != null) {
return error;
}
HttpURLConnection httpConnection = null;
int response = -1;
for (int retryCounter = 0; retryCounter < 3 && response == -1; ++retryCounter) {
final URL url = new URL(request.URL);
final URLConnection connection = url.openConnection();
if (!(connection instanceof HttpURLConnection)) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_UNSUPPORTED_PROTOCOL);
}
httpConnection = (HttpURLConnection) connection;
String err = setCommonHTTPOptions(request, httpConnection);
if (err != null) {
return err;
}
httpConnection.connect();
response = httpConnection.getResponseCode();
}
if (response == HttpURLConnection.HTTP_OK) {
InputStream stream = httpConnection.getInputStream();
try {
final String err = request.doHandleStream(httpConnection, stream);
if (err != null) {
return err;
}
} finally {
stream.close();
}
success = true;
} else {
if (response == HttpURLConnection.HTTP_UNAUTHORIZED) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_AUTHENTICATION_FAILED);
} else {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
}
}
} catch (SSLHandshakeException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_CONNECT, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLKeyException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_BAD_KEY, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLPeerUnverifiedException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PEER_UNVERIFIED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (SSLProtocolException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_PROTOCOL_ERROR);
} catch (SSLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SSL_SUBSYSTEM);
} catch (ConnectException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_CONNECTION_REFUSED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (NoRouteToHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_HOST_CANNOT_BE_REACHED, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (UnknownHostException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_RESOLVE_HOST, ZLNetworkUtil.hostFromUrl(request.URL));
} catch (MalformedURLException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_INVALID_URL);
} catch (SocketTimeoutException ex) {
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_TIMEOUT);
} catch (IOException ex) {
ex.printStackTrace();
return ZLNetworkErrors.errorMessage(ZLNetworkErrors.ERROR_SOMETHING_WRONG, ZLNetworkUtil.hostFromUrl(request.URL));
} finally {
final String err = request.doAfter(success);
if (success && err != null) {
return err;
}
}
return null;
}
|
diff --git a/test/models/UserTest.java b/test/models/UserTest.java
index 58ea78f5..78ea6342 100644
--- a/test/models/UserTest.java
+++ b/test/models/UserTest.java
@@ -1,159 +1,159 @@
package models;
import static org.fest.assertions.Assertions.assertThat;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.avaje.ebean.Page;
import play.data.validation.Validation;
public class UserTest extends ModelTest<User> {
@Test
public void save() throws Exception {
User user = new User();
user.loginId="foo";
assertThat(Validation.getValidator().validate(user).size()).describedAs("'foo' should be accepted.").isEqualTo(0);
user.loginId=".foo";
assertThat(Validation.getValidator().validate(user).size()).describedAs("'.foo' should NOT be accepted.").isGreaterThan(0);
user.loginId="foo.bar";
assertThat(Validation.getValidator().validate(user).size()).describedAs("'foo.bar' should be accepted.").isEqualTo(0);
user.loginId="foo.";
assertThat(Validation.getValidator().validate(user).size()).describedAs("'foo.' should NOT be accepted.").isGreaterThan(0);
user.loginId="_foo";
assertThat(Validation.getValidator().validate(user).size()).describedAs("'_foo' should NOT be accepted.").isGreaterThan(0);
user.loginId="foo_bar";
assertThat(Validation.getValidator().validate(user).size()).describedAs("'foo_bar' should be accepted.").isEqualTo(0);
user.loginId="foo_";
assertThat(Validation.getValidator().validate(user).size()).describedAs("'foo_' should NOT be accepted.").isGreaterThan(0);
user.loginId="-foo";
assertThat(Validation.getValidator().validate(user).size()).describedAs("'-foo' should be accepted.").isEqualTo(0);
user.loginId="foo-";
assertThat(Validation.getValidator().validate(user).size()).describedAs("'foo-' should be accepted.").isEqualTo(0);
}
@Test
public void findById() throws Exception {
// Given
// When
User user = User.find.byId(2l);
// Then
assertThat(user.name).isEqualTo("Yobi");
}
@Test
public void findNameById() throws Exception {
//Given
//When
String name = User.find.byId(2l).name;
//Then
assertThat(name).isEqualTo("Yobi");
}
@Test
public void options() throws Exception {
// Given
// When
Map<String, String> userOptions = User.options();
// Then
- assertThat(userOptions).hasSize(5);
+ assertThat(userOptions).hasSize(6);
}
@Test
public void findByLoginId() throws Exception {
// Given
// When
User user = User.findByLoginId("laziel");
// Then
assertThat(user.id).isEqualTo(3l);
}
@Test
public void findUsers() throws Exception {
// Given
// When
Page<User> searchUsers = User.findUsers(0, "yo");
// Then
assertThat(searchUsers.getTotalRowCount()).isEqualTo(1);
}
@Test
public void findUsersByProject() throws Exception {
// Given
// When
List<User> users = User.findUsersByProject(2l);
// Then
assertThat(users.size()).isEqualTo(2);
}
@Test
public void isLoginId() throws Exception {
// Given
String existingId = "yobi";
String nonExistingId = "yobiii";
// When
boolean result1 = User.isLoginIdExist(existingId);
boolean result2 = User.isLoginIdExist(nonExistingId);
boolean result3 = User.isLoginIdExist(null);
// Then
assertThat(result1).isEqualTo(true);
assertThat(result2).isEqualTo(false);
assertThat(result3).isEqualTo(false);
}
@Test
public void isEmailExist() throws Exception {
// Given
String expectedUser = "[email protected]";
// When // Then
assertThat(User.isEmailExist(expectedUser)).isTrue();
}
@Test
public void isEmailExist_nonExist() throws Exception {
// Given
String expectedEmail = "[email protected]";
// When // Then
assertThat(User.isEmailExist(expectedEmail)).isFalse();
}
@Test
public void watchingProject() {
// Given
Project project = Project.find.byId(1l);
User user = User.findByLoginId("doortts");
assertThat(project.watchingCount).isEqualTo(0);
assertThat(user.getWatchingProjects().size()).isEqualTo(0);
// When
user.addWatching(project);
// Then
assertThat(user.getWatchingProjects().size()).isEqualTo(1);
assertThat(user.getWatchingProjects().contains(project)).isTrue();
assertThat(project.watchingCount).isEqualTo(1);
// when
user.removeWatching(project);
// Then
assertThat(user.getWatchingProjects().size()).isEqualTo(0);
assertThat(user.getWatchingProjects().contains(project)).isFalse();
assertThat(project.watchingCount).isEqualTo(0);
}
}
| true | false | null | null |
diff --git a/deegree-core/src/main/java/org/deegree/rendering/r2d/legends/Legends.java b/deegree-core/src/main/java/org/deegree/rendering/r2d/legends/Legends.java
index 6e67839e33..e6ce9ab0b1 100644
--- a/deegree-core/src/main/java/org/deegree/rendering/r2d/legends/Legends.java
+++ b/deegree-core/src/main/java/org/deegree/rendering/r2d/legends/Legends.java
@@ -1,242 +1,249 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.rendering.r2d.legends;
import static java.awt.Font.PLAIN;
import static java.lang.Math.max;
import static org.deegree.commons.utils.CollectionUtils.AND;
import static org.deegree.commons.utils.CollectionUtils.map;
import static org.deegree.commons.utils.CollectionUtils.reduce;
import static org.deegree.rendering.r2d.styling.components.UOM.Metre;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.deegree.commons.utils.CollectionUtils;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.utils.CollectionUtils.Mapper;
import org.deegree.geometry.Geometry;
import org.deegree.geometry.GeometryFactory;
import org.deegree.geometry.primitive.LineString;
import org.deegree.geometry.primitive.Point;
import org.deegree.geometry.primitive.Polygon;
import org.deegree.geometry.standard.DefaultEnvelope;
import org.deegree.rendering.r2d.Java2DRenderer;
import org.deegree.rendering.r2d.Java2DTextRenderer;
import org.deegree.rendering.r2d.se.unevaluated.Style;
import org.deegree.rendering.r2d.styling.LineStyling;
import org.deegree.rendering.r2d.styling.PointStyling;
import org.deegree.rendering.r2d.styling.Styling;
import org.deegree.rendering.r2d.styling.TextStyling;
/**
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class Legends {
private int baseSizeX = 20, baseSizeY = 15, textSize = 12;
private GeometryFactory geofac = new GeometryFactory();
/**
* New legend renderer with base size of 20x15, text size of 12
*/
public Legends() {
// default values
}
/**
* @param baseSizeX
* @param baseSizeY
* @param textSize
*/
public Legends( int baseSizeX, int baseSizeY, int textSize ) {
this.baseSizeX = baseSizeX;
this.baseSizeY = baseSizeY;
this.textSize = textSize;
}
/**
* @param xpos
* @param ypos
* @param xsize
* @param ysize
* @return a made up rectangle to be used in a legend
*/
public Polygon getLegendRect( int xpos, int ypos, int xsize, int ysize ) {
Point p1 = geofac.createPoint( null, xpos, ypos, null );
Point p2 = geofac.createPoint( null, xpos + xsize, ypos, null );
Point p3 = geofac.createPoint( null, xpos + xsize, ypos + ysize, null );
Point p4 = geofac.createPoint( null, xpos, ypos + ysize, null );
List<Point> ps = new ArrayList<Point>( 5 );
ps.add( p1 );
ps.add( p2 );
ps.add( p3 );
ps.add( p4 );
ps.add( p1 );
return geofac.createPolygon( null, null, geofac.createLinearRing( null, null, geofac.createPoints( ps ) ), null );
}
/**
* @param xpos
* @param ypos
* @param xsz
* @param ysz
* @return a made up line string to be used in a legend
*/
public LineString getLegendLine( int xpos, int ypos, int xsz, int ysz ) {
Point p1 = geofac.createPoint( null, xpos, ypos, null );
Point p2 = geofac.createPoint( null, xpos + xsz / 3, ypos + ysz / 3 * 2, null );
Point p3 = geofac.createPoint( null, xpos + xsz / 3 * 2, ypos + ysz / 3, null );
Point p4 = geofac.createPoint( null, xpos + xsz, ypos + ysz, null );
List<Point> ps = new ArrayList<Point>( 4 );
ps.add( p1 );
ps.add( p2 );
ps.add( p3 );
ps.add( p4 );
return geofac.createLineString( null, null, geofac.createPoints( ps ) );
}
/**
* @param style
* @param width
* @param height
* @param g
*/
public void paintLegend( Style style, int width, int height, Graphics2D g ) {
Pair<Integer, Integer> size = getLegendSize( style );
Java2DRenderer renderer = new Java2DRenderer( g, width, height,
new DefaultEnvelope( geofac.createPoint( null, 0, 0, null ),
geofac.createPoint( null, size.first,
size.second, null ) ) );
Java2DTextRenderer textRenderer = new Java2DTextRenderer( renderer );
int ypos = 6;
int xpos = 6;
- Iterator<Class<?>> types = style.getRuleTypes().iterator();
+ LinkedList<Class<?>> ruleTypes = style.getRuleTypes();
+ Collections.reverse( ruleTypes );
+ Iterator<Class<?>> types = ruleTypes.iterator();
TextStyling textStyling = new TextStyling();
textStyling.font = new org.deegree.rendering.r2d.styling.components.Font();
textStyling.font.fontFamily.add( 0, "Arial" );
textStyling.font.fontSize = textSize;
textStyling.anchorPointX = 0;
textStyling.anchorPointY = 0.5;
textStyling.uom = Metre;
Mapper<Boolean, Styling> pointStylingMapper = CollectionUtils.<Styling> getInstanceofMapper( PointStyling.class );
Mapper<Boolean, Styling> lineStylingMapper = CollectionUtils.<Styling> getInstanceofMapper( LineStyling.class );
- Iterator<String> titles = style.getRuleTitles().iterator();
- for ( LinkedList<Styling> styles : style.getBases() ) {
+ LinkedList<String> ruleTitles = style.getRuleTitles();
+ Collections.reverse( ruleTitles );
+ Iterator<String> titles = ruleTitles.iterator();
+ ArrayList<LinkedList<Styling>> bases = style.getBases();
+ Collections.reverse( bases );
+ for ( LinkedList<Styling> styles : bases ) {
String title = titles.next();
Class<?> c = types.next();
boolean isPoint = c.equals( Point.class ) || reduce( true, map( styles, pointStylingMapper ), AND );
boolean isLine = c.equals( LineString.class ) || reduce( true, map( styles, lineStylingMapper ), AND );
Geometry geom;
if ( isPoint ) {
geom = geofac.createPoint( null, xpos + 10, ypos + 10, null );
} else if ( isLine ) {
geom = getLegendLine( xpos, ypos, baseSizeX, baseSizeY );
} else {
// something better?
geom = getLegendRect( xpos, ypos, baseSizeX, baseSizeY );
}
if ( title != null && title.length() > 0 ) {
textRenderer.render( textStyling, title, geofac.createPoint( null, 15 + baseSizeX,
ypos + baseSizeY / 2, null ) );
}
ypos += 12 + baseSizeY;
double maxSize = 0;
if ( isPoint ) {
for ( Styling s : styles ) {
if ( s instanceof PointStyling ) {
maxSize = max( ( (PointStyling) s ).graphic.size, maxSize );
}
}
}
for ( Styling styling : styles ) {
// normalize point symbols to 20 pixels
if ( styling instanceof PointStyling && isPoint ) {
PointStyling s = ( (PointStyling) styling ).copy();
s.uom = Metre;
s.graphic.size = s.graphic.size / maxSize * Math.max( baseSizeX, baseSizeY );
styling = s;
}
renderer.render( styling, geom );
}
}
g.dispose();
}
/**
* @param style
* @return the legend width/height given a base size of 32x32
*/
public Pair<Integer, Integer> getLegendSize( Style style ) {
Pair<Integer, Integer> res = new Pair<Integer, Integer>( 0, 0 );
res.second = ( 12 + baseSizeY ) * style.getBases().size();
res.first = 12 + baseSizeX;
Font font = new Font( "Arial", PLAIN, textSize );
for ( String s : style.getRuleTitles() ) {
if ( s != null && s.length() > 0 ) {
TextLayout layout = new TextLayout( s, font, new FontRenderContext( new AffineTransform(), true, false ) );
res.first = (int) max( layout.getBounds().getWidth() + ( 2 * baseSizeX ), res.first );
}
}
return res;
}
}
| false | false | null | null |
diff --git a/src/net/haltcondition/anode/Usage.java b/src/net/haltcondition/anode/Usage.java
index 00b0e3a..7d75c2e 100644
--- a/src/net/haltcondition/anode/Usage.java
+++ b/src/net/haltcondition/anode/Usage.java
@@ -1,56 +1,56 @@
package net.haltcondition.anode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Copyright Steve Smith ([email protected]): 16/05/2010
*/
public class Usage
{
private Long totalQuota;
private Calendar rollOver;
private Long used;
private SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd");
public Usage()
{
}
public Long getTotalQuota()
{
return totalQuota;
}
public void setTotalQuota(String str)
{
- this.totalQuota = Long.valueOf(str);
+ totalQuota = Long.valueOf(str);
}
public Calendar getRollOver()
{
return rollOver;
}
public void setRollOver(String str)
throws ParseException
{
Date d = dateParser.parse(str);
rollOver = new GregorianCalendar();
rollOver.setTime(d);
}
public Long getUsed()
{
return used;
}
public void setUsed(String str)
{
- this.used = Long.valueOf(used);
+ used = Long.valueOf(str);
}
}
diff --git a/tests/net/haltcondition/anode/UsageTest.java b/tests/net/haltcondition/anode/UsageTest.java
index 521834b..0fc989e 100644
--- a/tests/net/haltcondition/anode/UsageTest.java
+++ b/tests/net/haltcondition/anode/UsageTest.java
@@ -1,34 +1,48 @@
package net.haltcondition.anode;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import java.text.ParseException;
import java.util.Calendar;
@Test
public class UsageTest
{
private Usage usage;
@BeforeMethod
protected void setUp()
{
usage = new Usage();
}
@Test
void testDateParse(){
try {
usage.setRollOver("2000-12-21");
} catch (ParseException e) {
fail(e.getMessage(), e);
}
assertEquals(usage.getRollOver().get(Calendar.YEAR), 2000);
assertEquals(usage.getRollOver().get(Calendar.MONTH), Calendar.DECEMBER);
assertEquals(usage.getRollOver().get(Calendar.DAY_OF_MONTH), 21);
}
+
+ @Test
+ void testQuotaParse()
+ {
+ usage.setTotalQuota("120000000000");
+ assertEquals(true, usage.getTotalQuota().equals(120000000000L));
+ }
+
+ @Test
+ void testUsageParse()
+ {
+ usage.setUsed("120000000000");
+ assertEquals(true, usage.getUsed().equals(120000000000L));
+ }
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/com/mrockey28/bukkit/ItemRepair/AutoRepairSupport.java b/src/com/mrockey28/bukkit/ItemRepair/AutoRepairSupport.java
index a42084e..0ebc922 100644
--- a/src/com/mrockey28/bukkit/ItemRepair/AutoRepairSupport.java
+++ b/src/com/mrockey28/bukkit/ItemRepair/AutoRepairSupport.java
@@ -1,505 +1,503 @@
package com.mrockey28.bukkit.ItemRepair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import net.milkbowl.vault.Vault;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import com.mrockey28.bukkit.ItemRepair.AutoRepairPlugin.operationType;
/**
*
* @author lostaris, mrockey28
*/
public class AutoRepairSupport {
private final AutoRepairPlugin plugin;
protected static Player player;
public AutoRepairSupport(AutoRepairPlugin instance, Player player) {
plugin = instance;
AutoRepairSupport.player = player;
}
private boolean warning = false;
private boolean lastWarning = false;
private float CalcPercentUsed(ItemStack tool, int durability)
{
float percentUsed = -1;
percentUsed = (float)tool.getDurability() / (float)durability;
return percentUsed;
}
public boolean accountForRoundingType (int slot, ArrayList<ItemStack> req, String itemName)
{
return true;
}
public void toolReq(ItemStack tool, int slot) {
doRepairOperation(tool, slot, operationType.QUERY);
}
public void deduct(ArrayList<ItemStack> req) {
PlayerInventory inven = player.getInventory();
for (int i =0; i < req.size(); i++) {
ItemStack currItem = new ItemStack(req.get(i).getTypeId(), req.get(i).getAmount());
int neededAmount = req.get(i).getAmount();
int smallestSlot = findSmallest(currItem);
if (smallestSlot != -1) {
while (neededAmount > 0) {
smallestSlot = findSmallest(currItem);
ItemStack smallestItem = inven.getItem(smallestSlot);
if (neededAmount < smallestItem.getAmount()) {
// got enough in smallest stack deal and done
ItemStack newSize = new ItemStack(currItem.getType(), smallestItem.getAmount() - neededAmount);
inven.setItem(smallestSlot, newSize);
neededAmount = 0;
} else {
// need to remove from more than one stack, deal and continue
neededAmount -= smallestItem.getAmount();
inven.clear(smallestSlot);
}
}
}
}
}
public void doRepairOperation(ItemStack tool, int slot, AutoRepairPlugin.operationType op)
{
double balance = AutoRepairPlugin.econ.getBalance(player.getName());
if (!AutoRepairPlugin.isOpAllowed(getPlayer(), op)) {
return;
}
if (op == operationType.WARN && !AutoRepairPlugin.isRepairCosts() && !AutoRepairPlugin.isAutoRepair()) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
}
if (op == operationType.WARN && !warning) warning = true;
else if (op == operationType.WARN) return;
PlayerInventory inven = getPlayer().getInventory();
HashMap<String, ArrayList<ItemStack> > recipies = AutoRepairPlugin.getRepairRecipies();
String itemName = Material.getMaterial(tool.getTypeId()).toString();
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
ArrayList<ItemStack> req = new ArrayList<ItemStack>(recipies.get(itemName).size());
ArrayList<ItemStack> neededItems = new ArrayList<ItemStack>(0);
//do a deep copy of the required items list so we can modify it temporarily for rounding purposes
for (ItemStack i: recipies.get(itemName)) {
req.add((ItemStack)i.clone());
}
String toolString = tool.getType().toString();
int durability = durabilities.get(itemName);
double cost = 0;
if (AutoRepairPlugin.getiConCosts().containsKey(toolString)) {
cost = (double)AutoRepairPlugin.getiConCosts().get(itemName);
}
else
{
player.sendMessage("�cThis item is not in the AutoRepair database.");
return;
}
//do rounding based on dmg already done to item, if called for by config
if (op != operationType.AUTO_REPAIR && AutoRepairPlugin.rounding != "flat")
{
float percentUsed = CalcPercentUsed(inven.getItem(slot), durability);
for (int index = 0; index < req.size(); index++) {
float amnt = req.get(index).getAmount();
int amntInt;
amnt = amnt * percentUsed;
cost = cost * percentUsed;
amnt = Math.round(amnt);
amntInt = (int)amnt;
if (AutoRepairPlugin.rounding == "min")
{
if (amntInt == 0)
{
amntInt = 1;
}
}
req.get(index).setAmount(amntInt);
}
}
try {
//No repair costs
if (!AutoRepairPlugin.isRepairCosts()) {
switch (op)
{
case WARN:
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
getPlayer().sendMessage("�3Repaired " + itemName);
inven.setItem(slot, repItem(tool));
break;
case QUERY:
getPlayer().sendMessage("�3No materials needed to repair.");
break;
}
}
//Using economy to pay only
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("true") == 0)
{
switch (op)
{ case QUERY:
player.sendMessage("�6It costs " + AutoRepairPlugin.econ.format((double)cost)
+ " to repair " + tool.getType());
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " to repair " + itemName);
//inven.setItem(slot, repItem(tool));
inven.setItem(slot, repItem(tool));
} else {
iConWarn(itemName, cost);
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
if (cost > balance) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
iConWarn(toolString, cost);
}
break;
}
}
//Using both economy and item costs to pay
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("both") == 0)
{
switch (op)
{
case QUERY:
- isEnoughItems(req, neededItems);
player.sendMessage("�6To repair " + tool.getType() + " you need: "
+ AutoRepairPlugin.econ.format((double)cost) + " and");
- player.sendMessage("�6" + printFormatReqs(neededItems));
+ player.sendMessage("�6" + printFormatReqs(req));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance && isEnoughItems(req, neededItems)) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
deduct(req);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�3" + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (cost > balance || !isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
break;
}
}
//Just using item costs to pay
else
{
switch (op)
{
case QUERY:
- isEnoughItems(req, neededItems);
player.sendMessage("�6To repair " + tool.getType() + " you need:");
- player.sendMessage("�6" + printFormatReqs(neededItems));
+ player.sendMessage("�6" + printFormatReqs(req));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (isEnoughItems(req, neededItems)) {
deduct(req);
player.sendMessage("�3Using " + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
justItemsWarn(itemName, req);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (!isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
justItemsWarn(toolString, neededItems);
}
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public void repairWarn(ItemStack tool, int slot) {
doRepairOperation(tool, slot, operationType.WARN);
}
public boolean repArmourInfo(String query) {
if (AutoRepairPlugin.isRepairCosts()) {
try {
char getRecipe = query.charAt(0);
if (getRecipe == '?') {
//ArrayList<ItemStack> req = this.repArmourAmount(player);
//player.sendMessage("�6To repair all your armour you need:");
//player.sendMessage("�6" + this.printFormatReqs(req));
int total =0;
ArrayList<ItemStack> req = repArmourAmount();
PlayerInventory inven = player.getInventory();
if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("true") == 0){
for (ItemStack i : inven.getArmorContents()) {
if (AutoRepairPlugin.getiConCosts().containsKey(i.getType().toString())) {
total += AutoRepairPlugin.getiConCosts().get(i.getType().toString());
}
}
player.sendMessage("�6To repair all your armour you need: "
+ AutoRepairPlugin.econ.format((double)total));
// icon and item cost
} else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("both") == 0) {
for (ItemStack i : inven.getArmorContents()) {
if (AutoRepairPlugin.getiConCosts().containsKey(i.getType().toString())) {
total += AutoRepairPlugin.getiConCosts().get(i.getType().toString());
}
}
player.sendMessage("�6To repair all your armour you need: "
+ AutoRepairPlugin.econ.format((double)total));
player.sendMessage("�6" + this.printFormatReqs(req));
// just item cost
} else {
player.sendMessage("�6To repair all your armour you need:");
player.sendMessage("�6" + this.printFormatReqs(req));
}
}
} catch (Exception e) {
return false;
}
} else {
player.sendMessage("�3No materials needed to repair");
}
return true;
}
public ArrayList<ItemStack> repArmourAmount() {
HashMap<String, ArrayList<ItemStack> > recipies = AutoRepairPlugin.getRepairRecipies();
PlayerInventory inven = player.getInventory();
ItemStack[] armour = inven.getArmorContents();
HashMap<String, Integer> totalCost = new HashMap<String, Integer>();
for (int i=0; i<armour.length; i++) {
String item = armour[i].getType().toString();
if (recipies.containsKey(item)) {
ArrayList<ItemStack> reqItems = recipies.get(item);
for (int j =0; j<reqItems.size(); j++) {
if(totalCost.containsKey(reqItems.get(j).getType().toString())) {
int amount = totalCost.get(reqItems.get(j).getType().toString());
totalCost.remove(reqItems.get(j).getType().toString());
int newAmount = amount + reqItems.get(j).getAmount();
totalCost.put(reqItems.get(j).getType().toString(), newAmount);
} else {
totalCost.put(reqItems.get(j).getType().toString(), reqItems.get(j).getAmount());
}
}
}
}
ArrayList<ItemStack> req = new ArrayList<ItemStack>();
for (Object key: totalCost.keySet()) {
req.add(new ItemStack(Material.getMaterial(key.toString()), totalCost.get(key)));
}
return req;
}
public ItemStack repItem(ItemStack item) {
item.setDurability((short) 0);
return item;
}
//prints the durability left of the current tool to the player
public void durabilityLeft(ItemStack tool) {
if (AutoRepairPlugin.isAllowed(player, "info")) { //!AutoRepairPlugin.isPermissions || AutoRepairPlugin.Permissions.has(player, "AutoRepair.info")) {
int usesLeft = this.returnUsesLeft(tool);
if (usesLeft != -1) {
player.sendMessage("�3" + usesLeft + " blocks left untill this tool breaks." );
} else {
player.sendMessage("�6This is not a tool.");
}
} else {
player.sendMessage("�cYou dont have permission to do the ? or dmg commands.");
}
}
public int returnUsesLeft(ItemStack tool) {
int usesLeft = -1;
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
String itemName = Material.getMaterial(tool.getTypeId()).toString();
int durability = durabilities.get(itemName);
usesLeft = durability - tool.getDurability();
return usesLeft;
}
@SuppressWarnings("unchecked")
public int findSmallest(ItemStack item) {
PlayerInventory inven = player.getInventory();
HashMap<Integer, ? extends ItemStack> items = inven.all(item.getTypeId());
int slot = -1;
int smallest = 64;
//iterator for the hashmap
Set<?> set = items.entrySet();
Iterator<?> i = set.iterator();
//ItemStack highest = new ItemStack(repairItem.getType(), 0);
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
ItemStack item1 = (ItemStack) me.getValue();
//if the player has doesn't not have enough of the item used to repair
if (item1.getAmount() <= smallest) {
smallest = item1.getAmount();
slot = (Integer)me.getKey();
}
}
return slot;
}
@SuppressWarnings("unchecked")
public int getTotalItems(ItemStack item) {
int total = 0;
PlayerInventory inven = player.getInventory();
HashMap<Integer, ? extends ItemStack> items = inven.all(item.getTypeId());
//iterator for the hashmap
Set<?> set = items.entrySet();
Iterator<?> i = set.iterator();
//ItemStack highest = new ItemStack(repairItem.getType(), 0);
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
ItemStack item1 = (ItemStack) me.getValue();
//if the player has doesn't not have enough of the item used to repair
total += item1.getAmount();
}
return total;
}
// checks to see if the player has enough of a list of items
public boolean isEnough(String itemName) {
ArrayList<ItemStack> reqItems = AutoRepairPlugin.getRepairRecipies().get(itemName);
boolean enoughItemFlag = true;
for (int i =0; i < reqItems.size(); i++) {
ItemStack currItem = new ItemStack(reqItems.get(i).getTypeId(), reqItems.get(i).getAmount());
int neededAmount = reqItems.get(i).getAmount();
int currTotal = getTotalItems(currItem);
if (neededAmount > currTotal) {
enoughItemFlag = false;
}
}
return enoughItemFlag;
}
public boolean isEnoughItems (ArrayList<ItemStack> req, ArrayList<ItemStack> neededItems) {
boolean enough = true;
for (int i =0; i<req.size(); i++) {
ItemStack currItem = new ItemStack(req.get(i).getTypeId(), req.get(i).getAmount());
int neededAmount = req.get(i).getAmount();
int currTotal = getTotalItems(currItem);
if (neededAmount > currTotal) {
neededItems.add(req.get(i).clone());
enough = false;
}
}
return enough;
}
public void iConWarn(String itemName, double total) {
getPlayer().sendMessage("�cYou are cannot afford to repair " + itemName);
getPlayer().sendMessage("�cNeed: " + AutoRepairPlugin.econ.format((double)total));
}
public void bothWarn(String itemName, double total, ArrayList<ItemStack> req) {
getPlayer().sendMessage("�cYou are missing one or more items to repair " + itemName);
getPlayer().sendMessage("�cNeed: " + printFormatReqs(req) + " and " +
AutoRepairPlugin.econ.format((double)total));
}
public void justItemsWarn(String itemName, ArrayList<ItemStack> req) {
player.sendMessage("�cYou are missing one or more items to repair " + itemName);
player.sendMessage("�cNeed: " + printFormatReqs(req));
}
public String printFormatReqs(ArrayList<ItemStack> items) {
StringBuffer string = new StringBuffer();
string.append(" ");
for (int i = 0; i < items.size(); i++) {
string.append(items.get(i).getAmount() + " " + items.get(i).getType() + " ");
}
return string.toString();
}
public boolean getWarning() {
return warning;
}
public boolean getLastWarning() {
return lastWarning;
}
public void setWarning(boolean newValue) {
this.warning = newValue;
}
public void setLastWarning(boolean newValue) {
this.lastWarning = newValue;
}
public AutoRepairPlugin getPlugin() {
return plugin;
}
public static Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
AutoRepairSupport.player = player;
}
}
| false | true | public void doRepairOperation(ItemStack tool, int slot, AutoRepairPlugin.operationType op)
{
double balance = AutoRepairPlugin.econ.getBalance(player.getName());
if (!AutoRepairPlugin.isOpAllowed(getPlayer(), op)) {
return;
}
if (op == operationType.WARN && !AutoRepairPlugin.isRepairCosts() && !AutoRepairPlugin.isAutoRepair()) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
}
if (op == operationType.WARN && !warning) warning = true;
else if (op == operationType.WARN) return;
PlayerInventory inven = getPlayer().getInventory();
HashMap<String, ArrayList<ItemStack> > recipies = AutoRepairPlugin.getRepairRecipies();
String itemName = Material.getMaterial(tool.getTypeId()).toString();
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
ArrayList<ItemStack> req = new ArrayList<ItemStack>(recipies.get(itemName).size());
ArrayList<ItemStack> neededItems = new ArrayList<ItemStack>(0);
//do a deep copy of the required items list so we can modify it temporarily for rounding purposes
for (ItemStack i: recipies.get(itemName)) {
req.add((ItemStack)i.clone());
}
String toolString = tool.getType().toString();
int durability = durabilities.get(itemName);
double cost = 0;
if (AutoRepairPlugin.getiConCosts().containsKey(toolString)) {
cost = (double)AutoRepairPlugin.getiConCosts().get(itemName);
}
else
{
player.sendMessage("�cThis item is not in the AutoRepair database.");
return;
}
//do rounding based on dmg already done to item, if called for by config
if (op != operationType.AUTO_REPAIR && AutoRepairPlugin.rounding != "flat")
{
float percentUsed = CalcPercentUsed(inven.getItem(slot), durability);
for (int index = 0; index < req.size(); index++) {
float amnt = req.get(index).getAmount();
int amntInt;
amnt = amnt * percentUsed;
cost = cost * percentUsed;
amnt = Math.round(amnt);
amntInt = (int)amnt;
if (AutoRepairPlugin.rounding == "min")
{
if (amntInt == 0)
{
amntInt = 1;
}
}
req.get(index).setAmount(amntInt);
}
}
try {
//No repair costs
if (!AutoRepairPlugin.isRepairCosts()) {
switch (op)
{
case WARN:
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
getPlayer().sendMessage("�3Repaired " + itemName);
inven.setItem(slot, repItem(tool));
break;
case QUERY:
getPlayer().sendMessage("�3No materials needed to repair.");
break;
}
}
//Using economy to pay only
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("true") == 0)
{
switch (op)
{ case QUERY:
player.sendMessage("�6It costs " + AutoRepairPlugin.econ.format((double)cost)
+ " to repair " + tool.getType());
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " to repair " + itemName);
//inven.setItem(slot, repItem(tool));
inven.setItem(slot, repItem(tool));
} else {
iConWarn(itemName, cost);
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
if (cost > balance) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
iConWarn(toolString, cost);
}
break;
}
}
//Using both economy and item costs to pay
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("both") == 0)
{
switch (op)
{
case QUERY:
isEnoughItems(req, neededItems);
player.sendMessage("�6To repair " + tool.getType() + " you need: "
+ AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�6" + printFormatReqs(neededItems));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance && isEnoughItems(req, neededItems)) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
deduct(req);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�3" + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (cost > balance || !isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
break;
}
}
//Just using item costs to pay
else
{
switch (op)
{
case QUERY:
isEnoughItems(req, neededItems);
player.sendMessage("�6To repair " + tool.getType() + " you need:");
player.sendMessage("�6" + printFormatReqs(neededItems));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (isEnoughItems(req, neededItems)) {
deduct(req);
player.sendMessage("�3Using " + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
justItemsWarn(itemName, req);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (!isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
justItemsWarn(toolString, neededItems);
}
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
| public void doRepairOperation(ItemStack tool, int slot, AutoRepairPlugin.operationType op)
{
double balance = AutoRepairPlugin.econ.getBalance(player.getName());
if (!AutoRepairPlugin.isOpAllowed(getPlayer(), op)) {
return;
}
if (op == operationType.WARN && !AutoRepairPlugin.isRepairCosts() && !AutoRepairPlugin.isAutoRepair()) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
}
if (op == operationType.WARN && !warning) warning = true;
else if (op == operationType.WARN) return;
PlayerInventory inven = getPlayer().getInventory();
HashMap<String, ArrayList<ItemStack> > recipies = AutoRepairPlugin.getRepairRecipies();
String itemName = Material.getMaterial(tool.getTypeId()).toString();
HashMap<String, Integer> durabilities = AutoRepairPlugin.getDurabilityCosts();
ArrayList<ItemStack> req = new ArrayList<ItemStack>(recipies.get(itemName).size());
ArrayList<ItemStack> neededItems = new ArrayList<ItemStack>(0);
//do a deep copy of the required items list so we can modify it temporarily for rounding purposes
for (ItemStack i: recipies.get(itemName)) {
req.add((ItemStack)i.clone());
}
String toolString = tool.getType().toString();
int durability = durabilities.get(itemName);
double cost = 0;
if (AutoRepairPlugin.getiConCosts().containsKey(toolString)) {
cost = (double)AutoRepairPlugin.getiConCosts().get(itemName);
}
else
{
player.sendMessage("�cThis item is not in the AutoRepair database.");
return;
}
//do rounding based on dmg already done to item, if called for by config
if (op != operationType.AUTO_REPAIR && AutoRepairPlugin.rounding != "flat")
{
float percentUsed = CalcPercentUsed(inven.getItem(slot), durability);
for (int index = 0; index < req.size(); index++) {
float amnt = req.get(index).getAmount();
int amntInt;
amnt = amnt * percentUsed;
cost = cost * percentUsed;
amnt = Math.round(amnt);
amntInt = (int)amnt;
if (AutoRepairPlugin.rounding == "min")
{
if (amntInt == 0)
{
amntInt = 1;
}
}
req.get(index).setAmount(amntInt);
}
}
try {
//No repair costs
if (!AutoRepairPlugin.isRepairCosts()) {
switch (op)
{
case WARN:
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
getPlayer().sendMessage("�3Repaired " + itemName);
inven.setItem(slot, repItem(tool));
break;
case QUERY:
getPlayer().sendMessage("�3No materials needed to repair.");
break;
}
}
//Using economy to pay only
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("true") == 0)
{
switch (op)
{ case QUERY:
player.sendMessage("�6It costs " + AutoRepairPlugin.econ.format((double)cost)
+ " to repair " + tool.getType());
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " to repair " + itemName);
//inven.setItem(slot, repItem(tool));
inven.setItem(slot, repItem(tool));
} else {
iConWarn(itemName, cost);
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
if (cost > balance) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
iConWarn(toolString, cost);
}
break;
}
}
//Using both economy and item costs to pay
else if (AutoRepairPlugin.getiSICon().compareToIgnoreCase("both") == 0)
{
switch (op)
{
case QUERY:
player.sendMessage("�6To repair " + tool.getType() + " you need: "
+ AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�6" + printFormatReqs(req));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (cost <= balance && isEnoughItems(req, neededItems)) {
//balance = iConomy.db.get_balance(player.getName());
AutoRepairPlugin.econ.withdrawPlayer(player.getName(), cost);
deduct(req);
player.sendMessage("�3Using " + AutoRepairPlugin.econ.format((double)cost) + " and");
player.sendMessage("�3" + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (cost > balance || !isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
if (cost > balance && !isEnoughItems(req, neededItems)) bothWarn(itemName, cost, neededItems);
else if (cost > balance) iConWarn(itemName, cost);
else justItemsWarn(itemName, neededItems);
}
break;
}
}
//Just using item costs to pay
else
{
switch (op)
{
case QUERY:
player.sendMessage("�6To repair " + tool.getType() + " you need:");
player.sendMessage("�6" + printFormatReqs(req));
break;
case AUTO_REPAIR:
case MANUAL_REPAIR:
if (isEnoughItems(req, neededItems)) {
deduct(req);
player.sendMessage("�3Using " + printFormatReqs(req) + " to repair " + itemName);
inven.setItem(slot, repItem(tool));
} else {
if (op == operationType.MANUAL_REPAIR || !getLastWarning()) {
if (AutoRepairPlugin.isAllowed(player, "warn")) {
justItemsWarn(itemName, req);
}
if (op == operationType.AUTO_REPAIR) setLastWarning(true);
}
}
break;
case WARN:
if (!AutoRepairPlugin.isAutoRepair()) player.sendMessage("�6WARNING: " + tool.getType() + " will break soon, no auto repairing!");
else if (!isEnoughItems(req, neededItems)) {
player.sendMessage("�6WARNING: " + tool.getType() + " will break soon");
justItemsWarn(toolString, neededItems);
}
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/src/de/thm/ateam/memory/network/HostService.java b/src/de/thm/ateam/memory/network/HostService.java
index 7ffcda6..5f70e2c 100644
--- a/src/de/thm/ateam/memory/network/HostService.java
+++ b/src/de/thm/ateam/memory/network/HostService.java
@@ -1,135 +1,135 @@
package de.thm.ateam.memory.network;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import de.thm.ateam.memory.engine.type.*;
/**
*
* Service which starts a Task, responsible for handling connecting Clients
*
*/
public class HostService extends Service{
private static final String TAG = HostService.class.getSimpleName();
public static ArrayList<NetworkPlayer> clients = null;
public static int current = 0;
/** Clients can join the game or not */
public static boolean gameAvailable = false;
private static ServerSocket servSock = null;
private static Socket clientSock = null;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
Log.i(TAG, "Start Host Service!");
clients = new ArrayList<NetworkPlayer>();
gameAvailable = true;
Thread t = new Thread(new ServerTask());
t.start();
return START_NOT_STICKY;
}
/**
* Finds a player from the client list by a given socket
* @param sock Socket, which is compared to each client
* @return null if no Player was found, the found NetworkPlayer otherwise
*/
public static NetworkPlayer findPlayerBySocket(Socket sock){
if(clients.size() == 0) return null;
for(NetworkPlayer p : clients){
- if(p.sock != null && p.sock.getLocalAddress().equals(sock.getLocalAddress())){
+ if(p.sock != null && p.sock.getRemoteSocketAddress().toString().equals(sock.getRemoteSocketAddress().toString())){
return p;
}
}
return null;
}
@Override
public void onDestroy(){
super.onDestroy();
Log.i(TAG, "SERVICE WAS STOPPED!");
try {
servSock.close();
clientSock.shutdownInput();
clientSock.shutdownOutput();
} catch (IOException e) {
Log.e(TAG, "Socket could not be closed");
e.printStackTrace();
}
stopSelf();
}
private class ServerTask implements Runnable{
public void run() {
try {
servSock = new ServerSocket(6666);
Log.i(TAG, "Server is waiting for clients...");
while(true){
clientSock = servSock.accept();
if(!gameAvailable){
Log.i(TAG, "Client tried to connect, but Host doesn't accep connections anymore.");
}else{
Log.i(TAG, "A Client has connected!");
// add this client to the client List
clients.add(new NetworkPlayer(clientSock));
// create a new thread for this client
Thread t = new Thread(new ClientConnection(clientSock));
t.start();
}
}
} catch (IOException e) {
Log.e(TAG, "Server: Port 6666 could not be used ");
}
}
}
/**
* Compute the winner of a network game
* @return the Player who has won if he/she has the single most pairs
* if there is more than one player with the highest amount of pairs
* it is a draw and null is returned
*/
public static Player computeWinner() {
if(clients.size() == 0) return null;
int highscore = 0;
Player winner = null;
int numberOfWinners = 0;
for(Player p : clients){
if(p.roundHits > highscore){
highscore = p.roundHits;
numberOfWinners = 1;
winner = p;
}else if(p.roundHits == highscore){
numberOfWinners++;
}
//reset the hits of each player for the next round
p.roundHits = 0;
}
if(numberOfWinners == 1){
return winner;
}
return null;
}
}
diff --git a/src/de/thm/ateam/memory/network/Response.java b/src/de/thm/ateam/memory/network/Response.java
index 3bf00c3..7e05b59 100644
--- a/src/de/thm/ateam/memory/network/Response.java
+++ b/src/de/thm/ateam/memory/network/Response.java
@@ -1,135 +1,135 @@
package de.thm.ateam.memory.network;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import android.util.Log;
import de.thm.ateam.memory.engine.type.*;
/**
*
* process incoming messages and send responses to client(s)
*
*/
public class Response implements Runnable{
private final String TAG = this.getClass().getSimpleName();
String incMessage;
/** socket from the sender of this message */
Socket incSocket;
public Response(String incMessage, Socket incSocket){
this.incMessage = incMessage;
this.incSocket = incSocket;
}
/**
* Sets the current Player to the next one, "Round Robin"
* @return current Player
*/
public NetworkPlayer nextTurn(){
return HostService.clients.get((++HostService.current)%HostService.clients.size());
}
/**
* Gets the current Player (the one with the token) from the list
* @return current Player
*/
public NetworkPlayer currentPlayer(){
return HostService.clients.get(HostService.current%HostService.clients.size());
}
/**
* send Responses to one or multiple players
*/
public void run() {
PrintWriter out = null;
if(incMessage.startsWith("[token]")){
// currentPlayer made his move so notify the next player
NetworkPlayer nextPlayer = nextTurn();
try {
for(NetworkPlayer player : HostService.clients){
if(player.sock != null){
out = new PrintWriter(player.sock.getOutputStream(), true);
- if(player.sock.getLocalAddress().equals(nextPlayer.sock.getLocalAddress())){
+ if(player.sock.getRemoteSocketAddress().toString().equals(nextPlayer.sock.getRemoteSocketAddress().toString())){
Log.i(TAG, "Server sends out new token");
out.println("[token]");
}else{
/* notify the other player with the name of the currentPlayer so they can
* display a toast message or something
*/
out.println("[currentPlayer]"+ nextPlayer.nick);
}
}
}
} catch (IOException e) {
Log.e(TAG, "IOException");
}
}else if(incMessage.startsWith("[finish]")){
/* Game was finished so notify the players
* with the name of the Winner if there is one
*
*/
Player winner = HostService.computeWinner();
try {
for(NetworkPlayer player : HostService.clients){
if(player.sock != null){
out = new PrintWriter(player.sock.getOutputStream(), true);
if(winner == null){
out.println("[finish]");
}else{
out.println("[finish]"+ winner.nick);
}
}
}
} catch (IOException e) {
Log.e(TAG, "IOException");
}
}else if(incMessage.startsWith("[removePlayer")){
NetworkPlayer p = HostService.findPlayerBySocket(incSocket);
HostService.clients.remove(p);
}else{
/* here are the messages for all clients */
NetworkPlayer playerWhoSentThisMessage = HostService.findPlayerBySocket(this.incSocket);
for(NetworkPlayer player : HostService.clients){
if(player.sock != null){
try {
out = new PrintWriter(player.sock.getOutputStream(), true);
} catch (IOException e) {
Log.e(TAG, "IOException while opening writer");
}
if(incMessage.startsWith("[system]")){
Log.i(TAG, "Sending start message to a client");
out.println("[start]");
}else if(incMessage.startsWith("[nick]")){
Log.i(TAG, "Sending join message to a client");
String playerName = incMessage.substring(6, incMessage.length());
// set nickname of this player in the client list
- if(player.sock.getLocalAddress().equals(incSocket.getLocalAddress())){
+ if(player.sock.getRemoteSocketAddress().toString().equals(incSocket.getRemoteSocketAddress().toString())){
player.nick = playerName;
}
out.println(playerName + " joined the Game");
}else if(incMessage.startsWith("[delete]")){
Log.i(TAG, "a pair was found");
// increase round hits of the message's sender
- if(playerWhoSentThisMessage != null && playerWhoSentThisMessage.sock.getLocalAddress().equals(player.sock.getLocalAddress())){
+ if(playerWhoSentThisMessage != null && playerWhoSentThisMessage.sock.getRemoteSocketAddress().toString().equals(player.sock.getRemoteSocketAddress().toString())){
playerWhoSentThisMessage.roundHits += 1;
}
out.println(incMessage);
}else{
/* e.g. [flip], [field], [reset] !!! */
out.println(incMessage);
}
}
}
}
}
}
| false | false | null | null |
diff --git a/src/org/antlr/works/editor/actions/ActionsExport.java b/src/org/antlr/works/editor/actions/ActionsExport.java
index 9f0adfc..8a3619a 100644
--- a/src/org/antlr/works/editor/actions/ActionsExport.java
+++ b/src/org/antlr/works/editor/actions/ActionsExport.java
@@ -1,111 +1,117 @@
/*
[The "BSD licence"]
Copyright (c) 2005 Jean Bovet
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 name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.works.editor.actions;
import edu.usfca.xj.appkit.utils.XJAlert;
import edu.usfca.xj.appkit.utils.XJFileChooser;
import edu.usfca.xj.foundation.XJUtils;
import org.antlr.works.editor.EditorWindow;
import org.antlr.works.stats.Statistics;
import org.antlr.works.visualization.graphics.GContext;
import org.antlr.works.visualization.graphics.GEngine;
import org.antlr.works.visualization.graphics.GEnginePS;
import org.antlr.works.visualization.graphics.graph.GGraphAbstract;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public class ActionsExport extends AbstractActions {
public ActionsExport(EditorWindow editor) {
super(editor);
}
public void exportEventsAsTextFile() {
if(!XJFileChooser.shared().displaySaveDialog(editor.getWindowContainer(), "txt", "Text file", false))
return;
String file = XJFileChooser.shared().getSelectedFilePath();
if(file == null)
return;
StringBuffer text = new StringBuffer();
List events = editor.debugger.getEvents();
for(int i=0; i<events.size(); i++) {
text.append(i + 1);
text.append(": ");
text.append(events.get(i).toString());
text.append("\n");
}
try {
FileWriter writer = new FileWriter(file);
writer.write(text.toString());
writer.close();
} catch (IOException e) {
XJAlert.display(editor.getWindowContainer(), "Error", "Cannot save text file: "+file+"\nError: "+e);
}
Statistics.shared().recordEvent(Statistics.EVENT_EXPORT_EVENTS_TEXT);
}
public void exportRuleAsEPS() {
if(editor.rules.getEnclosingRuleAtPosition(editor.getCaretPosition()) == null) {
XJAlert.display(editor.getWindowContainer(), "Export Rule to EPS", "There is no rule at cursor position.");
return;
}
+ GGraphAbstract graph = editor.visual.getCurrentGraph();
+
+ if(graph == null) {
+ XJAlert.display(editor.getWindowContainer(), "Export Rule to EPS", "There is no graphical visualization.");
+ return;
+ }
+
if(!XJFileChooser.shared().displaySaveDialog(editor.getWindowContainer(), "eps", "EPS file", false))
return;
String file = XJFileChooser.shared().getSelectedFilePath();
if(file == null)
return;
try {
GEnginePS engine = new GEnginePS();
- GGraphAbstract graph = editor.visual.getCurrentGraph();
GContext context = graph.getContext();
GEngine oldEngine = context.engine;
context.setEngine(engine);
graph.draw();
context.setEngine(oldEngine);
XJUtils.writeStringToFile(engine.getPSText(), file);
} catch (Exception e) {
e.printStackTrace();
XJAlert.display(editor.getWindowContainer(), "Error", "Cannot export to EPS file: "+file+"\nError: "+e);
}
}
}
| false | false | null | null |
diff --git a/src/main/java/org/basex/gui/view/explore/ExploreArea.java b/src/main/java/org/basex/gui/view/explore/ExploreArea.java
index a7f3e8b81..1689f710d 100644
--- a/src/main/java/org/basex/gui/view/explore/ExploreArea.java
+++ b/src/main/java/org/basex/gui/view/explore/ExploreArea.java
@@ -1,349 +1,349 @@
package org.basex.gui.view.explore;
import static org.basex.core.Text.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import org.basex.core.cmd.Find;
import org.basex.data.Data;
import org.basex.data.StatsKey;
import org.basex.gui.GUIConstants;
import org.basex.gui.GUIProp;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.layout.BaseXBack;
import org.basex.gui.layout.BaseXCombo;
import org.basex.gui.layout.BaseXDSlider;
import org.basex.gui.layout.BaseXLabel;
import org.basex.gui.layout.BaseXLayout;
import org.basex.gui.layout.BaseXPanel;
import org.basex.gui.layout.BaseXTextField;
import org.basex.gui.layout.TableLayout;
import org.basex.index.Names;
import org.basex.util.StringList;
import org.basex.util.Token;
import org.basex.util.TokenBuilder;
import org.basex.util.TokenList;
import org.basex.util.Util;
import org.deepfs.fs.DeepFS;
/**
* This is a simple user search panel.
*
* @author BaseX Team 2005-11, ISC License
* @author Christian Gruen
* @author Bastian Lemke
*/
final class ExploreArea extends BaseXPanel implements ActionListener {
/** Component width. */
private static final int COMPW = 150;
/** Exact search pattern. */
private static final String PATEX = "[% = \"%\"]";
/** Substring search pattern. */
private static final String PATSUB = "[% contains text \"%\"]";
/** Numeric search pattern. */
private static final String PATNUM = "[% >= % and % <= %]";
/** Simple search pattern. */
private static final String PATSIMPLE = "[%]";
/** Main panel. */
private final ExploreView main;
/** Main panel. */
private final BaseXBack panel;
/** Query field. */
private final BaseXTextField all;
/** Last Query. */
private String last = "";
/**
* Default constructor.
* @param m main panel
*/
ExploreArea(final ExploreView m) {
super(m.gui);
main = m;
layout(new BorderLayout(0, 5)).mode(Fill.NONE);
all = new BaseXTextField(gui);
all.addKeyListener(main);
all.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(final KeyEvent e) {
query(false);
}
});
add(all, BorderLayout.NORTH);
panel = new BaseXBack(GUIConstants.Fill.NONE).layout(
new TableLayout(20, 2, 10, 5));
add(panel, BorderLayout.CENTER);
}
/**
* Initializes the panel.
*/
void init() {
panel.removeAll();
panel.revalidate();
panel.repaint();
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
final Data data = gui.context.data;
if(!main.visible() || data == null) return;
final boolean pi = data.meta.pathindex;
- if(panel.getComponentCount() != 0) {
+ if(!pi || panel.getComponentCount() != 0) {
if(!pi) init();
return;
}
if(!pi) return;
all.help(data.fs != null ? HELPSEARCHFS : HELPSEARCHXML);
addKeys(gui.context.data);
panel.revalidate();
panel.repaint();
}
/**
* Adds a text field.
* @param pos position
*/
private void addInput(final int pos) {
final BaseXTextField txt = new BaseXTextField(gui);
BaseXLayout.setWidth(txt, COMPW);
BaseXLayout.setHeight(txt, txt.getFont().getSize() + 11);
txt.setMargin(new Insets(0, 0, 0, 10));
txt.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(final KeyEvent e) {
query(false);
}
});
txt.addKeyListener(main);
panel.add(txt, pos);
}
/**
* Adds a category combobox.
* @param data data reference
*/
private void addKeys(final Data data) {
final TokenList tl = new TokenList();
final int cs = panel.getComponentCount();
final boolean fs = data.fs != null;
- if(fs) tl.add(Token.token(DeepFS.S_FILE));
- else {
+ if(fs) {
+ tl.add(Token.token(DeepFS.S_FILE));
+ } else {
for(int c = 0; c < cs; c += 2) {
final BaseXCombo combo = (BaseXCombo) panel.getComponent(c);
if(combo.getSelectedIndex() == 0) continue;
final String elem = combo.getSelectedItem().toString();
if(!elem.startsWith("@")) tl.add(Token.token(elem));
}
}
final TokenList tmp = data.pthindex.desc(tl, data, !fs, false);
- if(tmp.size() == 0) return;
-
final String[] keys = entries(tmp.toArray());
final BaseXCombo cm = new BaseXCombo(gui, keys);
cm.addActionListener(this);
cm.addKeyListener(main);
+ if(tmp.size() == 0) cm.setEnabled(false);
panel.add(cm);
panel.add(new BaseXLabel(""));
}
/**
* Adds a combobox.
* @param values combobox values
* @param pos position
*/
private void addCombo(final String[] values, final int pos) {
final BaseXCombo cm = new BaseXCombo(gui, values);
BaseXLayout.setWidth(cm, COMPW);
cm.addActionListener(this);
cm.addKeyListener(main);
panel.add(cm, pos);
}
/**
* Adds a combobox.
* @param min minimum value
* @param max maximum value
* @param pos position
* @param kb kilobyte flag
* @param date date flag
* @param itr integer flag
*/
private void addSlider(final double min, final double max, final int pos,
final boolean kb, final boolean date, final boolean itr) {
final BaseXDSlider sl = new BaseXDSlider(gui, min, max, this);
BaseXLayout.setWidth(sl, COMPW + BaseXDSlider.LABELW);
sl.kb = kb;
sl.date = date;
sl.itr = itr;
sl.addKeyListener(main);
panel.add(sl, pos);
}
@Override
public void actionPerformed(final ActionEvent e) {
if(e != null) {
final Object source = e.getSource();
// find modified component
int cp = 0;
final int cs = panel.getComponentCount();
for(int c = 0; c < cs; ++c) if(panel.getComponent(c) == source) cp = c;
if((cp & 1) == 0) {
// combo box with tags/attributes
final BaseXCombo combo = (BaseXCombo) source;
panel.remove(cp + 1);
final Data data = gui.context.data;
final boolean selected = combo.getSelectedIndex() != 0;
if(selected) {
final String item = combo.getSelectedItem().toString();
final boolean att = item.startsWith("@");
final Names names = att ? data.atts : data.tags;
final byte[] key = Token.token(att ? item.substring(1) : item);
final StatsKey stat = names.stat(names.id(key));
switch(stat.kind) {
case INT:
addSlider(stat.min, stat.max, cp + 1,
item.equals("@" + DeepFS.S_SIZE),
item.equals("@" + DeepFS.S_MTIME) ||
item.equals("@" + DeepFS.S_CTIME) ||
item.equals("@" + DeepFS.S_ATIME), true);
break;
case DBL:
addSlider(stat.min, stat.max, cp + 1, false, false, false);
break;
case CAT:
addCombo(entries(stat.cats.keys()), cp + 1);
break;
case TEXT:
addInput(cp + 1);
break;
case NONE:
panel.add(new BaseXLabel(""), cp + 1);
break;
}
} else {
panel.add(new BaseXLabel(""), cp + 1);
}
while(cp + 2 < panel.getComponentCount()) {
panel.remove(cp + 2);
panel.remove(cp + 2);
}
if(selected) addKeys(data);
panel.revalidate();
panel.repaint();
}
}
query(false);
}
/**
* Runs a query.
* @param force force the execution of a new query
*/
void query(final boolean force) {
final TokenBuilder tb = new TokenBuilder();
final Data data = gui.context.data;
final int cs = panel.getComponentCount();
for(int c = 0; c < cs; c += 2) {
final BaseXCombo com = (BaseXCombo) panel.getComponent(c);
final int k = com.getSelectedIndex();
if(k <= 0) continue;
String key = com.getSelectedItem().toString();
final boolean attr = key.startsWith("@");
if(!key.contains(":") && !attr) key = "*:" + key;
final Component comp = panel.getComponent(c + 1);
String pattern = "";
String val1 = null;
String val2 = null;
if(comp instanceof BaseXTextField) {
val1 = ((BaseXTextField) comp).getText();
if(!val1.isEmpty()) {
if(val1.startsWith("\"")) {
val1 = val1.replaceAll("\"", "");
pattern = PATEX;
} else {
pattern = attr && data.meta.attrindex ||
!attr && data.meta.textindex ? PATSUB : PATEX;
}
}
} else if(comp instanceof BaseXCombo) {
final BaseXCombo combo = (BaseXCombo) comp;
if(combo.getSelectedIndex() != 0) {
val1 = combo.getSelectedItem().toString();
pattern = PATEX;
}
} else if(comp instanceof BaseXDSlider) {
final BaseXDSlider slider = (BaseXDSlider) comp;
if(slider.min != slider.totMin || slider.max != slider.totMax) {
final double m = slider.min;
final double n = slider.max;
val1 = (long) m == m ? Long.toString((long) m) : Double.toString(m);
val2 = (long) n == n ? Long.toString((long) n) : Double.toString(n);
pattern = PATNUM;
}
}
if(data.fs != null && tb.size() == 0) {
tb.add("//" + DeepFS.S_FILE);
}
if(attr) {
if(tb.size() == 0) tb.add("//*");
if(pattern.isEmpty()) pattern = PATSIMPLE;
} else {
if(data.fs != null) tb.add("[" + key);
else tb.add("//" + key);
key = "text()";
}
tb.addExt(pattern, key, val1, key, val2);
if(data.fs != null && !attr) tb.add("]");
}
String qu = tb.toString();
final boolean root = gui.context.root();
final boolean rt = gui.gprop.is(GUIProp.FILTERRT);
if(!qu.isEmpty() && !rt && !root) qu = "." + qu;
String simple = all.getText().trim();
if(!simple.isEmpty()) {
simple = Find.find(simple, gui.context, rt);
qu = !qu.isEmpty() ? simple + " | " + qu : simple;
}
if(qu.isEmpty()) qu = rt || root ? "/" : ".";
if(!force && last.equals(qu)) return;
last = qu;
gui.xquery(qu, false);
}
/**
* Returns the combo box selections
* and the keys of the specified set.
* @param key keys
* @return key array
*/
private String[] entries(final byte[][] key) {
final StringList sl = new StringList();
sl.add(Util.info(INFOENTRIES, key.length));
for(final byte[] k : key) sl.add(Token.string(k));
sl.sort(true, true, 1);
return sl.toArray();
}
}
| false | false | null | null |
diff --git a/src/com/cyanogenmod/lockclock/misc/WidgetUtils.java b/src/com/cyanogenmod/lockclock/misc/WidgetUtils.java
index 15100d9..7196fca 100644
--- a/src/com/cyanogenmod/lockclock/misc/WidgetUtils.java
+++ b/src/com/cyanogenmod/lockclock/misc/WidgetUtils.java
@@ -1,80 +1,80 @@
/*
* Copyright (C) 2012 The Android Open Source Project
* Portions Copyright (C) 2012 The CyanogenMod 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.cyanogenmod.lockclock.misc;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.TypedValue;
import com.cyanogenmod.lockclock.R;
public class WidgetUtils {
static final String TAG = "WidgetUtils";
// Decide whether to show the Weather panel
public static boolean canFitWeather(Context context, int id) {
Bundle options = AppWidgetManager.getInstance(context).getAppWidgetOptions(id);
if (options == null) {
// no data to make the calculation, show the list anyway
return true;
}
Resources resources = context.getResources();
int minHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
int minHeightPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, minHeight,
resources.getDisplayMetrics());
int neededSize = (int) resources.getDimension(R.dimen.min_weather_widget_height);
// Check to see if the widget size is big enough, if it is return true.
return (minHeightPx > neededSize);
}
// Decide whether to show the Calendar panel
public static boolean canFitCalendar(Context context, int id) {
Bundle options = AppWidgetManager.getInstance(context).getAppWidgetOptions(id);
if (options == null) {
// no data to make the calculation, show the list anyway
return true;
}
Resources resources = context.getResources();
int minHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
int minHeightPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, minHeight,
resources.getDisplayMetrics());
int neededSize = (int) resources.getDimension(R.dimen.min_calendar_widget_height);
// Check to see if the widget size is big enough, if it is return true.
return (minHeightPx > neededSize);
}
// Calculate the scale factor of the fonts in the widget
public static float getScaleRatio(Context context, int id) {
Bundle options = AppWidgetManager.getInstance(context).getAppWidgetOptions(id);
if (options != null) {
int minWidth = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
if (minWidth == 0) {
// No data , do no scaling
return 1f;
}
Resources res = context.getResources();
- float ratio = minWidth / res.getDimension(R.dimen.min_digital_widget_width);
+ float ratio = minWidth / res.getDimension(R.dimen.def_digital_widget_width);
return (ratio > 1) ? 1f : ratio;
}
return 1f;
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/AeroControl/src/com/aero/control/helpers/FilePath.java b/AeroControl/src/com/aero/control/helpers/FilePath.java
index 70e3379..a0ed588 100644
--- a/AeroControl/src/com/aero/control/helpers/FilePath.java
+++ b/AeroControl/src/com/aero/control/helpers/FilePath.java
@@ -1,99 +1,102 @@
package com.aero.control.helpers;
import android.graphics.Typeface;
/**
* Created by Alexander Christ on 05.08.14.
*
* Contains most file paths for the individual fragments
*
*/
public final class FilePath {
/* Used by; AeroFragment, GPUFragment, MemoryFragment */
public static final String GOV_FILE = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor";
public static final String GOV_IO_FILE = "/sys/block/mmcblk0/queue/scheduler";
public static final String[] GPU_FILES = {"/sys/kernel/gpu_control/max_freq", /* Defy 2.6 Kernel */
"/sys/class/kgsl/kgsl-3d0/max_gpuclk", /* Adreno GPUs */
"/sys/devices/platform/omap/pvrsrvkm.0/sgx_fck_rate" /* Defy 3.0 Kernel */};
public static final String[] GPU_FILES_RATE = {"/sys/class/kgsl/kgsl-3d0/gpuclk", /* Adreno GPUs */
"/sys/devices/platform/omap/pvrsrvkm.0/sgx_fck_rate" /* Defy 3.0 Kernel */,
"/proc/gpu/cur_rate" /* Defy 2.6 Kernel */};
public static final String FILENAME_PROC_MEMINFO = "/proc/meminfo";
/* Used by; CPUFragment */
public static final String CPU_BASE_PATH = "/sys/devices/system/cpu/cpu";
public static final String CPU_AVAILABLE_FREQ = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies";
public static final String ALL_GOV_AVAILABLE = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors";
public static final String CURRENT_GOV_AVAILABLE = "/cpufreq/scaling_governor";
public static final String CPU_MAX_FREQ = "/cpufreq/scaling_max_freq";
public static final String CPU_MIN_FREQ = "/cpufreq/scaling_min_freq";
public static final String CPU_GOV_BASE = "/sys/devices/system/cpu/cpufreq/";
public static final String CPU_VSEL = "/proc/overclock/mpu_opps";
public static final String CPU_VSEL_MAX = "/proc/overclock/max_vsel";
public static final String CPU_MAX_RATE = "/proc/overclock/max_rate";
public static final String CPU_FREQ_TABLE = "/proc/overclock/freq_table";
/* Used by; HotplugFragment */
public static final String HOTPLUG_PATH = "/sys/kernel/hotplug_control";
/* Used by; DefyPartsFragment */
public static final String PROP_CHARGE_LED_MODE = "persist.sys.charge_led";
public static final String PROP_TOUCH_POINTS = "persist.sys.multitouch";
public static final String PROP_BUTTON_BRIGHTNESS = "persist.sys.button_brightness";
/* Used by; GPUFragment */
public static final String GPU_CONTROL_ACTIVE = "/sys/kernel/gpu_control/gpu_control_active";
public static final String DISPLAY_COLOR ="/sys/class/misc/mDisplayControl/display_brightness_value";
public static final String GPU_FREQ_NEXUS4_VALUES = "/sys/class/kgsl/kgsl-3d0/gpu_available_frequencies";
public static final String GPU_GOV_BASE = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/";
public static final String SWEEP2WAKE = "/sys/android_touch/sweep2wake";
public static final String DOUBLETAP2WAKE = "/sys/android_touch/doubletap2wake";
public static final String COLOR_CONTROL = "/sys/devices/platform/kcal_ctrl.0/kcal";
/* Used by; GPUGovernorFragment */
public static final String GPU_GOV_PATH = "/sys/module/msm_kgsl_core/parameters";
/* Used by; MemoryDalvikFragment */
public static final String DALVIK_TWEAK = "/proc/sys/vm";
/* Used by; MemoryFragment */
public static final String FSYNC = "/sys/module/sync/parameters/fsync_enabled";
public static final String DYANMIC_FSYNC = "/sys/kernel/dyn_fsync/Dyn_fsync_active";
public static final String CMDLINE_ZACHE = "/system/bootstrap/2nd-boot/cmdline";
public static final String WRITEBACK = "/sys/devices/virtual/misc/writeback/writeback_enabled";
public static final String LOW_MEM = "/system/build.prop";
public static final String FILENAME = "firstrun_trim";
public static final String GOV_IO_PARAMETER = "/sys/block/mmcblk0/queue/iosched";
/* Used by; MiscSettingsFragment */
public static final String MISC_VIBRATOR_CONTROL = "/sys/devices/virtual/timed_output/vibrator";
public static final String MISC_THERMAL_CONTROL = "/sys/module/msm_thermal/parameters";
+ public static final String MISC_VIBRATOR_CONTROL_FILE = "/sys/devices/virtual/timed_output/vibrator/vtg_level";
+ public static final String MISC_THERMAL_CONTROL_FILE = "/sys/module/msm_thermal/parameters/temp_threshold";
+
/* Used by; ProfileFragment */
public static final String sharedPrefsPath = "/data/data/com.aero.control/shared_prefs/";
/* Used by; StatisticsFragment */
public static final String[] color_code = {
"#009688", /* Turquoise */
"#ff5722", /* Orange */
"#8bc34a", /* Midnight Blue */
"#03a9f4", /* Nephritis */
"#e51c23", /* Monza */
"#00bcd4", /* Wisteria */
"#607d8b", /* Peter River */
"#e91e63", /* Pomegrante */
};
public static final String TIME_IN_STATE_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state";
public static final String OFFSET_STAT = "/data/data/com.aero.control/files/offset_stat";
public static final Typeface kitkatFont = Typeface.create("sans-serif-condensed", Typeface.NORMAL);
/* Used by; UpdaterFragment */
public static final String zImage = "/system/bootstrap/2nd-boot/zImage";
/* Used by; VoltageFrament */
public static final String VOLTAGE_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table";
}
diff --git a/AeroControl/src/com/aero/control/helpers/settingsHelper.java b/AeroControl/src/com/aero/control/helpers/settingsHelper.java
index 3f3870f..311a13a 100644
--- a/AeroControl/src/com/aero/control/helpers/settingsHelper.java
+++ b/AeroControl/src/com/aero/control/helpers/settingsHelper.java
@@ -1,502 +1,502 @@
package com.aero.control.helpers;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.aero.control.AeroActivity;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
/**
* Created by Alexander Christ on 05.01.14.
*/
public class settingsHelper {
public static final String PREF_CURRENT_GOV_AVAILABLE = "set_governor";
public static final String PREF_CPU_MAX_FREQ = "max_frequency";
public static final String PREF_CPU_MIN_FREQ = "min_frequency";
public static final String PREF_CPU_COMMANDS = "cpu_commands";
public static final String PREF_CURRENT_GPU_GOV_AVAILABLE = "set_gpu_governor";
public static final String PREF_GPU_FREQ_MAX = "gpu_max_freq";
public static final String PREF_GPU_CONTROL_ACTIVE = "gpu_control_enable";
public static final String PREF_DISPLAY_COLOR = "display_control";
public static final String PREF_SWEEP2WAKE = "sweeptowake";
public static final String PREF_DOUBLETAP2WAKE = "doubletaptowake";
public static final String PREF_GOV_IO_FILE = "io_scheduler_list";
public static final String PREF_DYANMIC_FSYNC = "dynFsync";
public static final String PREF_FSYNC = "fsync";
public static final String PREF_WRITEBACK = "writeback";
private SharedPreferences prefs;
private String gpu_file;
public static final int mNumCpus = Runtime.getRuntime().availableProcessors();
private static final shellHelper shell = new shellHelper();
private static final shellHelper shellPara = new shellHelper();
private static final ArrayList<String> defaultProfile = new ArrayList<String>();
public void setSettings(final Context context, final String Profile) {
new Thread(new Runnable() {
@Override
public void run() {
if (AeroActivity.files == null)
AeroActivity.files = new FilePath();
// We need to sleep here for a short while for the kernel
if (shell.setOverclockAddress()) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.e("Aero", "Something went really wrong...", e);
}
}
// Apply all our saved values;
doBackground(context, Profile);
}
}).start();
}
private void doBackground(Context context, String Profile) {
if (Profile == null)
prefs = PreferenceManager.getDefaultSharedPreferences(context);
else
prefs = context.getSharedPreferences(Profile, Context.MODE_PRIVATE);
// GET CPU VALUES AND COMMANDS FROM PREFERENCES
String cpu_max = prefs.getString(PREF_CPU_MAX_FREQ, null);
String cpu_min = prefs.getString(PREF_CPU_MIN_FREQ, null);
String cpu_gov = prefs.getString(PREF_CURRENT_GOV_AVAILABLE, null);
// Overclocking....
try {
HashSet<String> hashcpu_cmd = (HashSet<String>) prefs.getStringSet(PREF_CPU_COMMANDS, null);
if (hashcpu_cmd != null) {
for (String cmd : hashcpu_cmd) {
shell.queueWork(cmd);
}
}
} catch (ClassCastException e) {
// HashSet didn't work, so we make a fallback;
String cpu_cmd = prefs.getString(PREF_CPU_COMMANDS, null);
if (cpu_cmd != null) {
// Since we can't cast to hashmap, little workaround;
String[] array = cpu_cmd.substring(1, cpu_cmd.length() - 1).split(",");
for (String cmd : array) {
shell.queueWork(cmd);
}
}
}
String voltage = prefs.getString("voltage_values", null);
if (voltage != null)
shell.queueWork("echo " + voltage + " > " + AeroActivity.files.VOLTAGE_PATH);
// GET GPU VALUES FROM PREFERENCES
String gpu_gov = prefs.getString(PREF_CURRENT_GPU_GOV_AVAILABLE, null);
String gpu_max = prefs.getString(PREF_GPU_FREQ_MAX, null);
String display_color = prefs.getString(PREF_DISPLAY_COLOR, null);
Boolean gpu_enb = prefs.getString(PREF_GPU_CONTROL_ACTIVE, "0").equals("1") ? true : false;
Boolean sweep = prefs.getString(PREF_SWEEP2WAKE, "0").equals("1") ? true : false;
Boolean doubletap = prefs.getString(PREF_DOUBLETAP2WAKE, "0").equals("1") ? true : false;
String rgbValues = prefs.getString("rgbValues", null);
// GET MEM VALUES FROM PREFERENCES
String mem_ios = prefs.getString(PREF_GOV_IO_FILE, null);
Boolean mem_dfs = prefs.getString(PREF_DYANMIC_FSYNC, "0").equals("1") ? true : false;
Boolean mem_wrb = prefs.getString(PREF_WRITEBACK, "0").equals("1") ? true : false;
Boolean mem_fsy = prefs.getString(PREF_FSYNC, "Y").equals("Y") ? true : false;
// Get Misc Settings from preferences
- String misc_vib = prefs.getString(AeroActivity.files.MISC_VIBRATOR_CONTROL, null);
- String misc_thm = prefs.getString(AeroActivity.files.MISC_THERMAL_CONTROL, null);
+ String misc_vib = prefs.getString(AeroActivity.files.MISC_VIBRATOR_CONTROL_FILE, null);
+ String misc_thm = prefs.getString(AeroActivity.files.MISC_THERMAL_CONTROL_FILE, null);
// ADD CPU COMMANDS TO THE ARRAY
ArrayList<String> governorSettings = new ArrayList<String>();
String max_freq = shell.getInfo(AeroActivity.files.CPU_BASE_PATH + 0 + AeroActivity.files.CPU_MAX_FREQ);
String min_freq = shell.getInfo(AeroActivity.files.CPU_BASE_PATH + 0 + AeroActivity.files.CPU_MIN_FREQ);
for (int k = 0; k < mNumCpus; k++) {
if (cpu_max != null) {
shell.queueWork("echo 1 > " + AeroActivity.files.CPU_BASE_PATH + k + "/online");
shell.queueWork("chmod 0666 " + AeroActivity.files.CPU_BASE_PATH + k + AeroActivity.files.CPU_MAX_FREQ);
if (Profile != null) {
defaultProfile.add("echo 1 > " + AeroActivity.files.CPU_BASE_PATH + k + "/online");
defaultProfile.add("echo " + max_freq + " > " + AeroActivity.files.CPU_BASE_PATH + k + AeroActivity.files.CPU_MAX_FREQ);
}
shell.queueWork("echo " + cpu_max + " > " + AeroActivity.files.CPU_BASE_PATH + k + AeroActivity.files.CPU_MAX_FREQ);
}
if (cpu_min != null) {
shell.queueWork("echo 1 > " + AeroActivity.files.CPU_BASE_PATH + k + "/online");
shell.queueWork("chmod 0666 " + AeroActivity.files.CPU_BASE_PATH + k + AeroActivity.files.CPU_MIN_FREQ);
if (Profile != null) {
defaultProfile.add("echo 1 > " + AeroActivity.files.CPU_BASE_PATH + k + "/online");
defaultProfile.add("echo " + min_freq + " > " + AeroActivity.files.CPU_BASE_PATH + k + AeroActivity.files.CPU_MIN_FREQ);
}
shell.queueWork("echo " + cpu_min + " > " + AeroActivity.files.CPU_BASE_PATH + k + AeroActivity.files.CPU_MIN_FREQ);
}
if (cpu_gov != null) {
shell.queueWork("chmod 0666 " + AeroActivity.files.CPU_BASE_PATH + k + AeroActivity.files.CURRENT_GOV_AVAILABLE);
/*
* Needs to be executed first, otherwise we would get a NullPointer
* For safety reasons we sleep this thread later
*/
if (Profile != null) {
defaultProfile.add("echo 1 > " + AeroActivity.files.CPU_BASE_PATH + k + "/online");
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.CPU_BASE_PATH + k +
AeroActivity.files.CURRENT_GOV_AVAILABLE) + " > " + AeroActivity.files.CPU_BASE_PATH +
k + AeroActivity.files.CURRENT_GOV_AVAILABLE);
}
shell.queueWork("echo 1 > " + AeroActivity.files.CPU_BASE_PATH + k + "/online");
shell.queueWork("echo " + cpu_gov + " > " + AeroActivity.files.CPU_BASE_PATH + k + AeroActivity.files.CURRENT_GOV_AVAILABLE);
}
}
if (mem_ios != null) {
governorSettings.add("chmod 0666 " + AeroActivity.files.GOV_IO_FILE);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfoString(shell.getInfo(AeroActivity.files.GOV_IO_FILE)) + " > " + AeroActivity.files.GOV_IO_FILE);
governorSettings.add("echo " + mem_ios + " > " + AeroActivity.files.GOV_IO_FILE);
}
if (cpu_gov != null || mem_ios != null) {
// Seriously, we need to set this first because of dependencies;
shell.setRootInfo(governorSettings.toArray(new String[0]));
}
/* GPU Governor */
if (gpu_gov != null) {
shell.queueWork("chmod 0666 " + AeroActivity.files.GPU_GOV_BASE + "governor");
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.GPU_GOV_BASE + "governor") + " > " + AeroActivity.files.GPU_GOV_BASE + "governor");
shell.queueWork("echo " + gpu_gov + " > " + AeroActivity.files.GPU_GOV_BASE + "governor");
}
// ADD GPU COMMANDS TO THE ARRAY
if (gpu_max != null) {
for (String a : AeroActivity.files.GPU_FILES) {
if (new File(a).exists()) {
gpu_file = a;
break;
}
}
if (gpu_file != null) {
shell.queueWork("chmod 0666 " + gpu_file);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(gpu_file) + " > " + gpu_file);
shell.queueWork("echo " + gpu_max + " > " + gpu_file);
}
}
if(new File(AeroActivity.files.GPU_CONTROL_ACTIVE).exists()) {
shell.queueWork("chmod 0666 " + AeroActivity.files.GPU_CONTROL_ACTIVE);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.GPU_CONTROL_ACTIVE) + " > " + AeroActivity.files.GPU_CONTROL_ACTIVE);
shell.queueWork("echo " + (gpu_enb ? "1" : "0") + " > " + AeroActivity.files.GPU_CONTROL_ACTIVE);
}
if(new File(AeroActivity.files.SWEEP2WAKE).exists()) {
shell.queueWork("chmod 0666 " + AeroActivity.files.SWEEP2WAKE);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.SWEEP2WAKE) + " > " + AeroActivity.files.SWEEP2WAKE);
shell.queueWork("echo " + (sweep ? "1" : "0") + " > " + AeroActivity.files.SWEEP2WAKE);
}
if(new File(AeroActivity.files.DOUBLETAP2WAKE).exists()) {
shell.queueWork("chmod 0666 " + AeroActivity.files.DOUBLETAP2WAKE);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.DOUBLETAP2WAKE) + " > " + AeroActivity.files.DOUBLETAP2WAKE);
shell.queueWork("echo " + (doubletap ? "1" : "0") + " > " + AeroActivity.files.DOUBLETAP2WAKE);
}
if (display_color != null) {
shell.queueWork("chmod 0666 " + AeroActivity.files.DISPLAY_COLOR);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.DISPLAY_COLOR) + " > " + AeroActivity.files.DISPLAY_COLOR);
shell.queueWork("echo " + display_color + " > " + AeroActivity.files.DISPLAY_COLOR);
}
if (rgbValues != null) {
shell.queueWork("chmod 0666 " + AeroActivity.files.COLOR_CONTROL);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.COLOR_CONTROL) + " > " + AeroActivity.files.COLOR_CONTROL);
shell.queueWork("echo " + rgbValues + " > " + AeroActivity.files.COLOR_CONTROL);
}
// ADD MEM COMMANDS TO THE ARRAY
if (new File(AeroActivity.files.DYANMIC_FSYNC).exists()) {
shell.queueWork("chmod 0666 " + AeroActivity.files.DYANMIC_FSYNC);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.DYANMIC_FSYNC) + " > " + AeroActivity.files.DYANMIC_FSYNC);
shell.queueWork("echo " + (mem_dfs ? "1" : "0") + " > " + AeroActivity.files.DYANMIC_FSYNC);
}
if (new File(AeroActivity.files.WRITEBACK).exists()) {
shell.queueWork("chmod 0666 " + AeroActivity.files.WRITEBACK);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.WRITEBACK) + " > " + AeroActivity.files.WRITEBACK);
shell.queueWork("echo " + (mem_wrb ? "1" : "0") + " > " + AeroActivity.files.WRITEBACK);
}
if (new File(AeroActivity.files.FSYNC).exists()) {
shell.queueWork("chmod 0666 " + AeroActivity.files.FSYNC);
if (Profile != null)
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.FSYNC) + " > " + AeroActivity.files.FSYNC);
shell.queueWork("echo " + (mem_fsy ? "Y" : "N") + " > " + AeroActivity.files.FSYNC);
}
// Add misc commands to array
if (misc_vib != null) {
- shell.queueWork("chmod 0666 " + AeroActivity.files.MISC_VIBRATOR_CONTROL);
+ shell.queueWork("chmod 0666 " + AeroActivity.files.MISC_VIBRATOR_CONTROL_FILE);
if (Profile != null)
- defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.MISC_VIBRATOR_CONTROL) + " > " + AeroActivity.files.MISC_VIBRATOR_CONTROL);
+ defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.MISC_VIBRATOR_CONTROL_FILE) + " > " + AeroActivity.files.MISC_VIBRATOR_CONTROL_FILE);
- shell.queueWork("echo " + misc_vib + " > " + AeroActivity.files.MISC_VIBRATOR_CONTROL);
+ shell.queueWork("echo " + misc_vib + " > " + AeroActivity.files.MISC_VIBRATOR_CONTROL_FILE);
}
if (misc_thm != null) {
- shell.queueWork("chmod 0666 " + AeroActivity.files.MISC_THERMAL_CONTROL);
+ shell.queueWork("chmod 0666 " + AeroActivity.files.MISC_THERMAL_CONTROL_FILE);
if (Profile != null)
- defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.MISC_THERMAL_CONTROL) + " > " + AeroActivity.files.MISC_THERMAL_CONTROL);
+ defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.MISC_THERMAL_CONTROL_FILE) + " > " + AeroActivity.files.MISC_THERMAL_CONTROL_FILE);
- shell.queueWork("echo " + misc_thm + " > " + AeroActivity.files.MISC_THERMAL_CONTROL);
+ shell.queueWork("echo " + misc_thm + " > " + AeroActivity.files.MISC_THERMAL_CONTROL_FILE);
}
// EXECUTE ALL THE COMMANDS COLLECTED
shell.execWork();
shell.flushWork();
// Sleep here to avoid race conditions;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.e("Aero", "Something interrupted the main Thread, try again.", e);
}
try {
shellPara.queueWork("sleep 1");
if (mem_ios != null) {
String completeIOSchedulerSettings[] = shellPara.getDirInfo(AeroActivity.files.GOV_IO_PARAMETER, true);
/* IO Scheduler Specific Settings at boot */
for (String b : completeIOSchedulerSettings) {
final String ioSettings = prefs.getString(AeroActivity.files.GOV_IO_PARAMETER + "/" + b, null);
if (ioSettings != null) {
shellPara.queueWork("chmod 0666 " + AeroActivity.files.GOV_IO_PARAMETER + "/" + b);
if (Profile != null)
defaultProfile.add("echo " + shellPara.getInfo(AeroActivity.files.GOV_IO_PARAMETER + "/" + b) + " > " + AeroActivity.files.GOV_IO_PARAMETER + "/" + b);
shellPara.queueWork("echo " + ioSettings + " > " + AeroActivity.files.GOV_IO_PARAMETER + "/" + b);
//Log.e("Aero", "Output: " + "echo " + ioSettings + " > " + GOV_IO_PARAMETER + "/" + b);
}
}
}
final String completeVMSettings[] = shellPara.getDirInfo(AeroActivity.files.DALVIK_TWEAK, true);
/* VM specific settings at boot */
for (String c : completeVMSettings) {
final String vmSettings = prefs.getString(AeroActivity.files.DALVIK_TWEAK + "/" + c, null);
if (vmSettings != null) {
shellPara.queueWork("chmod 0666 " + AeroActivity.files.DALVIK_TWEAK + "/" + c);
if (Profile != null)
defaultProfile.add("echo " + shellPara.getInfo(AeroActivity.files.DALVIK_TWEAK + "/" + c) + " > " + AeroActivity.files.DALVIK_TWEAK + "/" + c);
shell.queueWork("echo " + vmSettings + " > " + AeroActivity.files.DALVIK_TWEAK + "/" + c);
//Log.e("Aero", "Output: " + "echo " + vmSettings + " > " + DALVIK_TWEAK + "/" + c);
}
}
if (new File(AeroActivity.files.HOTPLUG_PATH). exists()) {
final String completeHotplugSettings[] = shellPara.getDirInfo(AeroActivity.files.HOTPLUG_PATH, true);
/* Hotplug specific settings at boot */
for (String d : completeHotplugSettings) {
final String hotplugSettings = prefs.getString(AeroActivity.files.HOTPLUG_PATH + "/" + d, null);
if (hotplugSettings != null) {
shellPara.queueWork("chmod 0666 " + AeroActivity.files.HOTPLUG_PATH + "/" + d);
if (Profile != null)
defaultProfile.add("echo " + shellPara.getInfo(AeroActivity.files.HOTPLUG_PATH + "/" + d) + " > " + AeroActivity.files.HOTPLUG_PATH + "/" + d);
shellPara.queueWork("echo " + hotplugSettings + " > " + AeroActivity.files.HOTPLUG_PATH + "/" + d);
//Log.e("Aero", "Output: " + "echo " + hotplugSettings + " > " + PREF_HOTPLUG + "/" + d);
}
}
}
if (new File(AeroActivity.files.GPU_GOV_PATH).exists()) {
final String completeGPUGovSettings[] = shellPara.getDirInfo(AeroActivity.files.GPU_GOV_PATH, true);
/* GPU Governor specific settings at boot */
for (String e : completeGPUGovSettings) {
final String gpugovSettings = prefs.getString(AeroActivity.files.GPU_GOV_PATH + "/" + e, null);
if (gpugovSettings != null) {
shellPara.queueWork("chmod 0666 " + AeroActivity.files.GPU_GOV_PATH + "/" + e);
if (Profile != null)
defaultProfile.add("echo " + shellPara.getInfo(AeroActivity.files.GPU_GOV_PATH + "/" + e) + " > " + AeroActivity.files.GPU_GOV_PATH + "/" + e);
shellPara.queueWork("echo " + gpugovSettings + " > " + AeroActivity.files.GPU_GOV_PATH + "/" + e);
//Log.e("Aero", "Output: " + "echo " + gpugovSettings + " > " + PREF_GPU_GOV + "/" + e);
}
}
}
if (cpu_gov != null) {
final String completeGovernorSettingList[] = shellPara.getDirInfo(AeroActivity.files.CPU_GOV_BASE + cpu_gov, true);
/* Governor Specific Settings at boot */
if (completeGovernorSettingList != null) {
for (String b : completeGovernorSettingList) {
final String governorSetting = prefs.getString(AeroActivity.files.CPU_GOV_BASE + cpu_gov + "/" + b, null);
if (governorSetting != null) {
shellPara.queueWork("sleep 1");
shellPara.queueWork("chmod 0666 " + AeroActivity.files.CPU_GOV_BASE + cpu_gov + "/" + b);
if (Profile != null) {
defaultProfile.add("sleep 1");
defaultProfile.add("echo " + shell.getInfo(AeroActivity.files.CPU_GOV_BASE + cpu_gov + "/" + b) + " > " + AeroActivity.files.CPU_GOV_BASE + cpu_gov + "/" + b);
}
shellPara.queueWork("echo " + governorSetting + " > " + AeroActivity.files.CPU_GOV_BASE + cpu_gov + "/" + b);
//Log.e("Aero", "Output: " + "echo " + governorSetting + " > " + CPU_GOV_BASE + cpu_gov + "/" + b);
}
}
}
}
/* GPU Governor Parameters */
if (gpu_gov != null) {
final String completeGPUGovernorSetting[] = shell.getDirInfo(AeroActivity.files.GPU_GOV_BASE + gpu_gov, true);
/* Governor Specific Settings at boot */
for (String b : completeGPUGovernorSetting) {
final String governorSetting = prefs.getString(AeroActivity.files.GPU_GOV_BASE + gpu_gov + "/" + b, null);
if (governorSetting != null) {
shellPara.queueWork("chmod 0666 " + AeroActivity.files.GPU_GOV_BASE + gpu_gov + "/" + b);
if (Profile != null)
defaultProfile.add("echo " + shellPara.getInfo(AeroActivity.files.GPU_GOV_BASE + gpu_gov + "/" + b) + " > " + AeroActivity.files.GPU_GOV_BASE + gpu_gov + "/" + b);
shellPara.queueWork("echo " + governorSetting + " > " + AeroActivity.files.GPU_GOV_BASE + gpu_gov + "/" + b);
Log.e("Aero", "Output: " + "echo " + governorSetting + " > " + AeroActivity.files.GPU_GOV_BASE + gpu_gov + "/" + b);
}
}
}
} catch (NullPointerException e) {
Log.e("Aero", "This shouldn't happen.. Maybe a race condition. ", e);
}
// EXECUTE ALL THE COMMANDS COLLECTED
shellPara.execWork();
shellPara.flushWork();
}
public void executeDefault() {
String[] defaultValues = defaultProfile.toArray(new String[0]);
shell.setRootInfo(defaultValues);
defaultProfile.clear();
}
}
| false | false | null | null |
diff --git a/blocks/BaseBlock.java b/blocks/BaseBlock.java
index 1b81a0a..0e0f4c2 100644
--- a/blocks/BaseBlock.java
+++ b/blocks/BaseBlock.java
@@ -1,25 +1,23 @@
package mods.nordwest.blocks;
import mods.nordwest.common.NordWest;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
public class BaseBlock extends Block {
public BaseBlock(int par1, Material par2Material) {
super(par1, par2Material);
setCreativeTab(NordWest.tabNord);
// TODO Auto-generated constructor stub
}
@Override
public void registerIcons(IconRegister iconRegister) {
blockIcon = iconRegister.registerIcon("nordwest:" + this.getUnlocalizedName2());
}
- public void onBlockAdded(World world, int x, int y, int z, EntityPlayer player) {
- }
}
\ No newline at end of file
diff --git a/blocks/BlockCandle.java b/blocks/BlockCandle.java
deleted file mode 100644
index d91ca1b..0000000
--- a/blocks/BlockCandle.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package mods.nordwest.blocks;
-
-public class BlockCandle {
-
-}
| false | false | null | null |
diff --git a/IliConnect/src/com/android/iliConnect/dataproviders/RemoteDataProvider.java b/IliConnect/src/com/android/iliConnect/dataproviders/RemoteDataProvider.java
index 28f52c8..b0c6205 100644
--- a/IliConnect/src/com/android/iliConnect/dataproviders/RemoteDataProvider.java
+++ b/IliConnect/src/com/android/iliConnect/dataproviders/RemoteDataProvider.java
@@ -1,232 +1,237 @@
package com.android.iliConnect.dataproviders;
import static android.content.Context.CONNECTIVITY_SERVICE;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.accounts.NetworkErrorException;
import android.app.ProgressDialog;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import com.android.iliConnect.MainActivity;
import com.android.iliConnect.MainTabView;
import com.android.iliConnect.MessageBuilder;
import com.android.iliConnect.Exceptions.NetworkException;
import com.android.iliConnect.message.IliOnClickListener;
import com.android.iliConnect.ssl.HttpsClient;
public class RemoteDataProvider extends AsyncTask<String, Integer, Exception> implements IliOnClickListener {
private Object instance = this;
private boolean doLogout = false;
private List<NameValuePair> nameValuePairs;
private ProgressDialog pDialog;
public RemoteDataProvider() {
}
public RemoteDataProvider(ProgressDialog pDialog) {
this.pDialog = pDialog;
}
public RemoteDataProvider(List<NameValuePair> nameValuePairs, ProgressDialog pDialog) {
this.pDialog = pDialog;
this.nameValuePairs = nameValuePairs;
}
public RemoteDataProvider(List<NameValuePair> nameValuePairs) {
this.nameValuePairs = nameValuePairs;
}
@Override
protected Exception doInBackground(String... sUrl) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpClient httpsClient = HttpsClient.createHttpsClient(httpclient);
HttpPost httppost = new HttpPost(sUrl[0]);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", MainActivity.instance.localDataProvider.auth.user_id));
nameValuePairs.add(new BasicNameValuePair("password", MainActivity.instance.localDataProvider.auth.password));
if (this.nameValuePairs != null) {
nameValuePairs.addAll(this.nameValuePairs);
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpsClient.execute(httppost);
StatusLine status = response.getStatusLine();
if(status.getStatusCode() == 404 || status.getStatusCode() == 401) {
throw new HttpException(status.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
// String result = convertStreamToString(instream);
String targetName = MainActivity.instance.localDataProvider.remoteDataFileName;
if (sUrl.length > 1)
targetName = sUrl[1];
// download the file
InputStream input = instream;
String s = convertStreamToString(instream);
if (s.contains("ACCESS_DENIED"))
throw new AuthException(s);
BufferedWriter out = new BufferedWriter(new FileWriter(MainActivity.instance.getFilesDir() + "/" + targetName));
out.write(s);
out.flush();
out.close();
input.close();
}
} catch (Exception e) {
return e;
}
return null;
}
@Override
protected void onPreExecute() {
MainActivity.instance.localDataProvider.isUpdating = true;
if (pDialog != null)
pDialog.show();
};
@Override
protected void onProgressUpdate(Integer... values) {
// increment progress bar by progress value
if (pDialog != null)
pDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(Exception e) {
// super.onPostExecute(result);
if (e != null) {
String errMsg = null;
String errTtl = "Synchronisation fehlgeschlagen";
// Exceptions angepasst um DNS Fehler abzufangen.
- if (e instanceof UnknownHostException || e instanceof UnknownHostException || e instanceof NoHttpResponseException) {
+ if (e instanceof UnknownHostException) {
ConnectivityManager connManager = (ConnectivityManager) MainActivity.instance.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean logout = false;
if (wifi != null && wifi.isConnected()) {
logout = true;
} else if (mobile != null && mobile.isConnected()) {
logout = true;
}
if (logout) {
doLogout = true;
errMsg = "Es konnte keine Verbindung zum ILIAS-Server hergestellt werden. Bitte überprüfen Sie" +
" die Serveradresse und versuchen Sie es erneut.";
errTtl = "Verbindung fehlgeschlagen";
}
+ } else if ( e instanceof NoHttpResponseException || e instanceof HttpException) {
+ doLogout = true;
+ errMsg = "Es konnte keine Verbindung zum ILIAS-Server hergestellt werden. Bitte überprüfen Sie" +
+ " Ihre Internetverbindung und die Serveradresse und versuchen Sie es erneut.";
+ errTtl = "Verbindung fehlgeschlagen";
} else if (e instanceof AuthException) {
// Logout soll nach Bestätigung durchgeführt werden
doLogout = true;
MainActivity.instance.localDataProvider.deleteAuthentication();
errMsg = "Ihr Benutzername oder Kennwort ist falsch.";
} else {
errMsg = "Es ist ein Fehler während der Synchronisation aufgetreten.";
}
if (errMsg != null) {
//TODO: connection_failed
MessageBuilder.sync_exception(MainTabView.instance, errTtl, errMsg, (IliOnClickListener) instance);
}
}
else {
MainActivity.instance.localDataProvider.updateLocalData();
}
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
}
public String convertStreamToString(InputStream inputStream) throws IOException {
if (inputStream != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
inputStream.close();
}
return sb.toString();
} else {
return "";
}
}
public void onClickCoursePassword(String refID, String password) {
// TODO Auto-generated method stub
}
public void onClickJoinCourse(String refID, String courseName) {
// TODO Auto-generated method stub
}
public void onClickLeftCourse(String refID, String courseName) {
// TODO Auto-generated method stub
}
public void onClickMessageBox() {
// falls bei der Sync. die Benutzerdaten falsch sind, alte Daten löschen
if(doLogout) {
doLogout = true;
MainActivity.instance.logout();
}
}
}
| false | false | null | null |
diff --git a/src/main/java/org/neo4j/util/IndexedNeoCollection.java b/src/main/java/org/neo4j/util/IndexedNeoCollection.java
index a625435..4b35c62 100644
--- a/src/main/java/org/neo4j/util/IndexedNeoCollection.java
+++ b/src/main/java/org/neo4j/util/IndexedNeoCollection.java
@@ -1,217 +1,218 @@
package org.neo4j.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import org.neo4j.api.core.Direction;
import org.neo4j.api.core.NeoService;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Relationship;
import org.neo4j.api.core.Transaction;
import org.neo4j.util.btree.BTree.RelTypes;
import org.neo4j.util.sortedtree.SortedTree;
+import org.neo4j.commons.iterator.IterableWrapper;
public class IndexedNeoCollection<T extends NodeWrapper>
extends AbstractNeoSet<T>
{
private Node rootNode;
private Class<T> instanceClass;
private Comparator<T> comparator;
private SortedTree index;
public IndexedNeoCollection( NeoService neo, Node rootNode,
Comparator<T> comparator, Class<T> instanceClass )
{
super( neo );
this.rootNode = rootNode;
this.instanceClass = instanceClass;
this.comparator = comparator;
instantiateIndex();
}
private Node ensureTheresARoot()
{
Transaction tx = neo().beginTx();
try
{
Node result = null;
Relationship relationship = rootNode.getSingleRelationship(
RelTypes.TREE_ROOT, Direction.OUTGOING );
if ( relationship != null )
{
result = relationship.getOtherNode( rootNode );
}
else
{
result = neo().createNode();
rootNode.createRelationshipTo( result, RelTypes.TREE_ROOT );
}
tx.success();
return result;
}
finally
{
tx.finish();
}
}
private void instantiateIndex()
{
Transaction tx = neo().beginTx();
try
{
Node treeRootNode = ensureTheresARoot();
this.index = new SortedTree( neo(), treeRootNode,
new ComparatorWrapper( this.comparator ) );
tx.success();
}
finally
{
tx.finish();
}
}
protected Node rootNode()
{
return this.rootNode;
}
protected SortedTree index()
{
return this.index;
}
protected T instantiateItem( Node itemNode )
{
return NodeWrapperImpl.newInstance( instanceClass, neo(), itemNode );
}
public boolean add( T item )
{
return index().addNode( item.getUnderlyingNode() );
}
public void clear()
{
Transaction tx = neo().beginTx();
try
{
index().delete();
instantiateIndex();
tx.success();
}
finally
{
tx.finish();
}
}
public boolean contains( Object item )
{
T nodeItem = ( T ) item;
return index().containsNode( nodeItem.getUnderlyingNode() );
}
public boolean isEmpty()
{
return index().getSortedNodes().iterator().hasNext();
}
public Iterator<T> iterator()
{
Iterator<T> iterator = new IterableWrapper<T, Node>(
index().getSortedNodes() )
{
@Override
protected T underlyingObjectToObject( Node node )
{
return instantiateItem( node );
}
}.iterator();
return new TxIterator<T>( neo(), iterator );
}
public boolean remove( Object item )
{
T nodeItem = ( T ) item;
return index().removeNode( nodeItem.getUnderlyingNode() );
}
public boolean retainAll( Collection<?> items )
{
throw new UnsupportedOperationException( "Not implemented yet" );
}
public int size()
{
return toArray().length;
}
private <R> Collection<R> toCollection()
{
Transaction tx = neo().beginTx();
try
{
Collection<R> result = new ArrayList<R>();
for ( Node node : index().getSortedNodes() )
{
result.add( ( R ) instantiateItem( node ) );
}
tx.success();
return result;
}
finally
{
tx.finish();
}
}
public Object[] toArray()
{
return toCollection().toArray();
}
public <R> R[] toArray( R[] array )
{
return toCollection().toArray( array );
}
/**
* Since this collection creates a sub-root to the supplied collection
* root node, it will have to be explicitly deleted from outside when
* you don't want this collection to exist anymore.
*/
public void delete()
{
Transaction tx = neo().beginTx();
try
{
index().delete();
tx.success();
}
finally
{
tx.finish();
}
}
private class ComparatorWrapper implements Comparator<Node>
{
private Comparator<T> source;
ComparatorWrapper( Comparator<T> source )
{
this.source = source;
}
public int compare( Node o1, Node o2 )
{
// This is slow, I guess
return source.compare(
NodeWrapperImpl.newInstance( instanceClass, neo(), o1 ),
NodeWrapperImpl.newInstance( instanceClass, neo(), o2 ) );
}
}
}
diff --git a/src/main/java/org/neo4j/util/NeoPropertyArraySet.java b/src/main/java/org/neo4j/util/NeoPropertyArraySet.java
index 401775b..6d342de 100644
--- a/src/main/java/org/neo4j/util/NeoPropertyArraySet.java
+++ b/src/main/java/org/neo4j/util/NeoPropertyArraySet.java
@@ -1,210 +1,211 @@
package org.neo4j.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.neo4j.api.core.NeoService;
import org.neo4j.api.core.PropertyContainer;
import org.neo4j.api.core.Transaction;
+import org.neo4j.commons.iterator.CollectionWrapper;
/**
* This class uses the fact that node property values can be arrays.
* It looks at one property on a node as if it was a collection of values.
*
* @param <T> the type of values.
*/
public class NeoPropertyArraySet<T> extends AbstractNeoSet<T>
implements List<T>
{
private PropertyContainer container;
private String key;
private NeoUtil neoUtil;
public NeoPropertyArraySet( NeoService neo, PropertyContainer container,
String key )
{
super( neo );
this.neoUtil = new NeoUtil( neo );
this.container = container;
this.key = key;
}
protected NeoUtil neoUtil()
{
return this.neoUtil;
}
protected PropertyContainer container()
{
return this.container;
}
protected String key()
{
return this.key;
}
public boolean add( T o )
{
return neoUtil().addValueToArray( container(), key(), o );
}
public void clear()
{
neoUtil().removeProperty( container(), key() );
}
private List<Object> values()
{
return neoUtil().getPropertyValues( container(), key() );
}
private void setValues( Collection<?> collection )
{
neoUtil().setProperty( container(), key(),
neoUtil().asNeoProperty( collection ) );
}
public boolean contains( Object o )
{
return values().contains( o );
}
public boolean isEmpty()
{
return values().isEmpty();
}
public Iterator<T> iterator()
{
return new CollectionWrapper<T, Object>(
neoUtil().getPropertyValues( container(), key() ) )
{
@Override
protected Object objectToUnderlyingObject( T object )
{
return object;
}
@Override
protected T underlyingObjectToObject( Object object )
{
return ( T ) object;
}
}.iterator();
}
public boolean remove( Object o )
{
return neoUtil().removeValueFromArray( container(), key(), o );
}
public boolean retainAll( Collection<?> c )
{
Transaction tx = neoUtil().neo().beginTx();
try
{
Collection<Object> values = values();
boolean altered = values.retainAll( c );
if ( altered )
{
if ( values.isEmpty() )
{
container().removeProperty( key() );
}
else
{
container().setProperty( key(),
neoUtil().asNeoProperty( values ) );
}
}
tx.success();
return altered;
}
finally
{
tx.finish();
}
}
public int size()
{
return values().size();
}
public Object[] toArray()
{
return values().toArray();
}
public <R> R[] toArray( R[] a )
{
return values().toArray( a );
}
public T set( int index, T value )
{
List<Object> values = values();
T oldValue = ( T ) values.set( index, value );
setValues( values );
return oldValue;
}
public T remove( int index )
{
List<Object> values = values();
T oldValue = ( T ) values.remove( index );
setValues( values );
return oldValue;
}
public int lastIndexOf( Object value )
{
return values().lastIndexOf( value );
}
public int indexOf( Object value )
{
return values().indexOf( value );
}
public boolean addAll( int index, Collection collection )
{
List<Object> values = values();
boolean result = values.addAll( collection );
if ( result )
{
setValues( values );
}
return result;
}
public void add( int index, T item )
{
List<Object> values = values();
values.add( index, item );
setValues( values );
}
public ListIterator<T> listIterator()
{
throw new UnsupportedOperationException();
}
public ListIterator<T> listIterator( int index )
{
throw new UnsupportedOperationException();
}
public List<T> subList( int start, int end )
{
throw new UnsupportedOperationException();
}
public T get( int index )
{
return ( T ) values().get( index );
}
}
diff --git a/src/main/java/org/neo4j/util/NeoRelationshipSet.java b/src/main/java/org/neo4j/util/NeoRelationshipSet.java
index c9d9bf1..1a20631 100644
--- a/src/main/java/org/neo4j/util/NeoRelationshipSet.java
+++ b/src/main/java/org/neo4j/util/NeoRelationshipSet.java
@@ -1,370 +1,372 @@
package org.neo4j.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.neo4j.api.core.Direction;
import org.neo4j.api.core.NeoService;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Relationship;
import org.neo4j.api.core.RelationshipType;
import org.neo4j.api.core.Transaction;
+import org.neo4j.commons.iterator.FilteringIterator;
+import org.neo4j.commons.iterator.IteratorWrapper;
/**
* A {@link Set} implemented with neo.
* @author mattias
*
* @param <T> the type of objects in the set.
*/
public abstract class NeoRelationshipSet<T> extends AbstractNeoSet<T>
implements Set<T>
{
private Node node;
private RelationshipType type;
private Direction direction;
/**
* @param node the {@link Node} to act as the collection.
* @param type the relationship type to use internally for each object.
*/
public NeoRelationshipSet( NeoService neo, Node node,
RelationshipType type )
{
this( neo, node, type, Direction.OUTGOING );
}
/**
* @param node the {@link Node} to act as the collection.
* @param direction the direction to use for the relationships.
* @param type the relationship type to use internally for each object.
*/
public NeoRelationshipSet( NeoService neo, Node node, RelationshipType type,
Direction direction )
{
super( neo );
if ( direction == null || direction == Direction.BOTH )
{
throw new IllegalArgumentException(
"Only OUTGOING and INCOMING direction is allowed, since " +
"this is a read/write collection" );
}
this.node = node;
this.type = type;
this.direction = direction;
}
protected Node getUnderlyingNode()
{
return this.node;
}
protected RelationshipType getRelationshipType()
{
return this.type;
}
protected Direction getDirection()
{
return direction;
}
protected Direction getInverseDirection()
{
return getDirection().reverse();
}
protected boolean directionIsOut()
{
return getDirection() == Direction.OUTGOING;
}
public boolean add( T item )
{
Transaction tx = neo().beginTx();
try
{
if ( contains( item ) )
{
return false;
}
Node otherNode = getNodeFromItem( item );
Node startNode = directionIsOut() ? node : otherNode;
Node endNode = directionIsOut() ? otherNode : node;
Relationship relationship =
startNode.createRelationshipTo( endNode, type );
itemAdded( item, relationship );
tx.success();
return true;
}
finally
{
tx.finish();
}
}
protected void itemAdded( T item, Relationship relationship )
{
}
protected abstract Node getNodeFromItem( Object item );
public void clear()
{
Transaction tx = neo().beginTx();
try
{
Iterator<Relationship> itr = getAllRelationships();
while ( itr.hasNext() )
{
removeItem( itr.next() );
}
tx.success();
}
finally
{
tx.finish();
}
}
public boolean contains( Object item )
{
Transaction tx = neo().beginTx();
try
{
boolean result = findRelationship( item ) != null;
tx.success();
return result;
}
finally
{
tx.finish();
}
}
protected boolean shouldIncludeRelationship( Relationship rel )
{
return true;
}
protected Iterator<Relationship> getAllRelationships()
{
return new FilteringIterator<Relationship>(
node.getRelationships( type, getDirection() ).iterator() )
{
@Override
protected boolean passes( Relationship item )
{
return shouldIncludeRelationship( item );
}
};
}
protected Relationship findRelationship( Object item )
{
Node otherNode = getNodeFromItem( item );
Relationship result = null;
for ( Relationship rel : otherNode.getRelationships(
type, getInverseDirection() ) )
{
if ( !shouldIncludeRelationship( rel ) )
{
continue;
}
if ( rel.getOtherNode( otherNode ).equals( node ) )
{
result = rel;
break;
}
}
return result;
}
public boolean isEmpty()
{
Transaction tx = neo().beginTx();
try
{
return !getAllRelationships().hasNext();
}
finally
{
tx.finish();
}
}
public Iterator<T> iterator()
{
Transaction tx = neo().beginTx();
try
{
Iterator<T> result = new IteratorWrapper<T, Relationship>(
getAllRelationships() )
{
@Override
protected T underlyingObjectToObject( Relationship rel )
{
return newObject( rel.getOtherNode(
NeoRelationshipSet.this.node ), rel );
}
};
tx.success();
return result;
}
finally
{
tx.finish();
}
}
protected void removeItem( Relationship rel )
{
rel.delete();
}
public boolean remove( Object item )
{
Transaction tx = neo().beginTx();
try
{
Relationship rel = findRelationship( item );
boolean changed = false;
if ( rel != null )
{
removeItem( rel );
changed = true;
}
tx.success();
return changed;
}
finally
{
tx.finish();
}
}
public boolean retainAll( Collection<?> items )
{
Transaction tx = neo().beginTx();
try
{
Collection<Relationship> relationships =
new HashSet<Relationship>();
Iterator<Relationship> allRelationships = getAllRelationships();
while ( allRelationships.hasNext() )
{
relationships.add( allRelationships.next() );
}
for ( Object item : items )
{
Relationship rel = findRelationship( item );
if ( rel != null )
{
relationships.remove( rel );
}
}
Collection<T> itemsToRemove = new HashSet<T>();
for ( Relationship rel : relationships )
{
itemsToRemove.add( newObject( getOtherNode( rel ), rel ) );
}
boolean result = this.removeAll( itemsToRemove );
tx.success();
return result;
}
finally
{
tx.finish();
}
}
public int size()
{
Transaction tx = neo().beginTx();
try
{
int counter = 0;
Iterator<Relationship> itr = getAllRelationships();
while ( itr.hasNext() )
{
itr.next();
counter++;
}
tx.success();
return counter;
}
finally
{
tx.finish();
}
}
protected abstract T newObject( Node node, Relationship relationship );
protected Node getOtherNode( Relationship relationship )
{
return relationship.getOtherNode( this.getUnderlyingNode() );
}
public Object[] toArray()
{
Transaction tx = neo().beginTx();
try
{
Iterator<Relationship> itr = getAllRelationships();
Collection<Object> result = newArrayCollection();
while ( itr.hasNext() )
{
Relationship rel = itr.next();
result.add( newObject( getOtherNode( rel ), rel ) );
}
tx.success();
return result.toArray();
}
finally
{
tx.finish();
}
}
public <R> R[] toArray( R[] array )
{
Transaction tx = neo().beginTx();
try
{
Iterator<Relationship> itr = getAllRelationships();
Collection<R> result = newArrayCollection();
while ( itr.hasNext() )
{
Relationship rel = itr.next();
result.add( ( R ) newObject( getOtherNode( rel ), rel ) );
}
int i = 0;
for ( R item : result )
{
array[ i++ ] = item;
}
tx.success();
return array;
}
finally
{
tx.finish();
}
}
protected <R> Collection<R> newArrayCollection()
{
return new ArrayList<R>();
}
}
diff --git a/src/main/java/org/neo4j/util/RelationshipToNodeIterable.java b/src/main/java/org/neo4j/util/RelationshipToNodeIterable.java
index 2297938..d5e0dbb 100644
--- a/src/main/java/org/neo4j/util/RelationshipToNodeIterable.java
+++ b/src/main/java/org/neo4j/util/RelationshipToNodeIterable.java
@@ -1,23 +1,24 @@
package org.neo4j.util;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Relationship;
+import org.neo4j.commons.iterator.IterableWrapper;
public class RelationshipToNodeIterable
extends IterableWrapper<Node, Relationship>
{
private Node startNode;
public RelationshipToNodeIterable( Node startNode,
Iterable<Relationship> relationships )
{
super( relationships );
this.startNode = startNode;
}
@Override
protected Node underlyingObjectToObject( Relationship relationship )
{
return relationship.getOtherNode( startNode );
}
}
| false | false | null | null |
diff --git a/media/java/android/media/ThumbnailUtils.java b/media/java/android/media/ThumbnailUtils.java
index d8c581e..291d8a3 100644
--- a/media/java/android/media/ThumbnailUtils.java
+++ b/media/java/android/media/ThumbnailUtils.java
@@ -1,506 +1,506 @@
/*
* 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 android.media;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.MediaMetadataRetriever;
import android.media.MediaFile.MediaFileType;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;
import android.os.SystemProperties;
import java.io.FileInputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.OutputStream;
/**
* Thumbnail generation routines for media provider.
*/
public class ThumbnailUtils {
private static final String TAG = "ThumbnailUtils";
/* Maximum pixels size for created bitmap. */
private static final int MAX_NUM_PIXELS_THUMBNAIL = 512 * 384;
- private static final int MAX_NUM_PIXELS_MICRO_THUMBNAIL = 160 * 120;
+ private static final int MAX_NUM_PIXELS_MICRO_THUMBNAIL = 128 * 128;
private static final int UNCONSTRAINED = -1;
/* Options used internally. */
private static final int OPTIONS_NONE = 0x0;
private static final int OPTIONS_SCALE_UP = 0x1;
/**
* Constant used to indicate we should recycle the input in
* {@link #extractThumbnail(Bitmap, int, int, int)} unless the output is the input.
*/
public static final int OPTIONS_RECYCLE_INPUT = 0x2;
/**
* Constant used to indicate the dimension of mini thumbnail.
* @hide Only used by media framework and media provider internally.
*/
public static final int TARGET_SIZE_MINI_THUMBNAIL = 320;
/**
* Constant used to indicate the dimension of micro thumbnail.
* @hide Only used by media framework and media provider internally.
*/
public static final int TARGET_SIZE_MICRO_THUMBNAIL = 96;
/**
* This method first examines if the thumbnail embedded in EXIF is bigger than our target
* size. If not, then it'll create a thumbnail from original image. Due to efficiency
* consideration, we want to let MediaThumbRequest avoid calling this method twice for
* both kinds, so it only requests for MICRO_KIND and set saveImage to true.
*
* This method always returns a "square thumbnail" for MICRO_KIND thumbnail.
*
* @param filePath the path of image file
* @param kind could be MINI_KIND or MICRO_KIND
* @return Bitmap, or null on failures
*
* @hide This method is only used by media framework and media provider internally.
*/
public static Bitmap createImageThumbnail(String filePath, int kind) {
boolean wantMini = (kind == Images.Thumbnails.MINI_KIND);
int targetSize = wantMini
? TARGET_SIZE_MINI_THUMBNAIL
: TARGET_SIZE_MICRO_THUMBNAIL;
int maxPixels = wantMini
? MAX_NUM_PIXELS_THUMBNAIL
: MAX_NUM_PIXELS_MICRO_THUMBNAIL;
SizedThumbnailBitmap sizedThumbnailBitmap = new SizedThumbnailBitmap();
Bitmap bitmap = null;
MediaFileType fileType = MediaFile.getFileType(filePath);
if (fileType != null && ((fileType.fileType == MediaFile.FILE_TYPE_JPEG) ||
((SystemProperties.OMAP_ENHANCEMENT) && (fileType.fileType == MediaFile.FILE_TYPE_JPS)) ||
((SystemProperties.OMAP_ENHANCEMENT)&& (fileType.fileType == MediaFile.FILE_TYPE_MPO)))){
createThumbnailFromEXIF(filePath, targetSize, maxPixels, sizedThumbnailBitmap);
bitmap = sizedThumbnailBitmap.mBitmap;
}
if (bitmap == null) {
try {
FileDescriptor fd = new FileInputStream(filePath).getFD();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fd, null, options);
if (options.mCancel || options.outWidth == -1
|| options.outHeight == -1) {
return null;
}
options.inSampleSize = computeSampleSize(
options, targetSize, maxPixels);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeFileDescriptor(fd, null, options);
} catch (IOException ex) {
Log.e(TAG, "", ex);
} catch (OutOfMemoryError oom) {
Log.e(TAG, "Unable to decode file " + filePath + ". OutOfMemoryError.", oom);
}
}
if (kind == Images.Thumbnails.MICRO_KIND) {
// now we make it a "square thumbnail" for MICRO_KIND thumbnail
bitmap = extractThumbnail(bitmap,
TARGET_SIZE_MICRO_THUMBNAIL,
TARGET_SIZE_MICRO_THUMBNAIL, OPTIONS_RECYCLE_INPUT);
}
return bitmap;
}
/**
* Create a video thumbnail for a video. May return null if the video is
* corrupt or the format is not supported.
*
* @param filePath the path of video file
* @param kind could be MINI_KIND or MICRO_KIND
*/
public static Bitmap createVideoThumbnail(String filePath, int kind) {
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(filePath);
bitmap = retriever.getFrameAtTime(-1);
} catch (IllegalArgumentException ex) {
// Assume this is a corrupt video file
} catch (RuntimeException ex) {
// Assume this is a corrupt video file.
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
// Ignore failures while cleaning up.
}
}
if (kind == Images.Thumbnails.MICRO_KIND && bitmap != null) {
bitmap = extractThumbnail(bitmap,
TARGET_SIZE_MICRO_THUMBNAIL,
TARGET_SIZE_MICRO_THUMBNAIL,
OPTIONS_RECYCLE_INPUT);
}
return bitmap;
}
/**
* Creates a centered bitmap of the desired size.
*
* @param source original bitmap source
* @param width targeted width
* @param height targeted height
*/
public static Bitmap extractThumbnail(
Bitmap source, int width, int height) {
return extractThumbnail(source, width, height, OPTIONS_NONE);
}
/**
* Creates a centered bitmap of the desired size.
*
* @param source original bitmap source
* @param width targeted width
* @param height targeted height
* @param options options used during thumbnail extraction
*/
public static Bitmap extractThumbnail(
Bitmap source, int width, int height, int options) {
if (source == null) {
return null;
}
float scale;
if (source.getWidth() < source.getHeight()) {
scale = width / (float) source.getWidth();
} else {
scale = height / (float) source.getHeight();
}
Matrix matrix = new Matrix();
matrix.setScale(scale, scale);
Bitmap thumbnail = transform(matrix, source, width, height,
OPTIONS_SCALE_UP | options);
return thumbnail;
}
/*
* Compute the sample size as a function of minSideLength
* and maxNumOfPixels.
* minSideLength is used to specify that minimal width or height of a
* bitmap.
* maxNumOfPixels is used to specify the maximal size in pixels that is
* tolerable in terms of memory usage.
*
* The function returns a sample size based on the constraints.
* Both size and minSideLength can be passed in as IImage.UNCONSTRAINED,
* which indicates no care of the corresponding constraint.
* The functions prefers returning a sample size that
* generates a smaller bitmap, unless minSideLength = IImage.UNCONSTRAINED.
*
* Also, the function rounds up the sample size to a power of 2 or multiple
* of 8 because BitmapFactory only honors sample size this way.
* For example, BitmapFactory downsamples an image by 2 even though the
* request is 3. So we round up the sample size to avoid OOM.
*/
private static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8 ) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 :
(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == UNCONSTRAINED) ? 128 :
(int) Math.min(Math.floor(w / minSideLength),
Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == UNCONSTRAINED) &&
(minSideLength == UNCONSTRAINED)) {
return 1;
} else if (minSideLength == UNCONSTRAINED) {
return lowerBound;
} else {
return upperBound;
}
}
/**
* Make a bitmap from a given Uri, minimal side length, and maximum number of pixels.
* The image data will be read from specified pfd if it's not null, otherwise
* a new input stream will be created using specified ContentResolver.
*
* Clients are allowed to pass their own BitmapFactory.Options used for bitmap decoding. A
* new BitmapFactory.Options will be created if options is null.
*/
private static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
Uri uri, ContentResolver cr, ParcelFileDescriptor pfd,
BitmapFactory.Options options) {
Bitmap b = null;
try {
if (pfd == null) pfd = makeInputStream(uri, cr);
if (pfd == null) return null;
if (options == null) options = new BitmapFactory.Options();
FileDescriptor fd = pfd.getFileDescriptor();
options.inSampleSize = 1;
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fd, null, options);
if (options.mCancel || options.outWidth == -1
|| options.outHeight == -1) {
return null;
}
options.inSampleSize = computeSampleSize(
options, minSideLength, maxNumOfPixels);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
b = BitmapFactory.decodeFileDescriptor(fd, null, options);
} catch (OutOfMemoryError ex) {
Log.e(TAG, "Got oom exception ", ex);
return null;
} finally {
closeSilently(pfd);
}
return b;
}
private static void closeSilently(ParcelFileDescriptor c) {
if (c == null) return;
try {
c.close();
} catch (Throwable t) {
// do nothing
}
}
private static ParcelFileDescriptor makeInputStream(
Uri uri, ContentResolver cr) {
try {
return cr.openFileDescriptor(uri, "r");
} catch (IOException ex) {
return null;
}
}
/**
* Transform source Bitmap to targeted width and height.
*/
private static Bitmap transform(Matrix scaler,
Bitmap source,
int targetWidth,
int targetHeight,
int options) {
boolean scaleUp = (options & OPTIONS_SCALE_UP) != 0;
boolean recycle = (options & OPTIONS_RECYCLE_INPUT) != 0;
int deltaX = source.getWidth() - targetWidth;
int deltaY = source.getHeight() - targetHeight;
if (!scaleUp && (deltaX < 0 || deltaY < 0)) {
/*
* In this case the bitmap is smaller, at least in one dimension,
* than the target. Transform it by placing as much of the image
* as possible into the target and leaving the top/bottom or
* left/right (or both) black.
*/
Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b2);
int deltaXHalf = Math.max(0, deltaX / 2);
int deltaYHalf = Math.max(0, deltaY / 2);
Rect src = new Rect(
deltaXHalf,
deltaYHalf,
deltaXHalf + Math.min(targetWidth, source.getWidth()),
deltaYHalf + Math.min(targetHeight, source.getHeight()));
int dstX = (targetWidth - src.width()) / 2;
int dstY = (targetHeight - src.height()) / 2;
Rect dst = new Rect(
dstX,
dstY,
targetWidth - dstX,
targetHeight - dstY);
c.drawBitmap(source, src, dst, null);
if (recycle) {
source.recycle();
}
return b2;
}
float bitmapWidthF = source.getWidth();
float bitmapHeightF = source.getHeight();
float bitmapAspect = bitmapWidthF / bitmapHeightF;
float viewAspect = (float) targetWidth / targetHeight;
if (bitmapAspect > viewAspect) {
float scale = targetHeight / bitmapHeightF;
if (scale < .9F || scale > 1F) {
scaler.setScale(scale, scale);
} else {
scaler = null;
}
} else {
float scale = targetWidth / bitmapWidthF;
if (scale < .9F || scale > 1F) {
scaler.setScale(scale, scale);
} else {
scaler = null;
}
}
Bitmap b1;
if (scaler != null) {
// this is used for minithumb and crop, so we want to filter here.
b1 = Bitmap.createBitmap(source, 0, 0,
source.getWidth(), source.getHeight(), scaler, true);
} else {
b1 = source;
}
if (recycle && b1 != source) {
source.recycle();
}
int dx1 = Math.max(0, b1.getWidth() - targetWidth);
int dy1 = Math.max(0, b1.getHeight() - targetHeight);
Bitmap b2 = Bitmap.createBitmap(
b1,
dx1 / 2,
dy1 / 2,
targetWidth,
targetHeight);
if (b2 != b1) {
if (recycle || b1 != source) {
b1.recycle();
}
}
return b2;
}
/**
* SizedThumbnailBitmap contains the bitmap, which is downsampled either from
* the thumbnail in exif or the full image.
* mThumbnailData, mThumbnailWidth and mThumbnailHeight are set together only if mThumbnail
* is not null.
*
* The width/height of the sized bitmap may be different from mThumbnailWidth/mThumbnailHeight.
*/
private static class SizedThumbnailBitmap {
public byte[] mThumbnailData;
public Bitmap mBitmap;
public int mThumbnailWidth;
public int mThumbnailHeight;
}
/**
* Creates a bitmap by either downsampling from the thumbnail in EXIF or the full image.
* The functions returns a SizedThumbnailBitmap,
* which contains a downsampled bitmap and the thumbnail data in EXIF if exists.
*/
private static void createThumbnailFromEXIF(String filePath, int targetSize,
int maxPixels, SizedThumbnailBitmap sizedThumbBitmap) {
if (filePath == null) return;
ExifInterface exif = null;
byte [] thumbData = null;
try {
exif = new ExifInterface(filePath);
if (exif != null) {
thumbData = exif.getThumbnail();
}
} catch (IOException ex) {
Log.w(TAG, ex);
}
BitmapFactory.Options fullOptions = new BitmapFactory.Options();
BitmapFactory.Options exifOptions = new BitmapFactory.Options();
int exifThumbWidth = 0;
int fullThumbWidth = 0;
// Compute exifThumbWidth.
if (thumbData != null) {
exifOptions.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(thumbData, 0, thumbData.length, exifOptions);
exifOptions.inSampleSize = computeSampleSize(exifOptions, targetSize, maxPixels);
exifThumbWidth = exifOptions.outWidth / exifOptions.inSampleSize;
}
// Compute fullThumbWidth.
fullOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, fullOptions);
fullOptions.inSampleSize = computeSampleSize(fullOptions, targetSize, maxPixels);
fullThumbWidth = fullOptions.outWidth / fullOptions.inSampleSize;
// Choose the larger thumbnail as the returning sizedThumbBitmap.
if (thumbData != null && exifThumbWidth >= fullThumbWidth) {
int width = exifOptions.outWidth;
int height = exifOptions.outHeight;
exifOptions.inJustDecodeBounds = false;
sizedThumbBitmap.mBitmap = BitmapFactory.decodeByteArray(thumbData, 0,
thumbData.length, exifOptions);
if (sizedThumbBitmap.mBitmap != null) {
sizedThumbBitmap.mThumbnailData = thumbData;
sizedThumbBitmap.mThumbnailWidth = width;
sizedThumbBitmap.mThumbnailHeight = height;
}
} else {
fullOptions.inJustDecodeBounds = false;
sizedThumbBitmap.mBitmap = BitmapFactory.decodeFile(filePath, fullOptions);
}
}
}
| true | false | null | null |
diff --git a/contrib/src/main/java/com/datatorrent/contrib/redis/RedisNumberAggregateOutputOperator.java b/contrib/src/main/java/com/datatorrent/contrib/redis/RedisNumberAggregateOutputOperator.java
index 649aa8350..ca5d06e06 100644
--- a/contrib/src/main/java/com/datatorrent/contrib/redis/RedisNumberAggregateOutputOperator.java
+++ b/contrib/src/main/java/com/datatorrent/contrib/redis/RedisNumberAggregateOutputOperator.java
@@ -1,143 +1,146 @@
/*
* Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datatorrent.contrib.redis;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.mutable.MutableDouble;
import org.apache.commons.lang.mutable.MutableInt;
import org.apache.commons.lang.mutable.MutableLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>RedisNumberAggregateOutputOperator class.</p>
*
* @since 0.3.2
*/
public class RedisNumberAggregateOutputOperator<K, V> extends RedisOutputOperator<K, V>
{
private static final Logger LOG = LoggerFactory.getLogger(RedisNumberAggregateOutputOperator.class);
protected Number convertToNumber(Object o)
{
if (o == null) {
return null;
}
else if (o instanceof MutableDouble || o instanceof MutableLong) {
return (Number)o;
}
else if (o instanceof Double || o instanceof Float) {
return new MutableDouble((Number)o);
}
else if (o instanceof Number) {
return new MutableLong((Number)o);
}
else {
return new MutableDouble(o.toString());
}
}
@Override
public void process(Map<K, V> t)
{
for (Map.Entry<K, V> entry: t.entrySet()) {
process(entry.getKey(), entry.getValue());
}
}
@Override
public void store(Map<K, Object> t)
{
for (Map.Entry<K, Object> entry: t.entrySet()) {
String key = entry.getKey().toString();
Object value = entry.getValue();
if (value instanceof Map) {
for (Map.Entry<Object, Object> entry1: ((Map<Object, Object>)value).entrySet()) {
String field = entry1.getKey().toString();
Object hvalue = entry1.getValue();
if (hvalue instanceof Number) {
redisConnection.hincrbyfloat(key, field, ((Number)hvalue).doubleValue());
}
else {
redisConnection.hincrbyfloat(key, field, Double.parseDouble(hvalue.toString()));
}
}
}
else {
if (value instanceof Number) {
redisConnection.incrbyfloat(key, ((Number)value).doubleValue());
}
else {
redisConnection.incrbyfloat(key, Double.parseDouble(value.toString()));
}
}
+ if(keyExpiryTime != -1){
+ redisConnection.expire(key, keyExpiryTime);
+ }
}
}
public void process(K key, V value) throws RuntimeException
{
if (value instanceof Map) {
Object o = dataMap.get(key);
if (o == null) {
o = new HashMap<Object, Object>();
dataMap.put(key, o);
}
if (!(o instanceof Map)) {
throw new RuntimeException("Values of unexpected type in data map. Expecting Map");
}
Map<Object, Object> map = (Map<Object, Object>)o;
for (Map.Entry<Object, Object> entry1: ((Map<Object, Object>)value).entrySet()) {
Object field = entry1.getKey();
Number oldVal = (Number)map.get(field);
if (oldVal == null) {
map.put(field, convertToNumber(entry1.getValue()));
}
else if (oldVal instanceof MutableDouble) {
((MutableDouble)oldVal).add(convertToNumber(entry1.getValue()));
}
else if (oldVal instanceof MutableLong) {
((MutableLong)oldVal).add(convertToNumber(entry1.getValue()));
}
else {
throw new RuntimeException("Values of unexpected type in data map value field type. Expecting MutableLong or MutableDouble");
}
}
}
else {
Number oldVal = convertToNumber(dataMap.get(key));
if (oldVal == null) {
dataMap.put(key, convertToNumber(value));
}
else {
if (oldVal instanceof MutableDouble) {
((MutableDouble)oldVal).add(convertToNumber(value));
}
else if (oldVal instanceof MutableLong) {
((MutableLong)oldVal).add(convertToNumber(value));
}
else {
// should not get here
throw new RuntimeException("Values of unexpected type in data map value type. Expecting MutableLong or MutableDouble");
}
}
}
}
}
diff --git a/contrib/src/main/java/com/datatorrent/contrib/redis/RedisOutputOperator.java b/contrib/src/main/java/com/datatorrent/contrib/redis/RedisOutputOperator.java
index 634db2d14..e410d921c 100644
--- a/contrib/src/main/java/com/datatorrent/contrib/redis/RedisOutputOperator.java
+++ b/contrib/src/main/java/com/datatorrent/contrib/redis/RedisOutputOperator.java
@@ -1,152 +1,152 @@
/*
* Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datatorrent.contrib.redis;
import com.datatorrent.lib.io.AbstractKeyValueStoreOutputOperator;
import com.lambdaworks.redis.RedisClient;
import com.lambdaworks.redis.RedisConnection;
import com.lambdaworks.redis.RedisException;
import com.datatorrent.api.annotation.ShipContainingJars;
import com.datatorrent.api.Context.OperatorContext;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>RedisOutputOperator class.</p>
*
* @since 0.3.2
*/
@ShipContainingJars(classes = {RedisClient.class})
public class RedisOutputOperator<K, V> extends AbstractKeyValueStoreOutputOperator<K, V>
{
private static final Logger LOG = LoggerFactory.getLogger(RedisOutputOperator.class);
protected transient RedisClient redisClient;
protected transient RedisConnection<String, String> redisConnection;
private String host = "localhost";
private int port = 6379;
private int dbIndex = 0;
private int timeout= 10000;
- private long keyExpiryTime = -1;
+ protected long keyExpiryTime = -1;
public long getKeyExpiryTime()
{
return keyExpiryTime;
}
public void setKeyExpiryTime(long keyExpiryTime)
{
this.keyExpiryTime = keyExpiryTime;
}
public void setHost(String host)
{
this.host = host;
}
public void setPort(int port)
{
this.port = port;
}
public void setDatabase(int index)
{
this.dbIndex = index;
}
public void setTimeout(int timeout)
{
this.timeout = timeout;
}
@Override
public void setup(OperatorContext context)
{
redisClient = new RedisClient(host, port);
redisConnection = redisClient.connect();
redisConnection.select(dbIndex);
redisConnection.setTimeout(timeout, TimeUnit.MILLISECONDS);
super.setup(context);
}
@Override
public String get(String key)
{
return redisConnection.get(key);
}
@Override
public void put(String key, String value)
{
redisConnection.set(key, value);
if(keyExpiryTime != -1){
redisConnection.expire(key, keyExpiryTime);
}
}
@Override
public void startTransaction()
{
redisConnection.multi();
}
@Override
public void commitTransaction()
{
redisConnection.exec();
}
@Override
public void rollbackTransaction()
{
redisConnection.discard();
}
@Override
public void store(Map<K, Object> t)
{
for (Map.Entry<K, Object> entry: t.entrySet()) {
Object value = entry.getValue();
if (value instanceof Map) {
for (Map.Entry<Object, Object> entry1: ((Map<Object, Object>)value).entrySet()) {
redisConnection.hset(entry.getKey().toString(), entry1.getKey().toString(), entry1.getValue().toString());
}
}
else if (value instanceof Set) {
for (Object o: (Set)value) {
redisConnection.sadd(entry.getKey().toString(), o.toString());
}
}
else if (value instanceof List) {
int i = 0;
for (Object o: (List)value) {
redisConnection.lset(entry.getKey().toString(), i++, o.toString());
}
}
else {
redisConnection.set(entry.getKey().toString(), value.toString());
}
if(keyExpiryTime != -1){
redisConnection.expire(entry.getKey().toString(), keyExpiryTime);
}
}
}
}
| false | false | null | null |
diff --git a/src/main/java/net/sourceforge/cilib/entity/operators/creation/RandCreationStrategy.java b/src/main/java/net/sourceforge/cilib/entity/operators/creation/RandCreationStrategy.java
index 81975331..173485fb 100644
--- a/src/main/java/net/sourceforge/cilib/entity/operators/creation/RandCreationStrategy.java
+++ b/src/main/java/net/sourceforge/cilib/entity/operators/creation/RandCreationStrategy.java
@@ -1,147 +1,148 @@
/**
* 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.entity.operators.creation;
import java.util.Iterator;
import java.util.List;
import net.sourceforge.cilib.controlparameter.ConstantControlParameter;
import net.sourceforge.cilib.controlparameter.ControlParameter;
import net.sourceforge.cilib.entity.Entity;
import net.sourceforge.cilib.entity.Topology;
import net.sourceforge.cilib.math.random.generator.MersenneTwister;
import net.sourceforge.cilib.math.random.generator.RandomProvider;
import net.sourceforge.cilib.type.types.container.Vector;
+import net.sourceforge.cilib.util.ControlParameters;
import net.sourceforge.cilib.util.Sequence;
import net.sourceforge.cilib.util.selection.Samples;
import net.sourceforge.cilib.util.selection.Selection;
import net.sourceforge.cilib.util.selection.arrangement.RandomArrangement;
public class RandCreationStrategy implements CreationStrategy {
private static final long serialVersionUID = 930740770470361009L;
protected ControlParameter scaleParameter;
protected ControlParameter numberOfDifferenceVectors;
/**
* Create a new instance of {@code CurrentToRandCreationStrategy}.
*/
public RandCreationStrategy() {
this.scaleParameter = new ConstantControlParameter(0.5);
this.numberOfDifferenceVectors = new ConstantControlParameter(2);
}
/**
* Copy constructor. Create a copy of the provided instance.
* @param copy The instance to copy.
*/
public RandCreationStrategy(RandCreationStrategy copy) {
this.scaleParameter = copy.scaleParameter.getClone();
this.numberOfDifferenceVectors = copy.numberOfDifferenceVectors.getClone();
}
/**
* {@inheritDoc}
* @return A copy of the current instance.
*/
@Override
public RandCreationStrategy getClone() {
return new RandCreationStrategy(this);
}
/**
* {@inheritDoc}
*/
@Override
public Entity create(Entity targetEntity, Entity current, Topology<? extends Entity> topology) {
RandomProvider random = new MersenneTwister();
int number = Double.valueOf(this.numberOfDifferenceVectors.getParameter()).intValue();
List<Entity> participants = (List<Entity>) Selection.copyOf(topology.asList())
.exclude(targetEntity, current)
.orderBy(new RandomArrangement(random))
.select(Samples.first(number).unique());
Vector differenceVector = determineDistanceVector(participants);
Vector targetVector = (Vector) targetEntity.getCandidateSolution();
- Vector trialVector = targetVector.plus(differenceVector.multiply(scaleParameter.getParameter()));
+ Vector trialVector = targetVector.plus(differenceVector.multiply(ControlParameters.supplierOf(scaleParameter)));
Entity trialEntity = current.getClone();
trialEntity.setCandidateSolution(trialVector);
return trialEntity;
}
/**
* Calculate the {@linkplain Vector} that is the resultant of several difference vectors.
* @param participants The {@linkplain Entity} list to create the difference vectors from. It
* is very important to note that the {@linkplain Entity} objects within this list
* should not contain duplicates. If duplicates are contained, this will severely
* reduce the diversity of the population as not all entities will be considered.
* @return A {@linkplain Vector} representing the resultant of all calculated difference vectors.
*/
protected Vector determineDistanceVector(List<Entity> participants) {
Vector distanceVector = Vector.copyOf(Sequence.repeat(0.0, participants.get(0).getCandidateSolution().size()));
Iterator<Entity> iterator = participants.iterator();
while (iterator.hasNext()) {
Vector first = (Vector) iterator.next().getCandidateSolution();
Vector second = (Vector) iterator.next().getCandidateSolution();
Vector difference = first.subtract(second);
distanceVector = distanceVector.plus(difference);
}
return distanceVector;
}
/**
* Get the number of difference vectors to create.
* @return The {@code ControlParameter} describing the numberof difference vectors.
*/
public ControlParameter getNumberOfDifferenceVectors() {
return numberOfDifferenceVectors;
}
/**
* Set the number of difference vectors to create.
* @param numberOfDifferenceVectors The value to set.
*/
public void setNumberOfDifferenceVectors(ControlParameter numberOfDifferenceVectors) {
this.numberOfDifferenceVectors = numberOfDifferenceVectors;
}
/**
* Get the current scale parameter, used within the creation.
* @return The {@code ControlParameter} representing the scale parameter.
*/
public ControlParameter getScaleParameter() {
return scaleParameter;
}
/**
* Set the scale parameter for the creation strategy.
* @param scaleParameter The value to set.
*/
public void setScaleParameter(ControlParameter scaleParameter) {
this.scaleParameter = scaleParameter;
}
}
diff --git a/src/main/java/net/sourceforge/cilib/entity/operators/creation/RandPerDimensionCreationStrategy.java b/src/main/java/net/sourceforge/cilib/entity/operators/creation/RandPerDimensionCreationStrategy.java
index 5b1e351d..f3cd0484 100644
--- a/src/main/java/net/sourceforge/cilib/entity/operators/creation/RandPerDimensionCreationStrategy.java
+++ b/src/main/java/net/sourceforge/cilib/entity/operators/creation/RandPerDimensionCreationStrategy.java
@@ -1,167 +1,168 @@
/**
* 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.entity.operators.creation;
import java.util.Iterator;
import java.util.List;
import net.sourceforge.cilib.controlparameter.ConstantControlParameter;
import net.sourceforge.cilib.controlparameter.ControlParameter;
import net.sourceforge.cilib.entity.Entity;
import net.sourceforge.cilib.entity.Topology;
import net.sourceforge.cilib.math.random.generator.MersenneTwister;
import net.sourceforge.cilib.math.random.generator.RandomProvider;
import net.sourceforge.cilib.type.types.container.Vector;
+import net.sourceforge.cilib.util.ControlParameters;
import net.sourceforge.cilib.util.Sequence;
import net.sourceforge.cilib.util.selection.Samples;
import net.sourceforge.cilib.util.selection.Selection;
import net.sourceforge.cilib.util.selection.arrangement.RandomArrangement;
/**
* A creation strategy for DE where the difference vector is computed by
* selecting random entities from the population for each dimension.
*
* @author bennie
*/
public class RandPerDimensionCreationStrategy implements CreationStrategy {
private static final long serialVersionUID = 930740770470361009L;
protected ControlParameter scaleParameter;
protected ControlParameter numberOfDifferenceVectors;
/**
* Create a new instance of {@code CurrentToRandCreationStrategy}.
*/
public RandPerDimensionCreationStrategy() {
this.scaleParameter = new ConstantControlParameter(0.5);
this.numberOfDifferenceVectors = new ConstantControlParameter(2);
}
/**
* Copy constructor. Create a copy of the provided instance.
* @param copy The instance to copy.
*/
public RandPerDimensionCreationStrategy(RandPerDimensionCreationStrategy copy) {
this.scaleParameter = copy.scaleParameter.getClone();
this.numberOfDifferenceVectors = copy.numberOfDifferenceVectors.getClone();
}
/**
* {@inheritDoc}
* @return A copy of the current instance.
*/
@Override
public RandPerDimensionCreationStrategy getClone() {
return new RandPerDimensionCreationStrategy(this);
}
/**
* {@inheritDoc}
*/
@Override
public Entity create(Entity targetEntity, Entity current, Topology<? extends Entity> topology) {
RandomProvider random = new MersenneTwister();
List<Entity> participants = (List<Entity>) Selection.copyOf(topology.asList())
.exclude(targetEntity, current)
.select(Samples.all());
Vector differenceVector = determineDistanceVector(participants);
Vector targetVector = (Vector) targetEntity.getCandidateSolution();
- Vector trialVector = targetVector.plus(differenceVector.multiply(scaleParameter.getParameter()));
+ Vector trialVector = targetVector.plus(differenceVector.multiply(ControlParameters.supplierOf(scaleParameter)));
Entity trialEntity = current.getClone();
trialEntity.setCandidateSolution(trialVector);
return trialEntity;
}
/**
* Calculate the {@linkplain Vector} that is the resultant of several difference vectors.
* @param participants The {@linkplain Entity} list to create the difference vectors from. It
* is very important to note that the {@linkplain Entity} objects within this list
* should not contain duplicates. If duplicates are contained, this will severely
* reduce the diversity of the population as not all entities will be considered.
* @return A {@linkplain Vector} representing the resultant of all calculated difference vectors.
*/
protected Vector determineDistanceVector(List<Entity> participants) {
RandomProvider random = new MersenneTwister();
Vector distanceVector = Vector.copyOf(Sequence.repeat(0.0, participants.get(0).getCandidateSolution().size()));
Iterator<Entity> iterator;
int number = Double.valueOf(this.numberOfDifferenceVectors.getParameter()).intValue();
List<Entity> currentParticipants;
Vector first, second;
double difference;
for (int d = 0; d < distanceVector.size(); d++) {
//get random participants for this dimension
currentParticipants = (List<Entity>) Selection.copyOf(participants)
.orderBy(new RandomArrangement(random))
.select(Samples.first(number));
iterator = currentParticipants.iterator();
while (iterator.hasNext()) {
first = (Vector) iterator.next().getCandidateSolution();
second = (Vector) iterator.next().getCandidateSolution();
difference = first.doubleValueOf(d) - second.doubleValueOf(d);
distanceVector.setReal(d, distanceVector.get(d).doubleValue() + difference);
}
}
return distanceVector;
}
/**
* Get the number of difference vectors to create.
* @return The {@code ControlParameter} describing the numberof difference vectors.
*/
public ControlParameter getNumberOfDifferenceVectors() {
return numberOfDifferenceVectors;
}
/**
* Set the number of difference vectors to create.
* @param numberOfDifferenceVectors The value to set.
*/
public void setNumberOfDifferenceVectors(ControlParameter numberOfDifferenceVectors) {
this.numberOfDifferenceVectors = numberOfDifferenceVectors;
}
/**
* Get the current scale parameter, used within the creation.
* @return The {@code ControlParameter} representing the scale parameter.
*/
public ControlParameter getScaleParameter() {
return scaleParameter;
}
/**
* Set the scale parameter for the creation strategy.
* @param scaleParameter The value to set.
*/
public void setScaleParameter(ControlParameter scaleParameter) {
this.scaleParameter = scaleParameter;
}
}
| false | false | null | null |
diff --git a/amibe/src/org/jcae/mesh/amibe/algos3d/Remesh.java b/amibe/src/org/jcae/mesh/amibe/algos3d/Remesh.java
index 35fa3553..fc2bd60f 100644
--- a/amibe/src/org/jcae/mesh/amibe/algos3d/Remesh.java
+++ b/amibe/src/org/jcae/mesh/amibe/algos3d/Remesh.java
@@ -1,1069 +1,1074 @@
/* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD
modeler, Finite element mesher, Plugin architecture.
Copyright (C) 2009, by EADS France
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jcae.mesh.amibe.algos3d;
import org.jcae.mesh.amibe.ds.Mesh;
import org.jcae.mesh.amibe.ds.Triangle;
import org.jcae.mesh.amibe.ds.AbstractHalfEdge;
import org.jcae.mesh.amibe.ds.Vertex;
import org.jcae.mesh.amibe.metrics.KdTree;
import org.jcae.mesh.amibe.projection.MeshLiaison;
import org.jcae.mesh.amibe.ds.HalfEdge;
import org.jcae.mesh.amibe.metrics.EuclidianMetric3D;
import org.jcae.mesh.amibe.metrics.Matrix3D;
import org.jcae.mesh.amibe.metrics.Metric;
import org.jcae.mesh.amibe.traits.MeshTraitsBuilder;
import org.jcae.mesh.xmldata.MeshReader;
import org.jcae.mesh.xmldata.MeshWriter;
import org.jcae.mesh.xmldata.DoubleFileReader;
import org.jcae.mesh.xmldata.PrimitiveFileReaderFactory;
import gnu.trove.PrimeFinder;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Collection;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Remesh an existing mesh.
*
* See org.jcae.mesh.amibe.algos2d.Insertion
* @author Denis Barbier
*/
public class Remesh
{
private final static Logger LOGGER = Logger.getLogger(Remesh.class.getName());
private int progressBarStatus = 10000;
private final Mesh mesh;
private final MeshLiaison liaison;
// Octree to find nearest Vertex in current mesh
private final KdTree<Vertex> kdTree;
private Map<Vertex, Vertex> neighborBgMap = new HashMap<Vertex, Vertex>();
private DoubleFileReader dfrMetrics;
private final double minlen;
private final double maxlen;
private final boolean project;
private final boolean hasRidges;
+ private final boolean hasFreeEdges;
private AnalyticMetricInterface analyticMetric = LATER_BINDING;
private final Map<Vertex, EuclidianMetric3D> metrics;
private static final AnalyticMetricInterface LATER_BINDING = new AnalyticMetricInterface() {
public double getTargetSize(double x, double y, double z)
{
throw new RuntimeException();
}
};
public interface AnalyticMetricInterface
{
double getTargetSize(double x, double y, double z);
}
/**
* Creates a <code>Remesh</code> instance.
*
* @param m the <code>Mesh</code> instance to refine.
*/
public Remesh(Mesh m)
{
this(m, MeshTraitsBuilder.getDefault3D());
}
public Remesh(Mesh m, Map<String, String> opts)
{
this(m, MeshTraitsBuilder.getDefault3D(), opts);
}
private Remesh(Mesh m, MeshTraitsBuilder mtb)
{
this(m, mtb, new HashMap<String, String>());
}
/**
* Creates a <code>Remesh</code> instance.
*
* @param bgMesh the <code>Mesh</code> instance to refine.
* @param options map containing key-value pairs to modify algorithm
* behaviour. No options are available for now.
*/
private Remesh(final Mesh bgMesh, final MeshTraitsBuilder mtb, final Map<String, String> options)
{
liaison = new MeshLiaison(bgMesh, mtb);
mesh = liaison.getMesh();
double size = 0.0;
boolean proj = false;
boolean ridges = false;
for (final Map.Entry<String, String> opt: options.entrySet())
{
final String key = opt.getKey();
final String val = opt.getValue();
if (key.equals("size"))
{
size = Double.valueOf(val).doubleValue();
analyticMetric = null;
}
else if (key.equals("coplanarity"))
{
mesh.buildRidges(Double.valueOf(val).doubleValue());
ridges = true;
}
else if (key.equals("metricsFile"))
{
PrimitiveFileReaderFactory pfrf = new PrimitiveFileReaderFactory();
try {
dfrMetrics = pfrf.getDoubleReader(new File(val));
} catch (FileNotFoundException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
analyticMetric = null;
}
else if (key.equals("project"))
proj = Boolean.valueOf(val).booleanValue();
else
LOGGER.warning("Unknown option: "+key);
}
double targetSize = size;
minlen = 1.0 / Math.sqrt(2.0);
maxlen = Math.sqrt(2.0);
project = proj;
hasRidges = ridges;
// Compute bounding box
+ boolean freeEdges = false;
double [] bbox = new double[6];
bbox[0] = bbox[1] = bbox[2] = Double.MAX_VALUE;
bbox[3] = bbox[4] = bbox[5] = - (Double.MAX_VALUE / 2.0);
for (Triangle f: bgMesh.getTriangles())
{
if (f.hasAttributes(AbstractHalfEdge.OUTER))
continue;
+ if (!freeEdges && f.hasAttributes(AbstractHalfEdge.BOUNDARY))
+ freeEdges = true;
for (Vertex v : f.vertex)
{
double[] xyz = v.getUV();
for (int k = 2; k >= 0; k--)
{
if (xyz[k] < bbox[k])
bbox[k] = xyz[k];
if (xyz[k] > bbox[3+k])
bbox[3+k] = xyz[k];
}
}
}
LOGGER.fine("Bounding box: lower("+bbox[0]+", "+bbox[1]+", "+bbox[2]+"), upper("+bbox[3]+", "+bbox[4]+", "+bbox[5]+")");
+ hasFreeEdges = freeEdges;
kdTree = new KdTree<Vertex>(bbox);
Collection<Vertex> nodeset = mesh.getNodes();
if (nodeset == null)
{
nodeset = new LinkedHashSet<Vertex>(mesh.getTriangles().size() / 2);
for (Triangle f : mesh.getTriangles())
{
if (f.hasAttributes(AbstractHalfEdge.OUTER))
continue;
for (Vertex v: f.vertex)
nodeset.add(v);
}
}
Collection<Vertex> bgNodeset = bgMesh.getNodes();
if (bgNodeset == null)
{
bgNodeset = new LinkedHashSet<Vertex>(bgMesh.getTriangles().size() / 2);
for (Triangle f : bgMesh.getTriangles())
{
if (f.hasAttributes(AbstractHalfEdge.OUTER))
continue;
for (Vertex v: f.vertex)
bgNodeset.add(v);
}
}
for (Vertex v : nodeset)
kdTree.add(v);
for (Vertex v : nodeset)
{
Triangle t = liaison.getBackgroundTriangle(v);
double d0 = v.sqrDistance3D(t.vertex[0]);
double d1 = v.sqrDistance3D(t.vertex[1]);
double d2 = v.sqrDistance3D(t.vertex[2]);
if (d0 <= d1 && d0 <= d2)
neighborBgMap.put(v, t.vertex[0]);
else if (d1 <= d0 && d1 <= d2)
neighborBgMap.put(v, t.vertex[1]);
else
neighborBgMap.put(v, t.vertex[2]);
}
// Arbitrary size: 2*initial number of nodes
metrics = new HashMap<Vertex, EuclidianMetric3D>(2*nodeset.size());
if (dfrMetrics != null)
{
try {
for (Vertex v : nodeset)
metrics.put(v, new EuclidianMetric3D(dfrMetrics.get(v.getLabel() - 1)));
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
throw new RuntimeException("Error when loading metrics map file");
}
}
else if (targetSize > 0.0)
{
// If targetSize is 0.0, metrics will be set by calling setAnalyticMetric()
// below.
for (Vertex v : nodeset)
metrics.put(v, new EuclidianMetric3D(targetSize));
}
}
public void setAnalyticMetric(AnalyticMetricInterface m)
{
analyticMetric = m;
}
public final Mesh getOutputMesh()
{
return mesh;
}
private static AbstractHalfEdge findSurroundingTriangle(Vertex v, Vertex start)
{
Triangle t = start.getNeighbourIteratorTriangle().next();
AbstractHalfEdge ot = t.getAbstractHalfEdge();
if (start == ot.destination())
ot = ot.next(ot);
else if (start == ot.apex())
ot = ot.prev(ot);
assert start == ot.origin();
double[] pos = v.getUV();
double dmin = Double.MAX_VALUE;
int[] index = new int[2];
int i = -1;
Vertex d = ot.destination();
t = null;
// First, find the best triangle in the neighborhood of 'start' vertex
do
{
ot = ot.nextOriginLoop();
if (ot.hasAttributes(AbstractHalfEdge.OUTER))
continue;
double dist = sqrDistanceVertexTriangle(pos, ot.getTri(), index);
if (dist < dmin)
{
dmin = dist;
t = ot.getTri();
i = (index[1] - 1)/ 2;
}
}
while (ot.destination() != d);
assert i >= 0 && t != null;
ot = t.getAbstractHalfEdge(ot);
if (ot.origin() == t.vertex[i])
ot = ot.next();
else if (ot.destination() == t.vertex[i])
ot = ot.prev();
// Now cross edges to see if adjacent triangle is nearer
do
{
if (ot.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
break;
AbstractHalfEdge sym = ot.sym();
t = sym.getTri();
double dist = sqrDistanceVertexTriangle(pos, t, index);
if (dist >= dmin)
break;
dmin = dist;
ot = sym;
i = (index[1] - 1)/ 2;
if (ot.origin() == t.vertex[i])
ot = ot.next();
else if (ot.destination() == t.vertex[i])
ot = ot.prev();
} while (true);
return ot;
}
private static boolean isInside(double[] pos, Triangle t)
{
double [][] temp = new double[4][3];
double[] p0 = t.vertex[0].getUV();
double[] p1 = t.vertex[1].getUV();
double[] p2 = t.vertex[2].getUV();
Matrix3D.computeNormal3D(p0, p1, p2, temp[0], temp[1], temp[2]);
Matrix3D.computeNormal3D(p0, p1, pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) < 0.0)
return false;
Matrix3D.computeNormal3D(p1, p2, pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) < 0.0)
return false;
Matrix3D.computeNormal3D(p2, p0, pos, temp[0], temp[1], temp[3]);
return Matrix3D.prodSca(temp[2], temp[3]) >= 0.0;
}
/**
* Compute squared distance between a point and a triangle. See
* http://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf
*/
private static double sqrDistanceVertexTriangle(double[] pos, Triangle tri, int[] index)
{
double[] t0 = tri.vertex[0].getUV();
double[] t1 = tri.vertex[1].getUV();
double[] t2 = tri.vertex[2].getUV();
double a = tri.vertex[0].sqrDistance3D(tri.vertex[1]);
double b =
(t1[0] - t0[0]) * (t2[0] - t0[0]) +
(t1[1] - t0[1]) * (t2[1] - t0[1]) +
(t1[2] - t0[2]) * (t2[2] - t0[2]);
double c = tri.vertex[0].sqrDistance3D(tri.vertex[2]);
double d =
(t1[0] - t0[0]) * (t0[0] - pos[0]) +
(t1[1] - t0[1]) * (t0[1] - pos[1]) +
(t1[2] - t0[2]) * (t0[2] - pos[2]);
double e =
(t2[0] - t0[0]) * (t0[0] - pos[0]) +
(t2[1] - t0[1]) * (t0[1] - pos[1]) +
(t2[2] - t0[2]) * (t0[2] - pos[2]);
double f =
(pos[0] - t0[0]) * (pos[0] - t0[0]) +
(pos[1] - t0[1]) * (pos[1] - t0[1]) +
(pos[2] - t0[2]) * (pos[2] - t0[2]);
// Minimize Q(s,t) = a*s*s + 2.0*b*s*t + c*t*t + 2.0*d*s + 2.0*e*t + f
double det = a*c - b*b;
double s = b*e - c*d;
double t = b*d - a*e;
index[0] = index[1] = -1;
if ( s+t <= det )
{
if ( s < 0.0 )
{
if ( t < 0.0 )
{
// region 4
if (d < 0.0)
{
t = 0.0;
if (-d >= a)
{
index[1] = 6;
s = 1.0;
}
else
{
index[1] = 5;
s = -d/a;
}
}
else
{
s = 0.0;
if (e >= 0.0)
{
index[1] = 4;
t = 0.0;
}
else if (-e >= c)
{
index[1] = 2;
t = 1.0;
}
else
{
index[1] = 3;
t = -e/c;
}
}
}
else
{
// region 3
s = 0.0;
if (e >= 0.0)
{
index[1] = 4;
t = 0.0;
}
else if (-e >= c)
{
index[1] = 2;
t = 1.0;
}
else
{
index[1] = 3;
t = -e/c;
}
}
}
else if ( t < 0.0 )
{
// region 5
t = 0.0;
if (d >= 0.0)
{
index[1] = 4;
s = 0.0;
}
else if (-d >= a)
{
index[1] = 6;
s = 1.0;
}
else
{
index[1] = 5;
s = -d/a;
}
}
else
{
// region 0
double invDet = 1.0 / det;
s *= invDet;
t *= invDet;
if (t <= s && t <= 1.0 - s - t)
index[1] = 5;
else if (s <= t && s <= 1.0 - s - t)
index[1] = 3;
else if (s >= 1.0 - s - t && t >= 1.0 - s -t)
index[1] = 1;
else
throw new RuntimeException("Illegal arguments: s="+s+" t="+t+" "+det+"\n"+tri);
}
}
else
{
if ( s < 0.0 )
{
// region 2
if (c+e > b+d)
{
// minimum on edge s+t = 1
double numer = (c+e) - (b+d);
double denom = (a-b) + (c-b);
if (numer >= denom)
{
index[1] = 6;
s = 1.0;
}
else
{
index[1] = 1;
s = numer / denom;
}
t = 1.0 - s;
}
else
{
// minimum on edge s = 0
s = 0.0;
if (e >= 0.0)
{
index[1] = 4;
t = 0.0;
}
else if (-e >= c)
{
index[1] = 2;
t = 1.0;
}
else
{
index[1] = 3;
t = -e/c;
}
}
}
else if ( t < 0.0 )
{
// region 6
if (a+d > b+e)
{
// minimum on edge s+t = 1
double numer = (a+d) - (b+e);
double denom = (a-b) + (c-b);
if (numer >= denom)
{
index[1] = 6;
t = 1.0;
}
else
{
index[1] = 1;
t = numer / denom;
}
s = 1.0 - t;
}
else
{
// minimum on edge t=0
t = 0.0;
if (d >= 0.0)
{
index[1] = 4;
s = 0.0;
}
else if (-d >= a)
{
index[1] = 6;
s = 1.0;
}
else
{
index[1] = 5;
s = -d/a;
}
}
}
else
{
// region 1
double numer = (c+e) - (b+d);
if (numer <= 0.0)
{
index[1] = 2;
s = 0.0;
}
else
{
double denom = (a-b)+(c-b);
if (numer >= denom)
{
index[1] = 6;
s = 1.0;
}
else
{
index[1] = 1;
s = numer/denom;
}
}
t = 1.0 - s;
}
}
double ret = a*s*s + 2.0*b*s*t + c*t*t + 2.0*d*s + 2.0*e*t + f;
// Fix possible numerical errors
if (ret < 0.0)
ret = 0.0;
return ret;
}
private static double interpolatedDistance(Vertex pt1, Metric m1, Vertex pt2, Metric m2)
{
assert m1 != null : "Metric null at point "+pt1;
assert m2 != null : "Metric null at point "+pt2;
double[] p1 = pt1.getUV();
double[] p2 = pt2.getUV();
double a = Math.sqrt(m1.distance2(p1, p2));
double b = Math.sqrt(m2.distance2(p1, p2));
// Linear interpolation:
//double l = (2.0/3.0) * (a*a + a*b + b*b) / (a + b);
// Geometric interpolation
double l = Math.abs(a-b) < 1.e-6*(a+b) ? 0.5*(a+b) : (a - b)/Math.log(a/b);
return l;
}
public final Remesh compute()
{
LOGGER.info("Run "+getClass().getName());
if (analyticMetric != null)
{
if (analyticMetric.equals(LATER_BINDING))
throw new RuntimeException("Cannot determine metrics, either set 'size' or 'metricsMap' arguments, or call Remesh.setAnalyticMetric()");
for (Vertex v : kdTree.getAllVertices(metrics.size()))
{
double[] pos = v.getUV();
metrics.put(v, new EuclidianMetric3D(analyticMetric.getTargetSize(pos[0], pos[1], pos[2])));
}
}
ArrayList<Vertex> nodes = new ArrayList<Vertex>();
ArrayList<Vertex> triNodes = new ArrayList<Vertex>();
ArrayList<EuclidianMetric3D> triMetrics = new ArrayList<EuclidianMetric3D>();
Map<Vertex, Vertex> neighborMap = new HashMap<Vertex, Vertex>();
int nrIter = 0;
int processed = 0;
// Number of nodes which were skipped
int skippedNodes = 0;
AbstractHalfEdge h = null;
AbstractHalfEdge sym = null;
EuclidianMetric3D euclid = new EuclidianMetric3D();
double[][] temp = new double[4][3];
// We try to insert new nodes by splitting large edges. As edge collapse
// is costful, nodes are inserted only if it does not create small edges,
// which means that nodes are not deleted.
// We iterate over all edges, and put candidate nodes into triNodes.
// If an edge has no candidates, either because it is small or because no
// nodes can be inserted, it is tagged and will not have to be checked
// during next iterations.
// Clear MARKED attribute
for (Triangle f : mesh.getTriangles())
f.clearAttributes(AbstractHalfEdge.MARKED);
while (true)
{
for (int pass=0; pass < 2; pass++)
{
- if (pass == 0 && !hasRidges)
+ if (pass == 0 && !hasRidges && !hasFreeEdges)
continue;
nrIter++;
// Maximal number of nodes which are inserted on an edge
int maxNodes = 0;
// Number of checked edges
int checked = 0;
// Number of nodes which are too near from existing vertices
int tooNearNodes = 0;
// Number of quadtree cells split
int kdtreeSplit = 0;
nodes.clear();
neighborMap.clear();
skippedNodes = 0;
LOGGER.fine("Check all edges");
for(Triangle t : mesh.getTriangles())
{
if (t.hasAttributes(AbstractHalfEdge.OUTER))
continue;
h = t.getAbstractHalfEdge(h);
sym = t.getAbstractHalfEdge(sym);
triNodes.clear();
triMetrics.clear();
// Maximal number of nodes which are inserted on edges of this triangle
int nrTriNodes = 0;
for (int i = 0; i < 3; i++)
{
h = h.next(h);
if ((pass == 0) != (h.hasAttributes(AbstractHalfEdge.SHARP | AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD)))
continue;
if (h.hasAttributes(AbstractHalfEdge.MARKED))
{
// This edge has already been checked and cannot be split
continue;
}
// Tag symmetric edge to process edges only once
sym = h.sym(sym);
sym.setAttributes(AbstractHalfEdge.MARKED);
Vertex start = h.origin();
Vertex end = h.destination();
EuclidianMetric3D mS = metrics.get(start);
EuclidianMetric3D mE = metrics.get(end);
double l = interpolatedDistance(start, mS, end, mE);
if (l < maxlen)
{
// This edge is smaller than target size and is not split
h.setAttributes(AbstractHalfEdge.MARKED);
continue;
}
// Long edges are discretized, but do not create more than 2 subsegments
double lcrit = 1.0;
if (l > (3.0 - pass))
lcrit = l / (3.0 - pass);
// Ensure that start point has the lowest edge size
double [] xs = start.getUV();
double [] xe = end.getUV();
if (mS.distance2(xs, xe) < mE.distance2(xs, xe))
{
Vertex tempV = start;
start = end;
end = tempV;
xs = xe;
xe = end.getUV();
mS = mE;
mE = metrics.get(end);
}
int segments = (int) (2.0*l/lcrit) + 10;
Vertex [] np = new Vertex[segments-1];
double[] pos = new double[3];
double delta = 1.0 / (double) segments;
for (int ns = 1; ns < segments; ns++)
{
pos[0] = xs[0]+ns*(xe[0]-xs[0])*delta;
pos[1] = xs[1]+ns*(xe[1]-xs[1])*delta;
pos[2] = xs[2]+ns*(xe[2]-xs[2])*delta;
np[ns-1] = mesh.createVertex(pos);
}
if (project && !h.hasAttributes(AbstractHalfEdge.SHARP | AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
{
int mid = (segments + 1) / 2;
for (int ns = 0; ns < mid; ns++)
{
pos = np[ns].getUV();
liaison.project(np[ns], pos, start);
}
for (int ns = mid; ns < segments - 1; ns++)
{
pos = np[ns].getUV();
liaison.project(np[ns], pos, end);
}
}
Vertex last = start;
Metric lastMetric = mS;
int nrNodes = 0;
l = 0.0;
double hS = mS.getUnitBallBBox()[0];
double hE = mE.getUnitBallBBox()[0];
double logRatio = Math.log(hE/hS);
for (int ns = 0; ns < segments-1; ns++)
{
EuclidianMetric3D m;
if (analyticMetric != null)
{
pos = np[ns].getUV();
m = new EuclidianMetric3D(analyticMetric.getTargetSize(pos[0], pos[1], pos[2]));
}
else
m = new EuclidianMetric3D(hS*Math.exp((ns+1.0)*delta*logRatio));
l = interpolatedDistance(last, lastMetric, np[ns], m);
if (l > lcrit)
{
last = np[ns];
triNodes.add(last);
triMetrics.add(m);
if (2*ns < segments - 1)
neighborMap.put(last, start);
else
neighborMap.put(last, end);
l = 0.0;
nrNodes++;
}
}
if (nrNodes > nrTriNodes)
{
nrTriNodes = nrNodes;
}
checked++;
}
if (nrTriNodes > maxNodes)
maxNodes = nrTriNodes;
if (!triNodes.isEmpty())
{
// Process in pseudo-random order
int prime = PrimeFinder.nextPrime(nrTriNodes);
int imax = triNodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2;
for (int i = 0; i < imax; i++)
{
Vertex v = triNodes.get(index);
EuclidianMetric3D metric = triMetrics.get(index);
assert metric != null;
double[] uv = v.getUV();
Vertex n = kdTree.getNearestVertex(metric, uv);
if (interpolatedDistance(v, metric, n, metrics.get(n)) > minlen)
{
kdTree.add(v);
metrics.put(v, metric);
nodes.add(v);
}
else
tooNearNodes++;
index += prime;
if (index >= imax)
index -= imax;
}
}
}
if (nodes.isEmpty())
continue;
for (Vertex v : nodes)
{
// These vertices are not bound to any triangles, so
// they must be removed, otherwise getSurroundingOTriangle
// may return a null pointer.
kdTree.remove(v);
}
LOGGER.fine("Try to insert "+nodes.size()+" nodes");
// Process in pseudo-random order. There are at most maxNodes nodes
// on an edge, we choose an increment step greater than this value
// to try to split all edges.
int prime = PrimeFinder.nextPrime(maxNodes);
int imax = nodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2 - prime;
int totNrSwap = 0;
for (int i = 0; i < imax; i++)
{
index += prime;
if (index >= imax)
index -= imax;
Vertex v = nodes.get(index);
double[] pos = v.getUV();
Vertex near = neighborMap.get(v);
AbstractHalfEdge ot = findSurroundingTriangle(v, near);
if (!ot.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
{
// Check whether edge can be split
sym = ot.sym(sym);
Vertex o = ot.origin();
Vertex d = ot.destination();
Vertex n = sym.apex();
Matrix3D.computeNormal3D(o.getUV(), n.getUV(), pos, temp[0], temp[1], temp[2]);
Matrix3D.computeNormal3D(n.getUV(), d.getUV(), pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) <= 0.0)
{
// Vertex is not inserted
skippedNodes++;
continue;
}
}
if (pass == 1 && ot.hasAttributes(AbstractHalfEdge.SHARP | AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
{
// Vertex is not inserted
skippedNodes++;
continue;
}
ot.clearAttributes(AbstractHalfEdge.MARKED);
ot.sym().clearAttributes(AbstractHalfEdge.MARKED);
mesh.vertexSplit(ot, v);
assert ot.destination() == v : v+" "+ot;
kdTree.add(v);
Vertex bgNear = neighborBgMap.get(neighborMap.get(v));
Triangle bgT = findSurroundingTriangle(v, bgNear).getTri();
liaison.addVertex(v, bgT);
double d0 = v.sqrDistance3D(bgT.vertex[0]);
double d1 = v.sqrDistance3D(bgT.vertex[1]);
double d2 = v.sqrDistance3D(bgT.vertex[2]);
if (d0 <= d1 && d0 <= d2)
neighborBgMap.put(v, bgT.vertex[0]);
else if (d1 <= d0 && d1 <= d2)
neighborBgMap.put(v, bgT.vertex[1]);
else
neighborBgMap.put(v, bgT.vertex[2]);
processed++;
// Swap edges
HalfEdge edge = (HalfEdge) ot;
edge = edge.prev();
Vertex s = edge.origin();
int counter = 0;
do
{
edge = edge.nextApexLoop();
counter++;
if (edge.checkSwap3D(0.8) >= 0.0)
{
edge.getTri().clearAttributes(AbstractHalfEdge.MARKED);
edge.sym().getTri().clearAttributes(AbstractHalfEdge.MARKED);
edge = (HalfEdge) mesh.edgeSwap(edge);
counter--;
totNrSwap++;
}
}
while ((edge.origin() != s || counter == 0) && counter < 20);
if (processed > 0 && (processed % progressBarStatus) == 0)
LOGGER.info("Vertices inserted: "+processed);
}
assert mesh.isValid();
assert mesh.checkNoInvertedTriangles();
assert mesh.checkNoDegeneratedTriangles();
if (LOGGER.isLoggable(Level.FINE))
{
LOGGER.fine("Mesh now contains "+mesh.getTriangles().size()+" triangles");
if (checked > 0)
LOGGER.fine(checked+" edges checked");
if (imax > 0)
LOGGER.fine(imax+" nodes added");
if (tooNearNodes > 0)
LOGGER.fine(tooNearNodes+" nodes are too near from existing vertices and cannot be inserted");
if (skippedNodes > 0)
LOGGER.fine(skippedNodes+" nodes are skipped");
if (totNrSwap > 0)
LOGGER.fine(totNrSwap+" edges have been swapped during processing");
if (kdtreeSplit > 0)
LOGGER.fine(kdtreeSplit+" quadtree cells split");
}
}
if (nodes.size() == skippedNodes)
break;
}
LOGGER.info("Number of inserted vertices: "+processed);
LOGGER.fine("Number of iterations to insert all nodes: "+nrIter);
LOGGER.config("Leave compute()");
return this;
}
protected void postProcessIteration(Mesh mesh, int i)
{
// Can be overridden
}
public void setProgressBarStatus(int n)
{
progressBarStatus = n;
}
private static void usage(int rc)
{
System.out.println("Usage: Remesh [options] xmlDir outDir");
System.out.println("Options:");
System.out.println(" -h, --help Display this message and exit");
System.exit(rc);
}
public static void checkFindSurroundingTriangle(String[] args) throws FileNotFoundException
{
org.jcae.mesh.amibe.traits.MeshTraitsBuilder mtb = org.jcae.mesh.amibe.traits.MeshTraitsBuilder.getDefault3D();
mtb.addNodeList();
Mesh mesh = new Mesh(mtb);
Vertex v0 = mesh.createVertex(10.0, 20.0, 30.0);
Vertex v1 = mesh.createVertex(16.0, 20.0, 30.0);
Vertex v2 = mesh.createVertex(12.0, 26.0, 30.0);
Triangle t = mesh.createTriangle(v0, v1, v2);
int [] index = new int[2];
int nGrid = 128;
double[] pos = new double[3];
java.io.PrintStream outMesh = new java.io.PrintStream("test.mesh");
java.io.PrintStream outBB = new java.io.PrintStream("region.bb");
java.io.PrintStream distBB = new java.io.PrintStream("test.bb");
outMesh.println("MeshVersionFormatted 1\n\nDimension\n3\n\nGeometry\n\"test.mesh\"\n\nVertices");
outMesh.println(nGrid*nGrid+3);
outBB.println("3 1 "+(nGrid*nGrid+3)+" 2");
distBB.println("3 1 "+(nGrid*nGrid+3)+" 2");
for (int j = 0; j < nGrid; j++)
{
pos[1] = 15.0 + (j * 16) / (double)nGrid;
pos[2] = 30.05;
for (int i = 0; i < nGrid; i++)
{
pos[0] = 5.0 + (i * 16) / (double)nGrid;
double d = sqrDistanceVertexTriangle(pos, t, index);
outMesh.println(pos[0]+" "+pos[1]+" "+pos[2]+" 0");
outBB.println((double)index[1]);
distBB.println(d);
}
}
index[1] = 0;
pos = v0.getUV();
outMesh.println(pos[0]+" "+pos[1]+" "+pos[2]+" "+index[1]);
outBB.println("0.0");
distBB.println(sqrDistanceVertexTriangle(pos, t, index));
pos = v1.getUV();
outMesh.println(pos[0]+" "+pos[1]+" "+pos[2]+" "+index[1]);
outBB.println("0.0");
distBB.println(sqrDistanceVertexTriangle(pos, t, index));
pos = v2.getUV();
outMesh.println(pos[0]+" "+pos[1]+" "+pos[2]+" "+index[1]);
outBB.println("0.0");
distBB.println(sqrDistanceVertexTriangle(pos, t, index));
outMesh.println("\n\nQuadrilaterals\n"+((nGrid-1)*(nGrid-1)));
for (int j = 0; j < nGrid - 1; j++)
{
for (int i = 0; i < nGrid - 1; i++)
{
outMesh.println(""+(j*nGrid+i+1)+" "+(j*nGrid+i+2)+" "+((j+1)*nGrid+i+2)+" "+((j+1)*nGrid+i+1)+" 0");
}
}
int o = nGrid*nGrid;
outMesh.println("\n\nTriangles\n1\n"+(o+1)+" "+(o+2)+" "+(o+3)+" 0");
outMesh.println("\n\nEnd");
outMesh.close();
outBB.close();
distBB.close();
}
/**
*
* @param args [options] xmlDir outDir
*/
public static void main(String[] args) throws IOException
{
org.jcae.mesh.amibe.traits.MeshTraitsBuilder mtb = org.jcae.mesh.amibe.traits.MeshTraitsBuilder.getDefault3D();
mtb.addNodeList();
Mesh mesh = new Mesh(mtb);
Map<String, String> opts = new HashMap<String, String>();
int argc = 0;
for (String arg: args)
if (arg.equals("--help") || arg.equals("-h"))
usage(0);
if (argc + 3 != args.length)
usage(1);
opts.put("size", args[1]);
opts.put("coplanarity", "0.9");
if(false) {
String metricsFile = args[0]+File.separator+"metricsMap";
opts.put("metricsFile", metricsFile);
PrimitiveFileReaderFactory pfrf = new PrimitiveFileReaderFactory();
DoubleFileReader dfr = pfrf.getDoubleReader(new File(args[0]+File.separator+"jcae3d.files"+File.separator+"nodes3d.bin"));
long n = dfr.size();
java.io.DataOutputStream out = new java.io.DataOutputStream(new java.io.BufferedOutputStream(new java.io.FileOutputStream(metricsFile)));
for (long i = 0; i < n; i += 3)
{
double x = dfr.get();
double y = dfr.get();
double z = dfr.get();
double val = (x - 9000.0)*(x - 9000.0) / 2250.0;
if (val > 200.0)
val = 200.0;
out.writeDouble(val);
}
out.close();
}
System.out.println("Running "+args[0]+" "+args[1]+" "+args[2]);
try
{
MeshReader.readObject3D(mesh, args[0]);
}
catch (IOException ex)
{
ex.printStackTrace();
throw new RuntimeException(ex);
}
Remesh smoother = new Remesh(mesh, opts);
smoother.compute();
try
{
MeshWriter.writeObject3D(smoother.getOutputMesh(), args[2], null);
}
catch (IOException ex)
{
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
}
| false | false | null | null |
diff --git a/gen/com/example/autobahn/BuildConfig.java b/gen/com/example/autobahn/BuildConfig.java
index 5de5177..9fc9fef 100644
--- a/gen/com/example/autobahn/BuildConfig.java
+++ b/gen/com/example/autobahn/BuildConfig.java
@@ -1,6 +1,8 @@
+/*___Generated_by_IDEA___*/
+
/** Automatically generated file. DO NOT MODIFY */
package com.example.autobahn;
public final class BuildConfig {
public final static boolean DEBUG = true;
}
\ No newline at end of file
diff --git a/gen/com/example/autobahn/Manifest.java b/gen/com/example/autobahn/Manifest.java
index ec68866..ff61b14 100644
--- a/gen/com/example/autobahn/Manifest.java
+++ b/gen/com/example/autobahn/Manifest.java
@@ -1,5 +1,7 @@
+/*___Generated_by_IDEA___*/
+
package com.example.autobahn;
/* This stub is for using by IDE only. It is NOT the Manifest class actually packed into APK */
public final class Manifest {
}
\ No newline at end of file
diff --git a/gen/com/example/autobahn/R.java b/gen/com/example/autobahn/R.java
index 3bf2a2c..660904c 100644
--- a/gen/com/example/autobahn/R.java
+++ b/gen/com/example/autobahn/R.java
@@ -1,5 +1,7 @@
+/*___Generated_by_IDEA___*/
+
package com.example.autobahn;
/* This stub is for using by IDE only. It is NOT the R class actually packed into APK */
public final class R {
}
\ No newline at end of file
diff --git a/src/autobahn/android/LoginActivity.java b/src/autobahn/android/LoginActivity.java
index c714973..1076766 100644
--- a/src/autobahn/android/LoginActivity.java
+++ b/src/autobahn/android/LoginActivity.java
@@ -1,117 +1,117 @@
package autobahn.android;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.autobahn.R;
import java.io.IOException;
import java.net.URISyntaxException;
public class LoginActivity extends Activity implements View.OnClickListener {
Button loginButton;
EditText usernameField;
EditText passwordField;
AutobahnClient client;
public final TextWatcher watcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void afterTextChanged(Editable editable) {
checkFields();
}
};
/*
stores at client the host and the port
*/
private void initClient() {
client=AutobahnClient.getInstance();
client.setContext(this);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initClient();
setContentView(R.layout.login);
loginButton = (Button) findViewById(R.id.loginButton);
usernameField = (EditText) findViewById(R.id.username);
passwordField = (EditText) findViewById(R.id.password);
usernameField.addTextChangedListener(watcher);
passwordField.addTextChangedListener(watcher);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
usernameField.getText().append(prefs.getString("username","") );
passwordField.getText().append(prefs.getString("password","") );
loginButton.setOnClickListener(this);
}
public void checkFields(){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
if(username.equals("") || password.equals(""))
loginButton.setEnabled(false);
else
loginButton.setEnabled(true);
}
public void onClick(View view) {
loginButton.setEnabled(false);
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
client.setUserName(username);
client.setPassword(password);
try {
client.logIn();
} catch (AutobahnClientException e) {
Toast toast = Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
loginButton.setEnabled(true);
toast.show();
return ;
}
- loginButton.setEnabled(true);
+ //loginButton.setEnabled(true);
Intent menuActivity = new Intent();
menuActivity.setClass(getApplicationContext(),MainMenu.class);
startActivity(menuActivity);
}
}
\ No newline at end of file
diff --git a/src/autobahn/android/MainMenu.java b/src/autobahn/android/MainMenu.java
index 11c5b49..90ea382 100644
--- a/src/autobahn/android/MainMenu.java
+++ b/src/autobahn/android/MainMenu.java
@@ -1,85 +1,85 @@
package autobahn.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.example.autobahn.R;
public class MainMenu extends Activity {
/**
* Called when the activity is first created.
*/
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.about);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent aboutActivity = new Intent();
aboutActivity.setClass(getApplicationContext(), AboutActivity.class);
startActivity(aboutActivity);
}
});
button = (Button) findViewById(R.id.idms);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent idmsActivity = new Intent();
idmsActivity.setClass(getApplicationContext(), IdmsActivity.class);
startActivity(idmsActivity);
}
});
button = (Button) findViewById(R.id.request);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent requestActivity = new Intent();
- requestActivity.setClass(getApplicationContext(), RequestActivity.class);
+ requestActivity.setClass(getApplicationContext(), RequestActivity2.class);
startActivity(requestActivity);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
//
inflater.inflate(R.menu.menu, menu);
return true; //
}
// Called when an options item is clicked
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//
case R.id.itemPrefs:
startActivity(new Intent(this, PrefsActivity.class)); //
break;
}
return true;
//
}
}
| false | false | null | null |
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/expression/ExpressionTest2.java b/test/src/com/redhat/ceylon/compiler/java/test/expression/ExpressionTest2.java
index b01ec53b4..39a5add07 100644
--- a/test/src/com/redhat/ceylon/compiler/java/test/expression/ExpressionTest2.java
+++ b/test/src/com/redhat/ceylon/compiler/java/test/expression/ExpressionTest2.java
@@ -1,531 +1,535 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.expression;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
public class ExpressionTest2 extends CompilerTest {
@Override
protected String transformDestDir(String name) {
return name + "-2";
}
// Method invocation
@Test
public void testInvAnonymousFunctionPositionalInvocation(){
compareWithJavaSource("invoke/AnonymousFunctionPositionalInvocation");
}
@Test
public void testInvAnonymousFunctionPositionalInvocation2(){
compareWithJavaSource("invoke/AnonymousFunctionPositionalInvocation2");
}
@Test
public void testInvAnonymousStatementFunction(){
compareWithJavaSource("invoke/AnonymousStatementFunction");
}
@Test
public void testInvMethodArgumentNamedInvocation(){
compareWithJavaSource("invoke/MethodArgumentNamedInvocation");
}
@Test
public void testInvMethodArgumentNamedInvocationVoid(){
compareWithJavaSource("invoke/MethodArgumentNamedInvocationVoid");
}
@Test
public void testInvMethodArgumentNamedInvocation2(){
compareWithJavaSource("invoke/MethodArgumentNamedInvocation2");
}
@Test
public void testInvMethodArgumentNamedInvocationMPL(){
compareWithJavaSource("invoke/MethodArgumentNamedInvocationMPL");
}
@Test
public void testInvMethodArgumentWithVariableParameterNamedInvocation(){
compareWithJavaSource("invoke/MethodArgumentWithVariableParameterNamedInvocation");
}
@Test
public void testInvObjectArgumentNamedInvocation(){
compareWithJavaSource("invoke/ObjectArgumentNamedInvocation");
}
@Test
public void testInvObjectArgumentNamedInvocationChained(){
compareWithJavaSource("invoke/ObjectArgumentNamedInvocationChained");
compileAndRun("com.redhat.ceylon.compiler.java.test.expression.invoke.objectArgumentNamedInvocationChained", "invoke/ObjectArgumentNamedInvocationChained.ceylon");
}
@Test
public void testInvGetterArgumentNamedInvocation(){
compareWithJavaSource("invoke/GetterArgumentNamedInvocation");
}
@Test
public void testInvGetterArgumentNamedInvocationGeneric(){
compareWithJavaSource("invoke/GetterArgumentNamedInvocationGeneric");
}
@Test
public void testInvGetterArgumentNamedInvocationBoxing(){
compareWithJavaSource("invoke/GetterArgumentNamedInvocationBoxing");
}
@Test
public void testInvChainedInvocations(){
compareWithJavaSource("invoke/ChainedInvocations");
}
@Test
public void testInvGenericMethodInvocation(){
compareWithJavaSource("invoke/GenericMethodInvocation");
}
@Test
public void testInvGenericMethodInvocationMixed(){
compareWithJavaSource("invoke/GenericMethodInvocationMixed");
}
@Test
public void testInvInnerMethodInvocation(){
compareWithJavaSource("invoke/InnerMethodInvocation");
}
@Test
public void testInvInvocationErasure(){
compareWithJavaSource("invoke/InvocationErasure");
}
@Test
public void testInvMethodInvocation(){
compareWithJavaSource("invoke/MethodInvocation");
}
@Test
public void testInvMethodInvocationWithDefaultedParameters(){
compareWithJavaSource("invoke/MethodInvocationWithDefaultedParameters");
}
@Test
public void testInvNamedArgumentGetterInvocation(){
compareWithJavaSource("invoke/NamedArgumentGetterInvocation");
}
@Test
public void testInvNamedArgumentInvocation(){
compareWithJavaSource("invoke/NamedArgumentInvocation");
}
@Test
public void testInvNamedArgumentNoArgs(){
compareWithJavaSource("invoke/NamedArgumentNoArgs");
}
@Test
public void testInvNamedArgumentInvocationInit(){
compareWithJavaSource("invoke/NamedArgumentInvocationInit");
}
@Test
public void testInvNamedArgumentInvocationTopLevel(){
compareWithJavaSource("invoke/NamedArgumentInvocationTopLevel");
}
@Test
public void testInvNamedArgumentInvocationLocal(){
compareWithJavaSource("invoke/NamedArgumentInvocationLocal");
}
@Test
public void testInvNamedArgumentWithSequence(){
compareWithJavaSource("invoke/NamedArgumentWithSequence");
}
@Test
public void testInvNamedArgumentWithIterable(){
compareWithJavaSource("invoke/NamedArgumentWithIterable");
}
@Test
public void testInvInvocationWithVarargsAndComprehensions(){
compareWithJavaSource("invoke/InvocationWithVarargsAndComprehensions");
}
@Test
public void testInvNamedArgumentWithEmptySequence(){
compareWithJavaSource("invoke/NamedArgumentWithEmptySequence");
}
@Test
public void testInvNamedArgumentInvocationInitWithSequence(){
compareWithJavaSource("invoke/NamedArgumentInvocationInitWithSequence");
}
@Test
public void testInvNamedArgumentInvocationInitWithEmptySequence(){
compareWithJavaSource("invoke/NamedArgumentInvocationInitWithEmptySequence");
}
@Test
public void testInvNamedArgumentInvocationOnPrimitive(){
compareWithJavaSource("invoke/NamedArgumentInvocationOnPrimitive");
}
@Test
public void testInvNamedArgumentInvocationWithMethodReference(){
compareWithJavaSource("invoke/NamedArgumentInvocationWithMethodReference");
}
@Test
public void testInvNamedArgumentSequencedTypeParamInvocation(){
compareWithJavaSource("invoke/NamedArgumentSequencedTypeParamInvocation");
}
@Test
public void testInvSequencedParameterInvocation(){
compareWithJavaSource("invoke/SequencedParameterInvocation");
}
@Test
public void testInvSequencedTypeParamInvocation(){
compareWithJavaSource("invoke/SequencedTypeParamInvocation");
}
@Test
public void testInvSequencedTypeParamInvocation2(){
compareWithJavaSource("invoke/SequencedTypeParamInvocation2");
}
@Test
public void testInvZeroSequencedArgs(){
compareWithJavaSource("invoke/ZeroSequencedArgs");
}
@Test
public void testInvDefaultedAndSequenced(){
compareWithJavaSource("invoke/DefaultedAndSequencedParams");
}
@Test
public void testInvDefaultedAndTypeParams(){
compareWithJavaSource("invoke/DefaultedAndTypeParams");
}
@Test
public void testInvToplevelMethodInvocation(){
compareWithJavaSource("invoke/ToplevelMethodInvocation");
}
@Test
public void testInvToplevelMethodWithDefaultedParams(){
compareWithJavaSource("invoke/ToplevelMethodWithDefaultedParams");
}
@Test
public void testInvOptionalTypeParamArgument(){
compareWithJavaSource("invoke/OptionalTypeParamArgument");
}
@Test
public void testCallableAndDefaultedArguments(){
compile("invoke/CallableAndDefaultedArguments_foo.ceylon");
compareWithJavaSource("invoke/CallableAndDefaultedArguments_bar");
}
@Test
@Ignore("M5??: #512: Not supported at the moment")
public void testCallableArgumentWithDefaultedArguments(){
compareWithJavaSource("invoke/CallableArgumentWithDefaulted");
// Note we want to run it as well, because one of the problems
// is not found at compile time (#512)
compileAndRun("com.redhat.ceylon.compiler.java.test.expression.invoke.callableArgumentWithDefaulted_main",
"invoke/CallableArgumentWithDefaulted");
}
@Test
public void testCallableWithDefaultedArguments(){
compareWithJavaSource("invoke/CallableWithDefaulted");
}
@Test
public void testCallableArgumentVoid(){
compareWithJavaSource("invoke/CallableArgumentVoid");
}
@Test
public void testCallableArgumentNullary(){
compareWithJavaSource("invoke/CallableArgumentNullary");
}
@Test
public void testCallableArgumentUnary(){
compareWithJavaSource("invoke/CallableArgumentUnary");
}
@Test
public void testCallableArgumentBinary(){
compareWithJavaSource("invoke/CallableArgumentBinary");
}
@Test
public void testCallableArgumentTernary(){
compareWithJavaSource("invoke/CallableArgumentTernary");
}
@Test
public void testCallableArgumentNary(){
compareWithJavaSource("invoke/CallableArgumentNary");
}
@Test
public void testCallableArgumentSequenced(){
compareWithJavaSource("invoke/CallableArgumentSequenced");
}
@Test
public void testCallableArgumentParameterClass(){
compareWithJavaSource("invoke/CallableArgumentParameterClass");
}
@Test
public void testCallableArgumentParameterQualified(){
compareWithJavaSource("invoke/CallableArgumentParameterQualified");
}
@Test
public void testCallableArgumentParameterTypeParam(){
compareWithJavaSource("invoke/CallableArgumentParameterTypeParam");
}
@Test
public void testCallableArgumentParameterTypeParamMixed(){
compareWithJavaSource("invoke/CallableArgumentParameterTypeParamMixed");
}
@Test
@Ignore("M5: Awaiting support for parameter bounds")
public void testCallableArgumentParameterCtor(){
compareWithJavaSource("invoke/CallableArgumentParameterCtor");
}
@Test
public void testCallableArgumentPassed(){
compareWithJavaSource("invoke/CallableArgumentPassed");
}
@Test
public void testCallableArgumentReturningInteger(){
compareWithJavaSource("invoke/CallableArgumentReturningInteger");
}
@Test
public void testCallableArgumentReturningClass(){
compareWithJavaSource("invoke/CallableArgumentReturningClass");
}
@Test
public void testCallableArgumentReturningQualifiedClass(){
compareWithJavaSource("invoke/CallableArgumentReturningQualifiedClass");
}
@Test
public void testCallableArgumentReturningTypeParam(){
compareWithJavaSource("invoke/CallableArgumentReturningTypeParam");
}
@Test
public void testCallableReturnNullary(){
compareWithJavaSource("invoke/CallableReturnNullary");
}
@Test
public void testCallableReturnUnary(){
compareWithJavaSource("invoke/CallableReturnUnary");
}
@Test
public void testCallableReturnBinary(){
compareWithJavaSource("invoke/CallableReturnBinary");
}
@Test
public void testCallableReturnTernary(){
compareWithJavaSource("invoke/CallableReturnTernary");
}
@Test
public void testCallableReturnNary(){
compareWithJavaSource("invoke/CallableReturnNary");
}
@Test
public void testCallableReturnCallable(){
compareWithJavaSource("invoke/CallableReturnCallable");
}
@Test
public void testCallableReturnMethod(){
compareWithJavaSource("invoke/CallableReturnMethod");
}
@Test
public void testCallableReturnReturningInteger(){
compareWithJavaSource("invoke/CallableReturnReturningInteger");
}
@Test
public void testCallableReturnReturningClass(){
compareWithJavaSource("invoke/CallableReturnReturningClass");
}
@Test
public void testCallablePositionalInvocationNullary(){
compareWithJavaSource("invoke/CallablePositionalInvocationNullary");
}
@Test
public void testCallablePositionalInvocationUnary(){
compareWithJavaSource("invoke/CallablePositionalInvocationUnary");
}
@Test
public void testCallableCapture(){
compareWithJavaSource("invoke/CallableCapture");
}
@Test
public void testCallablePositionalInvocationAndReturn(){
compareWithJavaSource("invoke/CallablePositionalInvocationAndReturn");
}
@Test
public void testCallablePositionalInvocationSequenced(){
compareWithJavaSource("invoke/CallablePositionalInvocationSequenced");
}
@Test
public void testCallablePositionalInvocationSequencedComprehension(){
compareWithJavaSource("invoke/CallablePositionalInvocationSequencedComprehension");
}
@Test
public void testCallablePositionalInvocationQualified(){
compareWithJavaSource("invoke/CallablePositionalInvocationQualified");
}
@Test
public void testCallableNamedInvocationNullary(){
compareWithJavaSource("invoke/CallableNamedInvocationNullary");
}
@Test
public void testCallableNamedInvocationUnary(){
compareWithJavaSource("invoke/CallableNamedInvocationUnary");
}
@Test
public void testCallableNamedInvocationBinary(){
compareWithJavaSource("invoke/CallableNamedInvocationBinary");
}
@Test
public void testCallableNamedInvocationNary(){
compareWithJavaSource("invoke/CallableNamedInvocationNary");
}
@Test
public void testCallableNamedInvocationSequenced(){
compareWithJavaSource("invoke/CallableNamedInvocationSequenced");
}
@Test
public void testIndirectInvoke(){
compareWithJavaSource("invoke/IndirectInvoke");
}
@Test
public void testIndirectTypeParam(){
compareWithJavaSource("invoke/IndirectTypeParam");
}
@Test
public void testDefaultFunctionReference(){
compareWithJavaSource("invoke/DefaultFunctionReference");
}
@Test
public void testFunctionalParameterMpl(){
compile("invoke/FunctionalParameterMpl.ceylon");
compile("invoke/FunctionalParameterMpl2.ceylon");
}
@Test
public void testInvSelfType(){
compareWithJavaSource("invoke/SelfType");
}
@Test @Ignore("Functionality not available anymore, keeping it for possible future language enhancement")
public void testInvSelfTypeGeneric(){
compareWithJavaSource("invoke/SelfTypeGeneric");
}
@Test
public void testInvTypeFamily(){
compareWithJavaSource("invoke/TypeFamily");
}
@Test @Ignore("Functionality not available anymore, keeping it for possible future language enhancement")
public void testInvTypeFamilyGeneric(){
compareWithJavaSource("invoke/TypeFamilyGeneric");
}
@Test
public void testInvSelfTypeInstantiation(){
compareWithJavaSource("invoke/SelfTypeInstantiation");
}
@Test
public void testInvOptionalCallable(){
compareWithJavaSource("invoke/OptionalCallable");
}
@Test
public void testInvMultipleParameterLists(){
compareWithJavaSource("invoke/MultipleParameterLists");
compareWithJavaSource("invoke/MultipleParameterLists_call");
}
+ @Test
+ public void testInvMultipleParameterListsWithVariableParameters(){
+ compareWithJavaSource("invoke/MultipleParameterListsWithVariableParameters");
+ }
@Test
public void testAvoidBackwardBranchWithVarargs(){
compileAndRun(
"com.redhat.ceylon.compiler.java.test.expression.invoke.avoidBackwardBranchWithVarargs_run",
"invoke/AvoidBackwardBranchWithVarargs.ceylon");
}
@Test
public void testInvSpreadArguments(){
compareWithJavaSource("invoke/SpreadArguments");
}
}
| true | false | null | null |
diff --git a/src/main/java/org/vaadin/vol/Style.java b/src/main/java/org/vaadin/vol/Style.java
index 7a6e350..a9e7ba7 100644
--- a/src/main/java/org/vaadin/vol/Style.java
+++ b/src/main/java/org/vaadin/vol/Style.java
@@ -1,585 +1,616 @@
package org.vaadin.vol;
import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
// Style Properties
//
// The properties that you can use for styling are:
// -- fillColor
// Default is #ee9900. This is the color used for filling in Polygons. It is also used in the center of marks for points: the interior color of circles or other shapes. It is not used if an externalGraphic is applied to a point.
//
// -- fillOpacity:
// Default is 0.4. This is the opacity used for filling in Polygons. It is also used in the center of marks for points: the interior color of circles or other shapes. It is not used if an externalGraphic is applied to a point.
//
// -- strokeColor
// Default is #ee9900. This is color of the line on features. On polygons and point marks, it is used as an outline to the feature. On lines, this is the representation of the feature.
//
// -- strokeOpacity
// Default is 1 This is opacity of the line on features. On polygons and point marks, it is used as an outline to the feature. On lines, this is the representation of the feature.
//
// -- strokeWidth
// Default is 1 This is width of the line on features. On polygons and point marks, it is used as an outline to the feature. On lines, this is the representation of the feature.
//
// -- strokeLinecap
// Default is round. Options are butt, round, square. This property is similar to the SVG stroke-linecap property. It determines what the end of lines should look like. See the SVG link for image examples.
//
// -- strokeDashstyle
// Default is solid. Options are:
// -- dot
// -- dash
// -- dashdot
// -- longdash
// -- longdashdot
// -- solid
//
// -- pointRadius
// Default is 6.
//
// -- pointerEvents:
// Default is visiblePainted. Only used by the SVG Renderer. See SVG pointer-events definition for more.
//
// -- cursor
// Cursor used when mouse is over the feature. Default is an empty string, which inherits from parent elements.
//
// -- externalGraphic
// An external image to be used to represent a point.
//
// -- graphicWidth, graphicHeight
// These properties define the height and width of an externalGraphic. This is an alternative to the pointRadius symbolizer property to be used when your graphic has different sizes in the X and Y direction.
//
// -- graphicOpacity
// Opacity of an external graphic.
//
// -- graphicXOffset, graphicYOffset
// Where the center of an externalGraphic should be.
//
// -- rotation
// The rotation angle in degrees clockwise for a point symbolizer.
//
// -- graphicName
// Name of a type of symbol to be used for a point mark.
//
// -- display
// Can be set to none to hide features from rendering.
public class Style {
public static final String STROKE_DASHSTYLE_SOLID = "solid";
public static final String STROKE_DASHSTYLE_DASHDOT = "dashdot";
public static final String STROKE_DASHSTYLE_DOT = "dot";
public static final String STROKE_DASHSTYLE_DASH = "dash";
public static final String STROKE_DASHSTYLE_LONGDASH = "longdash";
public static final String STROKE_DASHSTYLE_LONGDASHDOT = "longdashdor";
public static final String STROKE_LINECAP_BUTT = "butt";
public static final String STROKE_LINECAP_ROUND = "round";
public static final String STROKE_LINECAP_SQUARE = "square";
private static long idx = 0;
private String name;
private JsObject styleProperty;
public Style() {
name = "Style" + String.valueOf(++idx);
styleProperty = new JsObject();
init();
}
public Style(String string) {
name = string;
styleProperty = new JsObject();
init();
}
public String getName() {
return name;
}
public void setProperty(String key, Object value) {
styleProperty.setProperty(key, value);
}
private Object getProperty(String key) {
return styleProperty.getProperty(key);
}
private void setPropertyByAttribute(String key, String value) {
styleProperty.setProperty(key, "${" + value + "}");
}
/**
* Hex fill color. Default is '#ee9900'.
*
* @param c
* - hexidecimal color code or a W3C standard color name
*/
public void setFillColor(String c) {
setProperty("fillColor", c);
}
public void setFillColorByAttribute(String c) {
setPropertyByAttribute("fillColor", c);
}
/** Hex fill color. */
public String getFillColor() {
return (String) getProperty("fillColor");
}
/** Fill opacity (0-1). Default is 0.4 */
public void setFillOpacity(double o) {
setProperty("fillOpacity", o);
}
public void setFillOpacityByAttribute(String o) {
setPropertyByAttribute("fillOpacity", o);
}
/** Fill opacity (0-1). */
public double getFillOpacity() {
double o = (Double) getProperty("fillOpacity");
return o;
}
/** Pixel point radius. Default is 6. */
public void setPointRadius(double r) {
setProperty("pointRadius", r);
}
public void setPointRadiusByAttribute(String r) {
setPropertyByAttribute("pointRadius", r);
}
/** Pixel point radius. */
public double getPointRadius() {
return (Double) getProperty("pointRadius");
}
/**
* Hex stroke color. Default is '#ee9900'.
*
* @param c
* - see setFillColor
*/
public void setStrokeColor(String c) {
setProperty("strokeColor", c);
}
public void setStrokeColorByAttribute(String c) {
setPropertyByAttribute("strokeColor", c);
}
/** Hex stroke html color. */
public String getStrokeColor() {
return (String) getProperty("strokeColor");
}
/** Pixel stroke width. Default is 1. */
public void setStrokeWidth(double w) {
setProperty("strokeWidth", w);
}
-
+
public void setStrokeWidthByAttribute(String w) {
setPropertyByAttribute("strokeWidth", w);
}
/** Pixel stroke width. */
public double getStrokeWidth() {
return (Double) getProperty("strokeWidth");
}
/** Url to an external graphic that will be used for rendering points. */
public void setExternalGraphic(String graphicURL) {
setProperty("externalGraphic", graphicURL);
}
public void setExternalGraphicByAttribute(String graphicURL) {
setPropertyByAttribute("externalGraphic", graphicURL);
}
/** Url to an external graphic that will be used for rendering points. */
public String getExternalGraphic() {
return (String) getProperty("externalGraphic");
}
/**
* Convenient method to set the pixel width and height for sizing an
* external graphic.
*
* @param width
* The width (in pixels) to set
* @param height
* The height (in pixels) to set
*/
public void setGraphicSize(int width, int height) {
setGraphicWidth(width);
setGraphicHeight(height);
}
public void setGraphicWidth(int width) {
setProperty("graphicWidth", width);
}
public void setGraphicWidthByAttribute(String widthAttr) {
setPropertyByAttribute("graphicWidth", widthAttr);
}
public void setGraphicHeight(int height) {
setProperty("graphicHeight", height);
}
public void setGraphicHeightByAttribute(String heightAttr) {
setPropertyByAttribute("graphicHeight", heightAttr);
}
/** Pixel width for sizing an external graphic. */
public int getGraphicWidth() {
return (Integer) getProperty("graphicWidth");
}
/** Pixel height for sizing an external graphic. */
public int getGraphicHeight() {
return (Integer) getProperty("graphicHeight");
}
/**
* Sets the offset for the displacement of the external graphic. The offset
* is from the top-lef of the image (which is considered the point 0,0).
*
* @param xOffset
* Pixel offset along the positive x axis for displacing an
* external graphic.
* @param yOffset
* Pixel offset along the positive y axis for displacing an
* external graphic.
*/
public void setGraphicOffset(int xOffset, int yOffset) {
setGraphicXOffset(xOffset);
setGraphicYOffset(yOffset);
}
public void setGraphicOffsetByAttribute(String xOffsetAttr,
String yOffsetAttr) {
setGraphicXOffsetByAttribute(xOffsetAttr);
setGraphicYOffsetByAttribute(yOffsetAttr);
}
public void setGraphicXOffset(int xOffset) {
setProperty("graphicXOffset", xOffset);
}
public void setGraphicXOffsetByAttribute(String xOffsetAttr) {
setPropertyByAttribute("graphicXOffset", xOffsetAttr);
}
public void setGraphicYOffset(int yOffset) {
setProperty("graphicYOffset", yOffset);
}
public void setGraphicYOffsetByAttribute(String yOffsetAttr) {
setPropertyByAttribute("graphicYOffset", yOffsetAttr);
}
/**
* Sets the size of the background graphic. If none of the dimensions are
* set, the external graphic size is used.
*
* @param backgroundWidth
* The width of the background width.
* @param backgroundHeight
* The height of the background graphic.
*/
public void setBackgroundGraphicSize(int backgroundWidth,
int backgroundHeight) {
setBackgroundWidth(backgroundWidth);
setBackgroundHeight(backgroundHeight);
}
/**
* The height of the background graphic. If not provided, the graphicHeight
* will be used.
*/
public void setBackgroundHeight(int backgroundHeight) {
setProperty("backgroundHeight", backgroundHeight);
}
/** The height of the background graphic. */
public int getBackgroundHeight() {
return (Integer) getProperty("backgroundHeight");
}
/**
* The width of the background width. If not provided, the graphicWidth will
* be used.
*/
public void setBackgroundWidth(int backgroundWidth) {
setProperty("backgroundWidth", backgroundWidth);
}
/** The width of the background width. */
public int getBackgroundWidth() {
return (Integer) getProperty("backgroundWidth");
}
/** Url to a graphic to be used as the background under an externalGraphic. */
public void setBackgroundGraphic(String graphicURL) {
setProperty("backgroundGraphic", graphicURL);
}
/** Url to a graphic to be used as the background under an externalGraphic. */
public String getBackgroundGraphic() {
return (String) getProperty("backgroundGraphic");
}
/**
* Sets the offset for the displacement of the background graphic. The
* offset is from the top-left of the image (which is considered the point
* 0,0).
*
* @param backgroundXOffset
* Pixel offset along the positive x axis for displacing an
* background graphic.
* @param backgroundYOffset
* Pixel offset along the positive y axis for displacing an
* background graphic.
*/
public void setBackgroundOffset(int backgroundXOffset, int backgroundYOffset) {
setBackgroundXOffset(backgroundXOffset);
setBackgroundYOffset(backgroundYOffset);
}
public void setBackgroundXOffset(int backgroundXOffset) {
setProperty("backgroundXOffset", backgroundXOffset);
}
public void setBackgroundYOffset(int backgroundYOffset) {
setProperty("backgroundYOffset", backgroundYOffset);
}
/** The integer z-index value to use in rendering. */
public void setGraphicZIndex(int graphicZIndex) {
setProperty("graphicZIndex", graphicZIndex);
}
/** The integer z-index value to use in rendering. */
public int getGraphicZIndex() {
return (Integer) getProperty("graphicZIndex");
}
/**
* The integer z-index value to use in rendering the background graphic.
* Usually is a number smaller then the GraphicZIndex, so the background can
* be behind the feature graphic.
*/
public void setBackgroundGraphicZIndex(int backgroundGraphicZIndex) {
setProperty("backgroundGraphicZIndex", backgroundGraphicZIndex);
}
/** The integer z-index value to use in rendering the background graphic. */
public int getBackgroundGraphicZIndex() {
return (Integer) getProperty("backgroundGraphicZIndex");
}
/** Stroke opacity (0-1). Default is 1. */
public void setStrokeOpacity(double strokeOpacity) {
setProperty("strokeOpacity", strokeOpacity);
}
public double getStrokeOpacity() {
return (Double) getProperty("strokeOpacity");
}
/**
* The text for an optional label. For browsers that use the canvas
* renderer, this requires either fillText or mozDrawText to be available.
* <p>
* Note: you can set a custom label for each feature added to a layer by
* using tags in the label, and setting attributes using
* {@link org.gwtopenmaps.openlayers.client.util.Attributes}. For example,
* set the style.label to "${customLabel}", then, for each feature added to
* the layer, add an "customLabel" attribute with
* <p>
* <code>attributes.setAttribute("customLabel","myLabel for this specific feature")</code>
* <p>
* Note: this can also be used in any style field of type String, such as
* fillColor, fontColor, etc
* */
public void setLabel(String label) {
setProperty("label", label);
}
-
+
public void setLabelByAttribute(String label) {
setPropertyByAttribute("label", label);
}
-
/** The font color for the label, to be provided like CSS. */
public void setFontColor(String fontColor) {
setProperty("fontColor", fontColor);
}
/** The font size for the label, to be provided like in CSS. */
public void setFontSize(String fontSize) {
setProperty("fontSize", fontSize);
}
/** The font family for the label, to be provided like in CSS. */
public void setFontFamily(String fontFamily) {
setProperty("fontFamily", fontFamily);
}
/** The font weight for the label, to be provided like in CSS. */
public void setFontWeight(String fontWeight) {
setProperty("fontWeight", fontWeight);
}
/**
* Sets the Label alignment string directly. This specifies the insertion
* point relative to the text. It is a string composed of two characters.
* <p>
* The first character is for the horizontal alignment, the second for the
* vertical alignment.
* <p>
* Valid values for horizontal alignment: 'l'=left, 'c'=center, 'r'=right.
* Valid values for vertical alignment: 't'=top, 'm'=middle, 'b'=bottom.
* Example values: 'lt', 'cm', 'rb'. The canvas renderer does not support
* vertical alignment, it will always use 'b'.
*/
public void setLabelAlign(String align) {
setProperty("labelAlign", align);
}
/**
* Vertical Label alignment. This specifies the insertion point relative to
* the text.
*/
public String getLabelAlign() {
return (String) getProperty("labelAlign");
}
+ public void setLabelXOffset(int offset) {
+ setProperty("labelXOffset", offset);
+ }
+
+ public Integer getLabelXOffset() {
+ return (Integer) getProperty("labelXOffset");
+ }
+
+ public void setLabelYOffset(int offset) {
+ setProperty("labelYOffset", offset);
+ }
+
+ public Integer getLabelYOffset() {
+ return (Integer) getProperty("labelYOffset");
+ }
+
+ public void setLabelOutlineColor(String color) {
+ setProperty("labelOutlineColor", color);
+ }
+
+ public String getLabelOutlineColor() {
+ return (String) getProperty("labelOutlineColor");
+ }
+
+ public void setLabelOutlineWidth(int width) {
+ setProperty("labelOutlineWidth", width);
+ }
+
+ public Integer getLabelOutlineWidth(){
+ return (Integer) getProperty("labelOutlineWidth");
+ }
+
/** Stroke linecap. */
public String getStrokeLinecap() {
return (String) getProperty("strokeLinecap");
}
/**
* Directly sets the StrokeLineCap string. Default is 'round'. [butt | round
* | square]
*/
public void setStrokeLinecap(String strokeLinecap) {
setProperty("strokeLinecap", strokeLinecap);
}
/**
* Directly sets the stroke dash style string. Default is Default is
* 'solid'. [dot | dash | dashdot | longdash | longdashdot | solid]
*/
public void setStrokeDashstyle(String strokeDashstyle) {
setProperty("strokeDashstyle", strokeDashstyle);
}
/**
* Stroke dash style.
*/
public String getStrokeDashstyle() {
return (String) getProperty("strokeDashstyle");
}
/** Set to false if no fill is desired. */
public void setFill(boolean fill) {
setProperty("fill", fill);
}
/** Set to false if no fill is desired. */
public boolean getFill() {
return (Boolean) getProperty("fill");
}
/** Set to false if no stroke is desired. */
public void setStroke(boolean stroke) {
setProperty("stroke", stroke);
}
/** Set to false if no stroke is desired. */
public boolean getStroke() {
return (Boolean) getProperty("stroke");
}
/** Set to false if no graphic is desired. */
public void setGraphic(boolean graphic) {
setProperty("graphic", graphic);
}
/** Set to false if no graphic is desired. */
public boolean getGraphic() {
return (Boolean) getProperty("graphic");
}
/** Cursor. Default is ''. */
public void setCursor(String cursor) {
setProperty("cursor", cursor);
}
/** Cursor. */
public String getCursor() {
return (String) getProperty("cursor");
}
/**
* Directly sets the named graphic to use when rendering points. Default is
* 'circle'.
* <p>
* Supported values include 'circle' (default), 'square', 'star', 'x',
* 'cross', 'triangle'.
*/
public void setGraphicName(String graphicName) {
setProperty("graphicName", graphicName);
}
/**
* Named graphic to use when rendering points. Supported values include
* 'circle' (default), 'square', 'star', 'x', 'cross', 'triangle'.
*/
public String getGraphicName() {
return (String) getProperty("graphicName");
}
/**
* Tooltip for an external graphic. Only supported in Firefox and Internet
* Explorer.
*/
public void setGraphicTitle(String graphicTitle) {
setProperty("graphicTitle", graphicTitle);
}
/**
* Tooltip for an external graphic. Only supported in Firefox and Internet
* Explorer.
*/
public String getGraphicTitle() {
return (String) getProperty("graphicTitle");
}
public void paint(String string, PaintTarget target) throws PaintException {
target.addAttribute(string, styleProperty.getKeyValueMap());
}
/**
* @param coreStyleName
* the core style name this Style should extend. E.g. 'default'
* or 'selected'
*/
public void extendCoreStyle(String coreStyleName) {
setProperty("__VOL_INHERIT", coreStyleName);
}
private void init() {
extendCoreStyle("default");
}
public void setContextJs(String js) {
setProperty("__VOL_CONTEXT", js);
}
}
| false | false | null | null |
diff --git a/core/src/main/java/com/jakeapp/core/synchronization/ProjectRequestListener.java b/core/src/main/java/com/jakeapp/core/synchronization/ProjectRequestListener.java
index ebad144a..74c51bc9 100644
--- a/core/src/main/java/com/jakeapp/core/synchronization/ProjectRequestListener.java
+++ b/core/src/main/java/com/jakeapp/core/synchronization/ProjectRequestListener.java
@@ -1,360 +1,360 @@
package com.jakeapp.core.synchronization;
import com.jakeapp.core.dao.exceptions.NoSuchLogEntryException;
import com.jakeapp.core.domain.FileObject;
import com.jakeapp.core.domain.ILogable;
import com.jakeapp.core.domain.JakeObject;
import com.jakeapp.core.domain.LogAction;
import com.jakeapp.core.domain.NoteObject;
import com.jakeapp.core.domain.Project;
import com.jakeapp.core.domain.UserId;
import com.jakeapp.core.domain.exceptions.IllegalProtocolException;
import com.jakeapp.core.domain.logentries.LogEntry;
import com.jakeapp.core.services.ICSManager;
import com.jakeapp.core.synchronization.helpers.MessageMarshaller;
import com.jakeapp.core.util.ProjectApplicationContextFactory;
import com.jakeapp.jake.fss.FSService;
import com.jakeapp.jake.ics.ICService;
import com.jakeapp.jake.ics.exceptions.NetworkException;
import com.jakeapp.jake.ics.exceptions.NotLoggedInException;
import com.jakeapp.jake.ics.exceptions.OtherUserOfflineException;
import com.jakeapp.jake.ics.filetransfer.FileRequestFileMapper;
import com.jakeapp.jake.ics.filetransfer.IncomingTransferListener;
import com.jakeapp.jake.ics.filetransfer.negotiate.FileRequest;
import com.jakeapp.jake.ics.filetransfer.runningtransfer.IFileTransfer;
import com.jakeapp.jake.ics.msgservice.IMessageReceiveListener;
import com.jakeapp.jake.ics.status.ILoginStateListener;
import com.jakeapp.jake.ics.status.IOnlineStatusListener;
import junit.framework.Assert;
import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.util.List;
import java.util.UUID;
public class ProjectRequestListener
implements IMessageReceiveListener, IOnlineStatusListener,
ILoginStateListener, IncomingTransferListener, FileRequestFileMapper {
private static final String BEGIN_LOGENTRY = "<le>";
private static final String END_LOGENTRY = "</le>";
private static final String BEGIN_PROJECT_UUID = "<project>";
private static final String END_PROJECT_UUID = "</project>";
private static final String LOGENTRIES_MESSAGE = "<logentries/>";
private static final String REQUEST_LOGS_MESSAGE = "<requestlogs/>";
private static final String NEW_FILE = "<newfile/>";
private static final String POKE_MESSAGE = "<poke/>"; // dup
private static final String NEW_NOTE = "<newnote/>";
private Project p;
private ICSManager ICSManager;
private ProjectApplicationContextFactory db;
private IInternalSyncService syncService;
private MessageMarshaller messageMarshaller;
private static Logger log = Logger.getLogger(ProjectRequestListener.class);
public ProjectRequestListener(Project p, ICSManager icsManager,
ProjectApplicationContextFactory db, IInternalSyncService syncService,
MessageMarshaller messageMarshaller) {
this.p = p;
this.ICSManager = icsManager;
this.db = db;
this.syncService = syncService;
this.messageMarshaller = messageMarshaller;
}
public ICSManager getICSManager() {
return ICSManager;
}
private void sendLogs(Project project, com.jakeapp.jake.ics.UserId user) {
ICService ics = ICSManager.getICService(project);
try {
List<LogEntry<? extends ILogable>> logs = db.getLogEntryDao(project).getAll();
String message = messageMarshaller.packLogEntries(project, logs);
ics.getMsgService().sendMessage(user, message);
} catch (NetworkException e) {
log.warn("Could not sync logs", e);
} catch (OtherUserOfflineException e) {
log.warn("Could not sync logs", e);
}
}
private String getProjectUUID(String content) {
int begin = content.indexOf(BEGIN_PROJECT_UUID) + BEGIN_PROJECT_UUID.length();
int end = content.indexOf(END_PROJECT_UUID);
return content.substring(begin, end);
}
@Override @Transactional
public void receivedMessage(com.jakeapp.jake.ics.UserId from_userid,
String content) {
String projectUUID = getProjectUUID(content);
log.debug("Received a message for project " + projectUUID);
if (!projectUUID.equals(p.getProjectId())) {
log.debug("Discarding message because it's not for this project");
return;
}
log.debug("Message is for this project!");
String message = content.substring(BEGIN_PROJECT_UUID.length() + projectUUID
.length() + END_PROJECT_UUID.length());
log.debug("Message content: \"" + message + "\"");
if (message.startsWith(POKE_MESSAGE)) {
log.info("Received poke from " + from_userid.getUserId());
log.debug("This means we should sync logs!");
// Eventually, this should consider things such as trust
UserId user = getICSManager().getFrontendUserId(p, from_userid);
try {
syncService.startLogSync(p, user);
} catch (IllegalProtocolException e) {
// This should neeeeeeeeever happen
log.fatal(
"Received an unexpected IllegalProtocolException while trying to perform logsync",
e);
}
return;
}
if (message.startsWith(REQUEST_LOGS_MESSAGE)) {
log.info("Received logs request from " + from_userid.getUserId());
sendLogs(p, from_userid);
return;
}
if (message.startsWith(LOGENTRIES_MESSAGE)) {
log.info("Received serialized logentries from " + from_userid.getUserId());
String les = message.substring(LOGENTRIES_MESSAGE.length() + BEGIN_LOGENTRY
.length(), message.length() - END_LOGENTRY.length());
List<LogEntry<? extends ILogable>> logEntries =
this.messageMarshaller.unpackLogEntries(les);
for (LogEntry<? extends ILogable> entry : logEntries) {
try {
log.debug("Deserialized successfully, it is a " + entry
.getLogAction() + " for object UUID " + entry.getObjectuuid());
db.getLogEntryDao(p).create(entry);
} catch (Throwable t) {
log.debug("Failed to deserialize and/or save", t);
}
}
}
// TODO: The stuff below here could use some refactoring
// (e.g. redeclaring parameter content)
int uuidlen = UUID.randomUUID().toString().length();
String projectid = message.substring(0, uuidlen);
message = message.substring(uuidlen);
Project p = syncService.getProjectById(projectid);
ChangeListener cl = syncService.getProjectChangeListener(projectid);
if (message.startsWith(NEW_NOTE)) {
log.debug("requesting note");
UUID uuid = UUID.fromString(message.substring(NEW_NOTE.length()));
log.debug("persisting object");
NoteObject no = new NoteObject(uuid, p, "loading ...");
db.getNoteObjectDao(p).persist(no);
log.debug("calling other user: " + from_userid);
try {
p.getMessageService().getIcsManager().getTransferService(p)
.request(new FileRequest("N" + uuid, false, from_userid),
cl.beganRequest(no));
} catch (NotLoggedInException e) {
log.error("Not logged in");
}
}
if (message.startsWith(NEW_FILE)) {
log.debug("requesting file");
String relpath = message.substring(NEW_FILE.length());
FileObject fo = new FileObject(p, relpath);
log.debug("persisting object");
db.getFileObjectDao(p).persist(fo);
log.debug("calling other user: " + from_userid);
try {
p.getMessageService().getIcsManager().getTransferService(p)
.request(new FileRequest("F" + relpath, false, from_userid),
cl.beganRequest(fo));
} catch (NotLoggedInException e) {
log.error("Not logged in");
}
}
}
@Override
public void onlineStatusChanged(com.jakeapp.jake.ics.UserId userid) {
- // TODO Auto-generated method stub
+
log.info("Online status of " + userid
.getUserId() + " changed... (Project " + p + ")");
}
public void loginHappened() {
log.info("We logged in with project " + this.p);
try {
getICSManager().getTransferService(p).startServing(this, this);
} catch (NotLoggedInException e) {
log.error("error starting file serving", e);
}
}
public void logoutHappened() {
log.info("We logged out with project " + this.p);
try {
// only stop the transfer service if it exists.
if (getICSManager().hasTransferService(p)) {
getICSManager().getTransferService(p).stopServing();
}
} catch (NotLoggedInException e) {
// ignore
}
}
@Override public void connectionStateChanged(ConnectionState le, Exception ex) {
if (ConnectionState.LOGGED_IN == le) {
loginHappened();
} else if (ConnectionState.LOGGED_OUT == le) {
logoutHappened();
}
}
private FileObject getFileObjectForRequest(String filerequest) {
if (!p.getProjectId()
.equals(this.messageMarshaller.getProjectUUIDFromRequestMessage(
filerequest))) {
log.debug("got request for a different project");
return null; // not our project
}
UUID leuuid =
this.messageMarshaller.getLogEntryUUIDFromRequestMessage(filerequest);
LogEntry<? extends ILogable> le;
try {
le = db.getLogEntryDao(p).get(leuuid);
} catch (NoSuchLogEntryException e) {
log.debug("we don't know about this version");
return null;
}
if (le.getLogAction() != LogAction.JAKE_OBJECT_NEW_VERSION) {
log.debug("the requested logentry is not a version");
return null;
}
log.debug("got request for file belonging to entry " + leuuid);
FileObject fo = (FileObject) le.getBelongsTo();
LogEntry<JakeObject> version;
try {
version = db.getLogEntryDao(p).getLastVersionOfJakeObject(fo);
} catch (NoSuchLogEntryException e1) {
log.debug("we don't have a version");
return null;
}
if (!version.getUuid().equals(leuuid)) {
log.debug("we have a other last version");
return null;
}
Attributed<FileObject> status;
try {
status = syncService.getJakeObjectSyncStatus(fo);
} catch (Exception e) {
log.debug("status of the requested object is weird", e);
return null;
}
if (status.isModifiedLocally()) {
log.debug("can't distribute tainted object");
return null;
}
return fo;
}
@Override
public boolean accept(FileRequest req) {
try {
log.info("incoming request: " + req);
FileObject fo = getFileObjectForRequest(req.getFileName());
if (fo == null) {
// reason has already been logged.
return false;
}
log.info("we accept the request");
return true;
} catch (Exception e) {
log.warn("unexpected Exception", e);
return false;
}
}
@Override
public void started(IFileTransfer t) {
log.debug("we are transmitting." + t);
// TODO: maybe we want to watch. maybe we don't.
}
private File getDeliveryDirectory() {
String systmpdir = System.getProperty("java.io.tmpdir", "");
if (!systmpdir.endsWith(File.separator))
systmpdir = systmpdir + File.separator;
File f = new File(systmpdir);
Assert.assertEquals("tmpdir", systmpdir, f.getAbsolutePath() + File.separator);
return new File(systmpdir + File.separator + "jakeDelivery");
}
@Override
public File getFileForRequest(FileRequest req) {
// this is a interesting function. watch this:
try {
log.info("incoming request: " + req);
FileObject fo = getFileObjectForRequest(req.getFileName());
if (fo == null) {
// reason has already been logged.
return null;
}
File origfile = syncService.getFile(fo);
log.info("original file at " + origfile);
File tempfile = new File(getDeliveryDirectory(), req.getFileName());
FSService.writeFileStreamAbs(tempfile.getAbsolutePath(),
FSService.readFileStreamAbs(origfile.getAbsolutePath()));
log.info("we accept the request and provided the file at " + tempfile);
return tempfile;
} catch (Exception e) {
log.warn("unexpected Exception", e);
return null;
}
}
}
\ No newline at end of file
diff --git a/ics-xmpp/src/main/java/com/jakeapp/jake/ics/impl/xmpp/status/XmppStatusService.java b/ics-xmpp/src/main/java/com/jakeapp/jake/ics/impl/xmpp/status/XmppStatusService.java
index 9a366c43..999cdba3 100644
--- a/ics-xmpp/src/main/java/com/jakeapp/jake/ics/impl/xmpp/status/XmppStatusService.java
+++ b/ics-xmpp/src/main/java/com/jakeapp/jake/ics/impl/xmpp/status/XmppStatusService.java
@@ -1,274 +1,277 @@
package com.jakeapp.jake.ics.impl.xmpp.status;
import com.jakeapp.jake.ics.UserId;
import com.jakeapp.jake.ics.exceptions.NetworkException;
import com.jakeapp.jake.ics.exceptions.NoSuchUseridException;
import com.jakeapp.jake.ics.exceptions.NotLoggedInException;
import com.jakeapp.jake.ics.exceptions.OtherUserOfflineException;
import com.jakeapp.jake.ics.exceptions.TimeoutException;
import com.jakeapp.jake.ics.impl.xmpp.XmppConnectionData;
import com.jakeapp.jake.ics.impl.xmpp.XmppUserId;
import com.jakeapp.jake.ics.impl.xmpp.helper.RosterPresenceChangeListener;
import com.jakeapp.jake.ics.impl.xmpp.helper.XmppCommons;
import com.jakeapp.jake.ics.status.ILoginStateListener;
import com.jakeapp.jake.ics.status.IStatusService;
import org.apache.log4j.Logger;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* The Status Service. There's a main one + one for every project.
*/
public class XmppStatusService implements IStatusService {
private static final Logger log = Logger.getLogger(XmppStatusService.class);
private XmppConnectionData con;
private List<ILoginStateListener> lsll = new LinkedList<ILoginStateListener>();
private ConnectionListener connectionListener = new XmppConnectionListener();
public XmppStatusService(XmppConnectionData connection) {
this.con = connection;
}
private void addDiscoveryFeature() {
// Obtain the ServiceDiscoveryManager associated with my XMPPConnection
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager
.getInstanceFor(this.con.getConnection());
// Register that a new feature is supported by this XMPP entity
discoManager.addFeature(this.con.getNamespace());
}
@Override
public String getFirstname(UserId userid) throws NoSuchUseridException,
OtherUserOfflineException {
// TODO replace with real implementation (VCard)
XmppUserId xid = new XmppUserId(userid);
if (!xid.isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (!xid.getUsername().contains(".")) {
return "";
}
return xid.getUsername().substring(0, xid.getUsername().indexOf("."));
}
@Override
public String getLastname(UserId userid) throws NoSuchUseridException,
OtherUserOfflineException {
// TODO replace with real implementation (VCard)
XmppUserId xid = new XmppUserId(userid);
if (!xid.isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (!xid.getUsername().contains(".")) {
return "";
}
return xid.getUsername().substring(
xid.getUsername().indexOf(".") + 1);
}
@Override
public UserId getUserId(String userid) {
UserId ui = new XmppUserId(userid);
if (ui.isOfCorrectUseridFormat())
return ui;
else
return null;
}
@Override
public XmppUserId getUserid() throws NotLoggedInException {
if (!isLoggedIn())
throw new NotLoggedInException();
return this.con.getUserId();
}
@Override
public Boolean isLoggedIn() {
return XmppCommons.isLoggedIn(this.con.getConnection());
}
@Override
public Boolean isLoggedIn(UserId userid) throws NetworkException, TimeoutException {
if (!new XmppUserId(userid).isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (XmppUserId.isSameUser(getUserid(), userid))
return isLoggedIn();
if (!isLoggedIn())
throw new NotLoggedInException();
if (getRoster().getEntry(userid.toString()) != null) {
log.debug("Type for " + userid + ": "
+ getRoster().getEntry(userid.toString()).getType());
log.debug("Status for " + userid + ": "
+ getRoster().getEntry(userid.toString()).getStatus());
}
Presence p = getRoster().getPresence(userid.toString());
log.debug("Presence for " + userid + ": " + p);
return p.isAvailable();
}
private Roster getRoster() throws NotLoggedInException {
if (!this.con.getService().getStatusService().isLoggedIn())
throw new NotLoggedInException();
return this.con.getConnection().getRoster();
}
@Override
public void login(UserId userid, String pw) throws NetworkException {
XmppUserId xuid = new XmppUserId(userid);
if (!xuid.isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (isLoggedIn()) {
log.warn("A XMPP Service was logged in which wasn't expected. I'll log it out...");
logout();
}
this.con.setConnection(null);
XMPPConnection connection;
fireConnectionStateChanged(ILoginStateListener.ConnectionState.CONNECTING);
try {
connection = XmppCommons.login(xuid.getUserId(), pw, xuid.getResource());
connection.addConnectionListener(connectionListener);
} catch (IOException e) {
log.debug("connecting failed (network problems?)", e);
throw new NetworkException(e);
}catch (XMPPException e) {
log.debug("connecting failed (wrong credientals, generic xmpp error)", e);
throw new NetworkException(e);
}
connection.sendPacket(new Presence(Presence.Type.available));
this.con.setConnection(connection);
addDiscoveryFeature();
registerForEvents();
getRoster().setSubscriptionMode(Roster.SubscriptionMode.accept_all);
fireConnectionStateChanged(ILoginStateListener.ConnectionState.LOGGED_IN);
}
private void registerForEvents() throws NotLoggedInException {
getRoster().addRosterListener(new RosterPresenceChangeListener() {
public void presenceChanged(Presence presence) {
final String xmppid = presence.getFrom();
XmppStatusService.log.debug("presenceChanged: " + xmppid
+ " - " + presence);
if (isLoggedIn()) {
try {
XmppStatusService.this.con.getService()
.getUsersService().requestOnlineNotification(
new XmppUserId(xmppid));
} catch (NotLoggedInException e) {
log.debug("Shouldn't happen", e);
}
} else {
// skip. We don't want notifications after we logout.
}
}
});
}
@Override
public void logout() throws NetworkException {
XmppCommons.logout(this.con.getConnection());
if(this.con.getConnection() != null) {
this.con.getConnection().removeConnectionListener(connectionListener);
}
this.con.setConnection(null);
fireConnectionStateChanged(ILoginStateListener.ConnectionState.LOGGED_OUT);
}
/**
* Fires the new Connection state to all registered listeners.
* @param state
*/
private void fireConnectionStateChanged(ILoginStateListener.ConnectionState state) {
- if (lsll.size()>0) {
- for (ILoginStateListener lsl : lsll) {
+ if (lsll.size() > 0) {
+ // we have to copy our current listeners cause e.g. XmppFileTransferMethod may
+ // registrate on our listener just as we are spreading the event...
+ for (ILoginStateListener lsl : new ArrayList<ILoginStateListener>(lsll)) {
lsl.connectionStateChanged(state,null);
}
}
}
@Override
public void createAccount(UserId userid, String pw) throws NetworkException {
if (!new XmppUserId(userid).isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (isLoggedIn())
logout();
this.con.setConnection(null);
XMPPConnection connection;
try {
connection = XmppCommons.createAccount(userid.getUserId(), pw);
} catch (IOException e) {
log.debug("create failed: " + e.getMessage());
throw new NetworkException(e);
}
if (connection == null) {
throw new RuntimeException("Connection is null!");
}
XmppCommons.logout(connection);
}
@Override
public void addLoginStateListener(ILoginStateListener lsl) {
log.debug("Adding LoginStateListener");
lsll.add(lsl);
}
@Override
public void removeLoginStateListener(ILoginStateListener lsl) {
log.debug("Removing LoginStateListener");
lsll.remove(lsl);
}
/**
* Inner class to translate smack's connection events to our common interface
*/
private class XmppConnectionListener implements ConnectionListener {
@Override public void connectionClosed() {
fireConnectionStateChanged(ILoginStateListener.ConnectionState.LOGGED_OUT);
}
@Override public void connectionClosedOnError(Exception e) {
fireConnectionStateChanged(ILoginStateListener.ConnectionState.LOGGED_OUT);
}
@Override public void reconnectingIn(int i) {
fireConnectionStateChanged(ILoginStateListener.ConnectionState.CONNECTING);
}
@Override public void reconnectionSuccessful() {
fireConnectionStateChanged(ILoginStateListener.ConnectionState.LOGGED_IN);
}
@Override public void reconnectionFailed(Exception e) {
fireConnectionStateChanged(ILoginStateListener.ConnectionState.LOGGED_OUT);
}
}
}
| false | false | null | null |
diff --git a/src/main/java/helper/CrowdHelper.java b/src/main/java/helper/CrowdHelper.java
index dce35b5..1db736b 100644
--- a/src/main/java/helper/CrowdHelper.java
+++ b/src/main/java/helper/CrowdHelper.java
@@ -1,41 +1,41 @@
package helper;
public class CrowdHelper {
public int getInt(String field, String value, boolean allowDefault, int defValue) throws Exception {
if (value==null || value.length()==0) {
if (allowDefault)
return defValue;
- throw new Exception(field+" cannot be blank");
+ else throw new Exception(field+" cannot be blank");
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new Exception(field+" must be a number");
}
}
public double getDouble(String field, String value, boolean allowDefault, double defValue) throws Exception {
if (value==null || value.length()==0) {
if (allowDefault)
return defValue;
- throw new Exception(field+" cannot be blank");
+ else throw new Exception(field+" cannot be blank");
}
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
throw new Exception(field+" must be a number");
}
}
public String getValue(String field, String value) throws Exception {
if (value==null || value.length()==0) {
throw new Exception(field+" cannot be blank");
}
return value;
}
}
diff --git a/src/main/java/webservice/LineService.java b/src/main/java/webservice/LineService.java
index 853d14c..927d49d 100644
--- a/src/main/java/webservice/LineService.java
+++ b/src/main/java/webservice/LineService.java
@@ -1,79 +1,79 @@
package webservice;
import java.util.ArrayList;
import java.lang.Integer;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import model.AccessManager;
import dto.Line;
import helper.CrowdHelper;
@Path("/lineService")
public class LineService {
@GET
@Path("/getlines")
@Produces("application/json")
public ArrayList<Line> getlines() {
String lines = null;
ArrayList<Line> lineList = new ArrayList<Line>();
try {
lineList = new AccessManager().getLines();
} catch (Exception e) {
e.printStackTrace();
}
return lineList;
}
@PUT
@Path("/addline")
@Produces(MediaType.TEXT_PLAIN)
public String addline(@FormParam("lat") String inlat,
@FormParam("lng") String inlng,
@FormParam("type") String type ,
@FormParam("count") String strcount,
@FormParam("vote") String strvote
) {
int lineId = 0;
try
{
+ System.out.print("---------" +inlat);
+ System.out.print("---------" +inlng);
+ System.out.print("---------" +type);
CrowdHelper helper = new CrowdHelper();
double lat = helper.getDouble("lat",inlat,false,0);
- double lng = helper.getDouble("lat",inlng,false,0);
+ double lng = helper.getDouble("lng",inlng,false,0);
int count = helper.getInt("count",strcount,false,0);
int vote = helper.getInt("vote",strvote,false,0);
- System.out.print("---------" +lng);
- System.out.print("---------" +lat);
- System.out.print("---------" +type);
Line line = new Line();
line.setLat(lat);
line.setLng(lng);
line.setType(type);
line.setCount(count);
line.setVote(vote);
- lineId = new AccessManager().addLine(line);
+ lineId = new AccessManager().addLine(line);
} catch (Exception e) {
e.printStackTrace();
}
return Integer.toString(lineId);
}
}
| false | false | null | null |
diff --git a/src/main/java/org/semanticscience/converter/RDFSyntaxConverter.java b/src/main/java/org/semanticscience/converter/RDFSyntaxConverter.java
index 5fb7fb1..58fcaea 100644
--- a/src/main/java/org/semanticscience/converter/RDFSyntaxConverter.java
+++ b/src/main/java/org/semanticscience/converter/RDFSyntaxConverter.java
@@ -1,187 +1,190 @@
/**
* Copyright (c) 2012 Jose Cruz-Toledo
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.semanticscience.converter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.zip.Checksum;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.tdb.TDBFactory;
import com.hp.hpl.jena.util.FileManager;
/**
* @author Jose Cruz-Toledo
*
*/
public class RDFSyntaxConverter {
static final Logger log = Logger.getLogger(RDFSyntaxConverter.class);
/**
* The file that is to be converted
*/
private File inputFile;
/**
* The converted file
*/
private File outputFile;
private Model m;
private Dataset d;
public RDFSyntaxConverter() {
inputFile = null;
outputFile = null;
m = null;
d = null;
}
/**
* Default converter, reads inputFile into a model, guesses the syntax and
* outputs an RDF/XML RDF file in outputFile
*
* @param inputFile
* the rdf file to be converted
* @param outputFile
* the default output RDF file RDF/XML syntax
* @throws Exception
*/
public RDFSyntaxConverter(File anInputFile, File anOutputFile)
throws Exception {
inputFile = anInputFile;
outputFile = anOutputFile;
try {
// Try reading the input file/directory
if (inputFile.isDirectory() && outputFile.isDirectory()) {
File[] files = inputFile.listFiles();
for (int i = 0; i < files.length; i++) {
File f = files[i];
System.out.println("Converting "+f.getAbsolutePath()+"... ");
FileUtils.cleanDirectory(new File("/tmp/jena"));
d = TDBFactory.createDataset("/tmp/jena/tdb");
m = d.getDefaultModel();
FileManager.get().readModel(m, f.getAbsolutePath());
// write it to file using rdf/xml syntax
String outname = FilenameUtils.getBaseName(f.getName());
File outFile = new File(outputFile.getAbsolutePath()+"/"
+ outname + ".rdf");
m.write(new FileOutputStream(outFile));
}
System.out.println("...done!");
} else {
throw new Exception(
"Input and output directories must be specified!");
}
} catch (FileNotFoundException e) {
log.error("could not write to file", e);
} finally {
try {
m.close();
d.close();
} catch (Exception e) {
log.error(e);
}
}
}
public RDFSyntaxConverter(File anInputFile, File anOutputFile,
String outputSyntax) throws Exception {
inputFile = anInputFile;
outputFile = anOutputFile;
if (inputFile.isDirectory() && outputFile.isDirectory()) {
if (checkOutputSyntax(outputSyntax)) {
File[] files = inputFile.listFiles();
for (int i = 0; i < files.length; i++) {
File f = files[i];
System.out.println("Converting "+f.getAbsolutePath()+" ...");
- FileUtils.cleanDirectory(new File("/tmp/jena"));
+ FileUtils.deleteDirectory(new File("/tmp/jena"));
+ FileUtils.forceMkdir(new File("/tmp/jena"));
+ FileUtils.forceMkdir(new File("/tmp/jena/tdb"));
d = TDBFactory.createDataset("/tmp/jena/tdb");
m = d.getDefaultModel();
FileManager.get().readModel(m, f.getAbsolutePath());
// write it to file using rdf/xml syntax
String outname = FilenameUtils.getBaseName(f.getName());
String suffix = null;
if (outputSyntax.equals("RDF/XML")
| outputSyntax.equals("RDF/XML-ABBREV")) {
suffix = ".rdf";
} else if (outputSyntax.equals("N-TRIPLE")) {
suffix = ".nt";
} else {
suffix = "." + outputSyntax.toLowerCase();
}
File outFile = new File(outputFile.getAbsolutePath()+"/"
+ outname + suffix);
try {
m.write(new FileOutputStream(outFile),
outputSyntax);
} catch (FileNotFoundException e) {
log.error("could not write to file!", e);
} finally {
- try {
- m.close();
- d.close();
- } catch (Exception e) {
- log.error(e);
- }
+
}
}
+ try {
+ m.close();
+ d.close();
+ } catch (Exception e) {
+ log.error(e);
+ }
} else {
System.out.println("Invalid syntax given! => " + outputSyntax);
}
} else {
throw new Exception(
"Input and output directories must be specified!");
}
}
public Model getModel() {
return this.m;
}
public File getOutputFile() {
return this.outputFile;
}
private boolean checkOutputSyntax(String aSyntax) {
if (aSyntax.equals("RDF/XML")) {
return true;
} else if (aSyntax.equals("RDF/XML-ABBREV")) {
return true;
} else if (aSyntax.equals("N-TRIPLE")) {
return true;
} else if (aSyntax.equals("TURTLE")) {
return true;
} else if (aSyntax.equals("TTL")) {
return true;
} else if (aSyntax.equals("N3")) {
return true;
} else {
return false;
}
}
}
diff --git a/src/test/java/org/semanticscience/converter/RDFSyntaxConverterTest.java b/src/test/java/org/semanticscience/converter/RDFSyntaxConverterTest.java
index 5e33806..7b47336 100644
--- a/src/test/java/org/semanticscience/converter/RDFSyntaxConverterTest.java
+++ b/src/test/java/org/semanticscience/converter/RDFSyntaxConverterTest.java
@@ -1,75 +1,75 @@
/**
* Copyright (c) 2012 Jose Cruz-Toledo
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.semanticscience.converter;
import static org.junit.Assert.*;
import java.io.File;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author Jose Cruz-Toledo
*
*/
public class RDFSyntaxConverterTest {
private static File inputFile;
private static File outputFile;
private static RDFSyntaxConverter rsc;
private static RDFSyntaxConverter rsc2;
@BeforeClass
public static void setup(){
- inputFile = new File("/home/alison/tmp/");
- outputFile = new File("/tmp/");
+ inputFile = new File("/tmp/input");
+ outputFile = new File("/tmp/output");
try {
rsc = new RDFSyntaxConverter(inputFile, outputFile);
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
- try {
+ /*try {
rsc2 = new RDFSyntaxConverter(inputFile, outputFile, "N-TRIPLE");
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
- }
+ }*/
}
@AfterClass
public static void teardown(){
}
@Test
public void test() {
}
}
| false | false | null | null |
diff --git a/src/main/java/edu/ucar/unidata/sruth/Processor.java b/src/main/java/edu/ucar/unidata/sruth/Processor.java
index a849269..ef0be6c 100644
--- a/src/main/java/edu/ucar/unidata/sruth/Processor.java
+++ b/src/main/java/edu/ucar/unidata/sruth/Processor.java
@@ -1,159 +1,159 @@
/**
* Copyright 2012 University Corporation for Atmospheric Research. All rights
* reserved. See file LICENSE.txt in the top-level directory for licensing
* information.
*/
package edu.ucar.unidata.sruth;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.jcip.annotations.ThreadSafe;
import org.slf4j.Logger;
/**
* Processes data-products according to client instructions.
* <p>
* Instances are thread-safe.
*
* @author Steven R. Emmerson
*/
@ThreadSafe
public final class Processor implements Callable<Void> {
/**
* The logger for this package
*/
private static final Logger logger = Util.getLogger();
/**
* Map from filters to actions.
*/
private final ConcurrentMap<Pattern, List<Action>> actions = new ConcurrentHashMap<Pattern, List<Action>>();
/**
- * The queue of unprocessed data-products.
+ * The queue of unprocessed data-products. It's synchronous to prevent an
+ * out-of-memory error.
*/
- // TODO: Use a more limited queue -- possibly a user preference
private final BlockingQueue<DataProduct> processingQueue = new SynchronousQueue<DataProduct>();
/**
* The "isRunning" latch.
*/
private final CountDownLatch isRunningLatch = new CountDownLatch(
1);
/**
* Adds a processing action to a data-product category.
*
* @param pattern
* The pattern that selects the relevant data-products.
* @param action
* The action to be executed on data-products that pass the
* filter.
*/
public void add(final Pattern pattern, final Action action) {
final List<Action> newList = new LinkedList<Action>();
List<Action> list = actions.putIfAbsent(pattern, newList);
if (list == null) {
list = newList;
}
synchronized (list) {
list.add(action);
}
}
@Override
public Void call() throws InterruptedException {
logger.trace("Starting up: {}", this);
isRunningLatch.countDown();
try {
for (;;) {
/*
* TODO: Handle interruption better when the queue is not empty
*/
final DataProduct product = processingQueue.take();
try {
matchAndProcess(product);
}
catch (final IOException e) {
logger.error("Couldn't process data-product: " + product, e);
}
}
}
finally {
logger.trace("Done: {}", this);
}
}
/**
* Waits until this instance is running.
* <p>
* This method is potentially slow.
*
* @throws InterruptedException
* if the current thread is interrupted
*/
public void waitUntilRunning() throws InterruptedException {
isRunningLatch.await();
}
/**
* Queues a data-product for processing. Blocks until the data-product can
* be queued.
*
* @param dataProduct
* The data-product to be processed
* @throws InterruptedException
* if the current thread is interrupted
*/
void put(final DataProduct dataProduct) throws InterruptedException {
processingQueue.put(dataProduct);
}
/**
* Processes a data-product. A data-product will be acted upon by matching
* actions in the order in which the actions were added.
*
* @param dataProduct
* The data-product to process.
* @return <code>true</code> if and only if the given data-product was
* selected for processing.
* @throws InterruptedException
* if the current thread is interrupted.
* @throws IOException
* if an I/O error occurs.
*/
private boolean matchAndProcess(final DataProduct dataProduct)
throws IOException, InterruptedException {
boolean processed = false;
for (final Map.Entry<Pattern, List<Action>> entry : actions.entrySet()) {
final Matcher matcher = dataProduct.matcher(entry.getKey());
if (matcher.matches()) {
for (final Action action : entry.getValue()) {
// Foreign method. Don't call while synchronized
action.execute(matcher, dataProduct);
processed = true;
}
}
}
return processed;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public synchronized String toString() {
return getClass().getSimpleName() + " [" + actions.size() + " actions]";
}
}
diff --git a/src/main/java/edu/ucar/unidata/sruth/Subscriber.java b/src/main/java/edu/ucar/unidata/sruth/Subscriber.java
index b17a039..ac78e03 100644
--- a/src/main/java/edu/ucar/unidata/sruth/Subscriber.java
+++ b/src/main/java/edu/ucar/unidata/sruth/Subscriber.java
@@ -1,523 +1,523 @@
/**
* Copyright 2012 University Corporation for Atmospheric Research. All rights
* reserved. See file LICENSE.txt in the top-level directory for licensing
* information.
*/
package edu.ucar.unidata.sruth;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import net.jcip.annotations.ThreadSafe;
import org.slf4j.Logger;
import edu.ucar.unidata.sruth.Archive.DistributedTrackerFiles;
/**
* A subscriber of data. A subscriber has a sink-node and a processor of
* received data.
* <p>
* Instances are thread-safe.
*
* @author Steven R. Emmerson
*/
@ThreadSafe
public final class Subscriber implements Callable<Void> {
/**
* The logger for this class.
*/
private static final Logger logger = Util.getLogger();
/**
* The sink-node.
*/
private final SinkNode sinkNode;
/**
* The data-selection predicate.
*/
private final Predicate predicate;
/**
* Whether or not this instance is running.
*/
private final AtomicBoolean isRunning = new AtomicBoolean(false);
/**
* The archive.
*/
private final Archive archive;
/**
* The processor of data-products.
*/
private final Processor processor;
/**
* Constructs from the pathname of the archive, the Internet address of the
* tracker, the predicate for the desired data, and the processor of
* received data.
*
* @param rootDir
* Pathname of the root of the file-tree.
* @param trackerAddress
* The address of the tracker.
* @param predicate
* The predicate for selecting the desired data.
* @param processor
* The processor of received data-products.
* @throws IOException
* if an unused port in the given range couldn't be found.
* @throws IOException
* if an I/O error occurs.
* @throws NullPointerException
* if {@code rootDir == null || trackerAddress == null ||
* predicate == null || processor == null}.
* @throws SocketException
* if a server-side socket couldn't be created.
*/
public Subscriber(final Path rootDir,
final InetSocketAddress trackerAddress, final Predicate predicate,
final Processor processor) throws IOException {
this(rootDir, trackerAddress, predicate, processor, 0);
}
/**
* Constructs from the pathname of the archive, the Internet address of the
* tracker, the predicate for the desired data, the processor of received
* data, and the port number for the local data-exchange server.
*
* @param rootDir
* Pathname of the root of the file-tree.
* @param trackerAddress
* The address of the tracker.
* @param predicate
* The predicate for selecting the desired data.
* @param processor
* The processor of received data-products.
* @param serverPort
* The port number on which the local data-exchange server will
* listen for connections. If zero, then an ephemeral port will
* be chosen by the operating-system.
* @throws IOException
* if an unused port in the given range couldn't be found.
* @throws IOException
* if an I/O error occurs.
* @throws NullPointerException
* if {@code rootDir == null || trackerAddress == null ||
* predicate == null || processor == null}.
* @throws SocketException
* if a server-side socket couldn't be created.
*/
public Subscriber(final Path rootDir,
final InetSocketAddress trackerAddress, Predicate predicate,
final Processor processor, final int serverPort) throws IOException {
if (null == rootDir) {
throw new NullPointerException();
}
if (null == trackerAddress) {
throw new NullPointerException();
}
if (null == predicate) {
throw new NullPointerException();
}
if (null == processor) {
throw new NullPointerException();
}
archive = new Archive(rootDir);
/*
* Ensure reception of the distributed tracker files.
*/
final DistributedTrackerFiles distributedTrackerFiles = new DistributedTrackerFiles(
archive, trackerAddress);
final Filter filterServerMapFilter = distributedTrackerFiles
.getFilter();
predicate = predicate.add(filterServerMapFilter);
archive.addDataProductListener(new DataProductListener() {
@Override
public void process(final DataProduct dataProduct)
throws InterruptedException {
processor.put(dataProduct);
}
});
sinkNode = new SinkNode(archive, predicate, trackerAddress, serverPort);
this.predicate = predicate;
- this.processor = new Processor();
+ this.processor = processor;
}
/**
* Returns the predicate used by this instance.
*
* @return The predicate used by this instance.
*/
Predicate getPredicate() {
return predicate;
}
/**
* Returns the pathname of the root of the archive.
*
* @return The pathname of the root of the archive.
*/
Path getRootDir() {
return archive.getRootDir();
}
/**
* Executes this instance. Returns normally if and only if all desired data
* has been received.
*
* @throws AssertionError
* if the impossible happens.
* @throws IllegalStateException
* if this method has been called before.
* @throws InterruptedException
* if the current thread is interrupted.
* @throws IOException
* if non-networking I/O error occurs
*/
public Void call() throws InterruptedException, IOException {
logger.trace("Starting up: {}", this);
if (!isRunning.compareAndSet(false, true)) {
throw new IllegalStateException();
}
final String origThreadName = Thread.currentThread().getName();
Thread.currentThread().setName(toString());
final CancellingExecutor executor = new CancellingExecutor(2, 2, 0,
TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
try {
/*
* A {@link CompletionService} is used so that both the sink-node
* task and the data-processing task can be waited on
* simultaneously.
*/
final CompletionService<Void> completionService = new ExecutorCompletionService<Void>(
executor);
/*
* Start the data-processing task. TODO: Use one processing thread
* per disk controller.
*/
final Future<Void> processingFuture = completionService
.submit(processor);
/*
* Start the sink-node task.
*/
final Future<Void> sinkNodeFuture = completionService
.submit(sinkNode);
/*
* Wait for one of the tasks to complete.
*/
for (int i = 0; i < 2; i++) {
final Future<Void> future = completionService.take();
if (future.isCancelled()) {
break;
}
if (future == processingFuture) {
/*
* The local-processing task completed -- ideally because it
* was cancelled
*/
try {
future.get();
throw new AssertionError();
}
catch (final ExecutionException e) {
throw new RuntimeException("Unexpected error: "
+ processor, e.getCause());
}
}
else {
assert future == sinkNodeFuture;
/*
* The sink-node task completed -- ideally because all the
* data was received
*/
try {
future.get();
// All desired data was received
processingFuture.cancel(true);
}
catch (final ExecutionException e) {
final Throwable cause = e.getCause();
logger.trace("Execution exception: {}",
cause.toString());
if (cause instanceof IOException) {
throw new IOException("IO error: " + sinkNode,
cause);
}
throw new RuntimeException("Unexpected error: "
+ sinkNode, cause);
}
}
}
}
finally {
executor.shutdownNow();
Thread.interrupted();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
try {
archive.close();
}
catch (final IOException ignored) {
}
Thread.currentThread().setName(origThreadName);
logger.trace("Done: {}", this);
}
return null;
}
/**
* Waits until this instance is running.
* <p>
* This method is potentially slow.
*
* @throws InterruptedException
* if the current thread is interrupted
*/
public void waitUntilRunning() throws InterruptedException {
processor.waitUntilRunning();
sinkNode.waitUntilRunning();
}
/**
* Returns the number of received files since {@link #call()} was called.
*
* @return The number of received files since {@link #call()} was called.
*/
public long getReceivedFileCount() {
return sinkNode.getReceivedFileCount();
}
/**
* Returns the current number of peers to which this instance is connected.
*
* @return The current number of peers to which this instance is connected.
*/
public int getPeerCount() {
return sinkNode.getClientCount() + sinkNode.getServletCount();
}
/**
* Returns the absolute pathname corresponding to a pathname in the archive.
*
* @param archivePath
* The pathname in the archive.
* @return the absolute pathname corresponding to the archive pathname.
*/
Path getAbsolutePath(final ArchivePath archivePath) {
return archive.resolve(archivePath);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Subscriber [sinkNode=" + sinkNode + "]";
}
/**
* Executes an instance of this class.
* <p>
* Usage:
*
* <pre>
* edu.ucar.unidata.sruth.Subscriber [options] subscription
*
* where:
* -a actions URL or pathname of the XML document specifying local
* processing actions. The default is to do no local
* processing of received data-products: the instance
* becomes a pure relay node in the network.
* -d archive Pathname of the root of the temporary data archive.
* The default is the {@code SRUTH} subdirectory of the
* user's home-directory.
* -s port Port number on which the local data-exchange server
* will listen for connections. If zero, then an ephemeral
* port will be chosen by the operating-system (which is
* the default).
* subscription URL or pathname of the XML document that contains
* the subscription information.
* </pre>
* <p>
* Exit status:
*
* <pre>
* 0 Success: all subscribed-to data was received and processed.
* 1 Invalid invocation
* </pre>
*
* @param args
* Program arguments.
* @throws IOException
* if an I/O error occurs
* @throws SecurityException
* if a security exception occurs
*/
public static void main(final String[] args) throws SecurityException,
IOException {
final int INVALID_INVOCATION = 1;
Path archivePath = Paths.get(System.getProperty("user.home")
+ File.separatorChar + Util.PACKAGE_NAME);
- Processor processor = new Processor();
+ Processor processor = new Processor(); // does nothing
Subscription subscription = null;
int serverPort = 0;
try {
int iarg;
String arg;
/*
* Process the optional arguments.
*/
for (iarg = 0; iarg < args.length; ++iarg) {
arg = args[iarg];
try {
if (arg.charAt(0) != '-') {
break;
}
final String optString = arg.substring(1);
arg = args[++iarg];
if (optString.equals("a")) {
/*
* Process the actions argument.
*/
try {
processor = Util.decodeUrlOrFile(arg,
new Decoder<Processor>() {
@Override
public Processor decode(
final InputStream input)
throws IOException {
return XmlActionFile
.getProcessor(input);
}
});
}
catch (final Exception e) {
logger.error(
"Couldn't process local-actions argument: \"{}\": {}",
arg, e.toString());
System.exit(INVALID_INVOCATION);
}
}
else if (optString.equals("d")) {
/*
* Process the archive argument.
*/
try {
archivePath = Paths.get(arg);
}
catch (final InvalidPathException e) {
logger.error(
"Couldn't process archive argument: \"{}\"",
arg);
throw new IllegalArgumentException();
}
}
else if (optString.equals("s")) {
/*
* Decode the server-port argument.
*/
try {
serverPort = Integer.valueOf(arg);
}
catch (final Exception e) {
logger.error(
"Couldn't decode server-port argument: \"{}\": {}",
arg, e.toString());
throw new IllegalArgumentException();
}
}
else {
logger.error("Invalid option: \"{}\"", optString);
throw new IllegalArgumentException();
}
}
catch (final IndexOutOfBoundsException e) {
logger.error("Invalid argument: \"{}\"", arg);
throw new IllegalArgumentException();
}
}
/*
* Process the subscription argument.
*/
if (iarg >= args.length) {
logger.error("The subscription argument is missing");
throw new IllegalArgumentException();
}
arg = args[iarg++];
try {
subscription = Util.decodeUrlOrFile(arg,
new Decoder<Subscription>() {
@Override
public Subscription decode(final InputStream input)
throws IOException {
return new Subscription(input);
}
});
}
catch (final Exception e) {
logger.error(
"Couldn't process subscription argument: \"{}\": {}",
arg, e.toString());
throw new IllegalArgumentException();
}
if (iarg < args.length) {
logger.error("Too many arguments");
throw new IllegalArgumentException();
}
}
catch (final IllegalArgumentException e) {
logger.info("Usage: ... [-a actions] [-d archive] [-s port] subscription\n"
+ "where:\n"
+ " -a actions URL or pathname of the XML document specifying local\n"
+ " processing actions. The default is to do no local\n"
+ " processing of received data-products: the instance\n"
+ " becomes a pure relay node in the network.\n"
+ " -d archive Pathname of the root of the temporary data archive.\n"
+ " The default is the subdirectory \"SRUTH\" of the\n"
+ " user's home-directory.\n"
+ " -s port Port number on which the local data-exchange server\n"
+ " will listen for connections. If zero, then an ephemeral\n"
+ " port will be chosen by the operating-system (which is\n"
+ " the default).\n"
+ " subscription URL or pathname of the XML document that contains\n"
+ " the subscription information.\n");
System.exit(INVALID_INVOCATION);
}
/*
* Create the subscriber.
*/
Subscriber subscriber = null;
subscriber = new Subscriber(archivePath,
subscription.getTrackerAddress(), subscription.getPredicate(),
processor, serverPort);
/*
* Execute the subscriber.
*/
try {
subscriber.call();
}
catch (final InterruptedException ignored) {
}
System.exit(0);
}
}
| false | false | null | null |
diff --git a/library/src/wei/mark/standout/StandOutWindow.java b/library/src/wei/mark/standout/StandOutWindow.java
index 0505aff..58ebdf5 100644
--- a/library/src/wei/mark/standout/StandOutWindow.java
+++ b/library/src/wei/mark/standout/StandOutWindow.java
@@ -1,1996 +1,1996 @@
package wei.mark.standout;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import wei.mark.standout.constants.StandOutFlags;
import wei.mark.standout.ui.Window;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
/**
* Extend this class to easily create and manage floating StandOut windows.
*
* @author Mark Wei <[email protected]>
*
* Contributors: Jason <github.com/jasonconnery>
*
*/
public abstract class StandOutWindow extends Service {
static final String TAG = "StandOutWindow";
/**
* StandOut window id: You may use this sample id for your first window.
*/
public static final int DEFAULT_ID = 0;
/**
* Special StandOut window id: You may NOT use this id for any windows.
*/
public static final int ONGOING_NOTIFICATION_ID = -1;
/**
* StandOut window id: You may use this id when you want it to be
* disregarded. The system makes no distinction for this id; it is only used
* to improve code readability.
*/
public static final int DISREGARD_ID = -2;
/**
* Intent action: Show a new window corresponding to the id.
*/
public static final String ACTION_SHOW = "SHOW";
/**
* Intent action: Restore a previously hidden window corresponding to the
* id. The window should be previously hidden with {@link #ACTION_HIDE}.
*/
public static final String ACTION_RESTORE = "RESTORE";
/**
* Intent action: Close an existing window with an existing id.
*/
public static final String ACTION_CLOSE = "CLOSE";
/**
* Intent action: Close all existing windows.
*/
public static final String ACTION_CLOSE_ALL = "CLOSE_ALL";
/**
* Intent action: Send data to a new or existing window.
*/
public static final String ACTION_SEND_DATA = "SEND_DATA";
/**
* Intent action: Hide an existing window with an existing id. To enable the
* ability to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*/
public static final String ACTION_HIDE = "HIDE";
/**
* Show a new window corresponding to the id, or restore a previously hidden
* window.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
*
* @see #show(int)
*/
public static void show(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getShowIntent(context, cls, id));
}
/**
* Hide the existing window corresponding to the id. To enable the ability
* to restore this window, make sure you implement
* {@link #getHiddenNotification(int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
* @see #hide(int)
*/
public static void hide(Context context,
Class<? extends StandOutWindow> cls, int id) {
- context.startService(getShowIntent(context, cls, id));
+ context.startService(getHideIntent(context, cls, id));
}
/**
* Close an existing window with an existing id.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. The window must previously be
* shown.
* @see #close(int)
*/
public static void close(Context context,
Class<? extends StandOutWindow> cls, int id) {
context.startService(getCloseIntent(context, cls, id));
}
/**
* Close all existing windows.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @see #closeAll()
*/
public static void closeAll(Context context,
Class<? extends StandOutWindow> cls) {
context.startService(getCloseAllIntent(context, cls));
}
/**
* This allows windows of different applications to communicate with each
* other.
*
* <p>
* Send {@link Parceleable} data in a {@link Bundle} to a new or existing
* windows. The implementation of the recipient window can handle what to do
* with the data. To receive a result, provide the class and id of the
* sender.
*
* @param context
* A Context of the application package implementing the class of
* the sending window.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window, or DISREGARD_ID.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
* @param fromCls
* Provide the class of the sending window if you want a result.
* @param fromId
* Provide the id of the sending window if you want a result.
* @see #sendData(int, Class, int, int, Bundle)
*/
public static void sendData(Context context,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
context.startService(getSendDataIntent(context, toCls, toId,
requestCode, data, fromCls, fromId));
}
/**
* See {@link #show(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that will be used
* to create and manage the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getShowIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
boolean cached = sWindowCache.isCached(id, cls);
String action = cached ? ACTION_RESTORE : ACTION_SHOW;
Uri uri = cached ? Uri.parse("standout://" + cls + '/' + id) : null;
return new Intent(context, cls).putExtra("id", id).setAction(action)
.setData(uri);
}
/**
* See {@link #hide(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getHideIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_HIDE);
}
/**
* See {@link #close(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @param id
* The id representing this window. If the id exists, and the
* corresponding window was previously hidden, then that window
* will be restored.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseIntent(Context context,
Class<? extends StandOutWindow> cls, int id) {
return new Intent(context, cls).putExtra("id", id).setAction(
ACTION_CLOSE);
}
/**
* See {@link #closeAll(Context, Class, int)}.
*
* @param context
* A Context of the application package implementing this class.
* @param cls
* The Service extending {@link StandOutWindow} that is managing
* the window.
* @return An {@link Intent} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getCloseAllIntent(Context context,
Class<? extends StandOutWindow> cls) {
return new Intent(context, cls).setAction(ACTION_CLOSE_ALL);
}
/**
* See {@link #sendData(Context, Class, int, int, Bundle, Class, int)}.
*
* @param context
* A Context of the application package implementing the class of
* the sending window.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
* @param fromCls
* If the sending window wants a result, provide the class of the
* sending window.
* @param fromId
* If the sending window wants a result, provide the id of the
* sending window.
* @return An {@link Intnet} to use with
* {@link Context#startService(Intent)}.
*/
public static Intent getSendDataIntent(Context context,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
return new Intent(context, toCls).putExtra("id", toId)
.putExtra("requestCode", requestCode)
.putExtra("wei.mark.standout.data", data)
.putExtra("wei.mark.standout.fromCls", fromCls)
.putExtra("fromId", fromId).setAction(ACTION_SEND_DATA);
}
// internal map of ids to shown/hidden views
static WindowCache sWindowCache;
static Window sFocusedWindow;
// static constructors
static {
sWindowCache = new WindowCache();
sFocusedWindow = null;
}
// internal system services
WindowManager mWindowManager;
private NotificationManager mNotificationManager;
LayoutInflater mLayoutInflater;
// internal state variables
private boolean startedForeground;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
startedForeground = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// intent should be created with
// getShowIntent(), getHideIntent(), getCloseIntent()
if (intent != null) {
String action = intent.getAction();
int id = intent.getIntExtra("id", DEFAULT_ID);
// this will interfere with getPersistentNotification()
if (id == ONGOING_NOTIFICATION_ID) {
throw new RuntimeException(
"ID cannot equals StandOutWindow.ONGOING_NOTIFICATION_ID");
}
if (ACTION_SHOW.equals(action) || ACTION_RESTORE.equals(action)) {
show(id);
} else if (ACTION_HIDE.equals(action)) {
hide(id);
} else if (ACTION_CLOSE.equals(action)) {
close(id);
} else if (ACTION_CLOSE_ALL.equals(action)) {
closeAll();
} else if (ACTION_SEND_DATA.equals(action)) {
if (!isExistingId(id) && id != DISREGARD_ID) {
Log.w(TAG,
"Sending data to non-existant window. If this is not intended, make sure toId is either an existing window's id or DISREGARD_ID.");
}
Bundle data = intent.getBundleExtra("wei.mark.standout.data");
int requestCode = intent.getIntExtra("requestCode", 0);
@SuppressWarnings("unchecked")
Class<? extends StandOutWindow> fromCls = (Class<? extends StandOutWindow>) intent
.getSerializableExtra("wei.mark.standout.fromCls");
int fromId = intent.getIntExtra("fromId", DEFAULT_ID);
onReceiveData(id, requestCode, data, fromCls, fromId);
}
} else {
Log.w(TAG, "Tried to onStartCommand() with a null intent.");
}
// the service is started in foreground in show()
// so we don't expect Android to kill this service
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// closes all windows
closeAll();
}
/**
* Return the name of every window in this implementation. The name will
* appear in the default implementations of the system window decoration
* title and notification titles.
*
* @return The name.
*/
public abstract String getAppName();
/**
* Return the icon resource for every window in this implementation. The
* icon will appear in the default implementations of the system window
* decoration and notifications.
*
* @return The icon.
*/
public abstract int getAppIcon();
/**
* Create a new {@link View} corresponding to the id, and add it as a child
* to the frame. The view will become the contents of this StandOut window.
* The view MUST be newly created, and you MUST attach it to the frame.
*
* <p>
* If you are inflating your view from XML, make sure you use
* {@link LayoutInflater#inflate(int, ViewGroup, boolean)} to attach your
* view to frame. Set the ViewGroup to be frame, and the boolean to true.
*
* <p>
* If you are creating your view programmatically, make sure you use
* {@link FrameLayout#addView(View)} to add your view to the frame.
*
* @param id
* The id representing the window.
* @param frame
* The {@link FrameLayout} to attach your view as a child to.
*/
public abstract void createAndAttachView(int id, FrameLayout frame);
/**
* Return the {@link StandOutWindow#LayoutParams} for the corresponding id.
* The system will set the layout params on the view for this StandOut
* window. The layout params may be reused.
*
*
* @param id
* The id of the window.
* @param window
* The window corresponding to the id. Given as courtesy, so you
* may get the existing layout params.
* @return The {@link StandOutWindow#LayoutParams} corresponding to the id.
* The layout params will be set on the window. The layout params
* returned will be reused whenever possible, minimizing the number
* of times getParams() will be called.
*/
public abstract StandOutLayoutParams getParams(int id, Window window);
/**
* Implement this method to change modify the behavior and appearance of the
* window corresponding to the id.
*
* <p>
* You may use any of the flags defined in {@link StandOutFlags}. This
* method will be called many times, so keep it fast.
*
* <p>
* Use bitwise OR (|) to set flags, and bitwise XOR (^) to unset flags. To
* test if a flag is set, use {@link Utils#isSet(int, int)}.
*
* @param id
* The id of the window.
* @return A combination of flags.
*/
public int getFlags(int id) {
return 0;
}
/**
* Implement this method to set a custom title for the window corresponding
* to the id.
*
* @param id
* The id of the window.
* @return The title of the window.
*/
public String getTitle(int id) {
return getAppName();
}
/**
* Implement this method to set a custom icon for the window corresponding
* to the id.
*
* @param id
* The id of the window.
* @return The icon of the window.
*/
public int getIcon(int id) {
return getAppIcon();
}
/**
* Return the title for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* @param id
* The id of the window shown.
* @return The title for the persistent notification.
*/
public String getPersistentNotificationTitle(int id) {
return getAppName() + " Running";
}
/**
* Return the message for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* @param id
* The id of the window shown.
* @return The message for the persistent notification.
*/
public String getPersistentNotificationMessage(int id) {
return "";
}
/**
* Return the intent for the persistent notification. This is called every
* time {@link #show(int)} is called.
*
* <p>
* The returned intent will be packaged into a {@link PendingIntent} to be
* invoked when the user clicks the notification.
*
* @param id
* The id of the window shown.
* @return The intent for the persistent notification.
*/
public Intent getPersistentNotificationIntent(int id) {
return null;
}
/**
* Return the icon resource for every hidden window in this implementation.
* The icon will appear in the default implementations of the hidden
* notifications.
*
* @return The icon.
*/
public int getHiddenIcon() {
return getAppIcon();
}
/**
* Return the title for the hidden notification corresponding to the window
* being hidden.
*
* @param id
* The id of the hidden window.
* @return The title for the hidden notification.
*/
public String getHiddenNotificationTitle(int id) {
return getAppName() + " Hidden";
}
/**
* Return the message for the hidden notification corresponding to the
* window being hidden.
*
* @param id
* The id of the hidden window.
* @return The message for the hidden notification.
*/
public String getHiddenNotificationMessage(int id) {
return "";
}
/**
* Return the intent for the hidden notification corresponding to the window
* being hidden.
*
* <p>
* The returned intent will be packaged into a {@link PendingIntent} to be
* invoked when the user clicks the notification.
*
* @param id
* The id of the hidden window.
* @return The intent for the hidden notification.
*/
public Intent getHiddenNotificationIntent(int id) {
return null;
}
/**
* Return a persistent {@link Notification} for the corresponding id. You
* must return a notification for AT LEAST the first id to be requested.
* Once the persistent notification is shown, further calls to
* {@link #getPersistentNotification(int)} may return null. This way Android
* can start the StandOut window service in the foreground and will not kill
* the service on low memory.
*
* <p>
* As a courtesy, the system will request a notification for every new id
* shown. Your implementation is encouraged to include the
* {@link PendingIntent#FLAG_UPDATE_CURRENT} flag in the notification so
* that there is only one system-wide persistent notification.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getPersistentNotification(int)} that keeps one system-wide
* persistent notification that creates a new window on every click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id, or null if
* you've previously returned a notification.
*/
public Notification getPersistentNotification(int id) {
// basic notification stuff
// http://developer.android.com/guide/topics/ui/notifiers/notifications.html
int icon = getAppIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getPersistentNotificationTitle(id);
String contentText = getPersistentNotificationMessage(id);
String tickerText = String.format("%s: %s", contentTitle, contentText);
// getPersistentNotification() is called for every new window
// so we replace the old notification with a new one that has
// a bigger id
Intent notificationIntent = getPersistentNotificationIntent(id);
PendingIntent contentIntent = null;
if (notificationIntent != null) {
contentIntent = PendingIntent.getService(this, 0,
notificationIntent,
// flag updates existing persistent notification
PendingIntent.FLAG_UPDATE_CURRENT);
}
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText,
contentIntent);
return notification;
}
/**
* Return a hidden {@link Notification} for the corresponding id. The system
* will request a notification for every id that is hidden.
*
* <p>
* If null is returned, StandOut will assume you do not wish to support
* hiding this window, and will {@link #close(int)} it for you.
*
* <p>
* See the StandOutExample project for an implementation of
* {@link #getHiddenNotification(int)} that for every hidden window keeps a
* notification which restores that window upon user's click.
*
* @param id
* The id of the window.
* @return The {@link Notification} corresponding to the id or null.
*/
public Notification getHiddenNotification(int id) {
// same basics as getPersistentNotification()
int icon = getHiddenIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getHiddenNotificationTitle(id);
String contentText = getHiddenNotificationMessage(id);
String tickerText = String.format("%s: %s", contentTitle, contentText);
// the difference here is we are providing the same id
Intent notificationIntent = getHiddenNotificationIntent(id);
PendingIntent contentIntent = null;
if (notificationIntent != null) {
contentIntent = PendingIntent.getService(this, 0,
notificationIntent,
// flag updates existing persistent notification
PendingIntent.FLAG_UPDATE_CURRENT);
}
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText,
contentIntent);
return notification;
}
/**
* Return the animation to play when the window corresponding to the id is
* shown.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
public Animation getShowAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
}
/**
* Return the animation to play when the window corresponding to the id is
* hidden.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
public Animation getHideAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
}
/**
* Return the animation to play when the window corresponding to the id is
* closed.
*
* @param id
* The id of the window.
* @return The animation to play or null.
*/
public Animation getCloseAnimation(int id) {
return AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
}
/**
* Implement this method to set a custom theme for all windows in this
* implementation.
*
* @return The theme to set on the window, or 0 for device default.
*/
public int getThemeStyle() {
return 0;
}
/**
* You probably want to leave this method alone and implement
* {@link #getDropDownItems(int)} instead. Only implement this method if you
* want more control over the drop down menu.
*
* <p>
* Implement this method to set a custom drop down menu when the user clicks
* on the icon of the window corresponding to the id. The icon is only shown
* when {@link StandOutFlags#FLAG_DECORATION_SYSTEM} is set.
*
* @param id
* The id of the window.
* @return The drop down menu to be anchored to the icon, or null to have no
* dropdown menu.
*/
public PopupWindow getDropDown(final int id) {
final List<DropDownListItem> items;
List<DropDownListItem> dropDownListItems = getDropDownItems(id);
if (dropDownListItems != null) {
items = dropDownListItems;
} else {
items = new ArrayList<StandOutWindow.DropDownListItem>();
}
// add default drop down items
items.add(new DropDownListItem(
android.R.drawable.ic_menu_close_clear_cancel, "Quit "
+ getAppName(), new Runnable() {
@Override
public void run() {
closeAll();
}
}));
// turn item list into views in PopupWindow
LinearLayout list = new LinearLayout(this);
list.setOrientation(LinearLayout.VERTICAL);
final PopupWindow dropDown = new PopupWindow(list,
StandOutLayoutParams.WRAP_CONTENT,
StandOutLayoutParams.WRAP_CONTENT, true);
for (final DropDownListItem item : items) {
ViewGroup listItem = (ViewGroup) mLayoutInflater.inflate(
R.layout.drop_down_list_item, null);
list.addView(listItem);
ImageView icon = (ImageView) listItem.findViewById(R.id.icon);
icon.setImageResource(item.icon);
TextView description = (TextView) listItem
.findViewById(R.id.description);
description.setText(item.description);
listItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
item.action.run();
dropDown.dismiss();
}
});
}
Drawable background = getResources().getDrawable(
android.R.drawable.editbox_dropdown_dark_frame);
dropDown.setBackgroundDrawable(background);
return dropDown;
}
/**
* Implement this method to populate the drop down menu when the user clicks
* on the icon of the window corresponding to the id. The icon is only shown
* when {@link StandOutFlags#FLAG_DECORATION_SYSTEM} is set.
*
* @param id
* The id of the window.
* @return The list of items to show in the drop down menu, or null or empty
* to have no dropdown menu.
*/
public List<DropDownListItem> getDropDownItems(int id) {
return null;
}
/**
* Implement this method to be alerted to touch events in the body of the
* window corresponding to the id.
*
* <p>
* Note that even if you set {@link #FLAG_DECORATION_SYSTEM}, you will not
* receive touch events from the system window decorations.
*
* @see {@link View.OnTouchListener#onTouch(View, MotionEvent)}
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
*/
public boolean onTouchBody(int id, Window window, View view,
MotionEvent event) {
return false;
}
/**
* Implement this method to be alerted to when the window corresponding to
* the id is moved.
*
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
* @see {@link #onTouchHandleMove(int, Window, View, MotionEvent)}
*/
public void onMove(int id, Window window, View view, MotionEvent event) {
}
/**
* Implement this method to be alerted to when the window corresponding to
* the id is resized.
*
* @param id
* The id of the view, provided as a courtesy.
* @param window
* The window corresponding to the id, provided as a courtesy.
* @param view
* The view where the event originated from.
* @param event
* See linked method.
* @see {@link #onTouchHandleResize(int, Window, View, MotionEvent)}
*/
public void onResize(int id, Window window, View view, MotionEvent event) {
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be shown. This callback will occur before the view is
* added to the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be shown.
* @return Return true to cancel the view from being shown, or false to
* continue.
* @see #show(int)
*/
public boolean onShow(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be hidden. This callback will occur before the view is
* removed from the window manager and {@link #getHiddenNotification(int)}
* is called.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be hidden.
* @return Return true to cancel the view from being hidden, or false to
* continue.
* @see #hide(int)
*/
public boolean onHide(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be closed. This callback will occur before the view is
* removed from the window manager.
*
* @param id
* The id of the view, provided as a courtesy.
* @param view
* The view about to be closed.
* @return Return true to cancel the view from being closed, or false to
* continue.
* @see #close(int)
*/
public boolean onClose(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when all windows are about to be
* closed. This callback will occur before any views are removed from the
* window manager.
*
* @return Return true to cancel the views from being closed, or false to
* continue.
* @see #closeAll()
*/
public boolean onCloseAll() {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id has received some data. The sender is described by fromCls and fromId
* if the sender wants a result. To send a result, use
* {@link #sendData(int, Class, int, int, Bundle)}.
*
* @param id
* The id of your receiving window.
* @param requestCode
* The sending window provided this request code to declare what
* kind of data is being sent.
* @param data
* A bundle of parceleable data that was sent to your receiving
* window.
* @param fromCls
* The sending window's class. Provided if the sender wants a
* result.
* @param fromId
* The sending window's id. Provided if the sender wants a
* result.
*/
public void onReceiveData(int id, int requestCode, Bundle data,
Class<? extends StandOutWindow> fromCls, int fromId) {
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be updated in the layout. This callback will occur before
* the view is updated by the window manager.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be updated.
* @param params
* The updated layout params.
* @return Return true to cancel the window from being updated, or false to
* continue.
* @see #updateViewLayout(int, Window, StandOutLayoutParams)
*/
public boolean onUpdate(int id, Window window, StandOutLayoutParams params) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to be bought to the front. This callback will occur before
* the window is brought to the front by the window manager.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be brought to the front.
* @return Return true to cancel the window from being brought to the front,
* or false to continue.
* @see #bringToFront(int)
*/
public boolean onBringToFront(int id, Window window) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id is about to have its focus changed. This callback will occur before
* the window's focus is changed.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to be brought to the front.
* @param focus
* Whether the window is gaining or losing focus.
* @return Return true to cancel the window's focus from being changed, or
* false to continue.
* @see #focus(int)
*/
public boolean onFocusChange(int id, Window window, boolean focus) {
return false;
}
/**
* Implement this callback to be alerted when a window corresponding to the
* id receives a key event. This callback will occur before the window
* handles the event with {@link Window#dispatchKeyEvent(KeyEvent)}.
*
* @param id
* The id of the window, provided as a courtesy.
* @param view
* The window about to receive the key event.
* @param event
* The key event.
* @return Return true to cancel the window from handling the key event, or
* false to let the window handle the key event.
* @see {@link Window#dispatchKeyEvent(KeyEvent)}
*/
public boolean onKeyEvent(int id, Window window, KeyEvent event) {
return false;
}
/**
* Show or restore a window corresponding to the id. Return the window that
* was shown/restored.
*
* @param id
* The id of the window.
* @return The window shown.
*/
public final synchronized Window show(int id) {
// get the window corresponding to the id
Window cachedWindow = getWindow(id);
final Window window;
// check cache first
if (cachedWindow != null) {
window = cachedWindow;
} else {
window = new Window(this, id);
}
if (window.visibility == Window.VISIBILITY_VISIBLE) {
throw new IllegalStateException("Tried to show(" + id
+ ") a window that is already shown.");
}
// alert callbacks and cancel if instructed
if (onShow(id, window)) {
Log.d(TAG, "Window " + id + " show cancelled by implementation.");
return null;
}
window.visibility = Window.VISIBILITY_VISIBLE;
// get animation
Animation animation = getShowAnimation(id);
// get the params corresponding to the id
StandOutLayoutParams params = window.getLayoutParams();
try {
// add the view to the window manager
mWindowManager.addView(window, params);
// animate
if (animation != null) {
window.getChildAt(0).startAnimation(animation);
}
} catch (Exception ex) {
ex.printStackTrace();
}
// add view to internal map
sWindowCache.putCache(id, getClass(), window);
// get the persistent notification
Notification notification = getPersistentNotification(id);
// show the notification
if (notification != null) {
notification.flags = notification.flags
| Notification.FLAG_NO_CLEAR;
// only show notification if not shown before
if (!startedForeground) {
// tell Android system to show notification
startForeground(
getClass().hashCode() + ONGOING_NOTIFICATION_ID,
notification);
startedForeground = true;
} else {
// update notification if shown before
mNotificationManager.notify(getClass().hashCode()
+ ONGOING_NOTIFICATION_ID, notification);
}
} else {
// notification can only be null if it was provided before
if (!startedForeground) {
throw new RuntimeException("Your StandOutWindow service must"
+ "provide a persistent notification."
+ "The notification prevents Android"
+ "from killing your service in low"
+ "memory situations.");
}
}
focus(id);
return window;
}
/**
* Hide a window corresponding to the id. Show a notification for the hidden
* window.
*
* @param id
* The id of the window.
*/
public final synchronized void hide(int id) {
// get the view corresponding to the id
final Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to hide(" + id
+ ") a null window.");
}
if (window.visibility == Window.VISIBILITY_GONE) {
throw new IllegalStateException("Tried to hide(" + id
+ ") a window that is not shown.");
}
// alert callbacks and cancel if instructed
if (onHide(id, window)) {
Log.w(TAG, "Window " + id + " hide cancelled by implementation.");
return;
}
// check if hide enabled
if (Utils.isSet(window.flags, StandOutFlags.FLAG_WINDOW_HIDE_ENABLE)) {
window.visibility = Window.VISIBILITY_TRANSITION;
// get the hidden notification for this view
Notification notification = getHiddenNotification(id);
// get animation
Animation animation = getHideAnimation(id);
try {
// animate
if (animation != null) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// remove the window from the window manager
mWindowManager.removeView(window);
window.visibility = Window.VISIBILITY_GONE;
}
});
window.getChildAt(0).startAnimation(animation);
} else {
// remove the window from the window manager
mWindowManager.removeView(window);
}
} catch (Exception ex) {
ex.printStackTrace();
}
// display the notification
notification.flags = notification.flags
| Notification.FLAG_NO_CLEAR
| Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(getClass().hashCode() + id,
notification);
} else {
// if hide not enabled, close window
close(id);
}
}
/**
* Close a window corresponding to the id.
*
* @param id
* The id of the window.
*/
public final synchronized void close(final int id) {
// get the view corresponding to the id
final Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to close(" + id
+ ") a null window.");
}
if (window.visibility == Window.VISIBILITY_TRANSITION) {
return;
}
// alert callbacks and cancel if instructed
if (onClose(id, window)) {
Log.w(TAG, "Window " + id + " close cancelled by implementation.");
return;
}
// remove hidden notification
mNotificationManager.cancel(getClass().hashCode() + id);
unfocus(window);
window.visibility = Window.VISIBILITY_TRANSITION;
// get animation
Animation animation = getCloseAnimation(id);
// remove window
try {
// animate
if (animation != null) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// remove the window from the window manager
mWindowManager.removeView(window);
window.visibility = Window.VISIBILITY_GONE;
// remove view from internal map
sWindowCache.removeCache(id,
StandOutWindow.this.getClass());
// if we just released the last window, quit
if (getExistingIds().size() == 0) {
// tell Android to remove the persistent
// notification
// the Service will be shutdown by the system on low
// memory
startedForeground = false;
stopForeground(true);
}
}
});
window.getChildAt(0).startAnimation(animation);
} else {
// remove the window from the window manager
mWindowManager.removeView(window);
// remove view from internal map
sWindowCache.removeCache(id, getClass());
// if we just released the last window, quit
if (sWindowCache.getCacheSize(getClass()) == 0) {
// tell Android to remove the persistent notification
// the Service will be shutdown by the system on low memory
startedForeground = false;
stopForeground(true);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Close all existing windows.
*/
public final synchronized void closeAll() {
// alert callbacks and cancel if instructed
if (onCloseAll()) {
Log.w(TAG, "Windows close all cancelled by implementation.");
return;
}
// add ids to temporary set to avoid concurrent modification
LinkedList<Integer> ids = new LinkedList<Integer>();
for (int id : getExistingIds()) {
ids.add(id);
}
// close each window
for (int id : ids) {
close(id);
}
}
/**
* Send {@link Parceleable} data in a {@link Bundle} to a new or existing
* windows. The implementation of the recipient window can handle what to do
* with the data. To receive a result, provide the id of the sender.
*
* @param fromId
* Provide the id of the sending window if you want a result.
* @param toCls
* The Service's class extending {@link StandOutWindow} that is
* managing the receiving window.
* @param toId
* The id of the receiving window.
* @param requestCode
* Provide a request code to declare what kind of data is being
* sent.
* @param data
* A bundle of parceleable data to be sent to the receiving
* window.
*/
public final void sendData(int fromId,
Class<? extends StandOutWindow> toCls, int toId, int requestCode,
Bundle data) {
StandOutWindow.sendData(this, toCls, toId, requestCode, data,
getClass(), fromId);
}
/**
* Bring the window corresponding to this id in front of all other windows.
* The window may flicker as it is removed and restored by the system.
*
* @param id
* The id of the window to bring to the front.
*/
public final synchronized void bringToFront(int id) {
Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to bringToFront(" + id
+ ") a null window.");
}
if (window.visibility == Window.VISIBILITY_GONE) {
throw new IllegalStateException("Tried to bringToFront(" + id
+ ") a window that is not shown.");
}
if (window.visibility == Window.VISIBILITY_TRANSITION) {
return;
}
// alert callbacks and cancel if instructed
if (onBringToFront(id, window)) {
Log.w(TAG, "Window " + id
+ " bring to front cancelled by implementation.");
return;
}
StandOutLayoutParams params = window.getLayoutParams();
// remove from window manager then add back
try {
mWindowManager.removeView(window);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
mWindowManager.addView(window, params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Request focus for the window corresponding to this id. A maximum of one
* window can have focus, and that window will receive all key events,
* including Back and Menu.
*
* @param id
* The id of the window.
* @return True if focus changed successfully, false if it failed.
*/
public final synchronized boolean focus(int id) {
// check if that window is focusable
final Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to focus(" + id
+ ") a null window.");
}
if (!Utils.isSet(window.flags,
StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE)) {
// remove focus from previously focused window
if (sFocusedWindow != null) {
unfocus(sFocusedWindow);
}
return window.onFocus(true);
}
return false;
}
/**
* Remove focus for the window corresponding to this id. Once a window is
* unfocused, it will stop receiving key events.
*
* @param id
* The id of the window.
* @return True if focus changed successfully, false if it failed.
*/
public final synchronized boolean unfocus(int id) {
Window window = getWindow(id);
return unfocus(window);
}
/**
* Courtesy method for your implementation to use if you want to. Gets a
* unique id to assign to a new window.
*
* @return The unique id.
*/
public final int getUniqueId() {
int unique = DEFAULT_ID;
for (int id : getExistingIds()) {
unique = Math.max(unique, id + 1);
}
return unique;
}
/**
* Return whether the window corresponding to the id exists. This is useful
* for testing if the id is being restored (return true) or shown for the
* first time (return false).
*
* @param id
* The id of the window.
* @return True if the window corresponding to the id is either shown or
* hidden, or false if it has never been shown or was previously
* closed.
*/
public final boolean isExistingId(int id) {
return sWindowCache.isCached(id, getClass());
}
/**
* Return the ids of all shown or hidden windows.
*
* @return A set of ids, or an empty set.
*/
public final Set<Integer> getExistingIds() {
return sWindowCache.getCacheIds(getClass());
}
/**
* Return the window corresponding to the id, if it exists in cache. The
* window will not be created with
* {@link #createAndAttachView(int, ViewGroup)}. This means the returned
* value will be null if the window is not shown or hidden.
*
* @param id
* The id of the window.
* @return The window if it is shown/hidden, or null if it is closed.
*/
public final Window getWindow(int id) {
return sWindowCache.getCache(id, getClass());
}
/**
* Return the window that currently has focus.
*
* @return The window that has focus.
*/
public final Window getFocusedWindow() {
return sFocusedWindow;
}
/**
* Sets the window that currently has focus.
*/
public final void setFocusedWindow(Window window) {
sFocusedWindow = window;
}
/**
* Change the title of the window, if such a title exists. A title exists if
* {@link StandOutFlags#FLAG_DECORATION_SYSTEM} is set, or if your own view
* contains a TextView with id R.id.title.
*
* @param id
* The id of the window.
* @param text
* The new title.
*/
public final void setTitle(int id, String text) {
Window window = getWindow(id);
if (window != null) {
View title = window.findViewById(R.id.title);
if (title instanceof TextView) {
((TextView) title).setText(text);
}
}
}
/**
* Change the icon of the window, if such a icon exists. A icon exists if
* {@link StandOutFlags#FLAG_DECORATION_SYSTEM} is set, or if your own view
* contains a TextView with id R.id.window_icon.
*
* @param id
* The id of the window.
* @param drawableRes
* The new icon.
*/
public final void setIcon(int id, int drawableRes) {
Window window = getWindow(id);
if (window != null) {
View icon = window.findViewById(R.id.window_icon);
if (icon instanceof ImageView) {
((ImageView) icon).setImageResource(drawableRes);
}
}
}
/**
* Internal touch handler for handling moving the window.
*
* @see {@link View#onTouchEvent(MotionEvent)}
*
* @param id
* @param window
* @param view
* @param event
* @return
*/
public boolean onTouchHandleMove(int id, Window window, View view,
MotionEvent event) {
StandOutLayoutParams params = window.getLayoutParams();
// how much you have to move in either direction in order for the
// gesture to be a move and not tap
int totalDeltaX = window.touchInfo.lastX - window.touchInfo.firstX;
int totalDeltaY = window.touchInfo.lastY - window.touchInfo.firstY;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
window.touchInfo.firstX = window.touchInfo.lastX;
window.touchInfo.firstY = window.touchInfo.lastY;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - window.touchInfo.lastX;
int deltaY = (int) event.getRawY() - window.touchInfo.lastY;
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
if (window.touchInfo.moving
|| Math.abs(totalDeltaX) >= params.threshold
|| Math.abs(totalDeltaY) >= params.threshold) {
window.touchInfo.moving = true;
// if window is moveable
if (Utils.isSet(window.flags,
StandOutFlags.FLAG_BODY_MOVE_ENABLE)) {
// update the position of the window
if (event.getPointerCount() == 1) {
params.x += deltaX;
params.y += deltaY;
}
window.edit().setPosition(params.x, params.y).commit();
}
}
break;
case MotionEvent.ACTION_UP:
window.touchInfo.moving = false;
if (event.getPointerCount() == 1) {
// bring to front on tap
boolean tap = Math.abs(totalDeltaX) < params.threshold
&& Math.abs(totalDeltaY) < params.threshold;
if (tap
&& Utils.isSet(
window.flags,
StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TAP)) {
StandOutWindow.this.bringToFront(id);
}
}
// bring to front on touch
else if (Utils.isSet(window.flags,
StandOutFlags.FLAG_WINDOW_BRING_TO_FRONT_ON_TOUCH)) {
StandOutWindow.this.bringToFront(id);
}
break;
}
onMove(id, window, view, event);
return true;
}
/**
* Internal touch handler for handling resizing the window.
*
* @see {@link View#onTouchEvent(MotionEvent)}
*
* @param id
* @param window
* @param view
* @param event
* @return
*/
public boolean onTouchHandleResize(int id, Window window, View view,
MotionEvent event) {
StandOutLayoutParams params = (StandOutLayoutParams) window
.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
window.touchInfo.lastX = (int) event.getRawX();
window.touchInfo.lastY = (int) event.getRawY();
window.touchInfo.firstX = window.touchInfo.lastX;
window.touchInfo.firstY = window.touchInfo.lastY;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) event.getRawX() - window.touchInfo.lastX;
int deltaY = (int) event.getRawY() - window.touchInfo.lastY;
// update the size of the window
params.width += deltaX;
params.height += deltaY;
// keep window between min/max width/height
if (params.width >= params.minWidth
&& params.width <= params.maxWidth) {
window.touchInfo.lastX = (int) event.getRawX();
}
if (params.height >= params.minHeight
&& params.height <= params.maxHeight) {
window.touchInfo.lastY = (int) event.getRawY();
}
window.edit().setSize(params.width, params.height).commit();
break;
case MotionEvent.ACTION_UP:
break;
}
onResize(id, window, view, event);
return true;
}
/**
* Remove focus for the window, which could belong to another application.
* Since we don't allow windows from different applications to directly
* interact with each other, except for
* {@link #sendData(Context, Class, int, int, Bundle, Class, int)}, this
* method is private.
*
* @param window
* The window to unfocus.
* @return True if focus changed successfully, false if it failed.
*/
public synchronized boolean unfocus(Window window) {
if (window == null) {
throw new IllegalArgumentException(
"Tried to unfocus a null window.");
}
return window.onFocus(false);
}
/**
* Update the window corresponding to this id with the given params.
*
* @param id
* The id of the window.
* @param params
* The updated layout params to apply.
*/
public void updateViewLayout(int id, StandOutLayoutParams params) {
Window window = getWindow(id);
if (window == null) {
throw new IllegalArgumentException("Tried to updateViewLayout("
+ id + ") a null window.");
}
if (window.visibility == Window.VISIBILITY_GONE) {
return;
}
if (window.visibility == Window.VISIBILITY_TRANSITION) {
return;
}
// alert callbacks and cancel if instructed
if (onUpdate(id, window, params)) {
Log.w(TAG, "Window " + id + " update cancelled by implementation.");
return;
}
try {
window.setLayoutParams(params);
mWindowManager.updateViewLayout(window, params);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* LayoutParams specific to floating StandOut windows.
*
* @author Mark Wei <[email protected]>
*
*/
public class StandOutLayoutParams extends WindowManager.LayoutParams {
/**
* Special value for x position that represents the left of the screen.
*/
public static final int LEFT = 0;
/**
* Special value for y position that represents the top of the screen.
*/
public static final int TOP = 0;
/**
* Special value for x position that represents the right of the screen.
*/
public static final int RIGHT = Integer.MAX_VALUE;
/**
* Special value for y position that represents the bottom of the
* screen.
*/
public static final int BOTTOM = Integer.MAX_VALUE;
/**
* Special value for x or y position that represents the center of the
* screen.
*/
public static final int CENTER = Integer.MIN_VALUE;
/**
* Special value for x or y position which requests that the system
* determine the position.
*/
public static final int AUTO_POSITION = Integer.MIN_VALUE + 1;
/**
* The distance that distinguishes a tap from a drag.
*/
public int threshold;
/**
* Optional constraints of the window.
*/
public int minWidth, minHeight, maxWidth, maxHeight;
/**
* @param id
* The id of the window.
*/
public StandOutLayoutParams(int id) {
super(200, 200, TYPE_PHONE,
StandOutLayoutParams.FLAG_NOT_TOUCH_MODAL
| StandOutLayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
int windowFlags = getFlags(id);
setFocusFlag(false);
if (!Utils.isSet(windowFlags,
StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE)) {
// windows may be moved beyond edges
flags |= FLAG_LAYOUT_NO_LIMITS;
}
x = getX(id, width);
y = getY(id, height);
gravity = Gravity.TOP | Gravity.LEFT;
threshold = 10;
minWidth = minHeight = 0;
maxWidth = maxHeight = Integer.MAX_VALUE;
}
/**
* @param id
* The id of the window.
* @param w
* The width of the window.
* @param h
* The height of the window.
*/
public StandOutLayoutParams(int id, int w, int h) {
this(id);
width = w;
height = h;
}
/**
* @param id
* The id of the window.
* @param w
* The width of the window.
* @param h
* The height of the window.
* @param xpos
* The x position of the window.
* @param ypos
* The y position of the window.
*/
public StandOutLayoutParams(int id, int w, int h, int xpos, int ypos) {
this(id, w, h);
if (xpos != AUTO_POSITION) {
x = xpos;
}
if (ypos != AUTO_POSITION) {
y = ypos;
}
Display display = mWindowManager.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
if (x == RIGHT) {
x = width - w;
} else if (x == CENTER) {
x = (width - w) / 2;
}
if (y == BOTTOM) {
y = height - h;
} else if (y == CENTER) {
y = (height - h) / 2;
}
}
/**
* @param id
* The id of the window.
* @param w
* The width of the window.
* @param h
* The height of the window.
* @param xpos
* The x position of the window.
* @param ypos
* The y position of the window.
* @param minWidth
* The minimum width of the window.
* @param minHeight
* The mininum height of the window.
*/
public StandOutLayoutParams(int id, int w, int h, int xpos, int ypos,
int minWidth, int minHeight) {
this(id, w, h, xpos, ypos);
this.minWidth = minWidth;
this.minHeight = minHeight;
}
/**
* @param id
* The id of the window.
* @param w
* The width of the window.
* @param h
* The height of the window.
* @param xpos
* The x position of the window.
* @param ypos
* The y position of the window.
* @param minWidth
* The minimum width of the window.
* @param minHeight
* The mininum height of the window.
* @param threshold
* The touch distance threshold that distinguishes a tap from
* a drag.
*/
public StandOutLayoutParams(int id, int w, int h, int xpos, int ypos,
int minWidth, int minHeight, int threshold) {
this(id, w, h, xpos, ypos, minWidth, minHeight);
this.threshold = threshold;
}
// helper to create cascading windows
private int getX(int id, int width) {
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int types = sWindowCache.size();
int initialX = 100 * types;
int variableX = 100 * id;
int rawX = initialX + variableX;
return rawX % (displayWidth - width);
}
// helper to create cascading windows
private int getY(int id, int height) {
Display display = mWindowManager.getDefaultDisplay();
int displayWidth = display.getWidth();
int displayHeight = display.getHeight();
int types = sWindowCache.size();
int initialY = 100 * types;
int variableY = x + 200 * (100 * id) / (displayWidth - width);
int rawY = initialY + variableY;
return rawY % (displayHeight - height);
}
public void setFocusFlag(boolean focused) {
if (focused) {
flags = flags ^ StandOutLayoutParams.FLAG_NOT_FOCUSABLE;
} else {
flags = flags | StandOutLayoutParams.FLAG_NOT_FOCUSABLE;
}
}
}
protected class DropDownListItem {
public int icon;
public String description;
public Runnable action;
public DropDownListItem(int icon, String description, Runnable action) {
super();
this.icon = icon;
this.description = description;
this.action = action;
}
@Override
public String toString() {
return description;
}
}
}
| true | false | null | null |
diff --git a/transfuse/src/main/java/org/androidtransfuse/analysis/AOPRepository.java b/transfuse/src/main/java/org/androidtransfuse/analysis/AOPRepository.java
index ceb6d997..2b4cb588 100644
--- a/transfuse/src/main/java/org/androidtransfuse/analysis/AOPRepository.java
+++ b/transfuse/src/main/java/org/androidtransfuse/analysis/AOPRepository.java
@@ -1,28 +1,26 @@
package org.androidtransfuse.analysis;
import org.androidtransfuse.analysis.adapter.ASTType;
-import javax.inject.Singleton;
import java.util.HashMap;
import java.util.Map;
/**
* @author John Ericksen
*/
-@Singleton
public class AOPRepository {
private Map<String, ASTType> interceptorAnnotationMap = new HashMap<String, ASTType>();
public void put(ASTType interceptor, ASTType annotationType) {
interceptorAnnotationMap.put(interceptor.getName(), annotationType);
}
public ASTType getInterceptor(String annotation) {
return interceptorAnnotationMap.get(annotation);
}
public boolean isInterceptor(String annotation) {
return interceptorAnnotationMap.containsKey(annotation);
}
}
diff --git a/transfuse/src/main/java/org/androidtransfuse/config/TransfuseGenerationGuiceModule.java b/transfuse/src/main/java/org/androidtransfuse/config/TransfuseGenerationGuiceModule.java
index a6cce1d1..56b6a0c4 100644
--- a/transfuse/src/main/java/org/androidtransfuse/config/TransfuseGenerationGuiceModule.java
+++ b/transfuse/src/main/java/org/androidtransfuse/config/TransfuseGenerationGuiceModule.java
@@ -1,64 +1,67 @@
package org.androidtransfuse.config;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.sun.codemodel.JCodeModel;
import com.thoughtworks.xstream.XStream;
+import org.androidtransfuse.analysis.AOPRepository;
+import org.androidtransfuse.analysis.AOPRepositoryProvider;
import org.androidtransfuse.analysis.AnalysisRepository;
import org.androidtransfuse.analysis.AnalysisRepositoryFactory;
import org.androidtransfuse.analysis.adapter.ASTFactory;
import org.androidtransfuse.analysis.astAnalyzer.BindingRepository;
import org.androidtransfuse.analysis.astAnalyzer.BindingRepositoryProvider;
import org.androidtransfuse.analysis.astAnalyzer.ScopeAspectFactoryRepository;
import org.androidtransfuse.analysis.astAnalyzer.ScopeAspectFactoryRepositoryProvider;
import org.androidtransfuse.gen.*;
import org.androidtransfuse.gen.scopeBuilder.ScopeBuilderFactory;
import org.androidtransfuse.gen.variableBuilder.VariableInjectionBuilderFactory;
import org.androidtransfuse.gen.variableBuilder.resource.MethodBasedResourceExpressionBuilderAdaptorFactory;
import org.androidtransfuse.gen.variableBuilder.resource.MethodBasedResourceExpressionBuilderFactory;
import org.androidtransfuse.gen.variableDecorator.ExpressionDecoratorFactory;
import org.androidtransfuse.gen.variableDecorator.VariableExpressionBuilder;
import org.androidtransfuse.gen.variableDecorator.VariableExpressionBuilderFactory;
import org.androidtransfuse.processor.ProcessorFactory;
import org.androidtransfuse.util.Logger;
import org.androidtransfuse.util.ManifestLocatorFactory;
/**
* @author John Ericksen
*/
public class TransfuseGenerationGuiceModule extends AbstractModule {
private Logger logger;
public TransfuseGenerationGuiceModule(Logger logger) {
this.logger = logger;
}
@Override
protected void configure() {
FactoryModuleBuilder factoryModuleBuilder = new FactoryModuleBuilder();
install(factoryModuleBuilder.build(InjectionBuilderContextFactory.class));
install(factoryModuleBuilder.build(VariableInjectionBuilderFactory.class));
install(factoryModuleBuilder.build(MethodBasedResourceExpressionBuilderFactory.class));
install(factoryModuleBuilder.build(MethodBasedResourceExpressionBuilderAdaptorFactory.class));
install(factoryModuleBuilder.build(ASTFactory.class));
install(factoryModuleBuilder.build(ManifestLocatorFactory.class));
install(factoryModuleBuilder.build(ProcessorFactory.class));
install(factoryModuleBuilder.build(VariableExpressionBuilderFactory.class));
install(factoryModuleBuilder.build(ScopeBuilderFactory.class));
bind(JCodeModel.class).asEagerSingleton();
bind(VariableExpressionBuilder.class).toProvider(ExpressionDecoratorFactory.class);
bind(BindingRepository.class).toProvider(BindingRepositoryProvider.class);
bind(ScopeAspectFactoryRepository.class).toProvider(ScopeAspectFactoryRepositoryProvider.class);
bind(XStream.class).toProvider(XStreamProvider.class);
bind(InjectionNodeBuilderRepository.class).toProvider(InjectionNodeBuilderRepositoryFactory.class).asEagerSingleton();
bind(AnalysisRepository.class).toProvider(AnalysisRepositoryFactory.class).asEagerSingleton();
+ bind(AOPRepository.class).toProvider(AOPRepositoryProvider.class).asEagerSingleton();
bind(InjectionExpressionBuilder.class).to(InjectionExpressionBuilderImpl.class);
bind(Logger.class).toInstance(logger);
}
}
| false | false | null | null |
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/editors/InvisibleContextElementsPart.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/editors/InvisibleContextElementsPart.java
index 1f1ee4bce..82be6b204 100644
--- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/editors/InvisibleContextElementsPart.java
+++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/editors/InvisibleContextElementsPart.java
@@ -1,410 +1,410 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.context.ui.editors;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.context.core.AbstractContextStructureBridge;
import org.eclipse.mylyn.context.core.ContextCore;
import org.eclipse.mylyn.context.core.IInteractionContext;
import org.eclipse.mylyn.context.core.IInteractionElement;
import org.eclipse.mylyn.internal.commons.ui.SwtUtil;
import org.eclipse.mylyn.internal.context.core.ContextCorePlugin;
import org.eclipse.mylyn.internal.context.ui.ContextUiPlugin;
import org.eclipse.mylyn.internal.provisional.commons.ui.WorkbenchUtil;
import org.eclipse.mylyn.tasks.ui.TasksUiImages;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.navigator.CommonViewer;
/**
* @author Shawn Minto
*/
public class InvisibleContextElementsPart {
private final class InteractionElementTableSorter extends ViewerSorter {
private int criteria = 0;
private boolean isDecending = true;
private final ITableLabelProvider labelProvider;
public InteractionElementTableSorter(ITableLabelProvider labelProvider) {
this.labelProvider = labelProvider;
}
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
int result = 0;
String value1 = labelProvider.getColumnText(e1, criteria);
String value2 = labelProvider.getColumnText(e2, criteria);
if (value1 == null && value2 != null) {
result = -1;
} else if (value1 != null && value2 == null) {
result = 1;
} else if (value1 != null && value2 != null) {
result = value1.compareTo(value2);
}
return isDecending() ? (result * -1) : result;
}
public boolean isDecending() {
return isDecending;
}
public void setCriteria(int index) {
if (criteria == index) {
isDecending = !isDecending;
} else {
isDecending = false;
}
criteria = index;
}
}
private final class InteractionElementTableLabelProvider extends LabelProvider implements ITableLabelProvider {
@Override
public String getText(Object element) {
if (element instanceof IInteractionElement) {
return ((IInteractionElement) element).getHandleIdentifier();
}
return super.getText(element);
}
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
if (element instanceof IInteractionElement) {
if (columnIndex == 0) {
return ((IInteractionElement) element).getHandleIdentifier();
} else if (columnIndex == 1) {
return ((IInteractionElement) element).getContentType();
}
}
return ""; //$NON-NLS-1$
}
}
private final class RemoveInvisibleAction extends Action {
public RemoveInvisibleAction() {
setText(Messages.ContextEditorFormPage_Remove_Invisible_);
setToolTipText(Messages.ContextEditorFormPage_Remove_Invisible_);
setImageDescriptor(TasksUiImages.CONTEXT_CLEAR);
}
@Override
public void run() {
if (commonViewer == null) {
MessageDialog.openWarning(WorkbenchUtil.getShell(), Messages.ContextEditorFormPage_Remove_Invisible,
Messages.ContextEditorFormPage_Activate_task_to_remove_invisible);
return;
}
boolean confirmed = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(),
Messages.ContextEditorFormPage_Remove_Invisible,
Messages.ContextEditorFormPage_Remove_every_element_not_visible);
if (confirmed) {
if (ContextCore.getContextManager().isContextActive()) {
try {
final Collection<Object> allVisible = getAllVisibleElementsInContextPage();
PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
monitor.beginTask(Messages.InvisibleContextElementsPart_Collecting_all_invisible,
IProgressMonitor.UNKNOWN);
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
final List<IInteractionElement> allToRemove = getAllInvisibleElements(context,
allVisible);
Display.getDefault().asyncExec(new Runnable() {
public void run() {
ContextCore.getContextManager().deleteElements(allToRemove);
}
});
} else {
MessageDialog.openInformation(Display.getCurrent().getActiveShell(),
Messages.ContextEditorFormPage_Remove_Invisible,
Messages.ContextEditorFormPage_No_context_active);
}
}
});
} catch (InvocationTargetException e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, e.getMessage(), e));
} catch (InterruptedException e) {
StatusHandler.log(new Status(IStatus.ERROR, ContextUiPlugin.ID_PLUGIN, e.getMessage(), e));
}
} else {
MessageDialog.openInformation(Display.getCurrent().getActiveShell(),
Messages.ContextEditorFormPage_Remove_Invisible,
Messages.ContextEditorFormPage_No_context_active);
}
}
}
}
private TableViewer invisibleTable;
private Section invisibleSection;
private final CommonViewer commonViewer;
public InvisibleContextElementsPart(CommonViewer commonViewer) {
this.commonViewer = commonViewer;
}
public Control createControl(FormToolkit toolkit, Composite composite) {
invisibleSection = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE);
invisibleSection.setText(NLS.bind(Messages.InvisibleContextElementsPart_Invisible_elements, "0")); //$NON-NLS-1$
invisibleSection.setEnabled(false);
Composite toolbarComposite = toolkit.createComposite(invisibleSection);
toolbarComposite.setBackground(null);
invisibleSection.setTextClient(toolbarComposite);
RowLayout rowLayout = new RowLayout();
rowLayout.marginTop = 0;
rowLayout.marginBottom = 0;
toolbarComposite.setLayout(rowLayout);
ToolBarManager toolbarManager = new ToolBarManager(SWT.FLAT);
toolbarManager.add(new RemoveInvisibleAction());
toolbarManager.createControl(toolbarComposite);
toolbarManager.markDirty();
toolbarManager.update(true);
Composite invisibleSectionClient = toolkit.createComposite(invisibleSection);
invisibleSectionClient.setLayout(new GridLayout());
invisibleSection.setClient(invisibleSectionClient);
Composite tableComposite = toolkit.createComposite(invisibleSectionClient);
- GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 200).grab(true, false).applyTo(tableComposite);
+ GridDataFactory.fillDefaults().hint(500, 200).grab(true, false).applyTo(tableComposite);
TableColumnLayout layout = new TableColumnLayout();
tableComposite.setLayout(layout);
invisibleTable = new TableViewer(tableComposite, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
invisibleTable.setColumnProperties(new String[] { Messages.InvisibleContextElementsPart_Structure_handle,
Messages.InvisibleContextElementsPart_Structure_kind });
invisibleTable.getTable().setHeaderVisible(true);
Table table = invisibleTable.getTable();
toolkit.adapt(table);
table.setMenu(null);
InteractionElementTableLabelProvider labelProvider = new InteractionElementTableLabelProvider();
invisibleTable.setLabelProvider(labelProvider);
invisibleTable.setContentProvider(new IStructuredContentProvider() {
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// ignore
}
public void dispose() {
// ignore
}
public Object[] getElements(Object inputElement) {
if (inputElement instanceof Collection<?>) {
return ((Collection<?>) inputElement).toArray();
}
return new Object[0];
}
});
InteractionElementTableSorter invisibleTableSorter = new InteractionElementTableSorter(labelProvider);
invisibleTableSorter.setCriteria(0);
invisibleTable.setSorter(invisibleTableSorter);
- createColumn(layout, 0, Messages.InvisibleContextElementsPart_Structure_handle, 300, table,
+ createColumn(layout, 0, Messages.InvisibleContextElementsPart_Structure_handle, 400, table,
invisibleTableSorter);
createColumn(layout, 1, Messages.InvisibleContextElementsPart_Structure_kind, 100, table, invisibleTableSorter);
table.setSortColumn(table.getColumn(0));
table.setSortDirection(SWT.DOWN);
if (ContextCore.getContextManager().isContextActive()) {
Collection<Object> allVisible = getAllVisibleElementsInContextPage();
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
updateInvisibleSectionInBackground(context, allVisible);
}
}
return invisibleSection;
}
private void createColumn(TableColumnLayout layout, final int index, String label, int weight, final Table table,
final InteractionElementTableSorter invisibleTableSorter) {
final TableColumn column = new TableColumn(table, SWT.LEFT, index);
column.setText(label);
column.setToolTipText(label);
column.setResizable(true);
layout.setColumnData(column, new ColumnPixelData(weight, true));
column.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
invisibleTableSorter.setCriteria(index);
table.setSortColumn(column);
if (invisibleTableSorter.isDecending()) {
table.setSortDirection(SWT.UP);
} else {
table.setSortDirection(SWT.DOWN);
}
invisibleTable.refresh();
}
});
}
public void updateInvisibleElementsSection() {
if (ContextCore.getContextManager().isContextActive()) {
Collection<Object> allVisible = getAllVisibleElementsInContextPage();
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
updateInvisibleSectionInBackground(context, allVisible);
}
}
}
private void updateInvisibleSectionInBackground(final IInteractionContext context,
final Collection<Object> allVisible) {
Job j = new Job(Messages.InvisibleContextElementsPart_Updating_invisible_element_list) {
@Override
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask(Messages.InvisibleContextElementsPart_Computing_invisible_elements,
IProgressMonitor.UNKNOWN);
final List<IInteractionElement> allInvisibleElements = getAllInvisibleElements(context, allVisible);
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (invisibleSection != null && !invisibleSection.isDisposed()) {
invisibleSection.setText(NLS.bind(Messages.InvisibleContextElementsPart_Invisible_elements,
allInvisibleElements.size()));
invisibleSection.layout();
if (allInvisibleElements.size() == 0) {
invisibleSection.setExpanded(false);
invisibleSection.setEnabled(false);
} else {
invisibleSection.setEnabled(true);
}
}
if (invisibleTable != null && !invisibleTable.getTable().isDisposed()) {
invisibleTable.setInput(allInvisibleElements);
}
}
});
return Status.OK_STATUS;
};
};
j.schedule();
}
private List<IInteractionElement> getAllInvisibleElements(IInteractionContext context, Collection<Object> allVisible) {
List<IInteractionElement> allToRemove = context.getAllElements();
List<IInteractionElement> allVisibleElements = new ArrayList<IInteractionElement>();
for (Object visibleObject : allVisible) {
for (AbstractContextStructureBridge bridge : ContextCorePlugin.getDefault().getStructureBridges().values()) {
// AbstractContextStructureBridge bridge = ContextCorePlugin.getDefault().getStructureBridge(visibleObject);
if (bridge != null) {
String handle = bridge.getHandleIdentifier(visibleObject);
if (handle != null) {
IInteractionElement element = context.get(handle);
if (element != null) {
allVisibleElements.add(element);
}
}
}
}
AbstractContextStructureBridge bridge = ContextCorePlugin.getDefault().getStructureBridge(
ContextCore.CONTENT_TYPE_RESOURCE);
if (bridge != null) {
String handle = bridge.getHandleIdentifier(visibleObject);
if (handle != null) {
IInteractionElement element = context.get(handle);
if (element != null) {
allVisibleElements.add(element);
}
}
}
}
IInteractionElement emptyElement = context.get(""); //$NON-NLS-1$
if (emptyElement != null) {
allVisibleElements.add(emptyElement);
}
allToRemove.removeAll(allVisibleElements);
return allToRemove;
}
private Collection<Object> getAllVisibleElementsInContextPage() {
if (commonViewer == null || commonViewer.getTree() == null || commonViewer.getTree().isDisposed()) {
return null;
}
Set<Object> allVisible = new HashSet<Object>();
SwtUtil.collectItemData(commonViewer.getTree().getItems(), allVisible);
return allVisible;
}
}
| false | true | public Control createControl(FormToolkit toolkit, Composite composite) {
invisibleSection = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE);
invisibleSection.setText(NLS.bind(Messages.InvisibleContextElementsPart_Invisible_elements, "0")); //$NON-NLS-1$
invisibleSection.setEnabled(false);
Composite toolbarComposite = toolkit.createComposite(invisibleSection);
toolbarComposite.setBackground(null);
invisibleSection.setTextClient(toolbarComposite);
RowLayout rowLayout = new RowLayout();
rowLayout.marginTop = 0;
rowLayout.marginBottom = 0;
toolbarComposite.setLayout(rowLayout);
ToolBarManager toolbarManager = new ToolBarManager(SWT.FLAT);
toolbarManager.add(new RemoveInvisibleAction());
toolbarManager.createControl(toolbarComposite);
toolbarManager.markDirty();
toolbarManager.update(true);
Composite invisibleSectionClient = toolkit.createComposite(invisibleSection);
invisibleSectionClient.setLayout(new GridLayout());
invisibleSection.setClient(invisibleSectionClient);
Composite tableComposite = toolkit.createComposite(invisibleSectionClient);
GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 200).grab(true, false).applyTo(tableComposite);
TableColumnLayout layout = new TableColumnLayout();
tableComposite.setLayout(layout);
invisibleTable = new TableViewer(tableComposite, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
invisibleTable.setColumnProperties(new String[] { Messages.InvisibleContextElementsPart_Structure_handle,
Messages.InvisibleContextElementsPart_Structure_kind });
invisibleTable.getTable().setHeaderVisible(true);
Table table = invisibleTable.getTable();
toolkit.adapt(table);
table.setMenu(null);
InteractionElementTableLabelProvider labelProvider = new InteractionElementTableLabelProvider();
invisibleTable.setLabelProvider(labelProvider);
invisibleTable.setContentProvider(new IStructuredContentProvider() {
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// ignore
}
public void dispose() {
// ignore
}
public Object[] getElements(Object inputElement) {
if (inputElement instanceof Collection<?>) {
return ((Collection<?>) inputElement).toArray();
}
return new Object[0];
}
});
InteractionElementTableSorter invisibleTableSorter = new InteractionElementTableSorter(labelProvider);
invisibleTableSorter.setCriteria(0);
invisibleTable.setSorter(invisibleTableSorter);
createColumn(layout, 0, Messages.InvisibleContextElementsPart_Structure_handle, 300, table,
invisibleTableSorter);
createColumn(layout, 1, Messages.InvisibleContextElementsPart_Structure_kind, 100, table, invisibleTableSorter);
table.setSortColumn(table.getColumn(0));
table.setSortDirection(SWT.DOWN);
if (ContextCore.getContextManager().isContextActive()) {
Collection<Object> allVisible = getAllVisibleElementsInContextPage();
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
updateInvisibleSectionInBackground(context, allVisible);
}
}
return invisibleSection;
}
| public Control createControl(FormToolkit toolkit, Composite composite) {
invisibleSection = toolkit.createSection(composite, ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE);
invisibleSection.setText(NLS.bind(Messages.InvisibleContextElementsPart_Invisible_elements, "0")); //$NON-NLS-1$
invisibleSection.setEnabled(false);
Composite toolbarComposite = toolkit.createComposite(invisibleSection);
toolbarComposite.setBackground(null);
invisibleSection.setTextClient(toolbarComposite);
RowLayout rowLayout = new RowLayout();
rowLayout.marginTop = 0;
rowLayout.marginBottom = 0;
toolbarComposite.setLayout(rowLayout);
ToolBarManager toolbarManager = new ToolBarManager(SWT.FLAT);
toolbarManager.add(new RemoveInvisibleAction());
toolbarManager.createControl(toolbarComposite);
toolbarManager.markDirty();
toolbarManager.update(true);
Composite invisibleSectionClient = toolkit.createComposite(invisibleSection);
invisibleSectionClient.setLayout(new GridLayout());
invisibleSection.setClient(invisibleSectionClient);
Composite tableComposite = toolkit.createComposite(invisibleSectionClient);
GridDataFactory.fillDefaults().hint(500, 200).grab(true, false).applyTo(tableComposite);
TableColumnLayout layout = new TableColumnLayout();
tableComposite.setLayout(layout);
invisibleTable = new TableViewer(tableComposite, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
invisibleTable.setColumnProperties(new String[] { Messages.InvisibleContextElementsPart_Structure_handle,
Messages.InvisibleContextElementsPart_Structure_kind });
invisibleTable.getTable().setHeaderVisible(true);
Table table = invisibleTable.getTable();
toolkit.adapt(table);
table.setMenu(null);
InteractionElementTableLabelProvider labelProvider = new InteractionElementTableLabelProvider();
invisibleTable.setLabelProvider(labelProvider);
invisibleTable.setContentProvider(new IStructuredContentProvider() {
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// ignore
}
public void dispose() {
// ignore
}
public Object[] getElements(Object inputElement) {
if (inputElement instanceof Collection<?>) {
return ((Collection<?>) inputElement).toArray();
}
return new Object[0];
}
});
InteractionElementTableSorter invisibleTableSorter = new InteractionElementTableSorter(labelProvider);
invisibleTableSorter.setCriteria(0);
invisibleTable.setSorter(invisibleTableSorter);
createColumn(layout, 0, Messages.InvisibleContextElementsPart_Structure_handle, 400, table,
invisibleTableSorter);
createColumn(layout, 1, Messages.InvisibleContextElementsPart_Structure_kind, 100, table, invisibleTableSorter);
table.setSortColumn(table.getColumn(0));
table.setSortDirection(SWT.DOWN);
if (ContextCore.getContextManager().isContextActive()) {
Collection<Object> allVisible = getAllVisibleElementsInContextPage();
if (allVisible != null) {
IInteractionContext context = ContextCore.getContextManager().getActiveContext();
updateInvisibleSectionInBackground(context, allVisible);
}
}
return invisibleSection;
}
|
diff --git a/src/main/java/org/jahia/services/usermanager/ldap/JahiaLDAPGroup.java b/src/main/java/org/jahia/services/usermanager/ldap/JahiaLDAPGroup.java
index 383fed4..b40656c 100644
--- a/src/main/java/org/jahia/services/usermanager/ldap/JahiaLDAPGroup.java
+++ b/src/main/java/org/jahia/services/usermanager/ldap/JahiaLDAPGroup.java
@@ -1,280 +1,297 @@
/**
* This file is part of Jahia, next-generation open source CMS:
* Jahia's next-generation, open source CMS stems from a widely acknowledged vision
* of enterprise application convergence - web, search, document, social and portal -
* unified by the simplicity of web content management.
*
* For more information, please visit http://www.jahia.com.
*
* Copyright (C) 2002-2013 Jahia Solutions Group SA. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* As a special exception to the terms and conditions of version 2.0 of
* the GPL (or any later version), you may redistribute this Program in connection
* with Free/Libre and Open Source Software ("FLOSS") applications as described
* in Jahia's FLOSS exception. You should have received a copy of the text
* describing the FLOSS exception, and it is also available here:
* http://www.jahia.com/license
*
* Commercial and Supported Versions of the program (dual licensing):
* alternatively, commercial and supported versions of the program may be used
* in accordance with the terms and conditions contained in a separate
* written agreement between you and Jahia Solutions Group SA.
*
* If you are unsure which license is appropriate for your use,
* please contact the sales department at [email protected].
*/
package org.jahia.services.usermanager.ldap;
import org.apache.commons.collections.iterators.EnumerationIterator;
import org.jahia.exceptions.JahiaException;
import org.jahia.registries.ServicesRegistry;
import org.jahia.services.SpringContextSingleton;
import org.jahia.services.usermanager.JahiaGroup;
import org.jahia.services.usermanager.JahiaUser;
import org.jahia.services.usermanager.JahiaUserManagerService;
import org.jahia.services.usermanager.jcr.JCRGroup;
import org.jahia.services.usermanager.jcr.JCRGroupManagerProvider;
+import org.jahia.utils.ClassLoaderUtils;
+import org.jahia.utils.ClassLoaderUtils.Callback;
import java.security.Principal;
import java.util.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
*
* @author Viceic Predrag <[email protected]>
* @version 1.0
*/
public class JahiaLDAPGroup extends JahiaGroup {
private static final long serialVersionUID = -2201602968581239379L;
/** Group's unique identification number */
protected int mID;
/** User Member type designation * */
protected static int mUSERTYPE = 1;
/** Group Member type designation * */
protected static int mGROUPTYPE = 2;
/** Group additional parameters. */
private Properties mProperties = new Properties ();
// LDAP dynamic group (groupOfURLs)
private boolean dynamic;
private String providerKey;
/**
*
*
* @throws JahiaException This class need to access the Services Registry and the DB Pool
* Service. If any of this services can't be accessed, a
* JahiaException is thrown.
* @param providerKey the provider key
* @param siteID The site id
* @param dynamic
*/
protected JahiaLDAPGroup (String providerKey, int id, String groupname, String groupKey, int siteID,
Map<String, Principal> members, Properties properties, boolean dynamic, boolean preloadedGroups) {
this.providerKey = providerKey;
mID = id;
mGroupname = groupname;
mGroupKey ="{"+providerKey+"}"+ groupKey;
mSiteID = siteID;
if (preloadedGroups || members != null && members.size() > 0) {
mMembers = members != null ? new HashSet<Principal>(members.values())
: new HashSet<Principal>();
}
if (properties != null) {
mProperties = properties;
}
this.dynamic = dynamic;
this.preloadedGroups = preloadedGroups;
}
private JahiaGroupManagerLDAPProvider getLDAPProvider() {
return (JahiaGroupManagerLDAPProvider) ServicesRegistry.getInstance().getJahiaGroupManagerService().getProvider(providerKey);
}
public boolean removeProperty (String key) {
boolean result = false;
if ((key != null) && (key.length () > 0)) {
// Remove these lines if LDAP problem --------------------
JCRGroupManagerProvider userManager = (JCRGroupManagerProvider) SpringContextSingleton.getInstance().getContext().getBean("JCRGroupManagerProvider");
JCRGroup jcrGroup = (JCRGroup) userManager.lookupExternalGroup(getName());
if(jcrGroup!=null) {
jcrGroup.removeProperty(key);
}
}
if (result) {
mProperties.remove (key);
}
// End remove --------------------
return result;
}
public Properties getProperties () {
return mProperties;
}
public boolean removeMember (Principal user) {
/**@todo Must check this*/
return false;
}
public String getProperty (String key) {
if ((mProperties != null) && (key != null)) {
return mProperties.getProperty (key);
}
return null;
}
public boolean addMember (Principal user) {
/**@todo Must check this*/
return false;
}
@Override
public void addMembers(Collection<Principal> principals) {
}
public boolean setProperty (String key, String value) {
boolean result = false;
if ((key != null) && (value != null)) {
// Remove these lines if LDAP problem --------------------
JCRGroupManagerProvider userManager = (JCRGroupManagerProvider) SpringContextSingleton.getInstance().getContext().getBean("JCRGroupManagerProvider");
JCRGroup jcrGroup = (JCRGroup) userManager.lookupExternalGroup(getName());
if(jcrGroup!=null) {
jcrGroup.setProperty(key, value);
}
// End remove --------------------
if (result) {
mProperties.setProperty(key, value);
}
}
return result;
}
public String getProviderName () {
return providerKey;
}
public boolean isDynamic() {
return dynamic;
}
public String toString () {
StringBuffer output = new StringBuffer ("Details of group [" + mGroupname + "] :\n");
output.append (" - ID : " + Integer.toString (mID) + "\n");
output.append (" - properties :");
@SuppressWarnings("unchecked")
Iterator<String> names = new EnumerationIterator(mProperties.propertyNames ());
String name;
if (names.hasNext ()) {
output.append ("\n");
while (names.hasNext ()) {
name = (String) names.next ();
output.append (
" " + name + " -> [" + (String) mProperties.getProperty (name) + "]\n");
}
} else {
output.append (" -no properties-\n");
}
// Add the user members useranames detail
output.append (" - members : ");
if (mMembers != null) {
if (mMembers.size() > 0) {
for (Principal member : mMembers) {
output.append ((member != null ? member.getName() : null) + "/");
}
} else {
output.append (" -no members-\n");
}
} else {
output.append (" -preloading of members disabled-\n");
}
return output.toString ();
}
public boolean equals (Object another) {
if (this == another) return true;
if (another != null && this.getClass() == another.getClass()) {
return (getGroupKey().equals(((JahiaGroup) another).getGroupKey()));
}
return false;
}
//-------------------------------------------------------------------------
public int hashCode () {
return mID;
}
public void setSiteID (int id) {
mSiteID = id;
}
- public boolean isMember(Principal principal) {
+ public boolean isMember(final Principal principal) {
Principal user = principal;
if (!(user instanceof JahiaLDAPUser) && !(user instanceof JahiaLDAPGroup)) {
return false;
}
if (super.isMember(user)) {
return true;
}
if (!preloadedGroups && user instanceof JahiaUser) {
- boolean result = getLDAPProvider().getUserMembership((JahiaUser)principal).contains(getGroupKey());
- membership.put(JahiaUserManagerService.getKey(principal), Boolean.valueOf(result));
+ final JahiaGroupManagerLDAPProvider provider = getLDAPProvider();
+ Boolean result = ClassLoaderUtils.executeWith(provider.getClass().getClassLoader(),
+ new Callback<Boolean>() {
+ @Override
+ public Boolean execute() {
+ return provider.getUserMembership((JahiaUser) principal).contains(getGroupKey());
+ }
+ });
+ membership.put(JahiaUserManagerService.getKey(principal), result);
return result;
}
return false;
}
@Override
protected Set<Principal> getMembersMap() {
if (mMembers == null) {
- mMembers = new HashSet<Principal>(getLDAPProvider().getGroupMembers(getGroupname(), isDynamic()).values());
+ final JahiaGroupManagerLDAPProvider provider = getLDAPProvider();
+ Collection<Principal> groupMembers = ClassLoaderUtils.executeWith(provider.getClass().getClassLoader(),
+ new Callback<Collection<Principal>>() {
+ @Override
+ public Collection<Principal> execute() {
+ return provider.getGroupMembers(getGroupname(), isDynamic()).values();
+ }
+ });
+ mMembers = new HashSet<Principal>(groupMembers);
preloadedGroups = true;
}
return mMembers;
}
}
| false | false | null | null |
diff --git a/eol-globi-data-tool/src/main/java/org/eol/globi/data/NodeFactory.java b/eol-globi-data-tool/src/main/java/org/eol/globi/data/NodeFactory.java
index f004d124..2692eb5b 100644
--- a/eol-globi-data-tool/src/main/java/org/eol/globi/data/NodeFactory.java
+++ b/eol-globi-data-tool/src/main/java/org/eol/globi/data/NodeFactory.java
@@ -1,509 +1,509 @@
package org.eol.globi.data;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.WildcardQuery;
import org.eol.globi.data.taxon.CorrectionService;
import org.eol.globi.data.taxon.TaxonNameCorrector;
import org.eol.globi.domain.Environment;
import org.eol.globi.domain.Location;
import org.eol.globi.domain.NamedNode;
import org.eol.globi.domain.PropertyAndValueDictionary;
import org.eol.globi.domain.Season;
import org.eol.globi.domain.Specimen;
import org.eol.globi.domain.Study;
import org.eol.globi.domain.Taxon;
import org.eol.globi.service.DOIResolver;
import org.eol.globi.service.EnvoLookupService;
import org.eol.globi.service.TaxonPropertyEnricher;
import org.eol.globi.service.TermLookupService;
import org.eol.globi.service.TermLookupServiceException;
import org.eol.globi.service.UberonLookupService;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.graphdb.index.IndexManager;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.index.lucene.QueryContext;
import org.neo4j.index.lucene.ValueContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class NodeFactory {
private static final Log LOG = LogFactory.getLog(NodeFactory.class);
private final TaxonPropertyEnricher taxonEnricher;
private GraphDatabaseService graphDb;
private final Index<Node> studies;
private final Index<Node> seasons;
private final Index<Node> locations;
private final Index<Node> environments;
private final Index<Node> taxons;
private final Index<Node> taxonNameSuggestions;
private final Index<Node> taxonPaths;
private final Index<Node> taxonCommonNames;
public static final org.eol.globi.domain.Term NO_MATCH_TERM = new org.eol.globi.domain.Term(PropertyAndValueDictionary.NO_MATCH, PropertyAndValueDictionary.NO_MATCH);
private TermLookupService termLookupService;
private TermLookupService envoLookupService;
private CorrectionService correctionService;
private DOIResolver doiResolver;
public NodeFactory(GraphDatabaseService graphDb, TaxonPropertyEnricher taxonEnricher) {
this.graphDb = graphDb;
this.taxonEnricher = taxonEnricher;
this.termLookupService = new UberonLookupService();
this.envoLookupService = new EnvoLookupService();
this.correctionService = new TaxonNameCorrector();
this.studies = graphDb.index().forNodes("studies");
this.seasons = graphDb.index().forNodes("seasons");
this.locations = graphDb.index().forNodes("locations");
this.environments = graphDb.index().forNodes("environments");
this.taxons = graphDb.index().forNodes("taxons");
this.taxonNameSuggestions = graphDb.index().forNodes("taxonNameSuggestions");
this.taxonPaths = graphDb.index().forNodes("taxonpaths", MapUtil.stringMap(IndexManager.PROVIDER, "lucene", "type", "fulltext"));
this.taxonCommonNames = graphDb.index().forNodes("taxonCommonNames", MapUtil.stringMap(IndexManager.PROVIDER, "lucene", "type", "fulltext"));
}
public static List<Study> findAllStudies(GraphDatabaseService graphService) {
List<Study> studies = new ArrayList<Study>();
Index<Node> studyIndex = graphService.index().forNodes("studies");
IndexHits<Node> hits = studyIndex.query("title", "*");
for (Node hit : hits) {
studies.add(new Study(hit));
}
return studies;
}
public GraphDatabaseService getGraphDb() {
return graphDb;
}
private void addToIndeces(Taxon taxon) {
// only index taxa with external id
if (StringUtils.isNotBlank(taxon.getName())) {
taxons.add(taxon.getUnderlyingNode(), Taxon.NAME, taxon.getName());
indexCommonNames(taxon);
indexTaxonPath(taxon);
}
}
private void indexTaxonPath(Taxon taxon) {
String path = taxon.getPath();
if (StringUtils.isNotBlank(path)) {
taxonPaths.add(taxon.getUnderlyingNode(), Taxon.PATH, path);
taxonCommonNames.add(taxon.getUnderlyingNode(), Taxon.PATH, path);
String[] pathElementArray = path.split(CharsetConstant.SEPARATOR);
for (String pathElement : pathElementArray) {
taxonNameSuggestions.add(taxon.getUnderlyingNode(), Taxon.NAME, StringUtils.lowerCase(pathElement));
}
}
}
private void indexCommonNames(Taxon taxon) {
String commonNames = taxon.getCommonNames();
if (StringUtils.isNotBlank(commonNames)) {
taxonCommonNames.add(taxon.getUnderlyingNode(), Taxon.COMMON_NAMES, commonNames);
String[] commonNameArray = commonNames.split(CharsetConstant.SEPARATOR);
for (String commonName : commonNameArray) {
taxonNameSuggestions.add(taxon.getUnderlyingNode(), Taxon.NAME, StringUtils.lowerCase(commonName));
}
}
}
public Taxon findTaxon(String taxonName) throws NodeFactoryException {
return findTaxonOfType(taxonName);
}
public Taxon findTaxonOfType(String taxonName) throws NodeFactoryException {
String cleanedTaxonName = correctionService.correct(taxonName);
- String query = "name:\"" + cleanedTaxonName + "\"";
+ String query = "name:\"" + cleanedTaxonName.replace("\"", "") + "\"";
IndexHits<Node> matchingTaxa = taxons.query(query);
Node matchingTaxon;
Taxon firstMatchingTaxon = null;
if (matchingTaxa.hasNext()) {
matchingTaxon = matchingTaxa.next();
firstMatchingTaxon = new Taxon(matchingTaxon);
}
ArrayList<Taxon> duplicateTaxons = null;
while (matchingTaxa.hasNext()) {
if (duplicateTaxons == null) {
duplicateTaxons = new ArrayList<Taxon>();
}
duplicateTaxons.add(new Taxon(matchingTaxa.next()));
}
if (duplicateTaxons != null) {
StringBuffer buffer = new StringBuffer();
duplicateTaxons.add(firstMatchingTaxon);
for (Taxon duplicateTaxon : duplicateTaxons) {
buffer.append('{');
buffer.append(duplicateTaxon.getName());
buffer.append(':');
buffer.append(duplicateTaxon.getExternalId());
buffer.append('}');
}
LOG.warn("found duplicates for taxon with name [" + taxonName + "], using first only: " + buffer.toString());
}
matchingTaxa.close();
return firstMatchingTaxon;
}
public Location findLocation(Double latitude, Double longitude, Double altitude) {
QueryContext queryOrQueryObject = QueryContext.numericRange(Location.LATITUDE, latitude, latitude);
IndexHits<Node> matchingLocations = locations.query(queryOrQueryObject);
Node matchingLocation = null;
for (Node node : matchingLocations) {
Double foundLongitude = (Double) node.getProperty(Location.LONGITUDE);
boolean altitudeMatches = false;
if (node.hasProperty(Location.ALTITUDE)) {
Double foundAltitude = (Double) node.getProperty(Location.ALTITUDE);
altitudeMatches = altitude != null && altitude.equals(foundAltitude);
} else if (null == altitude) {
// explicit null value matches
altitudeMatches = true;
}
if (longitude.equals(foundLongitude) && altitudeMatches) {
matchingLocation = node;
break;
}
}
matchingLocations.close();
return matchingLocation == null ? null : new Location(matchingLocation);
}
public Season createSeason(String seasonNameLower) {
Transaction transaction = graphDb.beginTx();
Season season;
try {
Node node = graphDb.createNode();
season = new Season(node, seasonNameLower);
seasons.add(node, Season.TITLE, seasonNameLower);
transaction.success();
} finally {
transaction.finish();
}
return season;
}
private Location createLocation(Double latitude, Double longitude, Double altitude) {
Transaction transaction = graphDb.beginTx();
Location location;
try {
Node node = graphDb.createNode();
location = new Location(node, latitude, longitude, altitude);
locations.add(node, Location.LATITUDE, ValueContext.numeric(latitude));
locations.add(node, Location.LONGITUDE, ValueContext.numeric(longitude));
if (altitude != null) {
locations.add(node, Location.ALTITUDE, ValueContext.numeric(altitude));
}
transaction.success();
} finally {
transaction.finish();
}
return location;
}
public Specimen createSpecimen(String specimenTaxonDescription) throws NodeFactoryException {
return createSpecimen(specimenTaxonDescription, null);
}
public Specimen createSpecimen(String specimenTaxonDescription, String taxonExternalId) throws NodeFactoryException {
Taxon taxon = getOrCreateTaxon(specimenTaxonDescription, taxonExternalId, null);
Specimen specimen = createSpecimen(taxon);
specimen.setOriginalTaxonDescription(specimenTaxonDescription);
return specimen;
}
private Specimen createSpecimen(Taxon taxon) {
Transaction transaction = graphDb.beginTx();
Specimen specimen;
try {
specimen = new Specimen(graphDb.createNode(), null);
if (taxon != null) {
specimen.classifyAs(taxon);
}
transaction.success();
} finally {
transaction.finish();
}
return specimen;
}
public Study createStudy(String title) {
return createStudy(title, null, null, null, null, null, null);
}
private Study createStudy(String title, String contributor, String institution, String period, String description, String publicationYear, String source) {
Transaction transaction = graphDb.beginTx();
Study study;
try {
Node node = graphDb.createNode();
study = new Study(node, title);
study.setSource(source);
study.setContributor(contributor);
study.setInstitution(institution);
study.setPeriod(period);
study.setDescription(description);
study.setPublicationYear(publicationYear);
if (doiResolver != null) {
String prefix = StringUtils.isBlank(contributor) ? "" : (contributor + " ");
String reference = StringUtils.isBlank(description) ? "" : (prefix + description);
try {
String doi = doiResolver.findDOIForReference(reference);
if (doi != null) {
study.setDOI(doi);
study.setCitation(doiResolver.findCitationForDOI(doi));
}
} catch (IOException e) {
LOG.warn("failed to lookup doi for [" + reference + "]");
}
}
studies.add(node, "title", title);
transaction.success();
} finally {
transaction.finish();
}
return study;
}
public Study getOrCreateStudy(String title, String contributor, String institution, String period, String description, String publicationYear, String source) {
Study study = findStudy(title);
if (null == study) {
study = createStudy(title, contributor, institution, period, description, publicationYear, source);
}
return study;
}
public Study findStudy(String title) {
Node foundStudyNode = studies.get(Study.TITLE, title).getSingle();
return foundStudyNode == null ? null : new Study(foundStudyNode);
}
public Season findSeason(String seasonName) {
IndexHits<Node> nodeIndexHits = seasons.get(Season.TITLE, seasonName);
Node seasonHit = nodeIndexHits.getSingle();
nodeIndexHits.close();
return seasonHit == null ? null : new Season(seasonHit);
}
public Location getOrCreateLocation(Double latitude, Double longitude, Double altitude) {
Location location = null;
if (latitude != null && longitude != null) {
location = findLocation(latitude, longitude, altitude);
if (null == location) {
location = createLocation(latitude, longitude, altitude);
}
}
return location;
}
public Taxon getOrCreateTaxon(String name) throws NodeFactoryException {
return getOrCreateTaxon(name, null, null);
}
public Taxon getOrCreateTaxon(String name, String externalId, String path) throws NodeFactoryException {
if (StringUtils.length(name) < 2) {
throw new NodeFactoryException("taxon name [" + name + "] must contains more than 1 character");
}
Taxon taxon = findTaxon(name);
if (taxon == null) {
String normalizedName = correctionService.correct(name);
Transaction transaction = graphDb.beginTx();
try {
taxon = new Taxon(graphDb.createNode(), normalizedName);
taxon.setExternalId(externalId);
taxon.setPath(path);
taxonEnricher.enrich(taxon);
addToIndeces(taxon);
transaction.success();
} catch (IOException e) {
transaction.failure();
} finally {
transaction.finish();
}
}
return taxon;
}
public Taxon createTaxonNoTransaction(String name, String externalId, String path) {
Node node = graphDb.createNode();
Taxon taxon = new Taxon(node, correctionService.correct(name));
if (null != externalId) {
taxon.setExternalId(externalId);
}
if (null != path) {
taxon.setPath(path);
}
addToIndeces(taxon);
return taxon;
}
public void setUnixEpochProperty(Relationship rel, Date date) {
if (date != null) {
Transaction tx = rel.getGraphDatabase().beginTx();
try {
rel.setProperty(Specimen.DATE_IN_UNIX_EPOCH, date.getTime());
tx.success();
} finally {
tx.finish();
}
}
}
public Date getUnixEpochProperty(Relationship rel) {
Date date = null;
if (rel != null) {
if (rel.hasProperty(Specimen.DATE_IN_UNIX_EPOCH)) {
Long unixEpoch = (Long) rel.getProperty(Specimen.DATE_IN_UNIX_EPOCH);
date = new Date(unixEpoch);
}
}
return date;
}
public IndexHits<Node> findCloseMatchesForTaxonName(String taxonName) {
return query(taxonName, Taxon.NAME, taxons);
}
public IndexHits<Node> findCloseMatchesForTaxonPath(String taxonPath) {
return query(taxonPath, Taxon.PATH, taxonPaths);
}
private IndexHits<Node> query(String taxonName, String name, Index<Node> taxonIndex) {
String capitalizedValue = StringUtils.capitalize(taxonName);
List<Query> list = new ArrayList<Query>();
addQueriesForProperty(capitalizedValue, name, list);
BooleanQuery fuzzyAndWildcard = new BooleanQuery();
for (Query query : list) {
fuzzyAndWildcard.add(query, BooleanClause.Occur.SHOULD);
}
return taxonIndex.query(fuzzyAndWildcard);
}
private void addQueriesForProperty(String capitalizedValue, String propertyName, List<Query> list) {
list.add(new FuzzyQuery(new Term(propertyName, capitalizedValue)));
list.add(new WildcardQuery(new Term(propertyName, capitalizedValue + "*")));
}
public IndexHits<Node> findTaxaByPath(String wholeOrPartialPath) {
return taxonPaths.query("path:\"" + wholeOrPartialPath + "\"");
}
public IndexHits<Node> findTaxaByCommonName(String wholeOrPartialName) {
return taxonCommonNames.query("commonNames:\"" + wholeOrPartialName + "\"");
}
public IndexHits<Node> suggestTaxaByName(String wholeOrPartialScientificOrCommonName) {
return taxonNameSuggestions.query("name:\"" + wholeOrPartialScientificOrCommonName + "\"");
}
public List<Environment> getOrCreateEnvironments(Location location, String externalId, String name) throws NodeFactoryException {
List<org.eol.globi.domain.Term> terms;
try {
terms = envoLookupService.lookupTermByName(name);
if (terms.size() == 0) {
terms.add(new org.eol.globi.domain.Term(externalId, name));
}
} catch (TermLookupServiceException e) {
throw new NodeFactoryException("failed to lookup environment [" + name + "]");
}
List<Environment> normalizedEnvironments = new ArrayList<Environment>();
for (org.eol.globi.domain.Term term : terms) {
Environment environment = findEnvironment(term.getName());
if (environment == null) {
Transaction transaction = graphDb.beginTx();
environment = new Environment(graphDb.createNode(), term.getId(), term.getName());
environments.add(environment.getUnderlyingNode(), NamedNode.NAME, name);
transaction.success();
transaction.finish();
}
location.addEnvironment(environment);
normalizedEnvironments.add(environment);
}
return normalizedEnvironments;
}
public Environment findEnvironment(String name) {
String query = "name:\"" + name + "\"";
IndexHits<Node> matches = environments.query(query);
Node matchingEnvironment;
Environment firstMatchingEnvironment = null;
if (matches.hasNext()) {
matchingEnvironment = matches.next();
firstMatchingEnvironment = new Environment(matchingEnvironment);
}
matches.close();
return firstMatchingEnvironment;
}
public org.eol.globi.domain.Term getOrCreateBodyPart(String externalId, String name) throws NodeFactoryException {
return matchTerm(externalId, name);
}
public org.eol.globi.domain.Term getOrCreatePhysiologicalState(String externalId, String name) throws NodeFactoryException {
return matchTerm(externalId, name);
}
public org.eol.globi.domain.Term getOrCreateLifeStage(String externalId, String name) throws NodeFactoryException {
return matchTerm(externalId, name);
}
private org.eol.globi.domain.Term matchTerm(String externalId, String name) throws NodeFactoryException {
try {
List<org.eol.globi.domain.Term> terms = getTermLookupService().lookupTermByName(name);
return terms.size() == 0 ? NO_MATCH_TERM : terms.get(0);
} catch (TermLookupServiceException e) {
throw new NodeFactoryException("failed to lookup term [" + externalId + "]:[" + name + "]");
}
}
public TermLookupService getTermLookupService() {
return termLookupService;
}
public void setEnvoLookupService(TermLookupService envoLookupService) {
this.envoLookupService = envoLookupService;
}
public void setTermLookupService(TermLookupService termLookupService) {
this.termLookupService = termLookupService;
}
public void setDoiResolver(DOIResolver doiResolver) {
this.doiResolver = doiResolver;
}
public void setCorrectionService(CorrectionService correctionService) {
this.correctionService = correctionService;
}
}
diff --git a/eol-globi-data-tool/src/test/java/org/eol/globi/data/StudyImporterForHechingerTest.java b/eol-globi-data-tool/src/test/java/org/eol/globi/data/StudyImporterForHechingerTest.java
index 08f1d475..c3e96e9c 100644
--- a/eol-globi-data-tool/src/test/java/org/eol/globi/data/StudyImporterForHechingerTest.java
+++ b/eol-globi-data-tool/src/test/java/org/eol/globi/data/StudyImporterForHechingerTest.java
@@ -1,43 +1,43 @@
package org.eol.globi.data;
import org.eol.globi.domain.Study;
import org.junit.Test;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.Relationship;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.containsString;
public class StudyImporterForHechingerTest extends GraphDBTestCase{
@Test
public void importStudy() throws StudyImporterException {
StudyImporter importer = new StudyImporterForHechinger(new ParserFactoryImpl(), nodeFactory);
Study study = importer.importStudy();
assertThat(study, is(notNullValue()));
Iterable<Relationship> specimens = study.getSpecimens();
int count = 0;
for (Relationship specimen : specimens) {
count++;
}
ExecutionEngine engine = new ExecutionEngine(getGraphDb());
String query = "START resourceTaxon = node:taxons(name='Suaeda')" +
" MATCH taxon<-[:CLASSIFIED_AS]-specimen-[r]->resourceSpecimen-[:CLASSIFIED_AS]-resourceTaxon, specimen-[:COLLECTED_AT]->location" +
" RETURN taxon.name, specimen.lifeStage?, type(r), resourceTaxon.name, resourceSpecimen.lifeStage?, location.latitude as lat, location.longitude as lng";
System.out.println(query);
ExecutionResult result = engine.execute(query);
- assertThat(result.dumpToString(), containsString("Anas acuta"));
- assertThat(result.dumpToString(), containsString("Aythya affinis"));
+ assertThat(result.dumpToString(), containsString("Lesser Scaup"));
+ assertThat(result.dumpToString(), containsString("Northern Pintail"));
assertThat(result.dumpToString(), containsString("30.378207 | -115.938835 |"));
assertThat(count, is(13966));
}
}
| false | false | null | null |
diff --git a/src/com/tophyr/custompagerdemo/CoverFlow.java b/src/com/tophyr/custompagerdemo/CoverFlow.java
index 7cc7274..6aa6d31 100644
--- a/src/com/tophyr/custompagerdemo/CoverFlow.java
+++ b/src/com/tophyr/custompagerdemo/CoverFlow.java
@@ -1,382 +1,383 @@
package com.tophyr.custompagerdemo;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.Adapter;
public class CoverFlow extends ViewGroup {
private static enum TouchState {
NONE,
DOWN,
SCROLLING,
DRAGGING;
public float X;
}
private static final int NUM_VIEWS_ON_SIDE = 2;
private static final int NUM_VIEWS_OFFSCREEN = 1;
private static final double HORIZ_MARGIN_FRACTION = .1;
private Adapter m_Adapter;
private View[] m_Views;
private ArrayList<Queue<View>> m_RecycledViews;
private int m_CurrentPosition;
private boolean m_Selected;
private int m_ScrollOffset;
private TouchState m_TouchState;
private ValueAnimator m_Animator;
private final DataSetObserver m_AdapterObserver;
public CoverFlow(Context context) {
this(context, null);
}
public CoverFlow(Context context, AttributeSet attrs) {
super(context, attrs);
m_Views = new View[1 + 2 * NUM_VIEWS_ON_SIDE + 2 * NUM_VIEWS_OFFSCREEN];
m_AdapterObserver = new DataSetObserver() {
@Override
public void onChanged() {
}
@Override
public void onInvalidated() {
}
};
}
@Override
protected void finalize() {
if (m_Adapter != null)
m_Adapter.unregisterDataSetObserver(m_AdapterObserver);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// we want to be twice as wide as we are tall
int width, height;
switch (MeasureSpec.getMode(widthMeasureSpec)) {
case MeasureSpec.UNSPECIFIED:
width = Integer.MAX_VALUE;
break;
case MeasureSpec.AT_MOST:
// fallthrough!
case MeasureSpec.EXACTLY:
// fallthrough!
default:
width = MeasureSpec.getSize(widthMeasureSpec);
break;
}
switch (MeasureSpec.getMode(heightMeasureSpec)) {
case MeasureSpec.UNSPECIFIED:
height = width / 2;
break;
case MeasureSpec.AT_MOST:
// fallthrough!
case MeasureSpec.EXACTLY:
// fallthrough!
default:
if (MeasureSpec.getSize(heightMeasureSpec) < width / 2) {
height = MeasureSpec.getSize(heightMeasureSpec);
if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY)
width = height * 2;
} else {
height = width / 2;
}
break;
}
setMeasuredDimension(width, height);
final int numChildren = getChildCount();
final int sizeLimit = MeasureSpec.makeMeasureSpec((int)(height * .8), MeasureSpec.AT_MOST);
for (int i = 0; i < numChildren; i++) {
View v = getChildAt(i);
v.measure(sizeLimit, sizeLimit);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < NUM_VIEWS_ON_SIDE; i++) {
layoutView(i + NUM_VIEWS_OFFSCREEN);
layoutView(m_Views.length - (i + NUM_VIEWS_OFFSCREEN) - 1);
}
layoutView(NUM_VIEWS_OFFSCREEN + NUM_VIEWS_ON_SIDE);
}
private void layoutView(int viewIndex) {
View v = m_Views[viewIndex];
if (v == null)
return;
final int vWidth = v.getMeasuredWidth();
final int vHeight = v.getMeasuredHeight();
final int hMargin = (int)(getMeasuredWidth() * HORIZ_MARGIN_FRACTION);
final int availWidth = getMeasuredWidth() - 2 * hMargin;
final int totalHeight = getMeasuredHeight();
final double numVisibleViews = NUM_VIEWS_ON_SIDE + 1 + NUM_VIEWS_ON_SIDE;
double positionRatio = (viewIndex - NUM_VIEWS_OFFSCREEN) / (numVisibleViews - NUM_VIEWS_OFFSCREEN); // gives [0, 1] range
positionRatio = (positionRatio - .5) * 2; // transform to [-1, +1] range
positionRatio = Math.signum(positionRatio) * Math.sqrt(Math.abs(positionRatio)); // "stretch" position away from center
positionRatio = positionRatio / 2 + .5; // transform back to [0, 1] range
int hCenterOffset;
hCenterOffset = (int)(positionRatio * availWidth);
hCenterOffset += hMargin;
hCenterOffset -= m_ScrollOffset;
v.layout(hCenterOffset - vWidth / 2, (totalHeight - vHeight) / 2, hCenterOffset + vWidth / 2, (totalHeight + vHeight) / 2);
v.setRotationY(90f * (getMeasuredWidth() - hCenterOffset * 2) / getMeasuredWidth());
}
// @Override
// public View getSelectedView() {
// return m_Selected ? m_Views[NUM_VIEWS_OFFSCREEN + NUM_VIEWS_ON_SIDE] : null;
// }
//
// @Override
// public void setSelection(int position) {
// if (position != m_CurrentPosition)
// setPosition(position);
//
// m_Selected = true;
// }
//
// @Override
public void setAdapter(Adapter adapter) {
if (m_Adapter != null)
m_Adapter.unregisterDataSetObserver(m_AdapterObserver);
m_Adapter = adapter;
removeAllViewsInLayout();
m_CurrentPosition = -1;
if (m_Adapter == null) {
m_RecycledViews = null; // TODO: introducing possible NPE's! code was written expecing this to never be null.
m_Views = null; // TODO: possible NPE's !
return;
}
m_RecycledViews = new ArrayList<Queue<View>>(m_Adapter.getViewTypeCount());
for (int i = 0; i < m_Adapter.getViewTypeCount(); i++)
m_RecycledViews.add(new LinkedList<View>());
for (int i = 0; i < m_Views.length; i++)
m_Views[i] = null;
m_Adapter.registerDataSetObserver(m_AdapterObserver);
setPosition(0);
}
public Adapter getAdapter() {
return m_Adapter;
}
private int getAdapterIndex(int viewIndex) {
return m_CurrentPosition - NUM_VIEWS_ON_SIDE - NUM_VIEWS_OFFSCREEN + viewIndex;
}
private void recycleView(int viewIndex) {
View v = m_Views[viewIndex];
if (v != null) {
m_Views[viewIndex] = null;
removeView(v);
final int adapterPosition = getAdapterIndex(viewIndex);
if (adapterPosition >= 0 && adapterPosition < m_Adapter.getCount())
m_RecycledViews.get(m_Adapter.getItemViewType(adapterPosition)).add(v);
}
}
private void loadView(int viewIndex) {
final int position = getAdapterIndex(viewIndex);
if (position < 0 || position >= m_Adapter.getCount())
return;
Queue<View> recycleQueue = m_RecycledViews.get(m_Adapter.getItemViewType(position));
View recycled = recycleQueue.poll();
View newView = m_Adapter.getView(position, recycled, this);
if (recycled != null && recycled != newView)
recycleQueue.add(recycled);
m_Views[viewIndex] = newView;
}
private void shiftViews(int shift) {
if (Math.abs(shift) >= m_Views.length) {
// whole m_Views list is invalid
for (int i = 0; i < m_Views.length; i++) {
recycleView(i);
}
} else if (shift < 0) {
// we want to scroll left, so we need to move items right
for (int i = m_Views.length - 1; i >= 0; i--) {
if (i + shift >= m_Views.length)
recycleView(i);
m_Views[i] = (i + shift < 0) ? null : m_Views[i + shift];
}
} else {
// all other options exhausted, they must want to scroll right, so move items left
for (int i = 0; i < m_Views.length; i++) {
if (i + shift < 0)
recycleView(i);
m_Views[i] = (i + shift >= m_Views.length) ? null : m_Views[i + shift];
}
}
}
public void setPosition(int position) {
if (position < 0 || position >= m_Adapter.getCount())
throw new IndexOutOfBoundsException("Cannot set position beyond bounds of adapter.");
if (position == m_CurrentPosition)
return;
shiftViews(m_CurrentPosition == -1 ? Integer.MAX_VALUE : position - m_CurrentPosition);
m_Selected = false;
m_CurrentPosition = position;
for (int i = 0; i < m_Views.length; i++) {
if (m_Views[i] == null)
loadView(i);
if (m_Views[i] != null) {
if (i >= NUM_VIEWS_OFFSCREEN && i < m_Views.length - NUM_VIEWS_OFFSCREEN && m_Views[i].getParent() != this)
addView(m_Views[i]);
else if ((i < NUM_VIEWS_OFFSCREEN || i >= m_Views.length - NUM_VIEWS_OFFSCREEN) && m_Views[i].getParent() == this)
removeView(m_Views[i]);
}
}
for (int i = 0; i < NUM_VIEWS_ON_SIDE; i++) {
if (m_Views[i + NUM_VIEWS_OFFSCREEN] != null)
m_Views[i + NUM_VIEWS_OFFSCREEN].bringToFront();
if (m_Views[m_Views.length - (i + NUM_VIEWS_OFFSCREEN) - 1] != null)
m_Views[m_Views.length - (i + NUM_VIEWS_OFFSCREEN) - 1].bringToFront();
}
if (m_Views[NUM_VIEWS_OFFSCREEN + NUM_VIEWS_ON_SIDE] != null)
m_Views[NUM_VIEWS_OFFSCREEN + NUM_VIEWS_ON_SIDE].bringToFront();
requestLayout();
}
private void adjustScrollOffset(int delta) {
if (delta == 0)
return;
m_ScrollOffset += delta;
- double crossover = getMeasuredWidth() / (NUM_VIEWS_ON_SIDE + 1.0 + NUM_VIEWS_ON_SIDE);
+ double crossover = getMeasuredWidth() / (NUM_VIEWS_ON_SIDE + 1.0 + NUM_VIEWS_ON_SIDE - 2);
+ Log.d("CoverPagerDemo", "offset: " + m_ScrollOffset + " crossover: " + crossover);
if (Math.abs(m_ScrollOffset / crossover) >= 1) {
int newPosition = m_CurrentPosition + (int)(m_ScrollOffset / crossover);
if (newPosition >= m_Adapter.getCount()) {
newPosition = m_Adapter.getCount() - 1;
m_ScrollOffset = (int)(crossover - 1);
} else if (newPosition < 0) {
newPosition = 0;
m_ScrollOffset = (int)(1 - crossover);
}
setPosition(newPosition);
m_ScrollOffset %= crossover;
+ Log.d("CoverPagerDemo", "Crossing over. New offset: " + m_ScrollOffset);
}
requestLayout();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && m_CurrentPosition > 0) {
setPosition(m_CurrentPosition - 1);
return true;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && m_CurrentPosition < m_Views.length) {
setPosition(m_CurrentPosition + 1);
return true;
}
if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
adjustScrollOffset(1);
}
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
adjustScrollOffset(-1);
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
m_TouchState = TouchState.DOWN;
m_TouchState.X = event.getX();
if (m_Animator != null)
m_Animator.cancel();
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (m_TouchState == TouchState.DOWN) {
if (Math.abs(m_TouchState.X - event.getX()) >= ViewConfiguration.get(getContext()).getScaledTouchSlop()) {
m_TouchState = TouchState.SCROLLING;
m_TouchState.X = event.getX();
}
} else if (m_TouchState == TouchState.SCROLLING) {
float x = event.getX();
adjustScrollOffset((int)(m_TouchState.X - x));
m_TouchState.X = x;
}
else {
Log.d("CoverPagerDemo", "Uhh, got an ACTION_MOVE but wasn't in DOWN or SCROLLING.");
}
}
else if (event.getAction() == MotionEvent.ACTION_CANCEL ||
event.getAction() == MotionEvent.ACTION_UP) {
m_TouchState = TouchState.NONE;
if (m_Animator != null)
m_Animator.cancel();
m_Animator = ValueAnimator.ofInt(m_ScrollOffset, 0);
m_Animator.setInterpolator(new DecelerateInterpolator());
m_Animator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int delta = (Integer)animation.getAnimatedValue() - m_ScrollOffset;
- Log.d("CoverPagerDemo", "Interperlatin: " + delta);
adjustScrollOffset(delta);
}
});
m_Animator.start();
}
else
return super.onTouchEvent(event);
return true;
}
}
| false | false | null | null |
diff --git a/src/core/org/apache/hadoop/fs/FsShell.java b/src/core/org/apache/hadoop/fs/FsShell.java
index 2821d095e..77d67f5c5 100644
--- a/src/core/org/apache/hadoop/fs/FsShell.java
+++ b/src/core/org/apache/hadoop/fs/FsShell.java
@@ -1,1876 +1,1882 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.shell.CommandFormat;
import org.apache.hadoop.fs.shell.Count;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RemoteException;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.util.StringUtils;
/** Provide command line access to a FileSystem. */
public class FsShell extends Configured implements Tool {
protected FileSystem fs;
private Trash trash;
public static final SimpleDateFormat dateForm =
new SimpleDateFormat("yyyy-MM-dd HH:mm");
protected static final SimpleDateFormat modifFmt =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
static final int BORDER = 2;
static {
modifFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
}
static final String SETREP_SHORT_USAGE="-setrep [-R] [-w] <rep> <path/file>";
static final String GET_SHORT_USAGE = "-get [-ignoreCrc] [-crc] <src> <localdst>";
static final String COPYTOLOCAL_SHORT_USAGE = GET_SHORT_USAGE.replace(
"-get", "-copyToLocal");
static final String TAIL_USAGE="-tail [-f] <file>";
/**
*/
public FsShell() {
this(null);
}
public FsShell(Configuration conf) {
super(conf);
fs = null;
trash = null;
}
protected void init() throws IOException {
getConf().setQuietMode(true);
if (this.fs == null) {
this.fs = FileSystem.get(getConf());
}
if (this.trash == null) {
this.trash = new Trash(getConf());
}
}
/**
* Copies from stdin to the indicated file.
*/
private void copyFromStdin(Path dst, FileSystem dstFs) throws IOException {
if (dstFs.isDirectory(dst)) {
throw new IOException("When source is stdin, destination must be a file.");
}
if (dstFs.exists(dst)) {
throw new IOException("Target " + dst.toString() + " already exists.");
}
FSDataOutputStream out = dstFs.create(dst);
try {
IOUtils.copyBytes(System.in, out, getConf(), false);
}
finally {
out.close();
}
}
/**
* Print from src to stdout.
*/
private void printToStdout(InputStream in) throws IOException {
try {
IOUtils.copyBytes(in, System.out, getConf(), false);
} finally {
in.close();
}
}
/**
* Add local files to the indicated FileSystem name. src is kept.
*/
void copyFromLocal(Path[] srcs, String dstf) throws IOException {
Path dstPath = new Path(dstf);
FileSystem dstFs = dstPath.getFileSystem(getConf());
if (srcs.length == 1 && srcs[0].toString().equals("-"))
copyFromStdin(dstPath, dstFs);
else
dstFs.copyFromLocalFile(false, false, srcs, dstPath);
}
/**
* Add local files to the indicated FileSystem name. src is removed.
*/
void moveFromLocal(Path[] srcs, String dstf) throws IOException {
Path dstPath = new Path(dstf);
FileSystem dstFs = dstPath.getFileSystem(getConf());
dstFs.moveFromLocalFile(srcs, dstPath);
}
/**
* Add a local file to the indicated FileSystem name. src is removed.
*/
void moveFromLocal(Path src, String dstf) throws IOException {
moveFromLocal((new Path[]{src}), dstf);
}
/**
* Obtain the indicated files that match the file pattern <i>srcf</i>
* and copy them to the local name. srcf is kept.
* When copying multiple files, the destination must be a directory.
* Otherwise, IOException is thrown.
* @param argv: arguments
* @param pos: Ignore everything before argv[pos]
* @exception: IOException
* @see org.apache.hadoop.fs.FileSystem.globStatus
*/
void copyToLocal(String[]argv, int pos) throws IOException {
CommandFormat cf = new CommandFormat("copyToLocal", 2,2,"crc","ignoreCrc");
String srcstr = null;
String dststr = null;
try {
List<String> parameters = cf.parse(argv, pos);
srcstr = parameters.get(0);
dststr = parameters.get(1);
}
catch(IllegalArgumentException iae) {
System.err.println("Usage: java FsShell " + GET_SHORT_USAGE);
throw iae;
}
boolean copyCrc = cf.getOpt("crc");
final boolean verifyChecksum = !cf.getOpt("ignoreCrc");
if (dststr.equals("-")) {
if (copyCrc) {
System.err.println("-crc option is not valid when destination is stdout.");
}
cat(srcstr, verifyChecksum);
} else {
File dst = new File(dststr);
Path srcpath = new Path(srcstr);
FileSystem srcFS = getSrcFileSystem(srcpath, verifyChecksum);
if (copyCrc && !(srcFS instanceof ChecksumFileSystem)) {
System.err.println("-crc option is not valid when source file system " +
"does not have crc files. Automatically turn the option off.");
copyCrc = false;
}
FileStatus[] srcs = srcFS.globStatus(srcpath);
boolean dstIsDir = dst.isDirectory();
if (srcs.length > 1 && !dstIsDir) {
throw new IOException("When copying multiple files, "
+ "destination should be a directory.");
}
for (FileStatus status : srcs) {
Path p = status.getPath();
File f = dstIsDir? new File(dst, p.getName()): dst;
copyToLocal(srcFS, p, f, copyCrc);
}
}
}
/**
* Return the {@link FileSystem} specified by src and the conf.
* It the {@link FileSystem} supports checksum, set verifyChecksum.
*/
private FileSystem getSrcFileSystem(Path src, boolean verifyChecksum
) throws IOException {
FileSystem srcFs = src.getFileSystem(getConf());
srcFs.setVerifyChecksum(verifyChecksum);
return srcFs;
}
/**
* The prefix for the tmp file used in copyToLocal.
* It must be at least three characters long, required by
* {@link java.io.File#createTempFile(String, String, File)}.
*/
static final String COPYTOLOCAL_PREFIX = "_copyToLocal_";
/**
* Copy a source file from a given file system to local destination.
* @param srcFS source file system
* @param src source path
* @param dst destination
* @param copyCrc copy CRC files?
* @exception IOException If some IO failed
*/
private void copyToLocal(final FileSystem srcFS, final Path src,
final File dst, final boolean copyCrc)
throws IOException {
/* Keep the structure similar to ChecksumFileSystem.copyToLocal().
* Ideal these two should just invoke FileUtil.copy() and not repeat
* recursion here. Of course, copy() should support two more options :
* copyCrc and useTmpFile (may be useTmpFile need not be an option).
*/
if (!srcFS.getFileStatus(src).isDir()) {
if (dst.exists()) {
// match the error message in FileUtil.checkDest():
throw new IOException("Target " + dst + " already exists");
}
// use absolute name so that tmp file is always created under dest dir
File tmp = FileUtil.createLocalTempFile(dst.getAbsoluteFile(),
COPYTOLOCAL_PREFIX, true);
if (!FileUtil.copy(srcFS, src, tmp, false, srcFS.getConf())) {
throw new IOException("Failed to copy " + src + " to " + dst);
}
if (!tmp.renameTo(dst)) {
throw new IOException("Failed to rename tmp file " + tmp +
" to local destination \"" + dst + "\".");
}
if (copyCrc) {
if (!(srcFS instanceof ChecksumFileSystem)) {
throw new IOException("Source file system does not have crc files");
}
ChecksumFileSystem csfs = (ChecksumFileSystem) srcFS;
File dstcs = FileSystem.getLocal(srcFS.getConf())
.pathToFile(csfs.getChecksumFile(new Path(dst.getCanonicalPath())));
copyToLocal(csfs.getRawFileSystem(), csfs.getChecksumFile(src),
dstcs, false);
}
} else {
// once FileUtil.copy() supports tmp file, we don't need to mkdirs().
dst.mkdirs();
for(FileStatus path : srcFS.listStatus(src)) {
copyToLocal(srcFS, path.getPath(),
new File(dst, path.getPath().getName()), copyCrc);
}
}
}
/**
* Get all the files in the directories that match the source file
* pattern and merge and sort them to only one file on local fs
* srcf is kept.
* @param srcf: a file pattern specifying source files
* @param dstf: a destination local file/directory
* @exception: IOException
* @see org.apache.hadoop.fs.FileSystem.globStatus
*/
void copyMergeToLocal(String srcf, Path dst) throws IOException {
copyMergeToLocal(srcf, dst, false);
}
/**
* Get all the files in the directories that match the source file pattern
* and merge and sort them to only one file on local fs
* srcf is kept.
*
* Also adds a string between the files (useful for adding \n
* to a text file)
* @param srcf: a file pattern specifying source files
* @param dstf: a destination local file/directory
* @param endline: if an end of line character is added to a text file
* @exception: IOException
* @see org.apache.hadoop.fs.FileSystem.globStatus
*/
void copyMergeToLocal(String srcf, Path dst, boolean endline) throws IOException {
Path srcPath = new Path(srcf);
FileSystem srcFs = srcPath.getFileSystem(getConf());
Path [] srcs = FileUtil.stat2Paths(srcFs.globStatus(srcPath),
srcPath);
for(int i=0; i<srcs.length; i++) {
if (endline) {
FileUtil.copyMerge(srcFs, srcs[i],
FileSystem.getLocal(getConf()), dst, false, getConf(), "\n");
} else {
FileUtil.copyMerge(srcFs, srcs[i],
FileSystem.getLocal(getConf()), dst, false, getConf(), null);
}
}
}
/**
* Obtain the indicated file and copy to the local name.
* srcf is removed.
*/
void moveToLocal(String srcf, Path dst) throws IOException {
System.err.println("Option '-moveToLocal' is not implemented yet.");
}
/**
* Fetch all files that match the file pattern <i>srcf</i> and display
* their content on stdout.
* @param srcf: a file pattern specifying source files
* @exception: IOException
* @see org.apache.hadoop.fs.FileSystem.globStatus
*/
void cat(String src, boolean verifyChecksum) throws IOException {
//cat behavior in Linux
// [~/1207]$ ls ?.txt
// x.txt z.txt
// [~/1207]$ cat x.txt y.txt z.txt
// xxx
// cat: y.txt: No such file or directory
// zzz
Path srcPattern = new Path(src);
new DelayedExceptionThrowing() {
@Override
void process(Path p, FileSystem srcFs) throws IOException {
if (srcFs.getFileStatus(p).isDir()) {
throw new IOException("Source must be a file.");
}
printToStdout(srcFs.open(p));
}
}.globAndProcess(srcPattern, getSrcFileSystem(srcPattern, verifyChecksum));
}
private class TextRecordInputStream extends InputStream {
SequenceFile.Reader r;
WritableComparable key;
Writable val;
DataInputBuffer inbuf;
DataOutputBuffer outbuf;
public TextRecordInputStream(FileStatus f) throws IOException {
r = new SequenceFile.Reader(fs, f.getPath(), getConf());
key = ReflectionUtils.newInstance(r.getKeyClass().asSubclass(WritableComparable.class),
getConf());
val = ReflectionUtils.newInstance(r.getValueClass().asSubclass(Writable.class),
getConf());
inbuf = new DataInputBuffer();
outbuf = new DataOutputBuffer();
}
public int read() throws IOException {
int ret;
if (null == inbuf || -1 == (ret = inbuf.read())) {
if (!r.next(key, val)) {
return -1;
}
byte[] tmp = key.toString().getBytes();
outbuf.write(tmp, 0, tmp.length);
outbuf.write('\t');
tmp = val.toString().getBytes();
outbuf.write(tmp, 0, tmp.length);
outbuf.write('\n');
inbuf.reset(outbuf.getData(), outbuf.getLength());
outbuf.reset();
ret = inbuf.read();
}
return ret;
}
}
private InputStream forMagic(Path p, FileSystem srcFs) throws IOException {
FSDataInputStream i = srcFs.open(p);
switch(i.readShort()) {
case 0x1f8b: // RFC 1952
i.seek(0);
return new GZIPInputStream(i);
case 0x5345: // 'S' 'E'
if (i.readByte() == 'Q') {
i.close();
return new TextRecordInputStream(srcFs.getFileStatus(p));
}
break;
}
i.seek(0);
return i;
}
void text(String srcf) throws IOException {
Path srcPattern = new Path(srcf);
new DelayedExceptionThrowing() {
@Override
void process(Path p, FileSystem srcFs) throws IOException {
if (srcFs.isDirectory(p)) {
throw new IOException("Source must be a file.");
}
printToStdout(forMagic(p, srcFs));
}
}.globAndProcess(srcPattern, srcPattern.getFileSystem(getConf()));
}
/**
* Parse the incoming command string
* @param cmd
* @param pos ignore anything before this pos in cmd
* @throws IOException
*/
private void setReplication(String[] cmd, int pos) throws IOException {
CommandFormat c = new CommandFormat("setrep", 2, 2, "R", "w");
String dst = null;
short rep = 0;
try {
List<String> parameters = c.parse(cmd, pos);
rep = Short.parseShort(parameters.get(0));
dst = parameters.get(1);
} catch (NumberFormatException nfe) {
System.err.println("Illegal replication, a positive integer expected");
throw nfe;
}
catch(IllegalArgumentException iae) {
System.err.println("Usage: java FsShell " + SETREP_SHORT_USAGE);
throw iae;
}
if (rep < 1) {
System.err.println("Cannot set replication to: " + rep);
throw new IllegalArgumentException("replication must be >= 1");
}
List<Path> waitList = c.getOpt("w")? new ArrayList<Path>(): null;
setReplication(rep, dst, c.getOpt("R"), waitList);
if (waitList != null) {
waitForReplication(waitList, rep);
}
}
/**
* Wait for all files in waitList to have replication number equal to rep.
* @param waitList The files are waited for.
* @param rep The new replication number.
* @throws IOException IOException
*/
void waitForReplication(List<Path> waitList, int rep) throws IOException {
for(Path f : waitList) {
System.out.print("Waiting for " + f + " ...");
System.out.flush();
boolean printWarning = false;
FileStatus status = fs.getFileStatus(f);
long len = status.getLen();
for(boolean done = false; !done; ) {
BlockLocation[] locations = fs.getFileBlockLocations(status, 0, len);
int i = 0;
for(; i < locations.length &&
locations[i].getHosts().length == rep; i++)
if (!printWarning && locations[i].getHosts().length > rep) {
System.out.println("\nWARNING: the waiting time may be long for "
+ "DECREASING the number of replication.");
printWarning = true;
}
done = i == locations.length;
if (!done) {
System.out.print(".");
System.out.flush();
try {Thread.sleep(10000);} catch (InterruptedException e) {}
}
}
System.out.println(" done");
}
}
/**
* Set the replication for files that match file pattern <i>srcf</i>
* if it's a directory and recursive is true,
* set replication for all the subdirs and those files too.
* @param newRep new replication factor
* @param srcf a file pattern specifying source files
* @param recursive if need to set replication factor for files in subdirs
* @throws IOException
* @see org.apache.hadoop.fs.FileSystem#globStatus(Path)
*/
void setReplication(short newRep, String srcf, boolean recursive,
List<Path> waitingList)
throws IOException {
Path srcPath = new Path(srcf);
FileSystem srcFs = srcPath.getFileSystem(getConf());
Path[] srcs = FileUtil.stat2Paths(srcFs.globStatus(srcPath),
srcPath);
for(int i=0; i<srcs.length; i++) {
setReplication(newRep, srcFs, srcs[i], recursive, waitingList);
}
}
private void setReplication(short newRep, FileSystem srcFs,
Path src, boolean recursive,
List<Path> waitingList)
throws IOException {
if (!srcFs.getFileStatus(src).isDir()) {
setFileReplication(src, srcFs, newRep, waitingList);
return;
}
FileStatus items[] = srcFs.listStatus(src);
if (items == null) {
throw new IOException("Could not get listing for " + src);
} else {
for (int i = 0; i < items.length; i++) {
if (!items[i].isDir()) {
setFileReplication(items[i].getPath(), srcFs, newRep, waitingList);
} else if (recursive) {
setReplication(newRep, srcFs, items[i].getPath(), recursive,
waitingList);
}
}
}
}
/**
* Actually set the replication for this file
* If it fails either throw IOException or print an error msg
* @param file: a file/directory
* @param newRep: new replication factor
* @throws IOException
*/
private void setFileReplication(Path file, FileSystem srcFs, short newRep, List<Path> waitList)
throws IOException {
if (srcFs.setReplication(file, newRep)) {
if (waitList != null) {
waitList.add(file);
}
System.out.println("Replication " + newRep + " set: " + file);
} else {
System.err.println("Could not set replication for: " + file);
}
}
/**
* Get a listing of all files in that match the file pattern <i>srcf</i>.
* @param srcf a file pattern specifying source files
* @param recursive if need to list files in subdirs
* @throws IOException
* @see org.apache.hadoop.fs.FileSystem#globStatus(Path)
*/
private int ls(String srcf, boolean recursive) throws IOException {
Path srcPath = new Path(srcf);
FileSystem srcFs = srcPath.getFileSystem(this.getConf());
FileStatus[] srcs = srcFs.globStatus(srcPath);
if (srcs==null || srcs.length==0) {
throw new FileNotFoundException("Cannot access " + srcf +
": No such file or directory.");
}
boolean printHeader = (srcs.length == 1) ? true: false;
int numOfErrors = 0;
for(int i=0; i<srcs.length; i++) {
numOfErrors += ls(srcs[i], srcFs, recursive, printHeader);
}
return numOfErrors == 0 ? 0 : -1;
}
/* list all files under the directory <i>src</i>
* ideally we should provide "-l" option, that lists like "ls -l".
*/
private int ls(FileStatus src, FileSystem srcFs, boolean recursive,
boolean printHeader) throws IOException {
final String cmd = recursive? "lsr": "ls";
final FileStatus[] items = shellListStatus(cmd, srcFs, src);
if (items == null) {
return 1;
} else {
int numOfErrors = 0;
if (!recursive && printHeader) {
if (items.length != 0) {
System.out.println("Found " + items.length + " items");
}
}
int maxReplication = 3, maxLen = 10, maxOwner = 0,maxGroup = 0;
for(int i = 0; i < items.length; i++) {
FileStatus stat = items[i];
int replication = String.valueOf(stat.getReplication()).length();
int len = String.valueOf(stat.getLen()).length();
int owner = String.valueOf(stat.getOwner()).length();
int group = String.valueOf(stat.getGroup()).length();
if (replication > maxReplication) maxReplication = replication;
if (len > maxLen) maxLen = len;
if (owner > maxOwner) maxOwner = owner;
if (group > maxGroup) maxGroup = group;
}
for (int i = 0; i < items.length; i++) {
FileStatus stat = items[i];
Path cur = stat.getPath();
String mdate = dateForm.format(new Date(stat.getModificationTime()));
System.out.print((stat.isDir() ? "d" : "-") +
stat.getPermission() + " ");
System.out.printf("%"+ maxReplication +
"s ", (!stat.isDir() ? stat.getReplication() : "-"));
if (maxOwner > 0)
System.out.printf("%-"+ maxOwner + "s ", stat.getOwner());
if (maxGroup > 0)
System.out.printf("%-"+ maxGroup + "s ", stat.getGroup());
System.out.printf("%"+ maxLen + "d ", stat.getLen());
System.out.print(mdate + " ");
System.out.println(cur.toUri().getPath());
if (recursive && stat.isDir()) {
numOfErrors += ls(stat,srcFs, recursive, printHeader);
}
}
return numOfErrors;
}
}
/**
* Show the size of all files that match the file pattern <i>src</i>
* @param src a file pattern specifying source files
* @throws IOException
* @see org.apache.hadoop.fs.FileSystem#globStatus(Path)
*/
void du(String src) throws IOException {
Path srcPath = new Path(src);
FileSystem srcFs = srcPath.getFileSystem(getConf());
Path[] pathItems = FileUtil.stat2Paths(srcFs.globStatus(srcPath),
srcPath);
FileStatus items[] = srcFs.listStatus(pathItems);
if ((items == null) || ((items.length == 0) &&
(!srcFs.exists(srcPath)))){
throw new FileNotFoundException("Cannot access " + src
+ ": No such file or directory.");
} else {
System.out.println("Found " + items.length + " items");
int maxLength = 10;
long length[] = new long[items.length];
for (int i = 0; i < items.length; i++) {
length[i] = items[i].isDir() ?
srcFs.getContentSummary(items[i].getPath()).getLength() :
items[i].getLen();
int len = String.valueOf(length[i]).length();
if (len > maxLength) maxLength = len;
}
for(int i = 0; i < items.length; i++) {
System.out.printf("%-"+ (maxLength + BORDER) +"d", length[i]);
System.out.println(items[i].getPath());
}
}
}
/**
* Show the summary disk usage of each dir/file
* that matches the file pattern <i>src</i>
* @param src a file pattern specifying source files
* @throws IOException
* @see org.apache.hadoop.fs.FileSystem#globStatus(Path)
*/
void dus(String src) throws IOException {
Path srcPath = new Path(src);
FileSystem srcFs = srcPath.getFileSystem(getConf());
FileStatus status[] = srcFs.globStatus(new Path(src));
if (status==null || status.length==0) {
throw new FileNotFoundException("Cannot access " + src +
": No such file or directory.");
}
for(int i=0; i<status.length; i++) {
long totalSize = srcFs.getContentSummary(status[i].getPath()).getLength();
String pathStr = status[i].getPath().toString();
System.out.println(("".equals(pathStr)?".":pathStr) + "\t" + totalSize);
}
}
/**
* Create the given dir
*/
void mkdir(String src) throws IOException {
Path f = new Path(src);
FileSystem srcFs = f.getFileSystem(getConf());
FileStatus fstatus = null;
try {
fstatus = srcFs.getFileStatus(f);
if (fstatus.isDir()) {
throw new IOException("cannot create directory "
+ src + ": File exists");
}
else {
throw new IOException(src + " exists but " +
"is not a directory");
}
} catch(FileNotFoundException e) {
if (!srcFs.mkdirs(f)) {
throw new IOException("failed to create " + src);
}
}
}
/**
* (Re)create zero-length file at the specified path.
* This will be replaced by a more UNIX-like touch when files may be
* modified.
*/
void touchz(String src) throws IOException {
Path f = new Path(src);
FileSystem srcFs = f.getFileSystem(getConf());
FileStatus st;
if (srcFs.exists(f)) {
st = srcFs.getFileStatus(f);
if (st.isDir()) {
// TODO: handle this
throw new IOException(src + " is a directory");
} else if (st.getLen() != 0)
throw new IOException(src + " must be a zero-length file");
}
FSDataOutputStream out = srcFs.create(f);
out.close();
}
/**
* Check file types.
*/
int test(String argv[], int i) throws IOException {
if (!argv[i].startsWith("-") || argv[i].length() > 2)
throw new IOException("Not a flag: " + argv[i]);
char flag = argv[i].toCharArray()[1];
Path f = new Path(argv[++i]);
FileSystem srcFs = f.getFileSystem(getConf());
switch(flag) {
case 'e':
return srcFs.exists(f) ? 0 : 1;
case 'z':
return srcFs.getFileStatus(f).getLen() == 0 ? 0 : 1;
case 'd':
return srcFs.getFileStatus(f).isDir() ? 0 : 1;
default:
throw new IOException("Unknown flag: " + flag);
}
}
/**
* Print statistics about path in specified format.
* Format sequences:
* %b: Size of file in blocks
* %n: Filename
* %o: Block size
* %r: replication
* %y: UTC date as "yyyy-MM-dd HH:mm:ss"
* %Y: Milliseconds since January 1, 1970 UTC
*/
void stat(char[] fmt, String src) throws IOException {
Path srcPath = new Path(src);
FileSystem srcFs = srcPath.getFileSystem(getConf());
FileStatus glob[] = srcFs.globStatus(srcPath);
if (null == glob)
throw new IOException("cannot stat `" + src + "': No such file or directory");
for (FileStatus f : glob) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < fmt.length; ++i) {
if (fmt[i] != '%') {
buf.append(fmt[i]);
} else {
if (i + 1 == fmt.length) break;
switch(fmt[++i]) {
case 'b':
buf.append(f.getLen());
break;
case 'F':
buf.append(f.isDir() ? "directory" : "regular file");
break;
case 'n':
buf.append(f.getPath().getName());
break;
case 'o':
buf.append(f.getBlockSize());
break;
case 'r':
buf.append(f.getReplication());
break;
case 'y':
buf.append(modifFmt.format(new Date(f.getModificationTime())));
break;
case 'Y':
buf.append(f.getModificationTime());
break;
default:
buf.append(fmt[i]);
break;
}
}
}
System.out.println(buf.toString());
}
}
/**
* Move files that match the file pattern <i>srcf</i>
* to a destination file.
* When moving mutiple files, the destination must be a directory.
* Otherwise, IOException is thrown.
* @param srcf a file pattern specifying source files
* @param dstf a destination local file/directory
* @throws IOException
* @see org.apache.hadoop.fs.FileSystem#globStatus(Path)
*/
void rename(String srcf, String dstf) throws IOException {
Path srcPath = new Path(srcf);
Path dstPath = new Path(dstf);
FileSystem srcFs = srcPath.getFileSystem(getConf());
FileSystem dstFs = dstPath.getFileSystem(getConf());
URI srcURI = srcFs.getUri();
URI dstURI = dstFs.getUri();
if (srcURI.compareTo(dstURI) != 0) {
throw new IOException("src and destination filesystems do not match.");
}
Path[] srcs = FileUtil.stat2Paths(srcFs.globStatus(srcPath), srcPath);
Path dst = new Path(dstf);
if (srcs.length > 1 && !srcFs.isDirectory(dst)) {
throw new IOException("When moving multiple files, "
+ "destination should be a directory.");
}
for(int i=0; i<srcs.length; i++) {
if (!srcFs.rename(srcs[i], dst)) {
FileStatus srcFstatus = null;
FileStatus dstFstatus = null;
try {
srcFstatus = srcFs.getFileStatus(srcs[i]);
} catch(FileNotFoundException e) {
throw new FileNotFoundException(srcs[i] +
": No such file or directory");
}
try {
dstFstatus = dstFs.getFileStatus(dst);
} catch(IOException e) {
}
if((srcFstatus!= null) && (dstFstatus!= null)) {
if (srcFstatus.isDir() && !dstFstatus.isDir()) {
throw new IOException("cannot overwrite non directory "
+ dst + " with directory " + srcs[i]);
}
}
throw new IOException("Failed to rename " + srcs[i] + " to " + dst);
}
}
}
/**
* Move/rename file(s) to a destination file. Multiple source
* files can be specified. The destination is the last element of
* the argvp[] array.
* If multiple source files are specified, then the destination
* must be a directory. Otherwise, IOException is thrown.
* @exception: IOException
*/
private int rename(String argv[], Configuration conf) throws IOException {
int i = 0;
int exitCode = 0;
String cmd = argv[i++];
String dest = argv[argv.length-1];
//
// If the user has specified multiple source files, then
// the destination has to be a directory
//
if (argv.length > 3) {
Path dst = new Path(dest);
FileSystem dstFs = dst.getFileSystem(getConf());
if (!dstFs.isDirectory(dst)) {
throw new IOException("When moving multiple files, "
+ "destination " + dest + " should be a directory.");
}
}
//
// for each source file, issue the rename
//
for (; i < argv.length - 1; i++) {
try {
//
// issue the rename to the fs
//
rename(argv[i], dest);
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage.
//
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
System.err.println(cmd.substring(1) + ": " + content[0]);
} catch (Exception ex) {
System.err.println(cmd.substring(1) + ": " +
ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
System.err.println(cmd.substring(1) + ": " +
e.getLocalizedMessage());
}
}
return exitCode;
}
/**
* Copy files that match the file pattern <i>srcf</i>
* to a destination file.
* When copying mutiple files, the destination must be a directory.
* Otherwise, IOException is thrown.
* @param srcf a file pattern specifying source files
* @param dstf a destination local file/directory
* @throws IOException
* @see org.apache.hadoop.fs.FileSystem#globStatus(Path)
*/
void copy(String srcf, String dstf, Configuration conf) throws IOException {
Path srcPath = new Path(srcf);
FileSystem srcFs = srcPath.getFileSystem(getConf());
Path dstPath = new Path(dstf);
FileSystem dstFs = dstPath.getFileSystem(getConf());
Path [] srcs = FileUtil.stat2Paths(srcFs.globStatus(srcPath), srcPath);
if (srcs.length > 1 && !dstFs.isDirectory(dstPath)) {
throw new IOException("When copying multiple files, "
+ "destination should be a directory.");
}
for(int i=0; i<srcs.length; i++) {
FileUtil.copy(srcFs, srcs[i], dstFs, dstPath, false, conf);
}
}
/**
* Copy file(s) to a destination file. Multiple source
* files can be specified. The destination is the last element of
* the argvp[] array.
* If multiple source files are specified, then the destination
* must be a directory. Otherwise, IOException is thrown.
* @exception: IOException
*/
private int copy(String argv[], Configuration conf) throws IOException {
int i = 0;
int exitCode = 0;
String cmd = argv[i++];
String dest = argv[argv.length-1];
//
// If the user has specified multiple source files, then
// the destination has to be a directory
//
if (argv.length > 3) {
Path dst = new Path(dest);
if (!fs.isDirectory(dst)) {
throw new IOException("When copying multiple files, "
+ "destination " + dest + " should be a directory.");
}
}
//
// for each source file, issue the copy
//
for (; i < argv.length - 1; i++) {
try {
//
// issue the copy to the fs
//
copy(argv[i], dest, conf);
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage.
//
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
System.err.println(cmd.substring(1) + ": " +
content[0]);
} catch (Exception ex) {
System.err.println(cmd.substring(1) + ": " +
ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
System.err.println(cmd.substring(1) + ": " +
e.getLocalizedMessage());
}
}
return exitCode;
}
/**
* Delete all files that match the file pattern <i>srcf</i>.
* @param srcf a file pattern specifying source files
* @param recursive if need to delete subdirs
* @throws IOException
* @see org.apache.hadoop.fs.FileSystem#globStatus(Path)
*/
void delete(String srcf, final boolean recursive) throws IOException {
//rm behavior in Linux
// [~/1207]$ ls ?.txt
// x.txt z.txt
// [~/1207]$ rm x.txt y.txt z.txt
// rm: cannot remove `y.txt': No such file or directory
Path srcPattern = new Path(srcf);
new DelayedExceptionThrowing() {
@Override
void process(Path p, FileSystem srcFs) throws IOException {
delete(p, srcFs, recursive);
}
}.globAndProcess(srcPattern, srcPattern.getFileSystem(getConf()));
}
/* delete a file */
private void delete(Path src, FileSystem srcFs, boolean recursive) throws IOException {
if (srcFs.isDirectory(src) && !recursive) {
throw new IOException("Cannot remove directory \"" + src +
"\", use -rmr instead");
}
Trash trashTmp = new Trash(srcFs, getConf());
if (trashTmp.moveToTrash(src)) {
System.out.println("Moved to trash: " + src);
return;
}
if (srcFs.delete(src, true)) {
System.out.println("Deleted " + src);
} else {
if (!srcFs.exists(src)) {
throw new FileNotFoundException("cannot remove "
+ src + ": No such file or directory.");
}
throw new IOException("Delete failed " + src);
}
}
private void expunge() throws IOException {
trash.expunge();
trash.checkpoint();
}
/**
* Returns the Trash object associated with this shell.
*/
public Path getCurrentTrashDir() {
return trash.getCurrentTrashDir();
}
/**
* Parse the incoming command string
* @param cmd
* @param pos ignore anything before this pos in cmd
* @throws IOException
*/
private void tail(String[] cmd, int pos) throws IOException {
CommandFormat c = new CommandFormat("tail", 1, 1, "f");
String src = null;
Path path = null;
try {
List<String> parameters = c.parse(cmd, pos);
src = parameters.get(0);
} catch(IllegalArgumentException iae) {
System.err.println("Usage: java FsShell " + TAIL_USAGE);
throw iae;
}
boolean foption = c.getOpt("f") ? true: false;
path = new Path(src);
FileSystem srcFs = path.getFileSystem(getConf());
if (srcFs.isDirectory(path)) {
throw new IOException("Source must be a file.");
}
long fileSize = srcFs.getFileStatus(path).getLen();
long offset = (fileSize > 1024) ? fileSize - 1024: 0;
while (true) {
FSDataInputStream in = srcFs.open(path);
in.seek(offset);
IOUtils.copyBytes(in, System.out, 1024, false);
offset = in.getPos();
in.close();
if (!foption) {
break;
}
fileSize = srcFs.getFileStatus(path).getLen();
offset = (fileSize > offset) ? offset: fileSize;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
break;
}
}
}
/**
* This class runs a command on a given FileStatus. This can be used for
* running various commands like chmod, chown etc.
*/
static abstract class CmdHandler {
protected int errorCode = 0;
protected boolean okToContinue = true;
protected String cmdName;
int getErrorCode() { return errorCode; }
boolean okToContinue() { return okToContinue; }
String getName() { return cmdName; }
protected CmdHandler(String cmdName, FileSystem fs) {
this.cmdName = cmdName;
}
public abstract void run(FileStatus file, FileSystem fs) throws IOException;
}
/** helper returns listStatus() */
private static FileStatus[] shellListStatus(String cmd,
FileSystem srcFs,
FileStatus src) {
if (!src.isDir()) {
FileStatus[] files = { src };
return files;
}
Path path = src.getPath();
try {
FileStatus[] files = srcFs.listStatus(path);
if ( files == null ) {
System.err.println(cmd +
": could not get listing for '" + path + "'");
}
return files;
} catch (IOException e) {
System.err.println(cmd +
": could not get get listing for '" + path + "' : " +
e.getMessage().split("\n")[0]);
}
return null;
}
/**
* Runs the command on a given file with the command handler.
* If recursive is set, command is run recursively.
*/
private static int runCmdHandler(CmdHandler handler, FileStatus stat,
FileSystem srcFs,
boolean recursive) throws IOException {
int errors = 0;
handler.run(stat, srcFs);
if (recursive && stat.isDir() && handler.okToContinue()) {
FileStatus[] files = shellListStatus(handler.getName(), srcFs, stat);
if (files == null) {
return 1;
}
for(FileStatus file : files ) {
errors += runCmdHandler(handler, file, srcFs, recursive);
}
}
return errors;
}
///top level runCmdHandler
int runCmdHandler(CmdHandler handler, String[] args,
int startIndex, boolean recursive)
throws IOException {
int errors = 0;
for (int i=startIndex; i<args.length; i++) {
Path srcPath = new Path(args[i]);
FileSystem srcFs = srcPath.getFileSystem(getConf());
Path[] paths = FileUtil.stat2Paths(srcFs.globStatus(srcPath), srcPath);
for(Path path : paths) {
try {
FileStatus file = srcFs.getFileStatus(path);
if (file == null) {
System.err.println(handler.getName() +
": could not get status for '" + path + "'");
errors++;
} else {
errors += runCmdHandler(handler, file, srcFs, recursive);
}
} catch (IOException e) {
String msg = (e.getMessage() != null ? e.getLocalizedMessage() :
(e.getCause().getMessage() != null ?
e.getCause().getLocalizedMessage() : "null"));
System.err.println(handler.getName() + ": could not get status for '"
+ path + "': " + msg.split("\n")[0]);
}
}
}
return (errors > 0 || handler.getErrorCode() != 0) ? 1 : 0;
}
/**
* Return an abbreviated English-language desc of the byte length
* @deprecated Consider using {@link org.apache.hadoop.util.StringUtils#byteDesc} instead.
*/
@Deprecated
public static String byteDesc(long len) {
return StringUtils.byteDesc(len);
}
/**
* @deprecated Consider using {@link org.apache.hadoop.util.StringUtils#limitDecimalTo2} instead.
*/
@Deprecated
public static synchronized String limitDecimalTo2(double d) {
return StringUtils.limitDecimalTo2(d);
}
private void printHelp(String cmd) {
String summary = "hadoop fs is the command to execute fs commands. " +
"The full syntax is: \n\n" +
"hadoop fs [-fs <local | file system URI>] [-conf <configuration file>]\n\t" +
"[-D <property=value>] [-ls <path>] [-lsr <path>] [-du <path>]\n\t" +
"[-dus <path>] [-mv <src> <dst>] [-cp <src> <dst>] [-rm <src>]\n\t" +
"[-rmr <src>] [-put <localsrc> ... <dst>] [-copyFromLocal <localsrc> ... <dst>]\n\t" +
"[-moveFromLocal <localsrc> ... <dst>] [" +
GET_SHORT_USAGE + "\n\t" +
"[-getmerge <src> <localdst> [addnl]] [-cat <src>]\n\t" +
"[" + COPYTOLOCAL_SHORT_USAGE + "] [-moveToLocal <src> <localdst>]\n\t" +
"[-mkdir <path>] [-report] [" + SETREP_SHORT_USAGE + "]\n\t" +
"[-touchz <path>] [-test -[ezd] <path>] [-stat [format] <path>]\n\t" +
"[-tail [-f] <path>] [-text <path>]\n\t" +
"[" + FsShellPermissions.CHMOD_USAGE + "]\n\t" +
"[" + FsShellPermissions.CHOWN_USAGE + "]\n\t" +
"[" + FsShellPermissions.CHGRP_USAGE + "]\n\t" +
"[" + Count.USAGE + "]\n\t" +
"[-help [cmd]]\n";
String conf ="-conf <configuration file>: Specify an application configuration file.";
String D = "-D <property=value>: Use value for given property.";
String fs = "-fs [local | <file system URI>]: \tSpecify the file system to use.\n" +
"\t\tIf not specified, the current configuration is used, \n" +
"\t\ttaken from the following, in increasing precedence: \n" +
"\t\t\tcore-default.xml inside the hadoop jar file \n" +
"\t\t\tcore-site.xml in $HADOOP_CONF_DIR \n" +
"\t\t'local' means use the local file system as your DFS. \n" +
"\t\t<file system URI> specifies a particular file system to \n" +
"\t\tcontact. This argument is optional but if used must appear\n" +
"\t\tappear first on the command line. Exactly one additional\n" +
"\t\targument must be specified. \n";
String ls = "-ls <path>: \tList the contents that match the specified file pattern. If\n" +
"\t\tpath is not specified, the contents of /user/<currentUser>\n" +
"\t\twill be listed. Directory entries are of the form \n" +
"\t\t\tdirName (full path) <dir> \n" +
"\t\tand file entries are of the form \n" +
"\t\t\tfileName(full path) <r n> size \n" +
"\t\twhere n is the number of replicas specified for the file \n" +
"\t\tand size is the size of the file, in bytes.\n";
String lsr = "-lsr <path>: \tRecursively list the contents that match the specified\n" +
"\t\tfile pattern. Behaves very similarly to hadoop fs -ls,\n" +
"\t\texcept that the data is shown for all the entries in the\n" +
"\t\tsubtree.\n";
String du = "-du <path>: \tShow the amount of space, in bytes, used by the files that \n" +
"\t\tmatch the specified file pattern. Equivalent to the unix\n" +
"\t\tcommand \"du -sb <path>/*\" in case of a directory, \n" +
"\t\tand to \"du -b <path>\" in case of a file.\n" +
"\t\tThe output is in the form \n" +
"\t\t\tname(full path) size (in bytes)\n";
String dus = "-dus <path>: \tShow the amount of space, in bytes, used by the files that \n" +
"\t\tmatch the specified file pattern. Equivalent to the unix\n" +
"\t\tcommand \"du -sb\" The output is in the form \n" +
"\t\t\tname(full path) size (in bytes)\n";
String mv = "-mv <src> <dst>: Move files that match the specified file pattern <src>\n" +
"\t\tto a destination <dst>. When moving multiple files, the \n" +
"\t\tdestination must be a directory. \n";
String cp = "-cp <src> <dst>: Copy files that match the file pattern <src> to a \n" +
"\t\tdestination. When copying multiple files, the destination\n" +
"\t\tmust be a directory. \n";
String rm = "-rm <src>: \tDelete all files that match the specified file pattern.\n" +
"\t\tEquivlent to the Unix command \"rm <src>\"\n";
String rmr = "-rmr <src>: \tRemove all directories which match the specified file \n" +
"\t\tpattern. Equivlent to the Unix command \"rm -rf <src>\"\n";
String put = "-put <localsrc> ... <dst>: \tCopy files " +
"from the local file system \n\t\tinto fs. \n";
String copyFromLocal = "-copyFromLocal <localsrc> ... <dst>:" +
" Identical to the -put command.\n";
String moveFromLocal = "-moveFromLocal <localsrc> ... <dst>:" +
" Same as -put, except that the source is\n\t\tdeleted after it's copied.\n";
String get = GET_SHORT_USAGE
+ ": Copy files that match the file pattern <src> \n" +
"\t\tto the local name. <src> is kept. When copying mutiple, \n" +
"\t\tfiles, the destination must be a directory. \n";
String getmerge = "-getmerge <src> <localdst>: Get all the files in the directories that \n" +
"\t\tmatch the source file pattern and merge and sort them to only\n" +
"\t\tone file on local fs. <src> is kept.\n";
String cat = "-cat <src>: \tFetch all files that match the file pattern <src> \n" +
"\t\tand display their content on stdout.\n";
- /*
- String text = "-text <path>: Attempt to decode contents if the first few bytes\n" +
- "\t\tmatch a magic number associated with a known format\n" +
- "\t\t(gzip, SequenceFile)\n";
- */
-
+
+ String text = "-text <src>: \tTakes a source file and outputs the file in text format.\n" +
+ "\t\tThe allowed formats are zip and TextRecordInputStream.\n";
+
+
String copyToLocal = COPYTOLOCAL_SHORT_USAGE
+ ": Identical to the -get command.\n";
String moveToLocal = "-moveToLocal <src> <localdst>: Not implemented yet \n";
String mkdir = "-mkdir <path>: \tCreate a directory in specified location. \n";
String setrep = SETREP_SHORT_USAGE
+ ": Set the replication level of a file. \n"
+ "\t\tThe -R flag requests a recursive change of replication level \n"
+ "\t\tfor an entire tree.\n";
String touchz = "-touchz <path>: Write a timestamp in yyyy-MM-dd HH:mm:ss format\n" +
"\t\tin a file at <path>. An error is returned if the file exists with non-zero length\n";
String test = "-test -[ezd] <path>: If file { exists, has zero length, is a directory\n" +
"\t\tthen return 0, else return 1.\n";
String stat = "-stat [format] <path>: Print statistics about the file/directory at <path>\n" +
"\t\tin the specified format. Format accepts filesize in blocks (%b), filename (%n),\n" +
"\t\tblock size (%o), replication (%r), modification date (%y, %Y)\n";
String tail = TAIL_USAGE
+ ": Show the last 1KB of the file. \n"
+ "\t\tThe -f option shows apended data as the file grows. \n";
String chmod = FsShellPermissions.CHMOD_USAGE + "\n" +
"\t\tChanges permissions of a file.\n" +
"\t\tThis works similar to shell's chmod with a few exceptions.\n\n" +
"\t-R\tmodifies the files recursively. This is the only option\n" +
"\t\tcurrently supported.\n\n" +
"\tMODE\tMode is same as mode used for chmod shell command.\n" +
"\t\tOnly letters recognized are 'rwxX'. E.g. a+r,g-w,+rwx,o=r\n\n" +
"\tOCTALMODE Mode specifed in 3 digits. Unlike shell command,\n" +
"\t\tthis requires all three digits.\n" +
"\t\tE.g. 754 is same as u=rwx,g=rx,o=r\n\n" +
"\t\tIf none of 'augo' is specified, 'a' is assumed and unlike\n" +
"\t\tshell command, no umask is applied.\n";
String chown = FsShellPermissions.CHOWN_USAGE + "\n" +
"\t\tChanges owner and group of a file.\n" +
"\t\tThis is similar to shell's chown with a few exceptions.\n\n" +
"\t-R\tmodifies the files recursively. This is the only option\n" +
"\t\tcurrently supported.\n\n" +
"\t\tIf only owner or group is specified then only owner or\n" +
"\t\tgroup is modified.\n\n" +
"\t\tThe owner and group names may only cosists of digits, alphabet,\n"+
"\t\tand any of '-_.@/' i.e. [-_.@/a-zA-Z0-9]. The names are case\n" +
"\t\tsensitive.\n\n" +
"\t\tWARNING: Avoid using '.' to separate user name and group though\n" +
"\t\tLinux allows it. If user names have dots in them and you are\n" +
"\t\tusing local file system, you might see surprising results since\n" +
"\t\tshell command 'chown' is used for local files.\n";
String chgrp = FsShellPermissions.CHGRP_USAGE + "\n" +
"\t\tThis is equivalent to -chown ... :GROUP ...\n";
String help = "-help [cmd]: \tDisplays help for given command or all commands if none\n" +
"\t\tis specified.\n";
if ("fs".equals(cmd)) {
System.out.println(fs);
} else if ("conf".equals(cmd)) {
System.out.println(conf);
} else if ("D".equals(cmd)) {
System.out.println(D);
} else if ("ls".equals(cmd)) {
System.out.println(ls);
} else if ("lsr".equals(cmd)) {
System.out.println(lsr);
} else if ("du".equals(cmd)) {
System.out.println(du);
} else if ("dus".equals(cmd)) {
System.out.println(dus);
} else if ("rm".equals(cmd)) {
System.out.println(rm);
} else if ("rmr".equals(cmd)) {
System.out.println(rmr);
} else if ("mkdir".equals(cmd)) {
System.out.println(mkdir);
} else if ("mv".equals(cmd)) {
System.out.println(mv);
} else if ("cp".equals(cmd)) {
System.out.println(cp);
} else if ("put".equals(cmd)) {
System.out.println(put);
} else if ("copyFromLocal".equals(cmd)) {
System.out.println(copyFromLocal);
} else if ("moveFromLocal".equals(cmd)) {
System.out.println(moveFromLocal);
} else if ("get".equals(cmd)) {
System.out.println(get);
} else if ("getmerge".equals(cmd)) {
System.out.println(getmerge);
} else if ("copyToLocal".equals(cmd)) {
System.out.println(copyToLocal);
} else if ("moveToLocal".equals(cmd)) {
System.out.println(moveToLocal);
} else if ("cat".equals(cmd)) {
System.out.println(cat);
} else if ("get".equals(cmd)) {
System.out.println(get);
} else if ("setrep".equals(cmd)) {
System.out.println(setrep);
} else if ("touchz".equals(cmd)) {
System.out.println(touchz);
} else if ("test".equals(cmd)) {
System.out.println(test);
+ } else if ("text".equals(cmd)) {
+ System.out.println(text);
} else if ("stat".equals(cmd)) {
System.out.println(stat);
} else if ("tail".equals(cmd)) {
System.out.println(tail);
} else if ("chmod".equals(cmd)) {
System.out.println(chmod);
} else if ("chown".equals(cmd)) {
System.out.println(chown);
} else if ("chgrp".equals(cmd)) {
System.out.println(chgrp);
} else if (Count.matches(cmd)) {
System.out.println(Count.DESCRIPTION);
} else if ("help".equals(cmd)) {
System.out.println(help);
} else {
System.out.println(summary);
System.out.println(fs);
System.out.println(ls);
System.out.println(lsr);
System.out.println(du);
System.out.println(dus);
System.out.println(mv);
System.out.println(cp);
System.out.println(rm);
System.out.println(rmr);
System.out.println(put);
System.out.println(copyFromLocal);
System.out.println(moveFromLocal);
System.out.println(get);
System.out.println(getmerge);
System.out.println(cat);
System.out.println(copyToLocal);
System.out.println(moveToLocal);
System.out.println(mkdir);
System.out.println(setrep);
+ System.out.println(tail);
+ System.out.println(touchz);
+ System.out.println(test);
+ System.out.println(text);
+ System.out.println(stat);
System.out.println(chmod);
System.out.println(chown);
System.out.println(chgrp);
System.out.println(Count.DESCRIPTION);
System.out.println(help);
}
}
/**
* Apply operation specified by 'cmd' on all parameters
* starting from argv[startindex].
*/
private int doall(String cmd, String argv[], int startindex) {
int exitCode = 0;
int i = startindex;
//
// for each source file, issue the command
//
for (; i < argv.length; i++) {
try {
//
// issue the command to the fs
//
if ("-cat".equals(cmd)) {
cat(argv[i], true);
} else if ("-mkdir".equals(cmd)) {
mkdir(argv[i]);
} else if ("-rm".equals(cmd)) {
delete(argv[i], false);
} else if ("-rmr".equals(cmd)) {
delete(argv[i], true);
} else if ("-du".equals(cmd)) {
du(argv[i]);
} else if ("-dus".equals(cmd)) {
dus(argv[i]);
} else if (Count.matches(cmd)) {
new Count(argv, i, getConf()).runAll();
} else if ("-ls".equals(cmd)) {
exitCode = ls(argv[i], false);
} else if ("-lsr".equals(cmd)) {
exitCode = ls(argv[i], true);
} else if ("-touchz".equals(cmd)) {
touchz(argv[i]);
} else if ("-text".equals(cmd)) {
text(argv[i]);
}
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error message.
//
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
System.err.println(cmd.substring(1) + ": " +
content[0]);
} catch (Exception ex) {
System.err.println(cmd.substring(1) + ": " +
ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
String content = e.getLocalizedMessage();
if (content != null) {
content = content.split("\n")[0];
}
System.err.println(cmd.substring(1) + ": " +
content);
}
}
return exitCode;
}
/**
* Displays format of commands.
*
*/
private static void printUsage(String cmd) {
String prefix = "Usage: java " + FsShell.class.getSimpleName();
if ("-fs".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [-fs <local | file system URI>]");
} else if ("-conf".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [-conf <configuration file>]");
} else if ("-D".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [-D <[property=value>]");
} else if ("-ls".equals(cmd) || "-lsr".equals(cmd) ||
"-du".equals(cmd) || "-dus".equals(cmd) ||
"-rm".equals(cmd) || "-rmr".equals(cmd) ||
"-touchz".equals(cmd) || "-mkdir".equals(cmd) ||
"-text".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [" + cmd + " <path>]");
} else if (Count.matches(cmd)) {
System.err.println(prefix + " [" + Count.USAGE + "]");
} else if ("-mv".equals(cmd) || "-cp".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [" + cmd + " <src> <dst>]");
} else if ("-put".equals(cmd) || "-copyFromLocal".equals(cmd) ||
"-moveFromLocal".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [" + cmd + " <localsrc> ... <dst>]");
} else if ("-get".equals(cmd)) {
System.err.println("Usage: java FsShell [" + GET_SHORT_USAGE + "]");
} else if ("-copyToLocal".equals(cmd)) {
System.err.println("Usage: java FsShell [" + COPYTOLOCAL_SHORT_USAGE+ "]");
} else if ("-moveToLocal".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [" + cmd + " [-crc] <src> <localdst>]");
} else if ("-cat".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [" + cmd + " <src>]");
} else if ("-setrep".equals(cmd)) {
System.err.println("Usage: java FsShell [" + SETREP_SHORT_USAGE + "]");
} else if ("-test".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [-test -[ezd] <path>]");
} else if ("-stat".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [-stat [format] <path>]");
} else if ("-tail".equals(cmd)) {
System.err.println("Usage: java FsShell [" + TAIL_USAGE + "]");
} else {
System.err.println("Usage: java FsShell");
System.err.println(" [-ls <path>]");
System.err.println(" [-lsr <path>]");
System.err.println(" [-du <path>]");
System.err.println(" [-dus <path>]");
System.err.println(" [" + Count.USAGE + "]");
System.err.println(" [-mv <src> <dst>]");
System.err.println(" [-cp <src> <dst>]");
System.err.println(" [-rm <path>]");
System.err.println(" [-rmr <path>]");
System.err.println(" [-expunge]");
System.err.println(" [-put <localsrc> ... <dst>]");
System.err.println(" [-copyFromLocal <localsrc> ... <dst>]");
System.err.println(" [-moveFromLocal <localsrc> ... <dst>]");
System.err.println(" [" + GET_SHORT_USAGE + "]");
System.err.println(" [-getmerge <src> <localdst> [addnl]]");
System.err.println(" [-cat <src>]");
System.err.println(" [-text <src>]");
System.err.println(" [" + COPYTOLOCAL_SHORT_USAGE + "]");
System.err.println(" [-moveToLocal [-crc] <src> <localdst>]");
System.err.println(" [-mkdir <path>]");
System.err.println(" [" + SETREP_SHORT_USAGE + "]");
System.err.println(" [-touchz <path>]");
System.err.println(" [-test -[ezd] <path>]");
System.err.println(" [-stat [format] <path>]");
System.err.println(" [" + TAIL_USAGE + "]");
System.err.println(" [" + FsShellPermissions.CHMOD_USAGE + "]");
System.err.println(" [" + FsShellPermissions.CHOWN_USAGE + "]");
System.err.println(" [" + FsShellPermissions.CHGRP_USAGE + "]");
System.err.println(" [-help [cmd]]");
System.err.println();
ToolRunner.printGenericCommandUsage(System.err);
}
}
/**
* run
*/
public int run(String argv[]) throws Exception {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-put".equals(cmd) || "-test".equals(cmd) ||
"-copyFromLocal".equals(cmd) || "-moveFromLocal".equals(cmd)) {
if (argv.length < 3) {
printUsage(cmd);
return exitCode;
}
} else if ("-get".equals(cmd) ||
"-copyToLocal".equals(cmd) || "-moveToLocal".equals(cmd)) {
if (argv.length < 3) {
printUsage(cmd);
return exitCode;
}
} else if ("-mv".equals(cmd) || "-cp".equals(cmd)) {
if (argv.length < 3) {
printUsage(cmd);
return exitCode;
}
} else if ("-rm".equals(cmd) || "-rmr".equals(cmd) ||
"-cat".equals(cmd) || "-mkdir".equals(cmd) ||
"-touchz".equals(cmd) || "-stat".equals(cmd) ||
"-text".equals(cmd)) {
if (argv.length < 2) {
printUsage(cmd);
return exitCode;
}
}
// initialize FsShell
try {
init();
} catch (RPC.VersionMismatch v) {
System.err.println("Version Mismatch between client and server" +
"... command aborted.");
return exitCode;
} catch (IOException e) {
System.err.println("Bad connection to FS. command aborted.");
return exitCode;
}
exitCode = 0;
try {
if ("-put".equals(cmd) || "-copyFromLocal".equals(cmd)) {
Path[] srcs = new Path[argv.length-2];
for (int j=0 ; i < argv.length-1 ;)
srcs[j++] = new Path(argv[i++]);
copyFromLocal(srcs, argv[i++]);
} else if ("-moveFromLocal".equals(cmd)) {
Path[] srcs = new Path[argv.length-2];
for (int j=0 ; i < argv.length-1 ;)
srcs[j++] = new Path(argv[i++]);
moveFromLocal(srcs, argv[i++]);
} else if ("-get".equals(cmd) || "-copyToLocal".equals(cmd)) {
copyToLocal(argv, i);
} else if ("-getmerge".equals(cmd)) {
if (argv.length>i+2)
copyMergeToLocal(argv[i++], new Path(argv[i++]), Boolean.parseBoolean(argv[i++]));
else
copyMergeToLocal(argv[i++], new Path(argv[i++]));
} else if ("-cat".equals(cmd)) {
exitCode = doall(cmd, argv, i);
} else if ("-text".equals(cmd)) {
exitCode = doall(cmd, argv, i);
} else if ("-moveToLocal".equals(cmd)) {
moveToLocal(argv[i++], new Path(argv[i++]));
} else if ("-setrep".equals(cmd)) {
setReplication(argv, i);
} else if ("-chmod".equals(cmd) ||
"-chown".equals(cmd) ||
"-chgrp".equals(cmd)) {
FsShellPermissions.changePermissions(fs, cmd, argv, i, this);
} else if ("-ls".equals(cmd)) {
if (i < argv.length) {
exitCode = doall(cmd, argv, i);
} else {
exitCode = ls(Path.CUR_DIR, false);
}
} else if ("-lsr".equals(cmd)) {
if (i < argv.length) {
exitCode = doall(cmd, argv, i);
} else {
exitCode = ls(Path.CUR_DIR, true);
}
} else if ("-mv".equals(cmd)) {
exitCode = rename(argv, getConf());
} else if ("-cp".equals(cmd)) {
exitCode = copy(argv, getConf());
} else if ("-rm".equals(cmd)) {
exitCode = doall(cmd, argv, i);
} else if ("-rmr".equals(cmd)) {
exitCode = doall(cmd, argv, i);
} else if ("-expunge".equals(cmd)) {
expunge();
} else if ("-du".equals(cmd)) {
if (i < argv.length) {
exitCode = doall(cmd, argv, i);
} else {
du(".");
}
} else if ("-dus".equals(cmd)) {
if (i < argv.length) {
exitCode = doall(cmd, argv, i);
} else {
dus(".");
}
} else if (Count.matches(cmd)) {
exitCode = new Count(argv, i, getConf()).runAll();
} else if ("-mkdir".equals(cmd)) {
exitCode = doall(cmd, argv, i);
} else if ("-touchz".equals(cmd)) {
exitCode = doall(cmd, argv, i);
} else if ("-test".equals(cmd)) {
exitCode = test(argv, i);
} else if ("-stat".equals(cmd)) {
if (i + 1 < argv.length) {
stat(argv[i++].toCharArray(), argv[i++]);
} else {
stat("%y".toCharArray(), argv[i]);
}
} else if ("-help".equals(cmd)) {
if (i < argv.length) {
printHelp(argv[i]);
} else {
printHelp("");
}
} else if ("-tail".equals(cmd)) {
tail(argv, i);
} else {
exitCode = -1;
System.err.println(cmd.substring(1) + ": Unknown command");
printUsage("");
}
} catch (IllegalArgumentException arge) {
exitCode = -1;
System.err.println(cmd.substring(1) + ": " + arge.getLocalizedMessage());
printUsage(cmd);
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage, ignore the stack trace.
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
System.err.println(cmd.substring(1) + ": " +
content[0]);
} catch (Exception ex) {
System.err.println(cmd.substring(1) + ": " +
ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
System.err.println(cmd.substring(1) + ": " +
e.getLocalizedMessage());
} catch (Exception re) {
exitCode = -1;
System.err.println(cmd.substring(1) + ": " + re.getLocalizedMessage());
} finally {
}
return exitCode;
}
public void close() throws IOException {
if (fs != null) {
fs.close();
fs = null;
}
}
/**
* main() has some simple utility methods
*/
public static void main(String argv[]) throws Exception {
FsShell shell = new FsShell();
int res;
try {
res = ToolRunner.run(shell, argv);
} finally {
shell.close();
}
System.exit(res);
}
/**
* Accumulate exceptions if there is any. Throw them at last.
*/
private abstract class DelayedExceptionThrowing {
abstract void process(Path p, FileSystem srcFs) throws IOException;
final void globAndProcess(Path srcPattern, FileSystem srcFs
) throws IOException {
List<IOException> exceptions = new ArrayList<IOException>();
for(Path p : FileUtil.stat2Paths(srcFs.globStatus(srcPattern),
srcPattern))
try { process(p, srcFs); }
catch(IOException ioe) { exceptions.add(ioe); }
if (!exceptions.isEmpty())
if (exceptions.size() == 1)
throw exceptions.get(0);
else
throw new IOException("Multiple IOExceptions: " + exceptions);
}
}
}
| false | false | null | null |
diff --git a/app/controllers/Application.java b/app/controllers/Application.java
index e857e64..1ce6d82 100644
--- a/app/controllers/Application.java
+++ b/app/controllers/Application.java
@@ -1,73 +1,81 @@
package controllers;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.List;
import org.junit.experimental.categories.Categories.IncludeCategory;
import controllers.CRUD.ObjectType;
import models.Incident;
import models.IncidentCategory;
import models.Location;
import models.User;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import play.mvc.Controller;
import services.Ushahidi;
public class Application extends Controller
{
public static final Ushahidi USHAHIDI = new Ushahidi("https://simpelers.crowdmap.com/api", "[email protected]", "qazwsx");
public static void index()
{
try {
List<Incident> all = Incident.find("order by incidentDate desc").fetch();
render(all);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void newReport() throws Exception
{
Incident incident = new Incident();
List<IncidentCategory> categories = IncidentCategory.findAll();
List<Location> locations = Location.findAll();
try {
render(incident, categories, locations);
} catch (TemplateNotFoundException e) {
e.printStackTrace();
}
}
- public static void saveReport(Long categoryId, String title, Long locationId, String content, String direction) throws Exception
+ public static void saveReport(Long categoryId, String title, Long locationId, String content, String duration, String direction) throws Exception
{
IncidentCategory cat = (IncidentCategory) IncidentCategory.findById(categoryId);
Incident i = new Incident(cat,
title,
content,
Calendar.getInstance().getTime(),
- cat.getDuration(),
+ getEstDuration(cat, duration),
(Location) Location.findById(locationId),
direction,
(User) User.find("byFirstName", "john").first()); //HARDCODED!!
// Validate
validation.valid(i);
if(validation.hasErrors()) {
render("@form", i);
}
// Save
i.save();
index();
}
+
+ private static long getEstDuration(IncidentCategory cat, String estDuration)
+ {
+ if(estDuration == null || estDuration.isEmpty()){
+ return cat.getDefaultDurationMins();
+ }
+ return Long.parseLong(estDuration);
+ }
}
\ No newline at end of file
diff --git a/app/models/IncidentCategory.java b/app/models/IncidentCategory.java
index 0388992..4fa3ab3 100644
--- a/app/models/IncidentCategory.java
+++ b/app/models/IncidentCategory.java
@@ -1,38 +1,43 @@
package models;
import java.util.*;
import javax.persistence.Entity;
import play.db.jpa.Model;
@Entity
public class IncidentCategory extends Model {
public String name;
public long duration;
public IncidentCategory(String name, long duration) {
super();
this.name = name;
this.duration = duration;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
+
+ public long getDefaultDurationMins()
+ {
+ return getDuration() / (1000 * 60);
+ }
}
\ No newline at end of file
| false | false | null | null |
diff --git a/org.orbisgis.core-ui/src/main/java/org/orbisgis/editors/table/TableComponent.java b/org.orbisgis.core-ui/src/main/java/org/orbisgis/editors/table/TableComponent.java
index 0274822b6..3a5e35d86 100644
--- a/org.orbisgis.core-ui/src/main/java/org/orbisgis/editors/table/TableComponent.java
+++ b/org.orbisgis.core-ui/src/main/java/org/orbisgis/editors/table/TableComponent.java
@@ -1,818 +1,825 @@
package org.orbisgis.editors.table;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeSet;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import org.gdms.data.DataSource;
import org.gdms.data.edition.EditionEvent;
import org.gdms.data.edition.EditionListener;
import org.gdms.data.edition.FieldEditionEvent;
import org.gdms.data.edition.MetadataEditionListener;
import org.gdms.data.edition.MultipleEditionEvent;
import org.gdms.data.metadata.Metadata;
import org.gdms.data.types.Constraint;
import org.gdms.data.types.Type;
import org.gdms.data.values.Value;
import org.gdms.data.values.ValueFactory;
import org.gdms.driver.DriverException;
import org.gdms.sql.strategies.SortComparator;
import org.orbisgis.Services;
import org.orbisgis.action.IActionAdapter;
import org.orbisgis.action.IActionFactory;
import org.orbisgis.action.ISelectableActionAdapter;
import org.orbisgis.action.MenuTree;
import org.orbisgis.editors.table.action.ITableCellAction;
import org.orbisgis.editors.table.action.ITableColumnAction;
import org.orbisgis.errorManager.ErrorManager;
import org.orbisgis.pluginManager.background.BackgroundJob;
import org.orbisgis.pluginManager.background.BackgroundManager;
import org.orbisgis.progress.IProgressMonitor;
import org.orbisgis.progress.NullProgressMonitor;
import org.orbisgis.ui.resourceTree.ContextualActionExtensionPointHelper;
import org.orbisgis.ui.sif.AskValue;
import org.orbisgis.ui.table.TextFieldCellEditor;
import org.sif.SQLUIPanel;
import org.sif.UIFactory;
public class TableComponent extends JPanel {
private static final String OPTIMALWIDTH = "OPTIMALWIDTH";
private static final String SETWIDTH = "SETWIDTH";
private static final String SORTUP = "SORTUP";
private static final String SORTDOWN = "SORTDOWN";
private static final String NOSORT = "NOSORT";
// Swing components
private javax.swing.JScrollPane jScrollPane = null;
private JTable table = null;
// Model
private int selectedColumn = -1;
private DataSourceDataModel tableModel;
private DataSource dataSource;
private ArrayList<Integer> indexes = null;
private Selection selection;
private TableEditableElement element;
// listeners
private ActionListener menuListener = new PopupActionListener();
private ModificationListener listener = new ModificationListener();
private SelectionListener selectionListener = new SyncSelectionListener();
// flags
private boolean managingSelection;
/**
* This is the default constructor
*
* @throws DriverException
*/
public TableComponent() {
initialize();
}
/**
* This method initializes this
*/
private void initialize() {
this.setLayout(new BorderLayout());
add(getJScrollPane(), BorderLayout.CENTER);
}
/**
* This method initializes table
*
* @return javax.swing.JTable
*/
private javax.swing.JTable getTable() {
if (table == null) {
table = new JTable();
table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
TextFieldCellEditor ce = new TextFieldCellEditor();
for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setCellEditor(ce);
}
table.getSelectionModel().setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
if (!managingSelection && (selection != null)) {
managingSelection = true;
- selection.setSelection(table
- .getSelectedRows());
+ int[] selectedRows = table
+ .getSelectedRows();
+ if (indexes != null) {
+ for (int i = 0; i < selectedRows.length; i++) {
+ selectedRows[i] = indexes
+ .get(selectedRows[i]);
+ }
+ }
+ selection.setSelection(selectedRows);
managingSelection = false;
}
}
}
});
table.getTableHeader().setReorderingAllowed(false);
table.getTableHeader().addMouseListener(
new HeaderPopupMouseAdapter());
table.addMouseListener(new CellPopupMouseAdapter());
table.setColumnSelectionAllowed(true);
table.getColumnModel().setSelectionModel(
new DefaultListSelectionModel());
}
return table;
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private javax.swing.JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new javax.swing.JScrollPane();
jScrollPane.setViewportView(getTable());
}
return jScrollPane;
}
/**
* Shows a dialog with the error type
*
* @param msg
*/
private void inputError(String msg, Exception e) {
Services.getService(ErrorManager.class).error(msg);
getTable().requestFocus();
}
public boolean tableHasFocus() {
return table.hasFocus() || table.isEditing();
}
public String[] getSelectedFieldNames() {
int[] selected = table.getSelectedColumns();
String[] ret = new String[selected.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = tableModel.getColumnName(selected[i]);
}
return ret;
}
public void setElement(TableEditableElement element) {
if (this.dataSource != null) {
this.dataSource.removeEditionListener(listener);
this.dataSource.removeMetadataEditionListener(listener);
this.selection.removeSelectionListener(selectionListener);
}
this.element = element;
if (this.element == null) {
this.dataSource = null;
this.selection = null;
table.setModel(new DefaultTableModel());
} else {
this.dataSource = element.getDataSource();
this.dataSource.addEditionListener(listener);
this.dataSource.addMetadataEditionListener(listener);
tableModel = new DataSourceDataModel();
table.setModel(tableModel);
autoResizeColWidth(Math.min(5, tableModel.getRowCount()),
new HashMap<String, Integer>(),
new HashMap<String, TableCellRenderer>());
this.selection = element.getSelection();
this.selection.setSelectionListener(selectionListener);
}
}
private void autoResizeColWidth(int rowsToCheck,
HashMap<String, Integer> widths,
HashMap<String, TableCellRenderer> renderers) {
DefaultTableColumnModel colModel = new DefaultTableColumnModel();
int maxWidth = 200;
for (int i = 0; i < tableModel.getColumnCount(); i++) {
TableColumn col = new TableColumn(i);
String columnName = tableModel.getColumnName(i);
col.setHeaderValue(columnName);
TableCellRenderer renderer = renderers.get(columnName);
if (renderer == null) {
renderer = new ButtonHeaderRenderer();
}
col.setHeaderRenderer(renderer);
Integer width = widths.get(columnName);
if (width == null) {
width = getColumnOptimalWidth(rowsToCheck, maxWidth, i,
new NullProgressMonitor());
}
col.setPreferredWidth(width);
colModel.addColumn(col);
}
table.setColumnModel(colModel);
}
private int getColumnOptimalWidth(int rowsToCheck, int maxWidth,
int column, IProgressMonitor pm) {
TableColumn col = table.getColumnModel().getColumn(column);
int margin = 5;
int width = 0;
// Get width of column header
TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component comp = renderer.getTableCellRendererComponent(table, col
.getHeaderValue(), false, false, 0, 0);
width = comp.getPreferredSize().width;
// Check header
comp = renderer.getTableCellRendererComponent(table, col
.getHeaderValue(), false, false, 0, column);
width = Math.max(width, comp.getPreferredSize().width);
// Get maximum width of column data
for (int r = 0; r < rowsToCheck; r++) {
if (r / 100 == r / 100.0) {
if (pm.isCancelled()) {
break;
} else {
pm.progressTo(100 * r / rowsToCheck);
}
}
renderer = table.getCellRenderer(r, column);
comp = renderer.getTableCellRendererComponent(table, table
.getValueAt(r, column), false, false, r, column);
width = Math.max(width, comp.getPreferredSize().width);
}
// limit
width = Math.min(width, maxWidth);
// Add margin
width += 2 * margin;
return width;
}
private void refreshTableStructure() {
TableColumnModel columnModel = table.getColumnModel();
HashMap<String, Integer> widths = new HashMap<String, Integer>();
HashMap<String, TableCellRenderer> renderers = new HashMap<String, TableCellRenderer>();
try {
for (int i = 0; i < dataSource.getMetadata().getFieldCount(); i++) {
String columnName = null;
try {
columnName = dataSource.getMetadata().getFieldName(i);
} catch (DriverException e) {
}
int columnIndex = -1;
if (columnName != null) {
try {
columnIndex = columnModel.getColumnIndex(columnName);
} catch (IllegalArgumentException e) {
columnIndex = -1;
}
if (columnIndex != -1) {
TableColumn column = columnModel.getColumn(columnIndex);
widths.put(columnName, column.getPreferredWidth());
renderers.put(columnName, column.getHeaderRenderer());
}
}
}
} catch (DriverException e) {
Services.getService(ErrorManager.class).warning(
"Cannot keep table configuration", e);
}
tableModel.fireTableStructureChanged();
autoResizeColWidth(Math.min(5, tableModel.getRowCount()), widths,
renderers);
}
private int getRowIndex(int row) {
if (indexes != null) {
row = indexes.get(row);
}
return row;
}
private class SyncSelectionListener implements SelectionListener {
@Override
public void selectionChanged() {
if (!managingSelection) {
managingSelection = true;
ListSelectionModel model = table.getSelectionModel();
model.setValueIsAdjusting(true);
model.clearSelection();
for (int i : selection.getSelection()) {
if (indexes != null) {
Integer sortedIndex = indexes.indexOf(i);
model.addSelectionInterval(sortedIndex, sortedIndex);
} else {
model.addSelectionInterval(i, i);
}
}
model.setValueIsAdjusting(false);
managingSelection = false;
}
}
}
private final class PopupActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (OPTIMALWIDTH.equals(e.getActionCommand())) {
BackgroundManager bm = Services
.getService(BackgroundManager.class);
bm.backgroundOperation(new BackgroundJob() {
@Override
public void run(IProgressMonitor pm) {
final int width = getColumnOptimalWidth(table
.getRowCount(), Integer.MAX_VALUE,
selectedColumn, pm);
final TableColumn col = table.getColumnModel()
.getColumn(selectedColumn);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
col.setPreferredWidth(width);
}
});
}
@Override
public String getTaskName() {
return "Calculating optimal width";
}
});
} else if (SETWIDTH.equals(e.getActionCommand())) {
TableColumn selectedTableColumn = table.getTableHeader()
.getColumnModel().getColumn(selectedColumn);
AskValue av = new AskValue("New column width", null, null,
Integer.toString(selectedTableColumn
.getPreferredWidth()));
av.setType(SQLUIPanel.INT);
if (UIFactory.showDialog(av)) {
selectedTableColumn.setPreferredWidth(Integer.parseInt(av
.getValue()));
}
} else if (SORTUP.equals(e.getActionCommand())) {
BackgroundManager bm = Services
.getService(BackgroundManager.class);
bm.backgroundOperation(new SortJob(true));
} else if (SORTDOWN.equals(e.getActionCommand())) {
BackgroundManager bm = Services
.getService(BackgroundManager.class);
bm.backgroundOperation(new SortJob(false));
} else if (NOSORT.equals(e.getActionCommand())) {
indexes = null;
tableModel.fireTableDataChanged();
}
table.getTableHeader().repaint();
}
}
private abstract class PopupMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
popup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
popup(e);
}
private void popup(MouseEvent e) {
Component component = getComponent();
selectedColumn = table.columnAtPoint(e.getPoint());
int clickedRow = table.rowAtPoint(e.getPoint());
component.repaint();
if (e.isPopupTrigger()) {
JPopupMenu pop = getPopupMenu();
MenuTree menuTree = new MenuTree();
String epid = getExtensionPointId();
ContextualActionExtensionPointHelper.createPopup(menuTree,
getFactory(getRowIndex(clickedRow)), epid);
JComponent[] menus = menuTree.getJMenus();
for (JComponent menu : menus) {
pop.add(menu);
}
pop.show(component, e.getX(), e.getY());
}
}
protected abstract IActionFactory getFactory(int clickedRow);
protected abstract Component getComponent();
protected abstract String getExtensionPointId();
protected abstract JPopupMenu getPopupMenu();
}
private class HeaderPopupMouseAdapter extends PopupMouseAdapter {
protected ColumnActionFactory getFactory(int clickedRow) {
return new ColumnActionFactory();
}
protected Component getComponent() {
return table.getTableHeader();
}
protected String getExtensionPointId() {
return "org.orbisgis.editors.table.ColumnAction";
}
protected JPopupMenu getPopupMenu() {
JPopupMenu pop = new JPopupMenu();
addMenu(pop, "Optimal width", OPTIMALWIDTH);
addMenu(pop, "Set width", SETWIDTH);
pop.addSeparator();
addMenu(pop, "Sort ascending", SORTUP);
addMenu(pop, "Sort descending", SORTDOWN);
addMenu(pop, "No Sort", NOSORT);
pop.addSeparator();
return pop;
}
private void addMenu(JPopupMenu pop, String text, String actionCommand) {
JMenuItem menu = new JMenuItem(text);
menu.setActionCommand(actionCommand);
menu.addActionListener(menuListener);
pop.add(menu);
}
}
private class CellPopupMouseAdapter extends PopupMouseAdapter {
protected Component getComponent() {
return table;
}
protected String getExtensionPointId() {
return "org.orbisgis.editors.table.CellAction";
}
protected JPopupMenu getPopupMenu() {
return new JPopupMenu();
}
@Override
protected IActionFactory getFactory(int clickedRow) {
return new CellActionFactory(clickedRow);
}
}
private class ModificationListener implements EditionListener,
MetadataEditionListener {
@Override
public void multipleModification(MultipleEditionEvent e) {
tableModel.fireTableDataChanged();
}
@Override
public void singleModification(EditionEvent e) {
if (e.getType() != EditionEvent.RESYNC) {
tableModel.fireTableCellUpdated((int) e.getRowIndex(), e
.getFieldIndex());
} else {
refreshTableStructure();
}
}
@Override
public void fieldAdded(FieldEditionEvent event) {
fieldRemoved(null);
}
@Override
public void fieldModified(FieldEditionEvent event) {
fieldRemoved(null);
}
@Override
public void fieldRemoved(FieldEditionEvent event) {
refreshTableStructure();
}
}
/**
* @author Fernando Gonzalez Cortes
*/
public class DataSourceDataModel extends AbstractTableModel {
private Metadata metadata;
private Metadata getMetadata() throws DriverException {
if (metadata == null) {
metadata = dataSource.getMetadata();
}
return metadata;
}
/**
* Returns the name of the field.
*
* @param col
* index of field
*
* @return Name of field
*/
public String getColumnName(int col) {
try {
return getMetadata().getFieldName(col);
} catch (DriverException e) {
return null;
}
}
/**
* Returns the number of fields.
*
* @return number of fields
*/
public int getColumnCount() {
try {
return getMetadata().getFieldCount();
} catch (DriverException e) {
return 0;
}
}
/**
* Returns number of rows.
*
* @return number of rows.
*/
public int getRowCount() {
try {
return (int) dataSource.getRowCount();
} catch (DriverException e) {
return 0;
}
}
/**
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
public Object getValueAt(int row, int col) {
try {
return dataSource.getFieldValue(getRowIndex(row), col)
.toString();
} catch (DriverException e) {
return "";
}
}
/**
* @see javax.swing.table.TableModel#isCellEditable(int, int)
*/
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (element.isEditable()) {
try {
Constraint c = getMetadata().getFieldType(columnIndex)
.getConstraint(Constraint.READONLY);
return c == null;
} catch (DriverException e) {
return false;
}
} else {
return false;
}
}
/**
* @see javax.swing.table.TableModel#setValueAt(java.lang.Object, int,
* int)
*/
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
try {
Type type = getMetadata().getFieldType(columnIndex);
String strValue = aValue.toString().trim();
Value v = ValueFactory.createValueByType(strValue, type
.getTypeCode());
String inputError = dataSource.check(columnIndex, v);
if (inputError != null) {
inputError(inputError, null);
} else {
dataSource.setFieldValue(getRowIndex(rowIndex),
columnIndex, v);
}
} catch (DriverException e1) {
throw new RuntimeException(e1);
} catch (NumberFormatException e) {
inputError(e.getMessage(), e);
} catch (ParseException e) {
inputError(e.getMessage(), e);
}
}
}
private final class SortJob implements BackgroundJob {
private boolean ascending;
public SortJob(boolean ascending) {
this.ascending = ascending;
}
@Override
public void run(IProgressMonitor pm) {
try {
int rowCount = (int) dataSource.getRowCount();
Value[][] cache = new Value[rowCount][1];
for (int i = 0; i < rowCount; i++) {
cache[i][0] = dataSource.getFieldValue(i, selectedColumn);
}
ArrayList<Boolean> order = new ArrayList<Boolean>();
order.add(ascending);
TreeSet<Integer> sortset = new TreeSet<Integer>(
new SortComparator(cache, order));
for (int i = 0; i < rowCount; i++) {
if (i / 100 == i / 100.0) {
if (pm.isCancelled()) {
break;
} else {
pm.progressTo(100 * i / rowCount);
}
}
sortset.add(new Integer(i));
}
ArrayList<Integer> indexes = new ArrayList<Integer>();
Iterator<Integer> it = sortset.iterator();
while (it.hasNext()) {
Integer integer = (Integer) it.next();
indexes.add(integer);
}
TableComponent.this.indexes = indexes;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
tableModel.fireTableDataChanged();
}
});
} catch (DriverException e) {
Services.getService(ErrorManager.class).error("Cannot sort", e);
}
}
@Override
public String getTaskName() {
return "Sorting";
}
}
class ButtonHeaderRenderer extends JButton implements TableCellRenderer {
public ButtonHeaderRenderer() {
setMargin(new Insets(0, 0, 0, 0));
}
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
setText((value == null) ? "" : value.toString());
boolean isPressed = (column == selectedColumn);
getModel().setPressed(isPressed);
getModel().setArmed(isPressed);
return this;
}
public void setPressedColumn(int col) {
selectedColumn = col;
}
}
private class ColumnActionFactory implements IActionFactory {
@Override
public IActionAdapter getAction(Object action,
HashMap<String, String> attributes) {
return new ColumnActionAdapter((ITableColumnAction) action);
}
@Override
public ISelectableActionAdapter getSelectableAction(Object action,
HashMap<String, String> attributes) {
throw new RuntimeException("Selectable action not allowed");
}
}
private class CellActionFactory implements IActionFactory {
private int clickedRow;
public CellActionFactory(int clickedRow) {
this.clickedRow = clickedRow;
}
@Override
public IActionAdapter getAction(Object action,
HashMap<String, String> attributes) {
return new CellActionAdapter((ITableCellAction) action, clickedRow);
}
@Override
public ISelectableActionAdapter getSelectableAction(Object action,
HashMap<String, String> attributes) {
throw new RuntimeException("Selectable action not allowed");
}
}
private class ColumnActionAdapter implements IActionAdapter {
private ITableColumnAction action;
public ColumnActionAdapter(ITableColumnAction action) {
this.action = action;
}
@Override
public void actionPerformed() {
action.execute(dataSource, selection, selectedColumn);
}
@Override
public boolean isVisible() {
return action.accepts(dataSource, selection, selectedColumn);
}
@Override
public boolean isEnabled() {
return true;
}
}
private class CellActionAdapter implements IActionAdapter {
private ITableCellAction action;
private int clickedRow;
public CellActionAdapter(ITableCellAction action, int clickedRow) {
this.action = action;
this.clickedRow = clickedRow;
}
@Override
public void actionPerformed() {
action.execute(dataSource, selection, clickedRow, selectedColumn);
}
@Override
public boolean isVisible() {
return action.accepts(dataSource, selection, clickedRow,
selectedColumn);
}
@Override
public boolean isEnabled() {
return true;
}
}
}
| true | false | null | null |
diff --git a/tests-arquillian/src/test/java/org/jboss/weld/tests/extensions/ExtensionObserver.java b/tests-arquillian/src/test/java/org/jboss/weld/tests/extensions/ExtensionObserver.java
index 78bfba81a..7416d0f2f 100644
--- a/tests-arquillian/src/test/java/org/jboss/weld/tests/extensions/ExtensionObserver.java
+++ b/tests-arquillian/src/test/java/org/jboss/weld/tests/extensions/ExtensionObserver.java
@@ -1,252 +1,252 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.extensions;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.AfterDeploymentValidation;
import javax.enterprise.inject.spi.BeforeBeanDiscovery;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import javax.enterprise.inject.spi.ProcessBean;
import javax.enterprise.inject.spi.ProcessInjectionTarget;
import javax.enterprise.inject.spi.ProcessManagedBean;
import javax.enterprise.inject.spi.ProcessObserverMethod;
import javax.enterprise.inject.spi.ProcessProducer;
import javax.enterprise.inject.spi.ProcessProducerField;
import javax.enterprise.inject.spi.ProcessProducerMethod;
import javax.enterprise.inject.spi.ProcessSessionBean;
public class ExtensionObserver implements Extension {
private boolean allBeforeBeanDiscovery;
private boolean allAfterBeanDiscovery;
private boolean allAfterDeploymentValidation;
private boolean allProcessBean;
private boolean allProcessInjectionTarget;
private boolean allProcessManagedBean;
private boolean allProcessObserverMethod;
private boolean allProcessProducer;
private boolean allProcessProducerField;
private boolean allProcessProducerMethod;
private boolean allProcessSessionBean;
private boolean allProcessAnnnotatedType;
private boolean beforeBeanDiscovery;
private boolean afterBeanDiscovery;
private boolean afterDeploymentValidation;
private boolean processBean;
private boolean processInjectionTarget;
private boolean processManagedBean;
private boolean processObserverMethod;
private boolean processProducer;
private boolean processProducerField;
private boolean processProducerMethod;
private boolean processSessionBean;
private boolean processAnnotatedType;
private ProcessProducerMethod<?, ?> processProducerMethodInstance;
public void observeAll(@Observes Object event) {
if (event instanceof BeforeBeanDiscovery) {
allBeforeBeanDiscovery = true;
}
if (event instanceof AfterBeanDiscovery) {
allAfterBeanDiscovery = true;
}
if (event instanceof AfterDeploymentValidation) {
allAfterDeploymentValidation = true;
}
if (event instanceof ProcessBean<?> && !(event instanceof ProcessProducerField<?, ?> || event instanceof ProcessProducerMethod<?, ?> || event instanceof ProcessManagedBean<?> || event instanceof ProcessSessionBean<?>)) {
allProcessBean = true;
}
if (event instanceof ProcessInjectionTarget<?>) {
allProcessInjectionTarget = true;
}
if (event instanceof ProcessManagedBean<?>) {
allProcessManagedBean = true;
}
if (event instanceof ProcessObserverMethod<?, ?>) {
allProcessObserverMethod = true;
}
if (event instanceof ProcessProducer<?, ?>) {
allProcessProducer = true;
}
if (event instanceof ProcessProducerField<?, ?>) {
allProcessProducerField = true;
}
if (event instanceof ProcessProducerMethod<?, ?>) {
allProcessProducerMethod = true;
}
if (event instanceof ProcessSessionBean<?>) {
allProcessSessionBean = true;
}
if (event instanceof ProcessAnnotatedType<?>) {
allProcessAnnnotatedType = true;
}
}
public void observeBeforeBeanDiscovery(@Observes BeforeBeanDiscovery event) {
beforeBeanDiscovery = true;
}
public void observeAfterBeanDiscovery(@Observes AfterBeanDiscovery event) {
afterBeanDiscovery = true;
}
public void observeAfterDeploymentValidation(@Observes AfterDeploymentValidation event) {
afterDeploymentValidation = true;
}
public void observeProcessBean(@Observes ProcessBean<?> event) {
processBean = true;
}
public void observeProcessInjectionTarget(@Observes ProcessInjectionTarget<?> event) {
processInjectionTarget = true;
}
public void observeProcessProducer(@Observes ProcessProducer<?, ?> event) {
processProducer = true;
}
- public void observeProcessProducerMethod(@Observes ProcessProducerMethod<?, ?> event) {
+ public void observeProcessProducerMethod(@Observes ProcessProducerMethod<?, Stable> event) {
processProducerMethod = true;
this.processProducerMethodInstance = event;
}
public void observeProcessProducerField(@Observes ProcessProducerField<?, ?> event) {
processProducerField = true;
}
public void observeProcessObserverMethod(@Observes ProcessObserverMethod<?, ?> event) {
processObserverMethod = true;
}
public void observeProcessManagedBean(@Observes ProcessManagedBean<?> event) {
processManagedBean = true;
}
public void observeProcessSessionBean(@Observes ProcessSessionBean<?> event) {
processSessionBean = true;
}
public void observeProcessAnnotatedType(@Observes ProcessAnnotatedType<?> event) {
processAnnotatedType = true;
}
public boolean isAllBeforeBeanDiscovery() {
return allBeforeBeanDiscovery;
}
public boolean isAllAfterBeanDiscovery() {
return allAfterBeanDiscovery;
}
public boolean isAllAfterDeploymentValidation() {
return allAfterDeploymentValidation;
}
public boolean isAllProcessBean() {
return allProcessBean;
}
public boolean isAllProcessInjectionTarget() {
return allProcessInjectionTarget;
}
public boolean isAllProcessManagedBean() {
return allProcessManagedBean;
}
public boolean isAllProcessObserverMethod() {
return allProcessObserverMethod;
}
public boolean isAllProcessProducer() {
return allProcessProducer;
}
public boolean isAllProcessProducerField() {
return allProcessProducerField;
}
public boolean isAllProcessProducerMethod() {
return allProcessProducerMethod;
}
public boolean isAllProcessSessionBean() {
return allProcessSessionBean;
}
public boolean isAllProcessAnnnotatedType() {
return allProcessAnnnotatedType;
}
public boolean isBeforeBeanDiscovery() {
return beforeBeanDiscovery;
}
public boolean isAfterBeanDiscovery() {
return afterBeanDiscovery;
}
public boolean isAfterDeploymentValidation() {
return afterDeploymentValidation;
}
public boolean isProcessBean() {
return processBean;
}
public boolean isProcessInjectionTarget() {
return processInjectionTarget;
}
public boolean isProcessManagedBean() {
return processManagedBean;
}
public boolean isProcessObserverMethod() {
return processObserverMethod;
}
public boolean isProcessProducer() {
return processProducer;
}
public boolean isProcessProducerField() {
return processProducerField;
}
public boolean isProcessProducerMethod() {
return processProducerMethod;
}
public ProcessProducerMethod<?, ?> getProcessProducerMethodInstance() {
return processProducerMethodInstance;
}
public boolean isProcessSessionBean() {
return processSessionBean;
}
public boolean isProcessAnnotatedType() {
return processAnnotatedType;
}
}
| true | false | null | null |
diff --git a/src/mmb/foss/aueb/icong/DrawableAreaView.java b/src/mmb/foss/aueb/icong/DrawableAreaView.java
index 2e75b22..26fd822 100644
--- a/src/mmb/foss/aueb/icong/DrawableAreaView.java
+++ b/src/mmb/foss/aueb/icong/DrawableAreaView.java
@@ -1,306 +1,308 @@
package mmb.foss.aueb.icong;
import java.io.InputStream;
import java.util.ArrayList;
import mmb.foss.aueb.icong.boxes.Box;
import mmb.foss.aueb.icong.boxes.SavedState;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawableAreaView extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private ArrayList<Box> boxes = new ArrayList<Box>();
private Context mContext;
private Box selectedBox = null;
private int pressedX, pressedY;
private int originalX, originalY;
private int[] buttonCenter = new int[2];
private int WIDTH, HEIGHT;
private ArrayList<BoxButtonPair[]> lines = new ArrayList<BoxButtonPair[]>();
private Box box = null;
private int buttonPressed = -1;
private int buttonHovered = -1;
private boolean drawingline = false;
private boolean foundPair = false;
private int lineStartX, lineStartY, lineCurrentX, lineCurrentY;
private long tap;
private final int DOUBLE_TAP_INTERVAL = (int) (0.3 * 1000);
private BitmapDrawable trash;
private boolean showTrash;
private int trashX, trashY;
private Box possibleTrash;
public DrawableAreaView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
mContext = context;
paint.setColor(Color.BLACK);
WIDTH = MainActivity.width;
HEIGHT = MainActivity.height;
boxes = SavedState.getBoxes();
lines = SavedState.getLines();
}
protected void onDraw(Canvas c) {
if (WIDTH == 0 || trash == null) {
WIDTH = this.getWidth();
HEIGHT = this.getHeight();
InputStream is = mContext.getResources().openRawResource(
R.drawable.trash);
Bitmap originalBitmap = BitmapFactory.decodeStream(is);
int w = WIDTH / 10, h = (w * originalBitmap.getHeight())
/ originalBitmap.getWidth();
trash = new BitmapDrawable(mContext.getResources(),
Bitmap.createScaledBitmap(originalBitmap, w, h, true));
trashX = (WIDTH - trash.getBitmap().getWidth()) / 2;
trashY = HEIGHT - 40;
}
for (Box box : boxes) {
// TODO: Zooming to be removed
box.setZoom(1.8);
c.drawBitmap(box.getBitmap(), box.getX(), box.getY(), null);
for (int i = 0; i < box.getNumOfButtons(); i++) {
if (box.isPressed(i)) {
buttonCenter = box.getButtonCenter(i);
c.drawCircle(buttonCenter[0], buttonCenter[1],
box.getButtonRadius(i), paint);
}
}
}
for (BoxButtonPair[] line : lines) {
Box box0 = line[0].getBox(), box1 = line[1].getBox();
int button0 = line[0].getButton(), button1 = line[1].getButton();
int[] center0 = box0.getButtonCenter(button0), center1 = box1
.getButtonCenter(button1);
c.drawLine(center0[0], center0[1], center1[0], center1[1], paint);
}
if (drawingline) {
c.drawLine(lineStartX, lineStartY, lineCurrentX, lineCurrentY,
paint);
}
if (showTrash) {
c.drawBitmap(trash.getBitmap(), trashX, trashY, paint);
}
}
public void addBox(Box box) {
int x, y;
if (mContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
y = getLower() + 15;
x = (WIDTH / 2) - (box.getWidth() / 2);
} else {
y = (HEIGHT / 2) - (box.getHeight() / 2);
x = getRighter() + 15;
}
box.setY(y);
box.setX(x);
boxes.add(box);
SavedState.addBox(box);
invalidate();
}
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (showTrash && onTrash(event.getX(), event.getY())) {
// if trash icon is visible and clicked delete the possibleTrash
// box
deleteBox(possibleTrash);
possibleTrash = null;
}
box = getBoxTouched((int) event.getX(), (int) event.getY());
if (box != null) {
// if we have touched inside a box
selectedBox = box;
buttonPressed = box.isButton((int) event.getX(),
(int) event.getY());
// TODO double tap implementation
long tap = System.currentTimeMillis();
if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) {
// if we have double tapped inside a box
System.out.println("this is double tap");
} else {
System.out.println("this is NOT double tap");
}
this.tap = tap;
if (buttonPressed == -1) {
// if we haven't touched the box's button
pressedX = (int) event.getX();
pressedY = (int) event.getY();
originalX = box.getX();
originalY = box.getY();
showTrash = true;
possibleTrash = box;
} else {
// if we have touched the box's button
showTrash = false;
possibleTrash = null;
if (buttonPressed >= box.getNoOfInputs()) {
// if button pressed is an output button
if (!box.isPressed(buttonPressed)) {
// if the button pressed wasn't pressed before
box.setButtonPressed(buttonPressed);
} else {
// if the button pressed was pressed before deletes
// this connection/line
- removeLine(box,buttonPressed);
+ removeLine(box, buttonPressed);
}
int[] center = box.getButtonCenter(buttonPressed);
lineStartX = center[0];
lineStartY = center[1];
lineCurrentX = lineStartX;
lineCurrentY = lineStartY;
drawingline = true;
}
invalidate();
selectedBox = null;
}
} else {
// if we haven't touched inside a box
showTrash = false;
possibleTrash = null;
}
break;
case MotionEvent.ACTION_MOVE:
if (selectedBox != null) {
// if we have selected a box by tapping once in it
selectedBox.setX((int) event.getX() - (pressedX - originalX));
selectedBox.setY((int) event.getY() - (pressedY - originalY));
invalidate();
}
if (drawingline) {
// if we have pressed a previously not pressed box's output
// button
lineCurrentX = (int) event.getX();
lineCurrentY = (int) event.getY();
Box boxHovered = getBoxTouched((int) event.getX(),
(int) event.getY());
if (boxHovered != null) {
// if we have drawned a line on another box
buttonHovered = boxHovered.isButton((int) event.getX(),
(int) event.getY());
if (buttonHovered != -1) {
// if we have drawned a line on another's box's button
- if (buttonHovered < boxHovered.getNoOfInputs() && !boxHovered.isPressed(buttonHovered)) {
+ if (buttonHovered < boxHovered.getNoOfInputs()
+ && !boxHovered.isPressed(buttonHovered)
+ && !box.equals(boxHovered)) {
// if we have drawned a line on another's box's
// input button
int[] center = boxHovered
.getButtonCenter(buttonHovered);
lineStartX = center[0];
lineStartY = center[1];
boxHovered.setButtonPressed(buttonHovered);
drawingline = false;
BoxButtonPair[] line = {
new BoxButtonPair(box, buttonPressed),
new BoxButtonPair(boxHovered, buttonHovered) };
lines.add(line);
SavedState.addLine(line);
foundPair = true;
}
}
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
drawingline = false;
selectedBox = null;
// if when drawing a line stops and we haven'd reached another box's
// input button then erase the line and unpress the button
if (!foundPair && buttonPressed != -1 && box != null)
if (!((buttonPressed + 1) <= box.getNoOfInputs()))
box.unsetButtonPressed(buttonPressed);
foundPair = false;
pressedX = pressedY = originalX = originalY = 0;
// TODO implement here to pou peftei
invalidate();
return false;
}
return true;
}
// returns the lower pixel of the lower element
private int getLower() {
int y = 0;
for (Box box : boxes) {
if (y < box.getYY())
y = box.getYY();
}
return y;
}
// returns the righter pixel of the righter element
private int getRighter() {
int x = 0;
for (Box box : boxes) {
if (x < box.getXX())
x = box.getXX();
}
return x;
}
// returns the box that was touched
private Box getBoxTouched(int x, int y) {
for (Box b : boxes) {
if (b.isOnBox(x, y)) {
return b;
}
}
return null;
}
private boolean onTrash(float f, float g) {
boolean isOnTrash = false;
if (f >= trashX && f <= (trashX + trash.getBitmap().getWidth())
&& g >= trashY && g <= (trashY + trash.getBitmap().getHeight())) {
isOnTrash = true;
}
return isOnTrash;
}
private void deleteBox(Box box2del) {
boxes.remove(box2del);
removeLines(box2del);
SavedState.removeBox(box2del);
}
private void removeLine(Box box, int button) {
BoxButtonPair pair = new BoxButtonPair(box, button);
for (BoxButtonPair[] line : lines) {
if (line[0].equals(pair)) {
Box otherBox = line[1].getBox();
int otherButton = line[1].getButton();
lines.remove(line);
SavedState.removeLine(line);
otherBox.unsetButtonPressed(otherButton);
break;
} else if (line[1].equals(pair)) {
Box otherBox = line[0].getBox();
int otherButton = line[0].getButton();
lines.remove(line);
SavedState.removeLine(line);
otherBox.unsetButtonPressed(otherButton);
break;
}
}
}
private void removeLines(Box box) {
for (int i = 0; i < box.getNumOfButtons(); i++) {
removeLine(box, i);
}
}
}
| false | true | public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (showTrash && onTrash(event.getX(), event.getY())) {
// if trash icon is visible and clicked delete the possibleTrash
// box
deleteBox(possibleTrash);
possibleTrash = null;
}
box = getBoxTouched((int) event.getX(), (int) event.getY());
if (box != null) {
// if we have touched inside a box
selectedBox = box;
buttonPressed = box.isButton((int) event.getX(),
(int) event.getY());
// TODO double tap implementation
long tap = System.currentTimeMillis();
if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) {
// if we have double tapped inside a box
System.out.println("this is double tap");
} else {
System.out.println("this is NOT double tap");
}
this.tap = tap;
if (buttonPressed == -1) {
// if we haven't touched the box's button
pressedX = (int) event.getX();
pressedY = (int) event.getY();
originalX = box.getX();
originalY = box.getY();
showTrash = true;
possibleTrash = box;
} else {
// if we have touched the box's button
showTrash = false;
possibleTrash = null;
if (buttonPressed >= box.getNoOfInputs()) {
// if button pressed is an output button
if (!box.isPressed(buttonPressed)) {
// if the button pressed wasn't pressed before
box.setButtonPressed(buttonPressed);
} else {
// if the button pressed was pressed before deletes
// this connection/line
removeLine(box,buttonPressed);
}
int[] center = box.getButtonCenter(buttonPressed);
lineStartX = center[0];
lineStartY = center[1];
lineCurrentX = lineStartX;
lineCurrentY = lineStartY;
drawingline = true;
}
invalidate();
selectedBox = null;
}
} else {
// if we haven't touched inside a box
showTrash = false;
possibleTrash = null;
}
break;
case MotionEvent.ACTION_MOVE:
if (selectedBox != null) {
// if we have selected a box by tapping once in it
selectedBox.setX((int) event.getX() - (pressedX - originalX));
selectedBox.setY((int) event.getY() - (pressedY - originalY));
invalidate();
}
if (drawingline) {
// if we have pressed a previously not pressed box's output
// button
lineCurrentX = (int) event.getX();
lineCurrentY = (int) event.getY();
Box boxHovered = getBoxTouched((int) event.getX(),
(int) event.getY());
if (boxHovered != null) {
// if we have drawned a line on another box
buttonHovered = boxHovered.isButton((int) event.getX(),
(int) event.getY());
if (buttonHovered != -1) {
// if we have drawned a line on another's box's button
if (buttonHovered < boxHovered.getNoOfInputs() && !boxHovered.isPressed(buttonHovered)) {
// if we have drawned a line on another's box's
// input button
int[] center = boxHovered
.getButtonCenter(buttonHovered);
lineStartX = center[0];
lineStartY = center[1];
boxHovered.setButtonPressed(buttonHovered);
drawingline = false;
BoxButtonPair[] line = {
new BoxButtonPair(box, buttonPressed),
new BoxButtonPair(boxHovered, buttonHovered) };
lines.add(line);
SavedState.addLine(line);
foundPair = true;
}
}
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
drawingline = false;
selectedBox = null;
// if when drawing a line stops and we haven'd reached another box's
// input button then erase the line and unpress the button
if (!foundPair && buttonPressed != -1 && box != null)
if (!((buttonPressed + 1) <= box.getNoOfInputs()))
box.unsetButtonPressed(buttonPressed);
foundPair = false;
pressedX = pressedY = originalX = originalY = 0;
// TODO implement here to pou peftei
invalidate();
return false;
}
return true;
}
| public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (showTrash && onTrash(event.getX(), event.getY())) {
// if trash icon is visible and clicked delete the possibleTrash
// box
deleteBox(possibleTrash);
possibleTrash = null;
}
box = getBoxTouched((int) event.getX(), (int) event.getY());
if (box != null) {
// if we have touched inside a box
selectedBox = box;
buttonPressed = box.isButton((int) event.getX(),
(int) event.getY());
// TODO double tap implementation
long tap = System.currentTimeMillis();
if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) {
// if we have double tapped inside a box
System.out.println("this is double tap");
} else {
System.out.println("this is NOT double tap");
}
this.tap = tap;
if (buttonPressed == -1) {
// if we haven't touched the box's button
pressedX = (int) event.getX();
pressedY = (int) event.getY();
originalX = box.getX();
originalY = box.getY();
showTrash = true;
possibleTrash = box;
} else {
// if we have touched the box's button
showTrash = false;
possibleTrash = null;
if (buttonPressed >= box.getNoOfInputs()) {
// if button pressed is an output button
if (!box.isPressed(buttonPressed)) {
// if the button pressed wasn't pressed before
box.setButtonPressed(buttonPressed);
} else {
// if the button pressed was pressed before deletes
// this connection/line
removeLine(box, buttonPressed);
}
int[] center = box.getButtonCenter(buttonPressed);
lineStartX = center[0];
lineStartY = center[1];
lineCurrentX = lineStartX;
lineCurrentY = lineStartY;
drawingline = true;
}
invalidate();
selectedBox = null;
}
} else {
// if we haven't touched inside a box
showTrash = false;
possibleTrash = null;
}
break;
case MotionEvent.ACTION_MOVE:
if (selectedBox != null) {
// if we have selected a box by tapping once in it
selectedBox.setX((int) event.getX() - (pressedX - originalX));
selectedBox.setY((int) event.getY() - (pressedY - originalY));
invalidate();
}
if (drawingline) {
// if we have pressed a previously not pressed box's output
// button
lineCurrentX = (int) event.getX();
lineCurrentY = (int) event.getY();
Box boxHovered = getBoxTouched((int) event.getX(),
(int) event.getY());
if (boxHovered != null) {
// if we have drawned a line on another box
buttonHovered = boxHovered.isButton((int) event.getX(),
(int) event.getY());
if (buttonHovered != -1) {
// if we have drawned a line on another's box's button
if (buttonHovered < boxHovered.getNoOfInputs()
&& !boxHovered.isPressed(buttonHovered)
&& !box.equals(boxHovered)) {
// if we have drawned a line on another's box's
// input button
int[] center = boxHovered
.getButtonCenter(buttonHovered);
lineStartX = center[0];
lineStartY = center[1];
boxHovered.setButtonPressed(buttonHovered);
drawingline = false;
BoxButtonPair[] line = {
new BoxButtonPair(box, buttonPressed),
new BoxButtonPair(boxHovered, buttonHovered) };
lines.add(line);
SavedState.addLine(line);
foundPair = true;
}
}
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
drawingline = false;
selectedBox = null;
// if when drawing a line stops and we haven'd reached another box's
// input button then erase the line and unpress the button
if (!foundPair && buttonPressed != -1 && box != null)
if (!((buttonPressed + 1) <= box.getNoOfInputs()))
box.unsetButtonPressed(buttonPressed);
foundPair = false;
pressedX = pressedY = originalX = originalY = 0;
// TODO implement here to pou peftei
invalidate();
return false;
}
return true;
}
|
diff --git a/lib-viewsupport/src/com/garlicg/cutinlib/viewsupport/SimpleCutinScreen.java b/lib-viewsupport/src/com/garlicg/cutinlib/viewsupport/SimpleCutinScreen.java
index 5c27e80..e592cea 100644
--- a/lib-viewsupport/src/com/garlicg/cutinlib/viewsupport/SimpleCutinScreen.java
+++ b/lib-viewsupport/src/com/garlicg/cutinlib/viewsupport/SimpleCutinScreen.java
@@ -1,241 +1,243 @@
package com.garlicg.cutinlib.viewsupport;
import java.util.ArrayList;
import java.util.List;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ServiceInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.garlicg.cutinlib.CutinInfo;
import com.garlicg.cutinlib.CutinItem;
import com.garlicg.cutinlib.CutinService;
import com.garlicg.cutinlib.Demo;
public class SimpleCutinScreen{
public final static int STATE_VIEW = 0;
public final static int STATE_PICK = 1;
private int mState = STATE_VIEW;
private View mViewParent;
private PickListener mListener;
private Demo mDemo;
private View mGetView;
private ListView mListView;
private Context mContext;
public SimpleCutinScreen(Context context , Intent intent){
mContext = context;
mViewParent = LayoutInflater.from(context).inflate(R.layout.cutin_simple_screen, null);
mDemo = new Demo(context);
String action = intent.getAction();
if(!TextUtils.isEmpty(action) && action.equals(CutinInfo.ACTION_PICK_CUTIN)){
// Call from official cut-in app
mState = STATE_PICK;
}
else{
mState = STATE_VIEW;
}
// setupListView
mListView = (ListView)mViewParent.findViewById(R.id.__cutin_simple_ListView);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Object item = arg0.getItemAtPosition(arg2);
if(item instanceof CutinItem){
CutinItem ci = (CutinItem)item;
mDemo.play(ci.serviceClass , ci.cutinId);
}
else if(arg2 == 0 && mGetView != null){
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.garlicg.cutin"));
mContext.startActivity(intent);
}
}
});
if(existManager(context)){
mListView.addHeaderView(newPaddingView(context));
}
else{
mGetView = LayoutInflater.from(context).inflate(R.layout.cutin_get_manager,null);
mListView.addHeaderView(mGetView);
}
mListView.addFooterView(newPaddingView(context));
}
private View newPaddingView(Context context){
View padding = new View(context);
ListView.LayoutParams padding8 = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT,dpToPx(context.getResources(),8));
padding.setLayoutParams(padding8);
return padding;
}
private int dpToPx(Resources res , int dp){
return (int)(res.getDisplayMetrics().density * dp + 0.5f);
}
private boolean existManager(Context context){
PackageManager pm = context.getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.garlicg.cutin");
return intent != null;
}
public View getView(){
return mViewParent;
}
public int getState(){
return mState;
}
public interface PickListener{
public void ok(Intent intent);
public void cancel();
}
public void setListener(PickListener listener){
mListener = listener;
}
public void resume(){
// remove view after get the manager app from this.
if(existManager(mContext) && mGetView != null){
mListView.removeHeaderView(mGetView);
}
}
public void pause(){
mDemo.forceStop();
}
public void setCutinList(ArrayList<CutinItem> list){
mListView = (ListView)mViewParent.findViewById(R.id.__cutin_simple_ListView);
// launched from launcher ,etc
if(mState == STATE_VIEW){
SimpleCutinAdapter adapter = new SimpleCutinAdapter(mViewParent.getContext(), R.layout.cutin_list_item_1,list);
mListView.setAdapter(adapter);
}
// launched from manage app
else if(mState == STATE_PICK){
// Set ListView with SingleChoiceMode.
SimpleCutinAdapter adapter = new SimpleCutinAdapter(mViewParent.getContext(), R.layout.cutin_list_item_single_choice,list);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// inflate footer
ViewStub stub = (ViewStub)mViewParent.findViewById(R.id.__cutin_simple_PickerFrame);
View bottomFrame = stub.inflate();
// OK button
View okButton = bottomFrame.findViewById(R.id.__cutin_okButton);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mListener != null){
int position = mListView.getCheckedItemPosition();
Object item = mListView.getItemAtPosition(position);
if(item != null && item instanceof CutinItem){
CutinItem ci = (CutinItem)item;
mListener.ok(CutinInfo.buildPickedIntent(ci));
}
else {
// no selected item
}
}
}
});
// Cancel button
View cancel = bottomFrame.findViewById(R.id.__cutin_cancelButton);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mListener != null){
mListener.cancel();
}
}
});
}
}
private class SimpleCutinAdapter extends ArrayAdapter<CutinItem>{
private Drawable[] mDrawables;
private final int RESOURCE_ID;
LayoutInflater mInflater;
public SimpleCutinAdapter(Context context, int resource,
List<CutinItem> objects) {
super(context, resource, android.R.id.text1,objects);
RESOURCE_ID = resource;
mInflater = LayoutInflater.from(context);
if(objects != null){
mDrawables = new Drawable[objects.size()];
int size = mDrawables.length;
PackageManager pm = context.getPackageManager();
for(int i = 0 ; i < size ; i++){
mDrawables[i] = getServiceIcon(objects.get(i).serviceClass, pm);
}
}
}
private Drawable getServiceIcon(Class<? extends CutinService> serviceClass ,PackageManager pm){
Drawable icon = null;
if(serviceClass != null){
try {
Resources res = getContext().getResources();
ServiceInfo si = pm.getServiceInfo(new ComponentName(getContext(), serviceClass), 0);
icon = res.getDrawable(si.icon);
int bond = (int)(res.getDisplayMetrics().density * 48 + 0.5f);
icon.setBounds(0, 0, bond,bond );
} catch (NameNotFoundException e) {
+ } catch (Resources.NotFoundException e) {
}
+
}
return icon;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null){
view = mInflater.inflate(RESOURCE_ID, null);
}
CutinItem item = getItem(position);
TextView text = (TextView)view.findViewById(android.R.id.text1);
text.setText(item.cutinName);
if(mDrawables[position] != null){
text.setCompoundDrawables(mDrawables[position],null, null, null);
}
else{
text.setCompoundDrawables(null,null, null, null);
}
return view;
}
}
}
| false | false | null | null |
diff --git a/mifos/src/org/mifos/application/accounts/loan/struts/action/LoanDisbursmentAction.java b/mifos/src/org/mifos/application/accounts/loan/struts/action/LoanDisbursmentAction.java
index 9a0c8aa40..5fea68a58 100644
--- a/mifos/src/org/mifos/application/accounts/loan/struts/action/LoanDisbursmentAction.java
+++ b/mifos/src/org/mifos/application/accounts/loan/struts/action/LoanDisbursmentAction.java
@@ -1,210 +1,207 @@
/**
*
*/
package org.mifos.application.accounts.loan.struts.action;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.mifos.application.accounts.exceptions.AccountException;
import org.mifos.application.accounts.loan.business.LoanBO;
import org.mifos.application.accounts.loan.business.service.LoanBusinessService;
import org.mifos.application.accounts.loan.struts.actionforms.LoanDisbursmentActionForm;
import org.mifos.application.accounts.loan.util.helpers.LoanConstants;
import org.mifos.application.accounts.loan.util.helpers.LoanExceptionConstants;
import org.mifos.application.master.business.service.MasterDataService;
import org.mifos.application.master.util.helpers.MasterConstants;
import org.mifos.application.personnel.business.PersonnelBO;
import org.mifos.application.personnel.persistence.PersonnelPersistence;
import org.mifos.application.util.helpers.TrxnTypes;
import org.mifos.framework.business.service.BusinessService;
import org.mifos.framework.business.service.ServiceFactory;
import org.mifos.framework.exceptions.ServiceException;
import org.mifos.framework.security.util.ActionSecurity;
import org.mifos.framework.security.util.UserContext;
import org.mifos.framework.security.util.resources.SecurityConstants;
import org.mifos.framework.struts.action.BaseAction;
import org.mifos.framework.util.helpers.BusinessServiceName;
import org.mifos.framework.util.helpers.CloseSession;
import org.mifos.framework.util.helpers.Constants;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.framework.util.helpers.SessionUtils;
import org.mifos.framework.util.helpers.TransactionDemarcate;
public class LoanDisbursmentAction extends BaseAction {
private LoanBusinessService loanBusinessService = null;
private MasterDataService masterDataService = null;
public static ActionSecurity getSecurity() {
ActionSecurity security = new ActionSecurity("loanDisbursmentAction");
security.allow("load", SecurityConstants.LOAN_CAN_DISBURSE_LOAN);
security.allow("preview", SecurityConstants.VIEW);
security.allow("previous", SecurityConstants.VIEW);
security.allow("update", SecurityConstants.VIEW);
return security;
}
@TransactionDemarcate(joinToken = true)
public ActionForward load(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserContext uc = (UserContext) SessionUtils.getAttribute(
Constants.USER_CONTEXT_KEY, request.getSession());
LoanDisbursmentActionForm loanDisbursmentActionForm = (LoanDisbursmentActionForm) form;
loanDisbursmentActionForm.clear();
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = ((LoanBusinessService) getService()).getAccount(Integer
.valueOf(loanDisbursmentActionForm.getAccountId()));
checkIfProductsOfferingCanCoexist(mapping,form,request,response);
SessionUtils.setAttribute(LoanConstants.PROPOSEDDISBDATE, loan
.getDisbursementDate(), request);
loanDisbursmentActionForm.setTransactionDate(DateUtils.getUserLocaleDate(getUserContext(request).getPreferredLocale(), SessionUtils.getAttribute(
LoanConstants.PROPOSEDDISBDATE, request)
.toString()));
loan.setUserContext(uc);
SessionUtils.setAttribute(Constants.BUSINESS_KEY, loan, request);
SessionUtils.setCollectionAttribute(MasterConstants.PAYMENT_TYPE,
getMasterDataService().getSupportedPaymentModes(
uc.getLocaleId(),
TrxnTypes.loan_disbursement.getValue()), request);
loanDisbursmentActionForm.setAmount(loan
.getAmountTobePaidAtdisburtail(currentDate));
loanDisbursmentActionForm.setLoanAmount(loan.getLoanAmount());
return mapping.findForward(Constants.LOAD_SUCCESS);
}
private void checkIfProductsOfferingCanCoexist(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoanDisbursmentActionForm loanDisbursmentActionForm = (LoanDisbursmentActionForm) form;
LoanBO newloan = ((LoanBusinessService) getService()).getAccount(Integer
.valueOf(loanDisbursmentActionForm.getAccountId()));
List<LoanBO> loanList = ((LoanBusinessService) getService())
.getLoanAccountsActiveInGoodBadStanding(newloan.getCustomer().getCustomerId());
// Check if the client has an active loan accounts
if(null!=loanList){
for (LoanBO oldloan : loanList){
// Check if the new loan product to disburse is allowed to the existent active loan product
if(!oldloan.prdOfferingsCanCoexist(newloan.getLoanOffering().getPrdOfferingId()))
{
- ActionErrors errors = new ActionErrors();
String[] param={oldloan.getLoanOffering().getPrdOfferingName(),newloan.getLoanOffering().getPrdOfferingName()};
- errors.add(LoanExceptionConstants.LOANCOULDNOTCOEXIST,new ActionMessage(LoanExceptionConstants.LOANCOULDNOTCOEXIST,param));
-
- throw new AccountException(LoanExceptionConstants.LOANCOULDNOTCOEXIST);
+ throw new AccountException(LoanExceptionConstants.LOANCOULDNOTCOEXIST,param);
}
}
}
}
@TransactionDemarcate(joinToken = true)
public ActionForward preview(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return mapping.findForward(Constants.PREVIEW_SUCCESS);
}
@TransactionDemarcate(joinToken = true)
public ActionForward previous(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return mapping.findForward(Constants.PREVIOUS_SUCCESS);
}
@TransactionDemarcate(validateAndResetToken = true)
@CloseSession
public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoanBO savedloan = (LoanBO) SessionUtils.getAttribute(
Constants.BUSINESS_KEY, request);
LoanDisbursmentActionForm actionForm = (LoanDisbursmentActionForm) form;
LoanBO loan = ((LoanBusinessService) getService()).getAccount(Integer
.valueOf(actionForm.getAccountId()));
checkVersionMismatch(savedloan.getVersionNo(),loan.getVersionNo());
loan.setVersionNo(savedloan.getVersionNo());
UserContext uc = (UserContext) SessionUtils.getAttribute(
Constants.USER_CONTEXT_KEY, request.getSession());
Date trxnDate = getDateFromString(actionForm.getTransactionDate(), uc
.getPreferredLocale());
trxnDate = DateUtils.getDateWithoutTimeStamp(trxnDate.getTime());
Date receiptDate = getDateFromString(actionForm.getReceiptDate(), uc
.getPreferredLocale());
PersonnelBO personnel = new PersonnelPersistence().getPersonnel(uc
.getId());
if (!loan.isTrxnDateValid(trxnDate))
throw new AccountException("errors.invalidTxndate");
if (actionForm.getPaymentModeOfPayment() != null
&& actionForm.getPaymentModeOfPayment().equals(""))
loan.disburseLoan(actionForm.getReceiptId(), trxnDate, Short
.valueOf(actionForm.getPaymentTypeId()), personnel,
receiptDate, Short.valueOf(actionForm
.getPaymentModeOfPayment()));
else
loan.disburseLoan(actionForm.getReceiptId(), trxnDate, Short
.valueOf(actionForm.getPaymentTypeId()), personnel,
receiptDate, Short.valueOf("1"));
return mapping.findForward(Constants.UPDATE_SUCCESS);
}
private LoanBusinessService getLoanBusinessService()
throws ServiceException {
if (loanBusinessService == null) {
loanBusinessService = new LoanBusinessService();
}
return loanBusinessService;
}
private MasterDataService getMasterDataService() throws ServiceException {
if (masterDataService == null)
masterDataService = (MasterDataService) ServiceFactory
.getInstance().getBusinessService(
BusinessServiceName.MasterDataService);
return masterDataService;
}
@TransactionDemarcate(joinToken = true)
public ActionForward validate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String method = (String) request.getAttribute("methodCalled");
String forward = null;
if (method != null) {
forward = method + "_failure";
}
return mapping.findForward(forward);
}
@Override
protected BusinessService getService() throws ServiceException {
return getLoanBusinessService();
}
@Override
protected boolean skipActionFormToBusinessObjectConversion(String method) {
return true;
}
@Override
protected boolean isNewBizRequired(HttpServletRequest request)
throws ServiceException {
return false;
}
}
| false | false | null | null |
diff --git a/src/com/felixware/gw2w/MainActivity.java b/src/com/felixware/gw2w/MainActivity.java
index 24b1ef5..8acd56d 100644
--- a/src/com/felixware/gw2w/MainActivity.java
+++ b/src/com/felixware/gw2w/MainActivity.java
@@ -1,564 +1,565 @@
package com.felixware.gw2w;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnActionExpandListener;
import com.felixware.gw2w.adapters.DropDownAdapter;
import com.felixware.gw2w.fragments.FirstLoadFragment;
import com.felixware.gw2w.fragments.ImageDialogFragment;
import com.felixware.gw2w.http.RequestTask;
import com.felixware.gw2w.http.WebService;
import com.felixware.gw2w.http.WebService.GetContentListener;
import com.felixware.gw2w.http.WebService.GetSearchResultsListener;
import com.felixware.gw2w.http.WebServiceException;
import com.felixware.gw2w.listeners.MainListener;
import com.felixware.gw2w.utilities.ArticleWebViewClient;
import com.felixware.gw2w.utilities.Constants;
import com.felixware.gw2w.utilities.Dialogs;
import com.felixware.gw2w.utilities.Language;
import com.felixware.gw2w.utilities.PrefsManager;
import com.felixware.gw2w.utilities.Regexer;
public class MainActivity extends SherlockFragmentActivity implements OnNavigationListener, OnActionExpandListener, OnClickListener, MainListener, OnEditorActionListener, GetContentListener, GetSearchResultsListener, OnItemClickListener, OnFocusChangeListener {
private WebView mWebContent;
private RelativeLayout mNavBar, mWebSpinner;
private EditText mSearchBox;
private TextView mPageTitle;
private ImageButton mSearchBtn;
private ImageView mFavoriteBtn;
private ProgressBar mSearchSpinner;
private Boolean isGoingBack = false, isNotSelectedResult = true, isFavorite = false, isFirstLoad = true, isRotating = false;
private List<String> backHistory = new ArrayList<String>(), favorites = new ArrayList<String>();
private String currentPageTitle;
private List<String> currentPageCategories;
private Handler mSearchHandle;
private ListView mSearchResultsListView;
private DropDownAdapter mAdapter;
private ActionBar mActionBar;
private MenuItem mSearch;
private View mSearchView;
private FrameLayout dummyView, firstLoadLayout;
private InputMethodManager imm;
private String[] languages;
private String[] langCodes;
private Dialogs mDialogs;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main_activity, menu);
mSearch = menu.findItem(R.id.search);
mSearchView = (View) mSearch.getActionView();
mSearch.setOnActionExpandListener(this);
mSearchBox = (EditText) mSearchView.findViewById(R.id.searchET);
mSearchBox.setOnEditorActionListener(this);
mSearchBox.addTextChangedListener(new SearchTextWatcher(mSearchBox));
mSearchBox.setOnFocusChangeListener(this);
mSearchBtn = (ImageButton) mSearchView.findViewById(R.id.searchBtn);
mSearchBtn.setOnClickListener(this);
mSearchSpinner = (ProgressBar) mSearchView.findViewById(R.id.spinner);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.favorites:
favorites = Constants.getFavoritesListFromJSON(this);
if (favorites.isEmpty()) {
mDialogs.buildNoFavoritesDialog();
} else {
mDialogs.buildFavoritesDialog(favorites);
}
return true;
case R.id.share:
shareArticle();
return true;
}
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mActionBar = getSupportActionBar();
imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
languages = getResources().getStringArray(R.array.Settings_wiki_languages);
langCodes = getResources().getStringArray(R.array.Settings_wiki_langcodes);
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
mDialogs = new Dialogs(this);
bindViews();
if (isFirstLoad) {
isFirstLoad = false;
firstLoadLayout.bringToFront();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.firstLoadLayout, new FirstLoadFragment());
ft.commit();
}
mSearchHandle = new Handler();
mWebContent = (WebView) findViewById(R.id.webContent);
mWebContent.setWebViewClient(new ArticleWebViewClient(this));
if (savedInstanceState != null) {
if (mWebContent.restoreState(savedInstanceState) == null) {
// Log.i("Something broke", "Dang");
}
} else if (getIntent().getDataString() != null) {
// open URI directly
Uri uri = getIntent().getData();
String title = null;
if (uri.getPath().startsWith("/wiki/"))
title = uri.getPath().substring(6);
else
title = uri.getQueryParameter("title");
// fallback to start page
if (title == null)
getContent(Constants.getStartPage(this));
// change language to match URI
String languageTag = uri.getHost().substring(4, uri.getHost().indexOf('.'));
if (languageTag.equals(Language.GERMAN.getSubdomainSuffix()))
PrefsManager.getInstance(this).setLanguage(Language.GERMAN);
else if (languageTag.equals(Language.FRENCH.getSubdomainSuffix()))
PrefsManager.getInstance(this).setLanguage(Language.FRENCH);
else if (languageTag.equals(Language.SPANISH.getSubdomainSuffix()))
PrefsManager.getInstance(this).setLanguage(Language.SPANISH);
else
PrefsManager.getInstance(this).setLanguage(Language.ENGLISH);
// open article
getContent(title);
} else {
getContent(Constants.getStartPage(this));
}
mActionBar.setSelectedNavigationItem(PrefsManager.getInstance(this).getWikiLanguage());
}
private void bindViews() {
dummyView = (FrameLayout) findViewById(R.id.dummy);
firstLoadLayout = (FrameLayout) findViewById(R.id.firstLoadLayout);
mSearchResultsListView = (ListView) findViewById(R.id.searchResultsListView);
mSearchResultsListView.setOnItemClickListener(this);
mNavBar = (RelativeLayout) findViewById(R.id.navBar);
mNavBar.bringToFront();
mWebSpinner = (RelativeLayout) findViewById(R.id.webSpinnerLayout);
mFavoriteBtn = (ImageView) findViewById(R.id.favoritesBtn);
mFavoriteBtn.setOnClickListener(this);
mPageTitle = (TextView) findViewById(R.id.pageTitle);
switch (getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_PORTRAIT:
mAdapter = new DropDownAdapter(this, languages, langCodes, DropDownAdapter.ORIENTATION_PORTRAIT);
mActionBar.setSelectedNavigationItem(PrefsManager.getInstance(this).getWikiLanguage());
break;
case Configuration.ORIENTATION_LANDSCAPE:
mAdapter = new DropDownAdapter(this, languages, langCodes, DropDownAdapter.ORIENTATION_LANDSCAPE);
mActionBar.setSelectedNavigationItem(PrefsManager.getInstance(this).getWikiLanguage());
break;
}
mActionBar.setListNavigationCallbacks(mAdapter, this);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
isRotating = true;
mActionBar.setListNavigationCallbacks(mAdapter, null);
switch (newConfig.orientation) {
case Configuration.ORIENTATION_PORTRAIT:
mAdapter = new DropDownAdapter(this, languages, langCodes, DropDownAdapter.ORIENTATION_PORTRAIT);
break;
case Configuration.ORIENTATION_LANDSCAPE:
mAdapter = new DropDownAdapter(this, languages, langCodes, DropDownAdapter.ORIENTATION_LANDSCAPE);
break;
}
mActionBar.setListNavigationCallbacks(mAdapter, this);
mActionBar.setSelectedNavigationItem(PrefsManager.getInstance(this).getWikiLanguage());
isRotating = false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (backHistory.size() > 1) {
navigateBack();
return true;
}
break;
}
return super.onKeyUp(keyCode, event);
}
private void navigateBack() {
backHistory.remove(backHistory.size() - 1);
getContent(backHistory.get(backHistory.size() - 1));
isGoingBack = true;
}
protected void onSaveInstanceState(Bundle outState) {
mWebContent.saveState(outState);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.searchBtn:
searchForTerm();
break;
case R.id.favoritesBtn:
if (currentPageTitle != null) {
if (!isFavorite) {
favorites.add(currentPageTitle);
PrefsManager.getInstance(this).setFavorites(Constants.getJSONStringFromList(favorites));
mFavoriteBtn.setImageResource(R.drawable.nav_favorites_on);
isFavorite = true;
} else {
favorites.remove(currentPageTitle);
PrefsManager.getInstance(this).setFavorites(Constants.getJSONStringFromList(favorites));
mFavoriteBtn.setImageResource(R.drawable.nav_favorites_off);
isFavorite = false;
}
}
break;
}
}
public void getContent(String title) {
if (title == null || title.equals(""))
return;
WebService.getInstance(this).cancelAllRequests();
mWebSpinner.setVisibility(View.VISIBLE);
if (PrefsManager.getInstance(this).getLanguage() == Language.ENGLISH) {
WebService.getInstance(this).getTitleEnglish(this, title);
} else {
WebService.getInstance(this).getContent(this, title);
}
}
private void searchForTerm() {
getContent(mSearchBox.getText().toString());
mSearch.collapseActionView();
}
@Override
public void onLink(String url) {
Matcher matcher = Pattern.compile("(?<=wiki/).*").matcher(url);
- matcher.find();
- getContent(matcher.group());
+ if (matcher.find()) {
+ getContent(matcher.group());
+ }
}
@Override
public void onExternalLink(String url) {
if (PrefsManager.getInstance(this).getExternalWarning()) {
mDialogs.buildExternalLinkDialog(url);
} else {
externalLink(url);
}
}
@Override
public void onExternalOkay(String url) {
externalLink(url);
}
public void externalLink(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
@Override
public void onShowCategories() {
mDialogs.buildCategoriesDialog(currentPageCategories);
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
searchForTerm();
return true;
}
return false;
}
@Override
public void onRequestError(RequestTask request, WebServiceException e) {
if (mSearchSpinner != null) {
mSearchSpinner.setVisibility(View.INVISIBLE);
}
mWebSpinner.setVisibility(View.GONE);
firstLoadLayout.removeAllViews();
firstLoadLayout.setVisibility(View.GONE);
mDialogs.buildErrorDialog(e.getErrorCode());
}
@Override
public void didGetContent(RequestTask request, String content, String title) {
StringBuilder html = new StringBuilder("<!DOCTYPE html><html><head>");
html.append("<title>GW2W</title>");
// load default site styles
html.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
html.append(Constants.getBaseURL(this) + "/index.php?title=MediaWiki:Common.css&action=raw&ctype=text/css");
html.append("\" />");
// load custom styles
html.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/style.css\" />");
html.append("</head><body><main>");
html.append(Regexer.strip(content));
html.append("</main>");
// category list
if (currentPageCategories != null && currentPageCategories.size() > 0) {
html.append("<a id=\"android-category-list\" href=\"about:categories\">");
html.append(TextUtils.htmlEncode(getString(R.string.categories, currentPageCategories.size())));
html.append("</a>");
}
html.append("</body></html>");
mWebContent.loadDataWithBaseURL(Constants.getBaseURL(this), html.toString(), "text/html", "UTF-8", title);
mPageTitle.setText(title);
// Log.i("checking titles", "current page title is " + currentPageTitle + " new title is " + title);
if (!isGoingBack && (currentPageTitle == null || !currentPageTitle.equals(title))) {
// Log.i("back history", "Adding " + title + " to the back history");
backHistory.add(title);
} else {
isGoingBack = false;
}
currentPageTitle = title;
mFavoriteBtn.setImageResource(R.drawable.nav_favorites_off);
isFavorite = false;
determineFavoriteStatus();
mWebSpinner.setVisibility(View.GONE);
firstLoadLayout.removeAllViews();
firstLoadLayout.setVisibility(View.GONE);
}
@Override
public void didGetFileUrl(RequestTask request, String url, String title) {
mWebSpinner.setVisibility(View.GONE);
ImageDialogFragment.newInstance(url).show(getSupportFragmentManager(), "dialog");
}
@Override
public void didGetCategories(RequestTask request, List<String> categories, String title) {
currentPageCategories = categories;
}
private void determineFavoriteStatus() {
favorites = Constants.getFavoritesListFromJSON(this);
for (String pageName : favorites) {
if (pageName.equals(currentPageTitle)) {
isFavorite = true;
mFavoriteBtn.setImageResource(R.drawable.nav_favorites_on);
break;
}
}
}
private void shareArticle() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
String pageURL = getPageURL().replace(" ", "_");
// most options will be able to use key Intent.EXTRA_TEXT
shareIntent.putExtra(Intent.EXTRA_TEXT, pageURL);
// sms sharing requires the message to be in key sms_body
shareIntent.putExtra("sms_body", pageURL);
shareIntent.setType("text/plain");
// Log.i("Sharing", pageURL);
startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share_picker_title)));
}
private String getPageURL() {
return new String(Constants.getBaseURL(this) + File.separator + currentPageTitle);
}
@Override
protected void onPause() {
super.onPause();
WebService.getInstance(this).cancelAllRequests();
if (mSearchSpinner != null) {
mSearchSpinner.setVisibility(View.GONE);
}
if (mWebSpinner != null) {
mWebSpinner.setVisibility(View.GONE);
}
}
private class SearchTextWatcher implements TextWatcher {
private Runnable mSearchRunnable;
public SearchTextWatcher(final EditText e) {
mSearchRunnable = new Runnable() {
public void run() {
String searchText = e.getText().toString().trim();
if (searchText != null && searchText.length() > 1) {
mSearchSpinner.setVisibility(View.VISIBLE);
WebService.getInstance(MainActivity.this).getSearchResults(MainActivity.this, searchText, 10);
} else {
}
}
};
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// nothing
}
@Override
public void afterTextChanged(Editable s) {
if (isNotSelectedResult) {
try {
mSearchHandle.removeCallbacks(mSearchRunnable);
mSearchHandle.postDelayed(mSearchRunnable, 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Override
public void didGetSearchResults(RequestTask request, List<String> list) {
mSearchSpinner.setVisibility(View.INVISIBLE);
mSearchResultsListView.setVisibility(View.VISIBLE);
mPageTitle.setText(R.string.search_results);
mSearchResultsListView.setAdapter(new ArrayAdapter<String>(this, R.layout.search_results_item, list));
}
@Override
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
mSearch.collapseActionView();
getContent(((TextView) v).getText().toString());
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
switch (v.getId()) {
case R.id.searchET:
if (hasFocus) {
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
} else {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
break;
default:
break;
}
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (PrefsManager.getInstance(this).getWikiLanguage() != itemPosition && !isRotating) {
PrefsManager.getInstance(this).setWikiLanguage(itemPosition);
backHistory.clear();
mWebContent.clearView();
mFavoriteBtn.setImageResource(R.drawable.nav_favorites_off);
currentPageTitle = null;
mPageTitle.setText("");
getContent(Constants.getStartPage(this));
}
return false;
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
mSearchBox.getSelectionStart();
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
mSearchSpinner.setVisibility(View.INVISIBLE);
mSearchBox.setText("");
dummyView.requestFocus();
mSearchResultsListView.setVisibility(View.GONE);
mPageTitle.setText(currentPageTitle);
return true;
}
}
| true | false | null | null |
diff --git a/src/main/java/com/gnapse/metric/CurrencyLoader.java b/src/main/java/com/gnapse/metric/CurrencyLoader.java
index 5f4dce6..c64a8cb 100644
--- a/src/main/java/com/gnapse/metric/CurrencyLoader.java
+++ b/src/main/java/com/gnapse/metric/CurrencyLoader.java
@@ -1,286 +1,294 @@
/*
* Copyright (C) 2012 Gnapse.com
*
* 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.gnapse.metric;
import com.gnapse.common.inflector.Inflectors;
import com.gnapse.common.inflector.Rule;
import com.gnapse.common.math.BigFraction;
import com.gnapse.common.math.Factorization;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.io.Files;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* A class responsible for loading currency exchange rates information and building the money
* property, which has currencies as its units. This allows a {@link Universe} to perform
* conversions between currencies. Supports loading the currency definitions and exchange rates
* remotely from the Internet and keeps a local copy that is reused whenever possible and updated
* when the local version is old enough and there's an Internet connection.
*
* @author Ernesto García
*/
final class CurrencyLoader {
private final Property property;
private final Universe universe;
private final File currencyFile;
private static final Logger LOGGER = Logger.getLogger(CurrencyLoader.class.getName());
/**
* The number of milliseconds in an hour.
*/
private static final long ONE_HOUR = 3600 * 1000;
/**
* The URL where the currency names are loaded from remotely.
*/
private static final String CURRENCY_NAMES_URL
= "http://openexchangerates.org/currencies.json";
/**
* The URL where the currency exchange rates are loaded from remotely.
*/
private static final String LATEST_EXCHANGE_RATES_URL
= "http://openexchangerates.org/latest.json";
/**
* A set of currency names that will be ignored if they exist in the currency definitions file.
*
* <p>This is a temporary solution to avoid importing currencies with names that clash with the
* names of existing units from other properties (e.g. CUP, the Cuban Peso).</p>
*/
private static final Set<String> IGNORED_CURRENCIES = Collections.unmodifiableSet(
new HashSet<String>(Arrays.asList("CUP")));
/**
* A map that defines extra custom names for certain currency codes.
*/
private final Multimap<String, String> currencyAliases;
/*
* Add some custom pluralization rules to properly handle a few problematic currency names.
*/
static {
Inflectors.getPluralInflector().addRules(new Rule[] {
Rule.irregulars(new String[][] {
{ "CFA Franc BCEAO", "CFA Francs BCEAO" },
}),
Rule.inflectSuffix("\\b(lita)s", "$3i"),
Rule.inflectSuffix("\\b(lat)s", "$3i"),
Rule.inflectSuffix("\\b(boliviano)", "$3s"),
});
}
/**
* Loads currency definitions for the given universe (either locally or remotely) and builds a
* new property with all the loaded currency as its units. The new property will have the
* given names.
*/
CurrencyLoader(Universe universe, List<String> names, Multimap<String, String> currencyAliases)
throws MetricException {
this.universe = universe;
this.currencyAliases = currencyAliases;
this.currencyFile = universe.getCurrencyFile();
try {
JSONObject currencyDefinitions = loadCurrencyDefinitions();
Iterable<UnitDefinition> unitDefs = createUnitDefinitions(currencyDefinitions);
property = new Property(universe, names);
for (UnitDefinition def : unitDefs) {
property.addUnits(def);
}
property.freezeUnits();
} catch (Exception e) {
- throw MetricException.wrapper("Error while loading currency definitions", e);
+ Throwables.propagateIfInstanceOf(e, MetricException.class);
+ throw Throwables.propagate(e);
}
}
/**
* The money property built by this currency loader.
*/
public Property getProperty() {
return property;
}
/**
* The universe for which this currency loader performs its task.
*/
public Universe getUniverse() {
return universe;
}
/**
* Creates a list of unit definitions from the JSON currency specification.
* @param map the JSON currency specification, already parsed and loaded as a {@link Map}.
* @return the resulting list of unit definitions
*/
private List<UnitDefinition> createUnitDefinitions(JSONObject map) {
final Map names = (Map) map.get("names");
final Map rates = (Map) map.get("rates");
final String baseUnitCode = (String) map.get("base");
final Factorization<String> baseUnitFactors = Factorization.factor(baseUnitCode, 1);
final List<UnitDefinition> result = new ArrayList<UnitDefinition>(rates.size());
String code = baseUnitCode;
String name = (String) names.get(code);
BigFraction rate = BigFraction.ONE;
result.add(newUnitDef(code, name, null, rate));
for (Object obj : rates.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
+
code = (String) entry.getKey();
if (code.equals(baseUnitCode) || IGNORED_CURRENCIES.contains(code)) {
continue;
}
+
name = (String) names.get(code);
+ if (name == null) {
+ continue;
+ }
+
rate = BigFraction.valueOf((Number) entry.getValue());
if (rate.equals(BigFraction.ZERO)) {
continue;
}
+
result.add(newUnitDef(code, name, baseUnitFactors, rate.reciprocal()));
}
return result;
}
/**
* Convenience helper method that creates a new unit definition from the given information.
*/
private UnitDefinition newUnitDef(String code, String name,
Factorization<String> baseUnitFactors, BigFraction rate) {
List<String> shortNames = Arrays.asList(code, code.toLowerCase());
List<String> longNames = Lists.newArrayList(name, name.toLowerCase());
longNames.addAll(currencyAliases.get(code));
return new UnitDefinition(longNames, shortNames, baseUnitFactors, rate, null, null);
}
/**
* Loads the currency definitions from the currency file, and updates it from the remote sources
* if the local version is older than a day, or if there's no local cached version yet.
*
* @return the loaded JSON content already converted to a {@link Map}.
* @throws IOException if there's a problem reading the file, or loading the updated remote
* definitions
* @throws ParseException if there's a problem while parsing the JSON file or the remote version
*/
private JSONObject loadCurrencyDefinitions() throws IOException, ParseException {
JSONObject result = loadLocalCurrencyDefinitions();
if (result == null) {
result = loadRemoteCurrencyDefinitions();
}
boolean isLocal = (Boolean) result.get("local");
double timestamp = ((Number) result.get("timestamp")).longValue() * 1000;
Date today = new Date();
if (isLocal && today.getTime() - timestamp > ONE_HOUR) {
try {
result = loadRemoteCurrencyDefinitions();
isLocal = false;
} catch (Exception e) {
LOGGER.info("Could not load currency exchange rates remotely");
}
}
if (!isLocal) {
try {
Files.write(result.toJSONString(), currencyFile, Charsets.UTF_8);
} catch (IOException e) {
LOGGER.warning("Could not save remote exchange rates locally");
}
}
LOGGER.info(String.format(
"Currency exchange rates were loaded %s", isLocal ? "locally" : "remotely"));
return result;
}
/**
* Loads the remote currency definitions.
*/
@SuppressWarnings(value = {"unchecked"})
private JSONObject loadRemoteCurrencyDefinitions() throws IOException, ParseException {
try {
URL currencyNamesURL = new URL(CURRENCY_NAMES_URL);
URL latestExchangeRatesURL = new URL(LATEST_EXCHANGE_RATES_URL);
JSONObject currencyNames = loadJSON(currencyNamesURL.openStream());
JSONObject latestExchangeRates = loadJSON(latestExchangeRatesURL.openStream());
latestExchangeRates.put("names", currencyNames);
latestExchangeRates.put("local", false);
LOGGER.fine("Remote currency exchange rates were loaded successfully");
return latestExchangeRates;
} catch (MalformedURLException ex) {
throw Throwables.propagate(ex);
}
}
/**
* Loads the currency definitions from the local file.
*/
@SuppressWarnings(value = "unchecked")
private JSONObject loadLocalCurrencyDefinitions() {
try {
InputStream in = new FileInputStream(currencyFile);
JSONObject result = loadJSON(in);
result.put("local", true);
LOGGER.fine("Cached currency exchange rates were loaded successfully");
return result;
} catch (Exception ex) {
LOGGER.info("Could not load cached currency exchange rates");
return null;
}
}
/**
* Loads and parses the JSON code from the given input stream.
*/
private static JSONObject loadJSON(InputStream in) throws IOException, ParseException {
Reader reader = new InputStreamReader(in, Charsets.UTF_8);
JSONParser parser = new JSONParser();
return (JSONObject) parser.parse(reader);
}
}
diff --git a/src/main/java/com/gnapse/metric/Parser.java b/src/main/java/com/gnapse/metric/Parser.java
index a140ba3..effe0ff 100755
--- a/src/main/java/com/gnapse/metric/Parser.java
+++ b/src/main/java/com/gnapse/metric/Parser.java
@@ -1,565 +1,574 @@
/*
* Copyright (C) 2012 Gnapse.com
*
* 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.gnapse.metric;
import static com.gnapse.common.inflector.Inflectors.pluralOf;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.gnapse.common.math.BigFraction;
import com.gnapse.common.math.Factorization;
import com.gnapse.common.parser.SyntaxError;
import com.gnapse.common.parser.Tokenizer;
import com.gnapse.common.parser.Tokenizer.Token;
import com.gnapse.common.parser.Tokenizer.TokenType;
import com.google.common.base.Joiner;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
/**
* Parses universe definition files and conversion queries in the context of a given
* {@link Universe} instance.
*
* @author Ernesto García
*/
class Parser {
private Tokenizer tokenizer;
private Token tok;
private final Universe universe;
+ private static final Logger LOGGER = Logger.getLogger(Parser.class.getName());
+
private static final Joiner wordJoiner = Joiner.on(' ');
/**
* Stores the keywords recognized as separator in a query expression. These keywords are the
* ones recognized to separate the quantity to convert and the unit to which it should be
* converted.
*/
private static final Set<String> keywords =
Collections.unmodifiableSet(Sets.newHashSet(Arrays.asList("in", "to", "as")));
/**
* Special prefixes that can be applied to unit names. This does not refer to the
* {@linkplain UnitPrefix SI prefixes}, but to 'cubic' and 'square', affecting the exponent of
* the unit.
*/
private static final Set<String> dimensionPrefix =
Collections.unmodifiableSet(Sets.newHashSet(Arrays.asList("square", "cubic")));
//
// Public API
//
/**
* Creates a new parser for the given universe.
* @param universe the universe in which this parser operates
*/
Parser(Universe universe) {
this.universe = checkNotNull(universe);
}
/**
* Parses a conversion query from the contents of the given string.
* @param query the string containing the conversion query
* @return the conversion query parsed from the query string
* @throws SyntaxError if the query string has some syntax error making it unable to interpret
* a conversion query out of it
* @throws MetricException if the conversion query is semantically incorrect (e.g. refers to an
* unknown unit, requests conversion between incompatible units, etc.)
*/
ConversionQuery parseConversionQuery(String query) throws SyntaxError, MetricException {
initTokenizer(new Tokenizer(query));
List<Quantity> quantities = parseQuantities();
ConversionQuery result = null;
if (tok.is(TokenType.EOF)) {
result = new ConversionQuery(quantities);
} else {
Unit destUnit = parseUnitExpression();
result = new ConversionQuery(quantities, destUnit);
}
tok.checkType(TokenType.EOF);
tokenizer = null;
tok = null;
return result;
}
/**
* Parses the universe definition file for this parser's {@link Universe}.
* @throws IOException if some error occurs trying to read the universe or currency files, or
* while reading updated currency exchange rates from the internet.
* @throws SyntaxError if the universe definition file or the currencies file has some syntax
* error
* @throws MetricException if there are semantical errors in the universe definition file, or
* in the currency definitions
*/
void parseUniverseFile() throws IOException, SyntaxError, MetricException {
initTokenizer(new Tokenizer(universe.getUniverseFile()));
do {
parsePropertyDefinition();
} while (!tok.is(TokenType.EOF));
tokenizer = null;
tok = null;
}
//
// Private parsing methods
//
private void initTokenizer(Tokenizer t) throws SyntaxError {
tokenizer = t;
tokenizer.addKeywords("plus", "and", "per", "PI");
tok = tokenizer.nextToken();
}
private Property parsePropertyDefinition() throws SyntaxError, MetricException {
Factorization<Property> fp = null;
List<String> names = parseNamesList();
if (tok.is(TokenType.DOLLAR)) {
- tok = tok.next();
- names.add("$"); // ensuring the money property isn't added twice in the same universe
- Multimap<String, String> currencyAliases = parseCurrencyAliases();
- return new CurrencyLoader(universe, names, currencyAliases).getProperty();
+ try {
+ tok = tok.next();
+ names.add("$"); // ensuring the money property isn't added twice in the same universe
+ Multimap<String, String> currencyAliases = parseCurrencyAliases();
+ return new CurrencyLoader(universe, names, currencyAliases).getProperty();
+ } catch (Exception e) {
+ LOGGER.log(Level.SEVERE, "Currency definitions were not loaded");
+ return null;
+ }
}
if (tok.is(TokenType.EQUALS)) {
tok = tok.next();
Factorization<String> fs = parseFactorization();
fp = fs.transformItems(universe.getPropertyByNameFn);
}
tok.checkType(TokenType.LBRACE);
tok = tok.next();
Property newProperty = new Property(universe, names, fp);
while (!tok.is(TokenType.RBRACE)) {
UnitDefinition def = parseUnitDefinition();
newProperty.addUnits(def);
}
tok = tok.next();
newProperty.freezeUnits();
return newProperty;
}
private Multimap<String, String> parseCurrencyAliases() throws SyntaxError {
Multimap<String, String> result = HashMultimap.create();
tok.checkType(TokenType.LBRACE);
tok = tok.next();
while (!tok.is(TokenType.RBRACE)) {
String code = tok.getWord();
tok = tok.next();
tok.checkType(TokenType.COLON);
tok = tok.next();
List<String> aliases = parseNamesList();
tok.checkType(TokenType.SEMICOLON);
tok = tok.next();
for (String alias : aliases) {
result.put(code, alias);
result.put(code, pluralOf(alias));
if (!alias.toLowerCase().equals(alias)) {
alias = alias.toLowerCase();
result.put(code, alias);
result.put(code, pluralOf(alias));
}
}
}
tok = tok.next();
return result;
}
private UnitDefinition parseUnitDefinition() throws SyntaxError {
EnumSet<UnitPrefix> prefixes = EnumSet.noneOf(UnitPrefix.class);
if (tok.is(TokenType.LBRACE)) {
tok = tok.next();
prefixes = parsePrefixes();
tok.checkType(TokenType.RBRACE);
tok = tok.next();
}
List<String> longNames = parseNamesList();
List<String> shortNames = Collections.emptyList();
if (tok.is(TokenType.LPAREN)) {
tok = tok.next();
shortNames = parseNamesList();
tok.checkType(TokenType.RPAREN);
tok = tok.next();
}
BigFraction multiplier = null, offset = null;
Factorization<String> baseUnitFactors = null;
if (tok.is(TokenType.EQUALS)) {
tok = tok.next();
multiplier = parseNumber();
baseUnitFactors = parseFactorization();
if (tok.isOneOf(TokenType.PLUS, TokenType.MINUS)) {
offset = parseNumber();
}
}
tok.checkType(TokenType.SEMICOLON);
tok = tok.next();
return new UnitDefinition(longNames, shortNames,
baseUnitFactors, multiplier, offset, prefixes);
}
//
// Parse names, numbers and prefixes
//
private String parseName() throws SyntaxError {
List<String> words = Lists.newArrayList();
do {
words.add(tok.getWord());
tok = tok.next();
} while (tok.is(TokenType.WORD));
return wordJoiner.join(words);
}
private List<String> parseNamesList() throws SyntaxError {
List<String> result = Lists.newArrayList();
if (tok.is(TokenType.WORD)) {
result.add(parseName());
}
while (tok.is(TokenType.COMMA)) {
tok = tok.next();
result.add(parseName());
}
return result;
}
/**
* Parses the name of a unit using the given tokenizer as the source of tokens.
*
* @param tok the source of tokens, split from the query expression.
* @param stopWithKeyword determines if while parsing for a unit name this method should
* recognize valid keywords and stop processing the unit name.
* @return A string with the name of the unit parsed.
* @throws SyntaxError if the tokens returned break in some way the structure of the valid
* syntax for unit names.
*/
private String parseUnitName() throws SyntaxError {
List<String> nameParts = Lists.newArrayList();
String word = null;
// Parse the first word into the name parts
word = tok.getWord();
nameParts.add(word);
tok = tok.next();
// If the first word was a dimension specification (square or cubic),
// then parse the next word too, into the name parts, no matter what it is.
if (dimensionPrefix.contains(word)) {
nameParts.add(tok.getWord());
tok = tok.next();
}
String result = wordJoiner.join(nameParts);
if (universe.getUnitByName(result) != null) {
return result;
}
// Now continue to add words into the name until a keyword or another token type comes next
// But, if at any moment we have a valid unit name in the universe, then return it.
while (tok.is(TokenType.WORD)) {
word = tok.getWord();
if (keywords.contains(word)) {
break;
}
tok = tok.next();
nameParts.add(word);
result = wordJoiner.join(nameParts);
if (universe.getUnitByName(result) != null) {
return result;
}
}
return result;
}
private Unit parseUnitExpression() throws SyntaxError, MetricException {
Factorization<String> fs = parseFactorization();
Factorization<Unit> fu = universe.getUnitFactors(fs);
return universe.getUnitByFactors(fu);
}
/**
* Attempts to interpret the current token as a numeric value. It recognizes explicit numeric
* values, but also translates some keywords that refer to recognized numeric constants such as
* {@link BigFraction#PI PI}. If the current token is neither a number or a keyword referring
* to a recognized numeric constant, then it returns {@code null} or fails by throwing a
* {@link SyntaxError} exception, depending on the {@code force} parameter.
*
* @param force if {@code true} then it tries to force the detection of a number and fails by
* throwing a {@link SyntaxError} exception if it can't; if {@code false} then it returns
* {@code null} if no number could be interpreted from the current token.
* @return the numeric value recognized from the current token, or {@code null} if the
* {@code force} parameter is {@code false} and the current token does not represent a
* number.
* @throws SyntaxError if the {@code force} parameter is {@code true} and the current token does
* not represent a number.
*/
private BigFraction getTokenNumber(boolean force) throws SyntaxError {
if (tok.is("PI")) {
return BigFraction.PI;
}
if (tok.is(TokenType.NUMBER)) {
return BigFraction.valueOf(tok.getNumber());
}
if (force) {
tok.checkType(TokenType.NUMBER);
}
return null;
}
/**
* Parses a numeric value. It recognizes single numbers and simple arithmetic expressions which
* are reduced to a single numeric value by performing the arithmetic operations implied by the
* expression. Any recognized expression can be optionally preceded by a {@code +} or
* {@code -} sign to alter the sign of the resulting value.
*
* <p>Additionally this method also returns the numeric value {@link BigFraction#ONE 1} if
* there's no recognized numeric value or expression. In that case the tokenizer's current
* token stays the same.</p>
*
* <p>The following is a comprehensive list of all forms of arithmetic expressions that this
* method recognizes:</p>
*
* <ul>
* <li><pre><num></pre></li>
* <li><pre><num> * <num></pre></li>
* <li><pre><num> / <num></pre></li>
* <li><pre><num> * <num> / <num></pre></li>
* </ul>
*
* <p>In all cases in the above list the pattern {@code <num>} stands for either an
* explicit integer or floating point number as parsed by the {@link Tokenizer#parseNumber()
* Tokenizer's parseNumber method}, or a keyword representing a constant value, such as
* {@link BigFraction#PI PI}.</p>
*
* <p>As mentioned above, the result is always a reduced {@link BigFraction fraction} resulting
* from evaluating the expression found, including the optional sign preceding the
* expression.</p>
*
* @return the numeric value of the expression parsed, or {@link BigFraction#ONE 1} if no
* numeric expression was found.
*/
private BigFraction parseNumber() throws SyntaxError {
int signum = 1;
if (tok.isOneOf(TokenType.PLUS, TokenType.MINUS)) {
signum = tok.is(TokenType.PLUS) ? 1 : -1;
tok = tok.next();
}
BigFraction num = getTokenNumber(false);
if (num == null) {
return BigFraction.ONE;
}
tok = tok.next();
if (tok.is(TokenType.STAR)) {
tok = tok.next();
num = num.multiply(getTokenNumber(true));
tok = tok.next();
}
if (tok.is(TokenType.SLASH)) {
tok = tok.next();
num = num.divide(getTokenNumber(true));
tok = tok.next();
}
return signum < 0 ? num.negate() : num;
}
/**
* Parses a {@link UnitPrefix prefix} name.
* @return the {@link UnitPrefix prefix} found
* @throws SyntaxError if it does not recognize a valid prefix name
*/
private UnitPrefix parsePrefix() throws SyntaxError {
String prefixName = tok.getWord();
UnitPrefix prefix = UnitPrefix.getLong(prefixName);
if (prefix == null) {
throw new SyntaxError(String.format("Invalid prefix name %s", prefixName), tok);
}
tok = tok.next();
return prefix;
}
/**
* Parses the list of prefixes, if any.
*/
private EnumSet<UnitPrefix> parsePrefixes() throws SyntaxError {
EnumSet<UnitPrefix> prefixes = EnumSet.noneOf(UnitPrefix.class);
prefixes.add(parsePrefix());
while (tok.is(TokenType.COMMA)) {
tok = tok.next(); // skip the comma
prefixes.add(parsePrefix());
}
return prefixes;
}
//
// Parsing quantities
//
/**
* Parses a quantity, consisting of a number followed by a unit expression.
*
* @throws SyntaxError if it does not recognize a valid quantity syntax
* @throws UnknownNameException if the unit expression does not map to a valid unit in the
* universe
*/
private Quantity parseQuantity() throws SyntaxError, MetricException {
BigFraction value = parseNumber();
Unit unit = parseUnitExpression();
return new Quantity(value, unit);
}
/**
* Parses a series or list of quantities, optionally binded by natural language "binding words"
* such as "and", "plus", or by the use of the comma as a separator.
*/
private List<Quantity> parseQuantities() throws SyntaxError, MetricException {
List<Quantity> quantities = Lists.newArrayList();
quantities.add(parseQuantity());
while (!tok.isOneOf(TokenType.WORD, TokenType.EOF)) {
if (tok.is(TokenType.COMMA)) {
tok = tok.next();
}
if (tok.isOneOf("and", "plus")) {
tok = tok.next();
}
quantities.add(parseQuantity());
}
if (!tok.is(TokenType.EOF)) {
// Check that we hit the conversion magic word and skip it
checkState(keywords.contains(tok.getWord()));
tok = tok.next();
}
return quantities;
}
//
// Factorization parsing methods
//
private int parseExponent() throws SyntaxError {
int exp = 1;
if (tok.is(TokenType.CARET)) {
tok = tok.next();
int signum = 1;
if (tok.isOneOf(TokenType.PLUS, TokenType.MINUS)) {
signum = tok.is(TokenType.PLUS) ? 1 : -1;
tok = tok.next();
}
exp = tok.getNumber().intValue() * signum;
tok = tok.next();
}
return exp;
}
private Factorization<String> parseFactor() throws SyntaxError {
if (tok.is(TokenType.LPAREN)) {
tok = tok.next();
Factorization<String> f = parseFactorization();
tok.checkType(TokenType.RPAREN);
tok = tok.next();
int exp = parseExponent();
f = f.pow(exp);
return f;
} else {
String unitName = parseUnitName();
int exp = parseExponent();
if (unitName.startsWith("cubic ")) {
exp *= 3;
unitName = unitName.substring(6);
} else if (unitName.startsWith("square ")) {
exp *= 2;
unitName = unitName.substring(7);
} else if (unitName.startsWith("inverse ")) {
exp *= -1;
unitName = unitName.substring(8);
}
return Factorization.factor(unitName, exp);
}
}
private Factorization<String> parseFactorMultiplication() throws SyntaxError {
Factorization<String> f = parseFactor();
while (tok.isOneOf(TokenType.STAR, TokenType.LPAREN, TokenType.WORD)
&& !tok.isOneOf(keywords)) {
if (tok.is(TokenType.STAR)) {
tok = tok.next();
}
f = f.multiply(parseFactor());
}
return f;
}
private Factorization<String> parseFactorDivision() throws SyntaxError {
Factorization<String> f = parseFactor();
while ((tok.isOneOf(TokenType.STAR, TokenType.SLASH, TokenType.LPAREN, TokenType.WORD)
|| tok.is("per")) && !tok.isOneOf(keywords)) {
if (tok.isOneOf(TokenType.STAR, TokenType.SLASH) || tok.is("per")) {
tok = tok.next();
}
f = f.multiply(parseFactor());
}
return f;
}
private Factorization<String> parseFactorization() throws SyntaxError {
Factorization<String> f = parseFactorMultiplication();
if (tok.is(TokenType.SLASH) || tok.is("per")) {
tok = tok.next();
f = f.divide(parseFactorDivision());
}
return f;
}
}
| false | false | null | null |
diff --git a/src/java/davmail/exchange/ews/EwsExchangeSession.java b/src/java/davmail/exchange/ews/EwsExchangeSession.java
index 6261304..e2fc9bc 100644
--- a/src/java/davmail/exchange/ews/EwsExchangeSession.java
+++ b/src/java/davmail/exchange/ews/EwsExchangeSession.java
@@ -1,1905 +1,1907 @@
/*
* DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
* Copyright (C) 2010 Mickael Guessant
*
* 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 davmail.exchange.ews;
import davmail.exception.DavMailAuthenticationException;
import davmail.exception.DavMailException;
import davmail.exception.HttpNotFoundException;
import davmail.exchange.ExchangeSession;
import davmail.exchange.VCalendar;
import davmail.exchange.VProperty;
import davmail.http.DavGatewayHttpClientFacade;
import davmail.util.IOUtil;
import davmail.util.StringUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.SharedByteArrayInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* EWS Exchange adapter.
* Compatible with Exchange 2007 and hopefully 2010.
*/
public class EwsExchangeSession extends ExchangeSession {
protected static final int PAGE_SIZE = 100;
/**
* Message types.
*
- * @see http://msdn.microsoft.com/en-us/library/aa565652%28v=EXCHG.140%29.aspx
+ * @see <a href="http://msdn.microsoft.com/en-us/library/aa565652%28v=EXCHG.140%29.aspx">http://msdn.microsoft.com/en-us/library/aa565652%28v=EXCHG.140%29.aspx</a>
*/
protected static final Set<String> MESSAGE_TYPES = new HashSet<String>();
static {
MESSAGE_TYPES.add("Message");
MESSAGE_TYPES.add("CalendarItem");
MESSAGE_TYPES.add("MeetingMessage");
MESSAGE_TYPES.add("MeetingRequest");
MESSAGE_TYPES.add("MeetingResponse");
MESSAGE_TYPES.add("MeetingCancellation");
// exclude types from IMAP
//MESSAGE_TYPES.add("Item");
//MESSAGE_TYPES.add("PostItem");
//MESSAGE_TYPES.add("Contact");
//MESSAGE_TYPES.add("DistributionList");
//MESSAGE_TYPES.add("Task");
//ReplyToItem
//ForwardItem
//ReplyAllToItem
//AcceptItem
//TentativelyAcceptItem
//DeclineItem
//CancelCalendarItem
//RemoveItem
//PostReplyItem
//SuppressReadReceipt
//AcceptSharingInvitation
}
protected Map<String, String> folderIdMap;
protected class Folder extends ExchangeSession.Folder {
public FolderId folderId;
}
protected static class FolderPath {
protected final String parentPath;
protected final String folderName;
protected FolderPath(String folderPath) {
int slashIndex = folderPath.lastIndexOf('/');
if (slashIndex < 0) {
parentPath = "";
folderName = folderPath;
} else {
parentPath = folderPath.substring(0, slashIndex);
folderName = folderPath.substring(slashIndex + 1);
}
}
}
/**
* @inheritDoc
*/
public EwsExchangeSession(String url, String userName, String password) throws IOException {
super(url, userName, password);
}
@Override
protected HttpMethod formLogin(HttpClient httpClient, HttpMethod initmethod, String userName, String password) throws IOException {
LOGGER.debug("Form based authentication detected");
HttpMethod logonMethod = buildLogonMethod(httpClient, initmethod);
if (logonMethod == null) {
LOGGER.debug("Authentication form not found at " + initmethod.getURI() + ", will try direct EWS access");
} else {
logonMethod = postLogonMethod(httpClient, logonMethod, userName, password);
}
return logonMethod;
}
/**
* Check endpoint url.
*
* @param endPointUrl endpoint url
* @throws IOException on error
*/
protected void checkEndPointUrl(String endPointUrl) throws IOException {
HttpMethod getMethod = new GetMethod(endPointUrl);
getMethod.setFollowRedirects(false);
try {
int status = DavGatewayHttpClientFacade.executeNoRedirect(httpClient, getMethod);
if (status == HttpStatus.SC_UNAUTHORIZED) {
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
} else if (status != HttpStatus.SC_MOVED_TEMPORARILY) {
throw DavGatewayHttpClientFacade.buildHttpException(getMethod);
}
// check Location
Header locationHeader = getMethod.getResponseHeader("Location");
if (locationHeader == null || !"/ews/services.wsdl".equalsIgnoreCase(locationHeader.getValue())) {
throw new IOException("Ews endpoint not available at " + getMethod.getURI().toString());
}
} finally {
getMethod.releaseConnection();
}
}
@Override
protected void buildSessionInfo(HttpMethod method) throws DavMailException {
// no need to check logon method body
if (method != null) {
method.releaseConnection();
// need to retrieve email and alias
getEmailAndAliasFromOptions();
}
if (email == null || alias == null) {
// OWA authentication failed, get email address from login
if (userName.indexOf('@') >= 0) {
// userName is email address
email = userName;
alias = userName.substring(0, userName.indexOf('@'));
} else {
// userName or domain\\username, rebuild email address
alias = getAliasFromLogin();
email = getAliasFromLogin() + getEmailSuffixFromHostname();
}
}
currentMailboxPath = "/users/" + email.toLowerCase();
// check EWS access
try {
checkEndPointUrl("/ews/exchange.asmx");
// workaround for Exchange bug: send fake request
internalGetFolder("");
} catch (IOException e) {
// first failover: retry with NTLM
DavGatewayHttpClientFacade.addNTLM(httpClient);
try {
checkEndPointUrl("/ews/exchange.asmx");
// workaround for Exchange bug: send fake request
internalGetFolder("");
} catch (IOException e2) {
LOGGER.debug(e2.getMessage());
try {
// failover, try to retrieve EWS url from autodiscover
checkEndPointUrl(getEwsUrlFromAutoDiscover());
// workaround for Exchange bug: send fake request
internalGetFolder("");
} catch (IOException e3) {
// autodiscover failed and initial exception was authentication failure => throw original exception
if (e instanceof DavMailAuthenticationException) {
throw (DavMailAuthenticationException) e;
}
LOGGER.error(e2.getMessage());
throw new DavMailAuthenticationException("EXCEPTION_EWS_NOT_AVAILABLE");
}
}
}
try {
folderIdMap = new HashMap<String, String>();
// load actual well known folder ids
folderIdMap.put(internalGetFolder(INBOX).folderId.value, INBOX);
folderIdMap.put(internalGetFolder(CALENDAR).folderId.value, CALENDAR);
folderIdMap.put(internalGetFolder(CONTACTS).folderId.value, CONTACTS);
folderIdMap.put(internalGetFolder(SENT).folderId.value, SENT);
folderIdMap.put(internalGetFolder(DRAFTS).folderId.value, DRAFTS);
folderIdMap.put(internalGetFolder(TRASH).folderId.value, TRASH);
folderIdMap.put(internalGetFolder(JUNK).folderId.value, JUNK);
folderIdMap.put(internalGetFolder(UNSENT).folderId.value, UNSENT);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
throw new DavMailAuthenticationException("EXCEPTION_EWS_NOT_AVAILABLE");
}
LOGGER.debug("Current user email is " + email + ", alias is " + alias + " on " + serverVersion);
}
protected static class AutoDiscoverMethod extends PostMethod {
AutoDiscoverMethod(String autodiscoverHost, String userEmail) {
super("https://" + autodiscoverHost + "/autodiscover/autodiscover.xml");
setAutoDiscoverRequestEntity(userEmail);
}
AutoDiscoverMethod(String userEmail) {
super("/autodiscover/autodiscover.xml");
setAutoDiscoverRequestEntity(userEmail);
}
void setAutoDiscoverRequestEntity(String userEmail) {
String body = "<Autodiscover xmlns=\"http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006\">" +
"<Request>" +
"<EMailAddress>" + userEmail + "</EMailAddress>" +
"<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>" +
"</Request>" +
"</Autodiscover>";
setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), "text/xml"));
}
String ewsUrl;
@Override
protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
Header contentTypeHeader = getResponseHeader("Content-Type");
if (contentTypeHeader != null &&
("text/xml; charset=utf-8".equals(contentTypeHeader.getValue())
|| "text/html; charset=utf-8".equals(contentTypeHeader.getValue())
)) {
BufferedReader autodiscoverReader = null;
try {
autodiscoverReader = new BufferedReader(new InputStreamReader(getResponseBodyAsStream()));
String line;
// find ews url
while ((line = autodiscoverReader.readLine()) != null
&& (line.indexOf("<EwsUrl>") == -1)
&& (line.indexOf("</EwsUrl>") == -1)) {
}
if (line != null) {
ewsUrl = line.substring(line.indexOf("<EwsUrl>") + 8, line.indexOf("</EwsUrl>"));
}
} catch (IOException e) {
LOGGER.debug(e);
} finally {
if (autodiscoverReader != null) {
try {
autodiscoverReader.close();
} catch (IOException e) {
LOGGER.debug(e);
}
}
}
}
}
}
protected String getEwsUrlFromAutoDiscover() throws DavMailAuthenticationException {
String ewsUrl;
try {
ewsUrl = getEwsUrlFromAutoDiscover(null);
} catch (IOException e) {
try {
ewsUrl = getEwsUrlFromAutoDiscover("autodiscover." + email.substring(email.indexOf('@') + 1));
} catch (IOException e2) {
LOGGER.error(e2.getMessage());
throw new DavMailAuthenticationException("EXCEPTION_EWS_NOT_AVAILABLE");
}
}
return ewsUrl;
}
protected String getEwsUrlFromAutoDiscover(String autodiscoverHostname) throws IOException {
String ewsUrl;
AutoDiscoverMethod autoDiscoverMethod;
if (autodiscoverHostname != null) {
autoDiscoverMethod = new AutoDiscoverMethod(autodiscoverHostname, email);
} else {
autoDiscoverMethod = new AutoDiscoverMethod(email);
}
try {
int status = DavGatewayHttpClientFacade.executeNoRedirect(httpClient, autoDiscoverMethod);
if (status != HttpStatus.SC_OK) {
throw DavGatewayHttpClientFacade.buildHttpException(autoDiscoverMethod);
}
ewsUrl = autoDiscoverMethod.ewsUrl;
// update host name
DavGatewayHttpClientFacade.setClientHost(httpClient, ewsUrl);
if (ewsUrl == null) {
throw new IOException("Ews url not found");
}
} finally {
autoDiscoverMethod.releaseConnection();
}
return ewsUrl;
}
class Message extends ExchangeSession.Message {
// message item id
ItemId itemId;
@Override
public String getPermanentId() {
return itemId.id;
}
}
/**
* Message create/update properties
*
* @param properties flag values map
* @return field values
*/
protected List<FieldUpdate> buildProperties(Map<String, String> properties) {
ArrayList<FieldUpdate> list = new ArrayList<FieldUpdate>();
for (Map.Entry<String, String> entry : properties.entrySet()) {
if ("read".equals(entry.getKey())) {
list.add(Field.createFieldUpdate("read", Boolean.toString("1".equals(entry.getValue()))));
} else if ("junk".equals(entry.getKey())) {
list.add(Field.createFieldUpdate("junk", entry.getValue()));
} else if ("flagged".equals(entry.getKey())) {
list.add(Field.createFieldUpdate("flagStatus", entry.getValue()));
} else if ("answered".equals(entry.getKey())) {
list.add(Field.createFieldUpdate("lastVerbExecuted", entry.getValue()));
if ("102".equals(entry.getValue())) {
list.add(Field.createFieldUpdate("iconIndex", "261"));
}
} else if ("forwarded".equals(entry.getKey())) {
list.add(Field.createFieldUpdate("lastVerbExecuted", entry.getValue()));
if ("104".equals(entry.getValue())) {
list.add(Field.createFieldUpdate("iconIndex", "262"));
}
} else if ("draft".equals(entry.getKey())) {
// note: draft is readonly after create
list.add(Field.createFieldUpdate("messageFlags", entry.getValue()));
} else if ("deleted".equals(entry.getKey())) {
list.add(Field.createFieldUpdate("deleted", entry.getValue()));
} else if ("datereceived".equals(entry.getKey())) {
list.add(Field.createFieldUpdate("datereceived", entry.getValue()));
}
}
return list;
}
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties, MimeMessage mimeMessage) throws IOException {
EWSMethod.Item item = new EWSMethod.Item();
item.type = "Message";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
mimeMessage.writeTo(baos);
} catch (MessagingException e) {
throw new IOException(e.getMessage());
}
baos.close();
item.mimeContent = Base64.encodeBase64(baos.toByteArray());
List<FieldUpdate> fieldUpdates = buildProperties(properties);
if (!properties.containsKey("draft")) {
// need to force draft flag to false
if (properties.containsKey("read")) {
fieldUpdates.add(Field.createFieldUpdate("messageFlags", "1"));
} else {
fieldUpdates.add(Field.createFieldUpdate("messageFlags", "0"));
}
}
fieldUpdates.add(Field.createFieldUpdate("urlcompname", messageName));
item.setFieldUpdates(fieldUpdates);
CreateItemMethod createItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, getFolderId(folderPath), item);
executeMethod(createItemMethod);
}
@Override
public void updateMessage(ExchangeSession.Message message, Map<String, String> properties) throws IOException {
UpdateItemMethod updateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly,
ConflictResolution.AlwaysOverwrite,
SendMeetingInvitationsOrCancellations.SendToNone,
((EwsExchangeSession.Message) message).itemId, buildProperties(properties));
executeMethod(updateItemMethod);
}
@Override
public void deleteMessage(ExchangeSession.Message message) throws IOException {
LOGGER.debug("Delete " + message.permanentUrl);
DeleteItemMethod deleteItemMethod = new DeleteItemMethod(((EwsExchangeSession.Message) message).itemId, DeleteType.HardDelete, SendMeetingCancellations.SendToNone);
executeMethod(deleteItemMethod);
}
@Override
public void sendMessage(byte[] messageBody) throws IOException {
EWSMethod.Item item = new EWSMethod.Item();
item.type = "Message";
item.mimeContent = Base64.encodeBase64(messageBody);
CreateItemMethod createItemMethod = new CreateItemMethod(MessageDisposition.SendAndSaveCopy, getFolderId(SENT), item);
executeMethod(createItemMethod);
}
@Override
public void sendMessage(MimeMessage mimeMessage) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
mimeMessage.writeTo(baos);
} catch (MessagingException e) {
throw new IOException(e.getMessage());
}
sendMessage(baos.toByteArray());
}
/**
* @inheritDoc
*/
@Override
protected byte[] getContent(ExchangeSession.Message message) throws IOException {
return getContent(((EwsExchangeSession.Message) message).itemId);
}
/**
* Get item content.
*
* @param itemId EWS item id
* @return item content as byte array
* @throws IOException on error
*/
protected byte[] getContent(ItemId itemId) throws IOException {
GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true);
executeMethod(getItemMethod);
return getItemMethod.getMimeContent();
}
protected Message buildMessage(EWSMethod.Item response) throws DavMailException {
Message message = new Message();
// get item id
message.itemId = new ItemId(response);
message.permanentUrl = response.get(Field.get("permanenturl").getResponseName());
message.size = response.getInt(Field.get("messageSize").getResponseName());
message.uid = response.get(Field.get("uid").getResponseName());
message.imapUid = response.getLong(Field.get("imapUid").getResponseName());
message.read = response.getBoolean(Field.get("read").getResponseName());
message.junk = response.getBoolean(Field.get("junk").getResponseName());
message.flagged = "2".equals(response.get(Field.get("flagStatus").getResponseName()));
message.draft = (response.getInt(Field.get("messageFlags").getResponseName()) & 8) != 0;
String lastVerbExecuted = response.get(Field.get("lastVerbExecuted").getResponseName());
message.answered = "102".equals(lastVerbExecuted) || "103".equals(lastVerbExecuted);
message.forwarded = "104".equals(lastVerbExecuted);
message.date = convertDateFromExchange(response.get(Field.get("date").getResponseName()));
message.deleted = "1".equals(response.get(Field.get("deleted").getResponseName()));
if (LOGGER.isDebugEnabled()) {
StringBuilder buffer = new StringBuilder();
buffer.append("Message");
if (message.imapUid != 0) {
buffer.append(" IMAP uid: ").append(message.imapUid);
}
if (message.uid != null) {
buffer.append(" uid: ").append(message.uid);
}
buffer.append(" ItemId: ").append(message.itemId.id);
buffer.append(" ChangeKey: ").append(message.itemId.changeKey);
LOGGER.debug(buffer.toString());
}
return message;
}
@Override
public MessageList searchMessages(String folderPath, Set<String> attributes, Condition condition) throws IOException {
MessageList messages = new MessageList();
List<EWSMethod.Item> responses = searchItems(folderPath, attributes, condition, FolderQueryTraversal.SHALLOW, 0);
for (EWSMethod.Item response : responses) {
if (MESSAGE_TYPES.contains(response.type)) {
Message message = buildMessage(response);
message.messageList = messages;
messages.add(message);
}
}
Collections.sort(messages);
return messages;
}
protected List<EWSMethod.Item> searchItems(String folderPath, Set<String> attributes, Condition condition, FolderQueryTraversal folderQueryTraversal, int maxCount) throws IOException {
int offset = 0;
List<EWSMethod.Item> results = new ArrayList<EWSMethod.Item>();
FindItemMethod findItemMethod;
do {
int fetchCount = PAGE_SIZE;
if (maxCount > 0) {
fetchCount = Math.min(PAGE_SIZE, maxCount - offset);
}
findItemMethod = new FindItemMethod(folderQueryTraversal, BaseShape.ID_ONLY, getFolderId(folderPath), offset, fetchCount);
for (String attribute : attributes) {
findItemMethod.addAdditionalProperty(Field.get(attribute));
}
if (condition != null && !condition.isEmpty()) {
findItemMethod.setSearchExpression((SearchExpression) condition);
}
executeMethod(findItemMethod);
results.addAll(findItemMethod.getResponseItems());
offset = results.size();
} while (!(findItemMethod.includesLastItemInRange || (maxCount > 0 && offset == maxCount)));
return results;
}
protected static class MultiCondition extends ExchangeSession.MultiCondition implements SearchExpression {
protected MultiCondition(Operator operator, Condition... condition) {
super(operator, condition);
}
public void appendTo(StringBuilder buffer) {
int actualConditionCount = 0;
for (Condition condition : conditions) {
if (!condition.isEmpty()) {
actualConditionCount++;
}
}
if (actualConditionCount > 0) {
if (actualConditionCount > 1) {
buffer.append("<t:").append(operator.toString()).append('>');
}
for (Condition condition : conditions) {
condition.appendTo(buffer);
}
if (actualConditionCount > 1) {
buffer.append("</t:").append(operator.toString()).append('>');
}
}
}
}
protected static class NotCondition extends ExchangeSession.NotCondition implements SearchExpression {
protected NotCondition(Condition condition) {
super(condition);
}
public void appendTo(StringBuilder buffer) {
buffer.append("<t:Not>");
condition.appendTo(buffer);
buffer.append("</t:Not>");
}
}
protected static class AttributeCondition extends ExchangeSession.AttributeCondition implements SearchExpression {
protected ContainmentMode containmentMode;
protected ContainmentComparison containmentComparison;
protected AttributeCondition(String attributeName, Operator operator, String value) {
super(attributeName, operator, value);
}
protected AttributeCondition(String attributeName, Operator operator, String value,
ContainmentMode containmentMode, ContainmentComparison containmentComparison) {
super(attributeName, operator, value);
this.containmentMode = containmentMode;
this.containmentComparison = containmentComparison;
}
protected FieldURI getFieldURI() {
FieldURI fieldURI = Field.get(attributeName);
if (fieldURI == null) {
throw new IllegalArgumentException("Unknown field: " + attributeName);
}
return fieldURI;
}
protected Operator getOperator() {
return operator;
}
public void appendTo(StringBuilder buffer) {
buffer.append("<t:").append(operator.toString());
if (containmentMode != null) {
containmentMode.appendTo(buffer);
}
if (containmentComparison != null) {
containmentComparison.appendTo(buffer);
}
buffer.append('>');
FieldURI fieldURI = getFieldURI();
fieldURI.appendTo(buffer);
if (operator != Operator.Contains) {
buffer.append("<t:FieldURIOrConstant>");
}
buffer.append("<t:Constant Value=\"");
// encode urlcompname
if (fieldURI instanceof ExtendedFieldURI && "0x10f3".equals(((ExtendedFieldURI) fieldURI).propertyTag)) {
buffer.append(StringUtil.xmlEncodeAttribute(StringUtil.encodeUrlcompname(value)));
} else if (fieldURI instanceof ExtendedFieldURI
&& ((ExtendedFieldURI) fieldURI).propertyType == ExtendedFieldURI.PropertyType.Integer) {
// check value
try {
Integer.parseInt(value);
buffer.append(value);
} catch (NumberFormatException e) {
// invalid value, replace with 0
buffer.append('0');
}
} else {
buffer.append(StringUtil.xmlEncodeAttribute(value));
}
buffer.append("\"/>");
if (operator != Operator.Contains) {
buffer.append("</t:FieldURIOrConstant>");
}
buffer.append("</t:").append(operator.toString()).append('>');
}
public boolean isMatch(ExchangeSession.Contact contact) {
String lowerCaseValue = value.toLowerCase();
String actualValue = contact.get(attributeName);
if (actualValue == null) {
return false;
}
actualValue = actualValue.toLowerCase();
if (operator == Operator.IsEqualTo) {
return lowerCaseValue.equals(actualValue);
} else {
return operator == Operator.Contains && ((containmentMode.equals(ContainmentMode.Substring) && actualValue.contains(lowerCaseValue)) ||
(containmentMode.equals(ContainmentMode.Prefixed) && actualValue.startsWith(lowerCaseValue)));
}
}
}
protected static class HeaderCondition extends AttributeCondition {
protected HeaderCondition(String attributeName, Operator operator, String value) {
super(attributeName, operator, value);
}
@Override
protected FieldURI getFieldURI() {
return new ExtendedFieldURI(ExtendedFieldURI.DistinguishedPropertySetType.InternetHeaders, attributeName);
}
}
protected static class IsNullCondition implements ExchangeSession.Condition, SearchExpression {
protected final String attributeName;
protected IsNullCondition(String attributeName) {
this.attributeName = attributeName;
}
public void appendTo(StringBuilder buffer) {
buffer.append("<t:Not><t:Exists>");
Field.get(attributeName).appendTo(buffer);
buffer.append("</t:Exists></t:Not>");
}
public boolean isEmpty() {
return false;
}
public boolean isMatch(ExchangeSession.Contact contact) {
String actualValue = contact.get(attributeName);
return actualValue == null;
}
}
@Override
public ExchangeSession.MultiCondition and(Condition... condition) {
return new MultiCondition(Operator.And, condition);
}
@Override
public ExchangeSession.MultiCondition or(Condition... condition) {
return new MultiCondition(Operator.Or, condition);
}
@Override
public Condition not(Condition condition) {
return new NotCondition(condition);
}
@Override
public Condition isEqualTo(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsEqualTo, value);
}
@Override
public Condition isEqualTo(String attributeName, int value) {
return new AttributeCondition(attributeName, Operator.IsEqualTo, String.valueOf(value));
}
@Override
public Condition headerIsEqualTo(String headerName, String value) {
return new HeaderCondition(headerName, Operator.IsEqualTo, value);
}
@Override
public Condition gte(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsGreaterThanOrEqualTo, value);
}
@Override
public Condition lte(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsLessThanOrEqualTo, value);
}
@Override
public Condition lt(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsLessThan, value);
}
@Override
public Condition gt(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.IsGreaterThan, value);
}
@Override
public Condition contains(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.Contains, value, ContainmentMode.Substring, ContainmentComparison.IgnoreCase);
}
@Override
public Condition startsWith(String attributeName, String value) {
return new AttributeCondition(attributeName, Operator.Contains, value, ContainmentMode.Prefixed, ContainmentComparison.IgnoreCase);
}
@Override
public Condition isNull(String attributeName) {
return new IsNullCondition(attributeName);
}
@Override
public Condition isTrue(String attributeName) {
return new AttributeCondition(attributeName, Operator.IsEqualTo, "true");
}
@Override
public Condition isFalse(String attributeName) {
return new AttributeCondition(attributeName, Operator.IsEqualTo, "false");
}
protected static final HashSet<FieldURI> FOLDER_PROPERTIES = new HashSet<FieldURI>();
static {
FOLDER_PROPERTIES.add(Field.get("urlcompname"));
FOLDER_PROPERTIES.add(Field.get("folderDisplayName"));
FOLDER_PROPERTIES.add(Field.get("lastmodified"));
FOLDER_PROPERTIES.add(Field.get("folderclass"));
FOLDER_PROPERTIES.add(Field.get("ctag"));
FOLDER_PROPERTIES.add(Field.get("unread"));
FOLDER_PROPERTIES.add(Field.get("hassubs"));
FOLDER_PROPERTIES.add(Field.get("uidNext"));
FOLDER_PROPERTIES.add(Field.get("highestUid"));
}
protected Folder buildFolder(String mailbox, EWSMethod.Item item) {
Folder folder = new Folder();
folder.folderId = new FolderId(mailbox, item);
folder.displayName = item.get(Field.get("folderDisplayName").getResponseName());
folder.folderClass = item.get(Field.get("folderclass").getResponseName());
folder.etag = item.get(Field.get("lastmodified").getResponseName());
folder.ctag = item.get(Field.get("ctag").getResponseName());
folder.unreadCount = item.getInt(Field.get("unread").getResponseName());
folder.hasChildren = item.getBoolean(Field.get("hassubs").getResponseName());
// noInferiors not implemented
folder.uidNext = item.getInt(Field.get("uidNext").getResponseName());
return folder;
}
/**
* @inheritDoc
*/
@Override
public List<ExchangeSession.Folder> getSubFolders(String folderPath, Condition condition, boolean recursive) throws IOException {
String baseFolderPath = folderPath;
if (baseFolderPath.startsWith("/users/")) {
int index = baseFolderPath.indexOf('/', "/users/".length());
if (index >= 0) {
baseFolderPath = baseFolderPath.substring(index + 1);
}
}
List<ExchangeSession.Folder> folders = new ArrayList<ExchangeSession.Folder>();
appendSubFolders(folders, baseFolderPath, getFolderId(folderPath), condition, recursive);
return folders;
}
protected void appendSubFolders(List<ExchangeSession.Folder> folders,
String parentFolderPath, FolderId parentFolderId,
Condition condition, boolean recursive) throws IOException {
FindFolderMethod findFolderMethod = new FindFolderMethod(FolderQueryTraversal.SHALLOW,
BaseShape.ID_ONLY, parentFolderId, FOLDER_PROPERTIES, (SearchExpression) condition);
executeMethod(findFolderMethod);
for (EWSMethod.Item item : findFolderMethod.getResponseItems()) {
Folder folder = buildFolder(parentFolderId.mailbox, item);
if (parentFolderPath.length() > 0) {
folder.folderPath = parentFolderPath + '/' + item.get(Field.get("folderDisplayName").getResponseName());
} else if (folderIdMap.get(folder.folderId.value) != null) {
folder.folderPath = folderIdMap.get(folder.folderId.value);
} else {
folder.folderPath = item.get(Field.get("folderDisplayName").getResponseName());
}
folders.add(folder);
if (recursive && folder.hasChildren) {
appendSubFolders(folders, folder.folderPath, folder.folderId, condition, recursive);
}
}
}
/**
* @inheritDoc
*/
@Override
public ExchangeSession.Folder getFolder(String folderPath) throws IOException {
return internalGetFolder(folderPath);
}
/**
* Get folder by path.
*
* @param folderPath folder path
* @return folder object
* @throws IOException on error
*/
protected EwsExchangeSession.Folder internalGetFolder(String folderPath) throws IOException {
FolderId folderId = getFolderId(folderPath);
GetFolderMethod getFolderMethod = new GetFolderMethod(BaseShape.ID_ONLY, folderId, FOLDER_PROPERTIES);
executeMethod(getFolderMethod);
EWSMethod.Item item = getFolderMethod.getResponseItem();
Folder folder;
if (item != null) {
folder = buildFolder(folderId.mailbox, item);
folder.folderPath = folderPath;
} else {
throw new HttpNotFoundException("Folder " + folderPath + " not found");
}
return folder;
}
/**
* @inheritDoc
*/
@Override
public int createFolder(String folderPath, String folderClass, Map<String, String> properties) throws IOException {
FolderPath path = new FolderPath(folderPath);
EWSMethod.Item folder = new EWSMethod.Item();
folder.type = "Folder";
folder.put("FolderClass", folderClass);
folder.put("DisplayName", path.folderName);
// TODO: handle properties
CreateFolderMethod createFolderMethod = new CreateFolderMethod(getFolderId(path.parentPath), folder);
executeMethod(createFolderMethod);
return HttpStatus.SC_CREATED;
}
/**
* @inheritDoc
*/
@Override
public void deleteFolder(String folderPath) throws IOException {
FolderId folderId = getFolderIdIfExists(folderPath);
if (folderId != null) {
DeleteFolderMethod deleteFolderMethod = new DeleteFolderMethod(folderId);
executeMethod(deleteFolderMethod);
} else {
LOGGER.debug("Folder " + folderPath + " not found");
}
}
/**
* @inheritDoc
*/
@Override
public void copyMessage(ExchangeSession.Message message, String targetFolder) throws IOException {
CopyItemMethod copyItemMethod = new CopyItemMethod(((EwsExchangeSession.Message) message).itemId, getFolderId(targetFolder));
executeMethod(copyItemMethod);
}
/**
* @inheritDoc
*/
@Override
public void moveFolder(String folderPath, String targetFolderPath) throws IOException {
FolderPath path = new FolderPath(folderPath);
FolderPath targetPath = new FolderPath(targetFolderPath);
FolderId folderId = getFolderId(folderPath);
FolderId toFolderId = getFolderId(targetPath.parentPath);
toFolderId.changeKey = null;
// move folder
if (!path.parentPath.equals(targetPath.parentPath)) {
MoveFolderMethod moveFolderMethod = new MoveFolderMethod(folderId, toFolderId);
executeMethod(moveFolderMethod);
}
// rename folder
if (!path.folderName.equals(targetPath.folderName)) {
ArrayList<FieldUpdate> updates = new ArrayList<FieldUpdate>();
updates.add(new FieldUpdate(Field.get("folderDisplayName"), targetPath.folderName));
UpdateFolderMethod updateFolderMethod = new UpdateFolderMethod(folderId, updates);
executeMethod(updateFolderMethod);
}
}
@Override
public void moveItem(String sourcePath, String targetPath) throws IOException {
FolderPath sourceFolderPath = new FolderPath(sourcePath);
Item item = getItem(sourceFolderPath.parentPath, sourceFolderPath.folderName);
FolderPath targetFolderPath = new FolderPath(targetPath);
FolderId toFolderId = getFolderId(targetFolderPath.parentPath);
MoveItemMethod moveItemMethod = new MoveItemMethod(((Event) item).itemId, toFolderId);
executeMethod(moveItemMethod);
}
/**
* @inheritDoc
*/
@Override
protected void moveToTrash(ExchangeSession.Message message) throws IOException {
MoveItemMethod moveItemMethod = new MoveItemMethod(((EwsExchangeSession.Message) message).itemId, getFolderId(TRASH));
executeMethod(moveItemMethod);
}
protected class Contact extends ExchangeSession.Contact {
// item id
ItemId itemId;
protected Contact(EWSMethod.Item response) throws DavMailException {
itemId = new ItemId(response);
permanentUrl = response.get(Field.get("permanenturl").getResponseName());
etag = response.get(Field.get("etag").getResponseName());
displayName = response.get(Field.get("displayname").getResponseName());
itemName = response.get(Field.get("urlcompname").getResponseName());
// workaround for missing urlcompname in Exchange 2010
if (itemName == null) {
itemName = StringUtil.base64ToUrl(itemId.id) + ".EML";
}
for (String attributeName : CONTACT_ATTRIBUTES) {
String value = response.get(Field.get(attributeName).getResponseName());
if (value != null && value.length() > 0) {
if ("bday".equals(attributeName) || "anniversary".equals(attributeName) || "lastmodified".equals(attributeName) || "datereceived".equals(attributeName)) {
value = convertDateFromExchange(value);
}
put(attributeName, value);
}
}
}
/**
* @inheritDoc
*/
protected Contact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) {
super(folderPath, itemName, properties, etag, noneMatch);
}
/**
* Empty constructor for GalFind
*/
protected Contact() {
}
protected void buildProperties(List<FieldUpdate> updates) {
for (Map.Entry<String, String> entry : entrySet()) {
if ("photo".equals(entry.getKey())) {
updates.add(Field.createFieldUpdate("haspicture", "true"));
} else if (!entry.getKey().startsWith("email") && !entry.getKey().startsWith("smtpemail")) {
updates.add(Field.createFieldUpdate(entry.getKey(), entry.getValue()));
}
}
// handle email addresses
IndexedFieldUpdate emailFieldUpdate = null;
for (Map.Entry<String, String> entry : entrySet()) {
if (entry.getKey().startsWith("smtpemail") && entry.getValue() != null) {
if (emailFieldUpdate == null) {
emailFieldUpdate = new IndexedFieldUpdate("EmailAddresses");
}
emailFieldUpdate.addFieldValue(Field.createFieldUpdate(entry.getKey(), entry.getValue()));
}
}
if (emailFieldUpdate != null) {
updates.add(emailFieldUpdate);
}
}
/**
* Create or update contact
*
* @return action result
* @throws IOException on error
*/
public ItemResult createOrUpdate() throws IOException {
String photo = get("photo");
ItemResult itemResult = new ItemResult();
EWSMethod createOrUpdateItemMethod;
// first try to load existing event
String currentEtag = null;
ItemId currentItemId = null;
FileAttachment currentFileAttachment = null;
EWSMethod.Item currentItem = getEwsItem(folderPath, itemName);
if (currentItem != null) {
currentItemId = new ItemId(currentItem);
currentEtag = currentItem.get(Field.get("etag").getResponseName());
// load current picture
GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, currentItemId, false);
getItemMethod.addAdditionalProperty(Field.get("attachments"));
executeMethod(getItemMethod);
EWSMethod.Item item = getItemMethod.getResponseItem();
if (item != null) {
currentFileAttachment = item.getAttachmentByName("ContactPicture.jpg");
}
}
if ("*".equals(noneMatch)) {
// create requested
if (currentItemId != null) {
itemResult.status = HttpStatus.SC_PRECONDITION_FAILED;
return itemResult;
}
} else if (etag != null) {
// update requested
if (currentItemId == null || !etag.equals(currentEtag)) {
itemResult.status = HttpStatus.SC_PRECONDITION_FAILED;
return itemResult;
}
}
List<FieldUpdate> properties = new ArrayList<FieldUpdate>();
if (currentItemId != null) {
buildProperties(properties);
// update
createOrUpdateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly,
ConflictResolution.AlwaysOverwrite,
SendMeetingInvitationsOrCancellations.SendToNone,
currentItemId, properties);
} else {
// create
EWSMethod.Item newItem = new EWSMethod.Item();
newItem.type = "Contact";
// force urlcompname on create
properties.add(Field.createFieldUpdate("urlcompname", convertItemNameToEML(itemName)));
buildProperties(properties);
newItem.setFieldUpdates(properties);
createOrUpdateItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, getFolderId(folderPath), newItem);
}
executeMethod(createOrUpdateItemMethod);
itemResult.status = createOrUpdateItemMethod.getStatusCode();
if (itemResult.status == HttpURLConnection.HTTP_OK) {
//noinspection VariableNotUsedInsideIf
if (etag == null) {
itemResult.status = HttpStatus.SC_CREATED;
LOGGER.debug("Created contact " + getHref());
} else {
LOGGER.debug("Updated contact " + getHref());
}
} else {
return itemResult;
}
ItemId newItemId = new ItemId(createOrUpdateItemMethod.getResponseItem());
// disable contact picture handling on Exchange 2007
if ("Exchange2010".equals(serverVersion)) {
// first delete current picture
if (currentFileAttachment != null) {
DeleteAttachmentMethod deleteAttachmentMethod = new DeleteAttachmentMethod(currentFileAttachment.attachmentId);
executeMethod(deleteAttachmentMethod);
}
if (photo != null) {
// convert image to jpeg
byte[] resizedImageBytes = IOUtil.resizeImage(Base64.decodeBase64(photo.getBytes()), 90);
FileAttachment attachment = new FileAttachment("ContactPicture.jpg", "image/jpeg", new String(Base64.encodeBase64(resizedImageBytes)));
if ("Exchange2010".equals(serverVersion)) {
attachment.setIsContactPhoto(true);
}
// update photo attachment
CreateAttachmentMethod createAttachmentMethod = new CreateAttachmentMethod(newItemId, attachment);
executeMethod(createAttachmentMethod);
}
}
GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, newItemId, false);
getItemMethod.addAdditionalProperty(Field.get("etag"));
executeMethod(getItemMethod);
itemResult.etag = getItemMethod.getResponseItem().get(Field.get("etag").getResponseName());
return itemResult;
}
}
protected class Event extends ExchangeSession.Event {
// item id
ItemId itemId;
String type;
protected Event(EWSMethod.Item response) {
itemId = new ItemId(response);
type = response.type;
permanentUrl = response.get(Field.get("permanenturl").getResponseName());
etag = response.get(Field.get("etag").getResponseName());
displayName = response.get(Field.get("displayname").getResponseName());
subject = response.get(Field.get("subject").getResponseName());
itemName = response.get(Field.get("urlcompname").getResponseName());
// workaround for missing urlcompname in Exchange 2010
if (itemName == null) {
itemName = StringUtil.base64ToUrl(itemId.id) + ".EML";
}
}
/**
* @inheritDoc
*/
protected Event(String folderPath, String itemName, String contentClass, String itemBody, String etag, String noneMatch) throws IOException {
super(folderPath, itemName, contentClass, itemBody, etag, noneMatch);
}
@Override
public ItemResult createOrUpdate() throws IOException {
byte[] itemContent = Base64.encodeBase64(vCalendar.toString().getBytes("UTF-8"));
ItemResult itemResult = new ItemResult();
EWSMethod createOrUpdateItemMethod;
// first try to load existing event
String currentEtag = null;
ItemId currentItemId = null;
EWSMethod.Item currentItem = getEwsItem(folderPath, itemName);
if (currentItem != null) {
currentItemId = new ItemId(currentItem);
currentEtag = currentItem.get(Field.get("etag").getResponseName());
LOGGER.debug("Existing item found with etag: " + currentEtag + " id: " + currentItemId.id);
}
if ("*".equals(noneMatch)) {
// create requested
if (currentItemId != null) {
itemResult.status = HttpStatus.SC_PRECONDITION_FAILED;
return itemResult;
}
} else if (etag != null) {
// update requested
if (currentItemId == null || !etag.equals(currentEtag)) {
itemResult.status = HttpStatus.SC_PRECONDITION_FAILED;
return itemResult;
}
}
if (currentItemId != null) {
/*Set<FieldUpdate> updates = new HashSet<FieldUpdate>();
// TODO: update properties instead of brute force delete/add
updates.add(new FieldUpdate(Field.get("mimeContent"), new String(Base64.encodeBase64(itemContent))));
// update
createOrUpdateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly,
ConflictResolution.AutoResolve,
SendMeetingInvitationsOrCancellations.SendToNone,
currentItemId, updates);*/
// hard method: delete/create on update
DeleteItemMethod deleteItemMethod = new DeleteItemMethod(currentItemId, DeleteType.HardDelete, SendMeetingCancellations.SendToNone);
executeMethod(deleteItemMethod);
} //else {
// create
EWSMethod.Item newItem = new EWSMethod.Item();
newItem.type = "CalendarItem";
newItem.mimeContent = itemContent;
ArrayList<FieldUpdate> updates = new ArrayList<FieldUpdate>();
if (!vCalendar.hasVAlarm()) {
updates.add(Field.createFieldUpdate("reminderset", "false"));
}
//updates.add(Field.createFieldUpdate("outlookmessageclass", "IPM.Appointment"));
// force urlcompname
updates.add(Field.createFieldUpdate("urlcompname", convertItemNameToEML(itemName)));
if (vCalendar.isMeeting() && vCalendar.isMeetingOrganizer()) {
updates.add(Field.createFieldUpdate("apptstateflags", "1"));
} else {
updates.add(Field.createFieldUpdate("apptstateflags", "0"));
}
// store mozilla invitations option
String xMozSendInvitations = vCalendar.getFirstVeventPropertyValue("X-MOZ-SEND-INVITATIONS");
if (xMozSendInvitations != null) {
updates.add(Field.createFieldUpdate("xmozsendinvitations", xMozSendInvitations));
}
// handle mozilla alarm
String xMozLastack = vCalendar.getFirstVeventPropertyValue("X-MOZ-LASTACK");
if (xMozLastack != null) {
updates.add(Field.createFieldUpdate("xmozlastack", xMozLastack));
}
String xMozSnoozeTime = vCalendar.getFirstVeventPropertyValue("X-MOZ-SNOOZE-TIME");
if (xMozSnoozeTime != null) {
updates.add(Field.createFieldUpdate("xmozsnoozetime", xMozSnoozeTime));
}
if (vCalendar.isMeeting()) {
VCalendar.Recipients recipients = vCalendar.getRecipients(false);
if (recipients.attendees != null) {
updates.add(Field.createFieldUpdate("to", recipients.attendees));
}
if (recipients.optionalAttendees != null) {
updates.add(Field.createFieldUpdate("cc", recipients.optionalAttendees));
}
if (recipients.organizer != null && !vCalendar.isMeetingOrganizer()) {
updates.add(Field.createFieldUpdate("from", recipients.optionalAttendees));
}
}
// patch allday date values
if (vCalendar.isCdoAllDay()) {
updates.add(Field.createFieldUpdate("dtstart", convertCalendarDateToExchange(vCalendar.getFirstVeventPropertyValue("DTSTART"))));
updates.add(Field.createFieldUpdate("dtend", convertCalendarDateToExchange(vCalendar.getFirstVeventPropertyValue("DTEND"))));
}
updates.add(Field.createFieldUpdate("busystatus", "BUSY".equals(vCalendar.getFirstVeventPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS")) ? "Busy" : "Free"));
if (vCalendar.isCdoAllDay()) {
if ("Exchange2010".equals(serverVersion)) {
updates.add(Field.createFieldUpdate("starttimezone", vCalendar.getVTimezone().getPropertyValue("TZID")));
} else {
updates.add(Field.createFieldUpdate("meetingtimezone", vCalendar.getVTimezone().getPropertyValue("TZID")));
}
}
newItem.setFieldUpdates(updates);
createOrUpdateItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, SendMeetingInvitations.SendToNone, getFolderId(folderPath), newItem);
//}
executeMethod(createOrUpdateItemMethod);
itemResult.status = createOrUpdateItemMethod.getStatusCode();
if (itemResult.status == HttpURLConnection.HTTP_OK) {
//noinspection VariableNotUsedInsideIf
if (currentItemId == null) {
itemResult.status = HttpStatus.SC_CREATED;
LOGGER.debug("Updated event " + getHref());
} else {
LOGGER.warn("Overwritten event " + getHref());
}
}
ItemId newItemId = new ItemId(createOrUpdateItemMethod.getResponseItem());
GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, newItemId, false);
getItemMethod.addAdditionalProperty(Field.get("etag"));
executeMethod(getItemMethod);
itemResult.etag = getItemMethod.getResponseItem().get(Field.get("etag").getResponseName());
return itemResult;
}
@Override
public byte[] getEventContent() throws IOException {
byte[] content;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Get event: " + itemName);
}
try {
GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true);
if (!"Message".equals(type)) {
getItemMethod.addAdditionalProperty(Field.get("reminderset"));
getItemMethod.addAdditionalProperty(Field.get("calendaruid"));
getItemMethod.addAdditionalProperty(Field.get("requiredattendees"));
getItemMethod.addAdditionalProperty(Field.get("optionalattendees"));
getItemMethod.addAdditionalProperty(Field.get("xmozlastack"));
getItemMethod.addAdditionalProperty(Field.get("xmozsnoozetime"));
getItemMethod.addAdditionalProperty(Field.get("xmozsendinvitations"));
}
executeMethod(getItemMethod);
content = getItemMethod.getMimeContent();
if (content == null) {
throw new IOException("empty event body");
}
if (!"CalendarItem".equals(type)) {
content = getICS(new SharedByteArrayInputStream(content));
}
VCalendar localVCalendar = new VCalendar(content, email, getVTimezone());
// remove additional reminder
if (!"true".equals(getItemMethod.getResponseItem().get(Field.get("reminderset").getResponseName()))) {
localVCalendar.removeVAlarm();
}
String calendaruid = getItemMethod.getResponseItem().get(Field.get("calendaruid").getResponseName());
if (calendaruid != null) {
localVCalendar.setFirstVeventPropertyValue("UID", calendaruid);
}
List<EWSMethod.Attendee> attendees = getItemMethod.getResponseItem().getAttendees();
if (attendees != null) {
for (EWSMethod.Attendee attendee : attendees) {
VProperty attendeeProperty = new VProperty("ATTENDEE", "mailto:" + attendee.email);
attendeeProperty.addParam("CN", attendee.name);
attendeeProperty.addParam("PARTSTAT", attendee.partstat);
//attendeeProperty.addParam("RSVP", "TRUE");
attendeeProperty.addParam("ROLE", attendee.role);
localVCalendar.addFirstVeventProperty(attendeeProperty);
}
}
// restore mozilla invitations option
localVCalendar.setFirstVeventPropertyValue("X-MOZ-SEND-INVITATIONS",
getItemMethod.getResponseItem().get(Field.get("xmozsendinvitations").getResponseName()));
// restore mozilla alarm status
localVCalendar.setFirstVeventPropertyValue("X-MOZ-LASTACK",
getItemMethod.getResponseItem().get(Field.get("xmozlastack").getResponseName()));
localVCalendar.setFirstVeventPropertyValue("X-MOZ-SNOOZE-TIME",
getItemMethod.getResponseItem().get(Field.get("xmozsnoozetime").getResponseName()));
// overwrite method
// localVCalendar.setPropertyValue("METHOD", "REQUEST");
content = localVCalendar.toString().getBytes("UTF-8");
} catch (IOException e) {
throw buildHttpException(e);
} catch (MessagingException e) {
throw buildHttpException(e);
}
return content;
}
}
@Override
public List<ExchangeSession.Contact> searchContacts(String folderPath, Set<String> attributes, Condition condition, int maxCount) throws IOException {
List<ExchangeSession.Contact> contacts = new ArrayList<ExchangeSession.Contact>();
List<EWSMethod.Item> responses = searchItems(folderPath, attributes, condition,
FolderQueryTraversal.SHALLOW, maxCount);
for (EWSMethod.Item response : responses) {
contacts.add(new Contact(response));
}
return contacts;
}
@Override
public List<ExchangeSession.Event> getEventMessages(String folderPath) throws IOException {
return searchEvents(folderPath, ITEM_PROPERTIES,
and(startsWith("outlookmessageclass", "IPM.Schedule.Meeting."),
or(isNull("processed"), isFalse("processed"))));
}
@Override
public List<ExchangeSession.Event> searchEvents(String folderPath, Set<String> attributes, Condition condition) throws IOException {
List<ExchangeSession.Event> events = new ArrayList<ExchangeSession.Event>();
List<EWSMethod.Item> responses = searchItems(folderPath, attributes,
condition,
FolderQueryTraversal.SHALLOW, 0);
for (EWSMethod.Item response : responses) {
Event event = new Event(response);
if ("Message".equals(event.type)) {
// need to check body
try {
event.getEventContent();
events.add(event);
} catch (HttpException e) {
LOGGER.warn("Ignore invalid event " + event.getHref());
}
} else {
events.add(event);
}
}
return events;
}
protected static final HashSet<String> EVENT_REQUEST_PROPERTIES = new HashSet<String>();
static {
EVENT_REQUEST_PROPERTIES.add("permanenturl");
EVENT_REQUEST_PROPERTIES.add("etag");
EVENT_REQUEST_PROPERTIES.add("displayname");
EVENT_REQUEST_PROPERTIES.add("subject");
EVENT_REQUEST_PROPERTIES.add("urlcompname");
}
protected EWSMethod.Item getEwsItem(String folderPath, String itemName) throws IOException {
EWSMethod.Item item = null;
String urlcompname = convertItemNameToEML(itemName);
// workaround for missing urlcompname in Exchange 2010
if (isItemId(urlcompname)) {
ItemId itemId = new ItemId(StringUtil.urlToBase64(urlcompname.substring(0, 152)));
GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
for (String attribute : EVENT_REQUEST_PROPERTIES) {
getItemMethod.addAdditionalProperty(Field.get(attribute));
}
executeMethod(getItemMethod);
item = getItemMethod.getResponseItem();
- } else {
+ }
+ // find item by urlcompname
+ if (item == null) {
List<EWSMethod.Item> responses = searchItems(folderPath, EVENT_REQUEST_PROPERTIES, isEqualTo("urlcompname", urlcompname), FolderQueryTraversal.SHALLOW, 0);
if (!responses.isEmpty()) {
item = responses.get(0);
}
}
return item;
}
@Override
public Item getItem(String folderPath, String itemName) throws IOException {
EWSMethod.Item item = getEwsItem(folderPath, itemName);
if (item == null) {
throw new HttpNotFoundException(itemName + " not found in " + folderPath);
}
String itemType = item.type;
if ("Contact".equals(itemType)) {
// retrieve Contact properties
ItemId itemId = new ItemId(item);
GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
for (String attribute : CONTACT_ATTRIBUTES) {
getItemMethod.addAdditionalProperty(Field.get(attribute));
}
executeMethod(getItemMethod);
item = getItemMethod.getResponseItem();
if (item == null) {
throw new HttpNotFoundException(itemName + " not found in " + folderPath);
}
return new Contact(item);
} else if ("CalendarItem".equals(itemType)
|| "MeetingRequest".equals(itemType)
// VTODOs appear as Messages
|| "Message".equals(itemType)) {
return new Event(item);
} else {
throw new HttpNotFoundException(itemName + " not found in " + folderPath);
}
}
@Override
public ContactPhoto getContactPhoto(ExchangeSession.Contact contact) throws IOException {
ContactPhoto contactPhoto = null;
GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, ((EwsExchangeSession.Contact) contact).itemId, false);
getItemMethod.addAdditionalProperty(Field.get("attachments"));
executeMethod(getItemMethod);
EWSMethod.Item item = getItemMethod.getResponseItem();
if (item != null) {
FileAttachment attachment = item.getAttachmentByName("ContactPicture.jpg");
if (attachment != null) {
// get attachment content
GetAttachmentMethod getAttachmentMethod = new GetAttachmentMethod(attachment.attachmentId);
executeMethod(getAttachmentMethod);
contactPhoto = new ContactPhoto();
contactPhoto.content = getAttachmentMethod.getResponseItem().get("Content");
if (attachment.contentType == null) {
contactPhoto.contentType = "image/jpeg";
} else {
contactPhoto.contentType = attachment.contentType;
}
}
}
return contactPhoto;
}
@Override
public void deleteItem(String folderPath, String itemName) throws IOException {
EWSMethod.Item item = getEwsItem(folderPath, itemName);
if (item != null) {
DeleteItemMethod deleteItemMethod = new DeleteItemMethod(new ItemId(item), DeleteType.HardDelete, SendMeetingCancellations.SendToNone);
executeMethod(deleteItemMethod);
}
}
@Override
public void processItem(String folderPath, String itemName) throws IOException {
EWSMethod.Item item = getEwsItem(folderPath, itemName);
if (item != null) {
HashMap<String, String> localProperties = new HashMap<String, String>();
localProperties.put("processed", "1");
localProperties.put("read", "1");
UpdateItemMethod updateItemMethod = new UpdateItemMethod(MessageDisposition.SaveOnly,
ConflictResolution.AlwaysOverwrite,
SendMeetingInvitationsOrCancellations.SendToNone,
new ItemId(item), buildProperties(localProperties));
executeMethod(updateItemMethod);
}
}
@Override
public int sendEvent(String icsBody) throws IOException {
String itemName = UUID.randomUUID().toString() + ".EML";
byte[] mimeContent = new Event(DRAFTS, itemName, "urn:content-classes:calendarmessage", icsBody, null, null).createMimeContent();
if (mimeContent == null) {
// no recipients, cancel
return HttpStatus.SC_NO_CONTENT;
} else {
sendMessage(mimeContent);
return HttpStatus.SC_OK;
}
}
@Override
protected ItemResult internalCreateOrUpdateContact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) throws IOException {
return new Contact(folderPath, itemName, properties, etag, noneMatch).createOrUpdate();
}
@Override
protected ItemResult internalCreateOrUpdateEvent(String folderPath, String itemName, String contentClass, String icsBody, String etag, String noneMatch) throws IOException {
return new Event(folderPath, itemName, contentClass, icsBody, etag, noneMatch).createOrUpdate();
}
@Override
public boolean isSharedFolder(String folderPath) {
return folderPath.startsWith("/") && !folderPath.toLowerCase().startsWith(currentMailboxPath);
}
@Override
protected String getFreeBusyData(String attendee, String start, String end, int interval) throws IOException {
GetUserAvailabilityMethod getUserAvailabilityMethod = new GetUserAvailabilityMethod(attendee, start, end, interval);
executeMethod(getUserAvailabilityMethod);
return getUserAvailabilityMethod.getMergedFreeBusy();
}
@Override
protected void loadVtimezone() {
try {
String timezoneId = null;
if ("Exchange2010".equals(serverVersion)) {
GetUserConfigurationMethod getUserConfigurationMethod = new GetUserConfigurationMethod();
executeMethod(getUserConfigurationMethod);
EWSMethod.Item item = getUserConfigurationMethod.getResponseItem();
if (item != null) {
timezoneId = item.get("timezone");
}
} else {
timezoneId = getTimezoneidFromOptions();
}
if (timezoneId != null) {
createCalendarFolder("davmailtemp", null);
EWSMethod.Item item = new EWSMethod.Item();
item.type = "CalendarItem";
if ("Exchange2010".equals(serverVersion)) {
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
dateFormatter.setTimeZone(GMT_TIMEZONE);
Calendar cal = Calendar.getInstance();
item.put("Start", dateFormatter.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, 1);
item.put("End", dateFormatter.format(cal.getTime()));
item.put("StartTimeZone", timezoneId);
} else {
item.put("MeetingTimeZone", timezoneId);
}
CreateItemMethod createItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, SendMeetingInvitations.SendToNone, getFolderId("davmailtemp"), item);
executeMethod(createItemMethod);
item = createItemMethod.getResponseItem();
VCalendar vCalendar = new VCalendar(getContent(new ItemId(item)), email, null);
this.vTimezone = vCalendar.getVTimezone();
// delete temporary folder
deleteFolder("davmailtemp");
}
} catch (IOException e) {
LOGGER.warn("Unable to get VTIMEZONE info: " + e, e);
}
}
protected String getTimezoneidFromOptions() {
String result = null;
// get user mail URL from html body
BufferedReader optionsPageReader = null;
GetMethod optionsMethod = new GetMethod("/owa/?ae=Options&t=Regional");
try {
DavGatewayHttpClientFacade.executeGetMethod(httpClient, optionsMethod, false);
optionsPageReader = new BufferedReader(new InputStreamReader(optionsMethod.getResponseBodyAsStream()));
String line;
// find email
//noinspection StatementWithEmptyBody
while ((line = optionsPageReader.readLine()) != null
&& (line.indexOf("tblTmZn") == -1)
&& (line.indexOf("selTmZn") == -1)) {
}
if (line != null) {
if (line.indexOf("tblTmZn") >= 0) {
int start = line.indexOf("oV=\"") + 4;
int end = line.indexOf('\"', start);
result = line.substring(start, end);
} else {
int end = line.lastIndexOf("\" selected>");
int start = line.lastIndexOf('\"', end - 1);
result = line.substring(start + 1, end);
}
}
} catch (IOException e) {
LOGGER.error("Error parsing options page at " + optionsMethod.getPath());
} finally {
if (optionsPageReader != null) {
try {
optionsPageReader.close();
} catch (IOException e) {
LOGGER.error("Error parsing options page at " + optionsMethod.getPath());
}
}
optionsMethod.releaseConnection();
}
return result;
}
private FolderId getFolderId(String folderPath) throws IOException {
FolderId folderId = getFolderIdIfExists(folderPath);
if (folderId == null) {
throw new HttpNotFoundException("Folder '" + folderPath + "' not found");
}
return folderId;
}
protected static final String USERS_ROOT = "/users/";
protected FolderId getFolderIdIfExists(String folderPath) throws IOException {
String lowerCaseFolderPath = folderPath.toLowerCase();
if (currentMailboxPath.equals(lowerCaseFolderPath)) {
return getSubFolderIdIfExists(null, "");
} else if (lowerCaseFolderPath.startsWith(currentMailboxPath + '/')) {
return getSubFolderIdIfExists(null, folderPath.substring(currentMailboxPath.length() + 1));
} else if (folderPath.startsWith("/users/")) {
int slashIndex = folderPath.indexOf('/', USERS_ROOT.length());
String mailbox;
String subFolderPath;
if (slashIndex >= 0) {
mailbox = folderPath.substring(USERS_ROOT.length(), slashIndex);
subFolderPath = folderPath.substring(slashIndex + 1);
} else {
mailbox = folderPath.substring(USERS_ROOT.length());
subFolderPath = "";
}
return getSubFolderIdIfExists(mailbox, subFolderPath);
} else {
return getSubFolderIdIfExists(null, folderPath);
}
}
protected FolderId getSubFolderIdIfExists(String mailbox, String folderPath) throws IOException {
String[] folderNames;
FolderId currentFolderId;
if (folderPath.startsWith(PUBLIC_ROOT)) {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.publicfoldersroot);
folderNames = folderPath.substring(PUBLIC_ROOT.length()).split("/");
} else if (folderPath.startsWith(INBOX) || folderPath.startsWith(LOWER_CASE_INBOX)) {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.inbox);
folderNames = folderPath.substring(INBOX.length()).split("/");
} else if (folderPath.startsWith(CALENDAR)) {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.calendar);
folderNames = folderPath.substring(CALENDAR.length()).split("/");
} else if (folderPath.startsWith(CONTACTS)) {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.contacts);
folderNames = folderPath.substring(CONTACTS.length()).split("/");
} else if (folderPath.startsWith(SENT)) {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.sentitems);
folderNames = folderPath.substring(SENT.length()).split("/");
} else if (folderPath.startsWith(DRAFTS)) {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.drafts);
folderNames = folderPath.substring(DRAFTS.length()).split("/");
} else if (folderPath.startsWith(TRASH)) {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.deleteditems);
folderNames = folderPath.substring(TRASH.length()).split("/");
} else if (folderPath.startsWith(JUNK)) {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.junkemail);
folderNames = folderPath.substring(JUNK.length()).split("/");
} else if (folderPath.startsWith(UNSENT)) {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.outbox);
folderNames = folderPath.substring(UNSENT.length()).split("/");
} else {
currentFolderId = DistinguishedFolderId.getInstance(mailbox, DistinguishedFolderId.Name.msgfolderroot);
folderNames = folderPath.split("/");
}
for (String folderName : folderNames) {
if (folderName.length() > 0) {
currentFolderId = getSubFolderByName(currentFolderId, folderName);
if (currentFolderId == null) {
break;
}
}
}
return currentFolderId;
}
protected FolderId getSubFolderByName(FolderId parentFolderId, String folderName) throws IOException {
FolderId folderId = null;
FindFolderMethod findFolderMethod = new FindFolderMethod(
FolderQueryTraversal.SHALLOW,
BaseShape.ID_ONLY,
parentFolderId,
FOLDER_PROPERTIES,
new TwoOperandExpression(TwoOperandExpression.Operator.IsEqualTo,
Field.get("folderDisplayName"), folderName)
);
executeMethod(findFolderMethod);
EWSMethod.Item item = findFolderMethod.getResponseItem();
if (item != null) {
folderId = new FolderId(parentFolderId.mailbox, item);
}
return folderId;
}
protected void executeMethod(EWSMethod ewsMethod) throws IOException {
try {
ewsMethod.setServerVersion(serverVersion);
httpClient.executeMethod(ewsMethod);
if (serverVersion == null) {
serverVersion = ewsMethod.getServerVersion();
}
ewsMethod.checkSuccess();
} finally {
ewsMethod.releaseConnection();
}
}
protected static final HashMap<String, String> GALFIND_ATTRIBUTE_MAP = new HashMap<String, String>();
static {
GALFIND_ATTRIBUTE_MAP.put("imapUid", "Name");
GALFIND_ATTRIBUTE_MAP.put("cn", "DisplayName");
GALFIND_ATTRIBUTE_MAP.put("givenName", "GivenName");
GALFIND_ATTRIBUTE_MAP.put("sn", "Surname");
GALFIND_ATTRIBUTE_MAP.put("smtpemail1", "EmailAddress1");
GALFIND_ATTRIBUTE_MAP.put("smtpemail2", "EmailAddress2");
GALFIND_ATTRIBUTE_MAP.put("smtpemail3", "EmailAddress3");
GALFIND_ATTRIBUTE_MAP.put("roomnumber", "OfficeLocation");
GALFIND_ATTRIBUTE_MAP.put("street", "BusinessStreet");
GALFIND_ATTRIBUTE_MAP.put("l", "BusinessCity");
GALFIND_ATTRIBUTE_MAP.put("o", "CompanyName");
GALFIND_ATTRIBUTE_MAP.put("postalcode", "BusinessPostalCode");
GALFIND_ATTRIBUTE_MAP.put("st", "BusinessState");
GALFIND_ATTRIBUTE_MAP.put("co", "BusinessCountryOrRegion");
GALFIND_ATTRIBUTE_MAP.put("manager", "Manager");
GALFIND_ATTRIBUTE_MAP.put("middlename", "Initials");
GALFIND_ATTRIBUTE_MAP.put("title", "JobTitle");
GALFIND_ATTRIBUTE_MAP.put("department", "Department");
GALFIND_ATTRIBUTE_MAP.put("otherTelephone", "OtherTelephone");
GALFIND_ATTRIBUTE_MAP.put("telephoneNumber", "BusinessPhone");
GALFIND_ATTRIBUTE_MAP.put("mobile", "MobilePhone");
GALFIND_ATTRIBUTE_MAP.put("facsimiletelephonenumber", "BusinessFax");
GALFIND_ATTRIBUTE_MAP.put("secretarycn", "AssistantName");
}
protected static final HashSet<String> IGNORE_ATTRIBUTE_SET = new HashSet<String>();
static {
IGNORE_ATTRIBUTE_SET.add("ContactSource");
IGNORE_ATTRIBUTE_SET.add("Culture");
IGNORE_ATTRIBUTE_SET.add("AssistantPhone");
}
protected Contact buildGalfindContact(EWSMethod.Item response) {
Contact contact = new Contact();
contact.setName(response.get("Name"));
contact.put("imapUid", response.get("Name"));
contact.put("uid", response.get("Name"));
if (LOGGER.isDebugEnabled()) {
for (String key : response.keySet()) {
if (!IGNORE_ATTRIBUTE_SET.contains(key) && !GALFIND_ATTRIBUTE_MAP.containsValue(key)) {
LOGGER.debug("Unsupported ResolveNames in " + contact.getName() + " response attribute: " + key + " value: " + response.get(key));
}
}
}
for (Map.Entry<String, String> entry : GALFIND_ATTRIBUTE_MAP.entrySet()) {
String attributeValue = response.get(entry.getValue());
if (attributeValue != null) {
contact.put(entry.getKey(), attributeValue);
}
}
return contact;
}
@Override
public Map<String, ExchangeSession.Contact> galFind(Condition condition, Set<String> returningAttributes, int sizeLimit) throws IOException {
Map<String, ExchangeSession.Contact> contacts = new HashMap<String, ExchangeSession.Contact>();
if (condition instanceof MultiCondition) {
List<Condition> conditions = ((ExchangeSession.MultiCondition) condition).getConditions();
Operator operator = ((ExchangeSession.MultiCondition) condition).getOperator();
if (operator == Operator.Or) {
for (Condition innerCondition : conditions) {
contacts.putAll(galFind(innerCondition, returningAttributes, sizeLimit));
}
} else if (operator == Operator.And && !conditions.isEmpty()) {
Map<String, ExchangeSession.Contact> innerContacts = galFind(conditions.get(0), returningAttributes, sizeLimit);
for (ExchangeSession.Contact contact : innerContacts.values()) {
if (condition.isMatch(contact)) {
contacts.put(contact.getName().toLowerCase(), contact);
}
}
}
} else if (condition instanceof AttributeCondition) {
String mappedAttributeName = GALFIND_ATTRIBUTE_MAP.get(((ExchangeSession.AttributeCondition) condition).getAttributeName());
if (mappedAttributeName != null) {
String value = ((ExchangeSession.AttributeCondition) condition).getValue().toLowerCase();
Operator operator = ((AttributeCondition) condition).getOperator();
String searchValue = value;
if (mappedAttributeName.startsWith("EmailAddress")) {
searchValue = "smtp:" + searchValue;
}
if (operator == Operator.IsEqualTo) {
searchValue = '=' + searchValue;
}
ResolveNamesMethod resolveNamesMethod = new ResolveNamesMethod(searchValue);
executeMethod(resolveNamesMethod);
List<EWSMethod.Item> responses = resolveNamesMethod.getResponseItems();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("ResolveNames(" + searchValue + ") returned " + responses.size() + " results");
}
for (EWSMethod.Item response : responses) {
Contact contact = buildGalfindContact(response);
if (condition.isMatch(contact)) {
contacts.put(contact.getName().toLowerCase(), contact);
}
}
}
}
return contacts;
}
protected String convertDateFromExchange(String exchangeDateValue) throws DavMailException {
String zuluDateValue = null;
if (exchangeDateValue != null) {
try {
zuluDateValue = getZuluDateFormat().format(getExchangeZuluDateFormat().parse(exchangeDateValue));
} catch (ParseException e) {
throw new DavMailException("EXCEPTION_INVALID_DATE", exchangeDateValue);
}
}
return zuluDateValue;
}
protected String convertCalendarDateToExchange(String vcalendarDateValue) throws DavMailException {
String zuluDateValue = null;
if (vcalendarDateValue != null) {
try {
SimpleDateFormat dateParser;
if (vcalendarDateValue.length() == 8) {
dateParser = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
} else {
dateParser = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
}
dateParser.setTimeZone(GMT_TIMEZONE);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
dateFormatter.setTimeZone(GMT_TIMEZONE);
zuluDateValue = dateFormatter.format(dateParser.parse(vcalendarDateValue));
} catch (ParseException e) {
throw new DavMailException("EXCEPTION_INVALID_DATE", vcalendarDateValue);
}
}
return zuluDateValue;
}
/**
* Format date to exchange search format.
*
* @param date date object
* @return formatted search date
*/
@Override
public String formatSearchDate(Date date) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(YYYY_MM_DD_T_HHMMSS_Z, Locale.ENGLISH);
dateFormatter.setTimeZone(GMT_TIMEZONE);
return dateFormatter.format(date);
}
protected static boolean isItemId(String itemName) {
return itemName.length() == 156;
}
}
| false | false | null | null |
diff --git a/libs/SalesforceSDK/src/com/salesforce/androidsdk/app/SalesforceSDKManager.java b/libs/SalesforceSDK/src/com/salesforce/androidsdk/app/SalesforceSDKManager.java
index c7cb1bdaa..7775bee6d 100644
--- a/libs/SalesforceSDK/src/com/salesforce/androidsdk/app/SalesforceSDKManager.java
+++ b/libs/SalesforceSDK/src/com/salesforce/androidsdk/app/SalesforceSDKManager.java
@@ -1,1002 +1,1003 @@
/*
* Copyright (c) 2014, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software 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 salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.app;
import java.net.URI;
import java.util.List;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import com.salesforce.androidsdk.accounts.UserAccount;
import com.salesforce.androidsdk.accounts.UserAccountManager;
import com.salesforce.androidsdk.auth.AuthenticatorService;
import com.salesforce.androidsdk.auth.HttpAccess;
import com.salesforce.androidsdk.auth.LoginServerManager;
import com.salesforce.androidsdk.auth.OAuth2;
import com.salesforce.androidsdk.push.PushMessaging;
import com.salesforce.androidsdk.push.PushNotificationInterface;
import com.salesforce.androidsdk.rest.AdminPrefsManager;
import com.salesforce.androidsdk.rest.BootConfig;
import com.salesforce.androidsdk.rest.ClientManager;
import com.salesforce.androidsdk.rest.ClientManager.LoginOptions;
import com.salesforce.androidsdk.security.Encryptor;
import com.salesforce.androidsdk.security.PRNGFixes;
import com.salesforce.androidsdk.security.PasscodeManager;
import com.salesforce.androidsdk.ui.AccountSwitcherActivity;
import com.salesforce.androidsdk.ui.LoginActivity;
import com.salesforce.androidsdk.ui.PasscodeActivity;
import com.salesforce.androidsdk.ui.SalesforceR;
import com.salesforce.androidsdk.ui.sfhybrid.SalesforceDroidGapActivity;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;
/**
* This class serves as an interface to the various
* functions of the Salesforce SDK. In order to use the SDK,
* your app must first instantiate the singleton SalesforceSDKManager
* object by calling the static init() method. After calling init(),
* use the static getInstance() method to access the
* singleton SalesforceSDKManager object.
*/
public class SalesforceSDKManager {
/**
* Current version of this SDK.
*/
public static final String SDK_VERSION = "3.1.0.unstable";
/**
* Default app name.
*/
private static final String DEFAULT_APP_DISPLAY_NAME = "Salesforce";
/**
* Instance of the SalesforceSDKManager to use for this process.
*/
protected static SalesforceSDKManager INSTANCE;
/**
* Timeout value for push un-registration.
*/
private static final int PUSH_UNREGISTER_TIMEOUT_MILLIS = 30000;
protected Context context;
protected KeyInterface keyImpl;
protected LoginOptions loginOptions;
protected Class<? extends Activity> mainActivityClass;
protected Class<? extends Activity> loginActivityClass = LoginActivity.class;
protected Class<? extends PasscodeActivity> passcodeActivityClass = PasscodeActivity.class;
protected Class<? extends AccountSwitcherActivity> switcherActivityClass = AccountSwitcherActivity.class;
private String encryptionKey;
private SalesforceR salesforceR = new SalesforceR();
private PasscodeManager passcodeManager;
private LoginServerManager loginServerManager;
private boolean isTestRun = false;
private boolean isLoggingOut = false;
private AdminPrefsManager adminPrefsManager;
private PushNotificationInterface pushNotificationInterface;
private volatile boolean loggedOut = false;
/**
* PasscodeManager object lock.
*/
private Object passcodeManagerLock = new Object();
/**
* Returns a singleton instance of this class.
*
* @param context Application context.
* @return Singleton instance of SalesforceSDKManager.
*/
public static SalesforceSDKManager getInstance() {
if (INSTANCE != null) {
return INSTANCE;
} else {
throw new RuntimeException("Applications need to call SalesforceSDKManager.init() first.");
}
}
/**
* Protected constructor.
*
* @param context Application context.
* @param keyImpl Implementation for KeyInterface.
* @param mainActivity Activity that should be launched after the login flow.
* @param loginActivity Login activity.
*/
protected SalesforceSDKManager(Context context, KeyInterface keyImpl,
Class<? extends Activity> mainActivity, Class<? extends Activity> loginActivity) {
this.context = context;
this.keyImpl = keyImpl;
this.mainActivityClass = mainActivity;
if (loginActivity != null) {
this.loginActivityClass = loginActivity;
}
}
/**
* Returns the class for the main activity.
*
* @return The class for the main activity.
*/
public Class<? extends Activity> getMainActivityClass() {
return mainActivityClass;
}
/**
* Returns the class for the account switcher activity.
*
* @return The class for the account switcher activity.
*/
public Class<? extends AccountSwitcherActivity> getAccountSwitcherActivityClass() {
return switcherActivityClass;
}
/**
* Returns the class for the account switcher activity.
*
* @return The class for the account switcher activity.
*/
public void setAccountSwitcherActivityClass(Class<? extends AccountSwitcherActivity> activity) {
if (activity != null) {
switcherActivityClass = activity;
}
}
public interface KeyInterface {
/**
* Defines a single function for retrieving the key
* associated with a given name.
*
* For the given name, this function must return the same key
* even when the application is restarted. The value this
* function returns must be Base64 encoded.
*
* {@link Encryptor#isBase64Encoded(String)} can be used to
* determine whether the generated key is Base64 encoded.
*
* {@link Encryptor#hash(String, String)} can be used to
* generate a Base64 encoded string.
*
* For example:
* <code>
* Encryptor.hash(name + "12s9adfgret=6235inkasd=012", name + "12kl0dsakj4-cuygsdf625wkjasdol8");
* </code>
*
* @param name The name associated with the key.
* @return The key used for encrypting salts and keys.
*/
public String getKey(String name);
}
/**
* For the given name, this function must return the same key
* even when the application is restarted. The value this
* function returns must be Base64 encoded.
*
* {@link Encryptor#isBase64Encoded(String)} can be used to
* determine whether the generated key is Base64 encoded.
*
* {@link Encryptor#hash(String, String)} can be used to
* generate a Base64 encoded string.
*
* For example:
* <code>
* Encryptor.hash(name + "12s9adfgret=6235inkasd=012", name + "12kl0dsakj4-cuygsdf625wkjasdol8");
* </code>
*
* @param name The name associated with the key.
* @return The key used for encrypting salts and keys.
*/
public String getKey(String name) {
String key = null;
if (keyImpl != null) {
key = keyImpl.getKey(name);
}
return key;
}
/**
* Before Mobile SDK 1.3, SalesforceSDK was packaged as a jar, and each project had to provide
* a subclass of SalesforceR.
*
* Since 1.3, SalesforceSDK is packaged as a library project, so the SalesforceR subclass is no longer needed.
* @return SalesforceR object which allows reference to resources living outside the SDK.
*/
public SalesforceR getSalesforceR() {
return salesforceR;
}
/**
* Returns the class of the activity used to perform the login process and create the account.
*
* @return the class of the activity used to perform the login process and create the account.
*/
public Class<? extends Activity> getLoginActivityClass() {
return loginActivityClass;
}
/**
* Returns login options associated with the app.
*
* @return LoginOptions instance.
*/
public LoginOptions getLoginOptions() {
if (loginOptions == null) {
final BootConfig config = BootConfig.getBootConfig(context);
loginOptions = new LoginOptions(null, getPasscodeHash(), config.getOauthRedirectURI(),
config.getRemoteAccessConsumerKey(), config.getOauthScopes());
}
return loginOptions;
}
/**
* For internal use only. Initializes required components.
*
* @param context Application context.
* @param keyImpl Implementation of KeyInterface.
* @param mainActivity Activity to be launched after the login flow.
* @param loginActivity Login activity.
*/
private static void init(Context context, KeyInterface keyImpl,
Class<? extends Activity> mainActivity, Class<? extends Activity> loginActivity) {
if (INSTANCE == null) {
INSTANCE = new SalesforceSDKManager(context, keyImpl, mainActivity, loginActivity);
}
initInternal(context);
}
/**
* For internal use by Salesforce Mobile SDK or by subclasses
* of SalesforceSDKManager. Initializes required components.
*
* @param context Application context.
*/
public static void initInternal(Context context) {
// Applies PRNG fixes for certain older versions of Android.
PRNGFixes.apply();
// Initializes the encryption module.
Encryptor.init(context);
// Initializes the HTTP client.
HttpAccess.init(context, INSTANCE.getUserAgent());
// Ensures that we have a CookieSyncManager instance.
CookieSyncManager.createInstance(context);
// Upgrades to the latest version.
UpgradeManager.getInstance().upgradeAccMgr();
EventsObservable.get().notifyEvent(EventType.AppCreateComplete);
}
/**
* Initializes required components. Hybrid apps must call one overload of
* this method before using the Salesforce Mobile SDK.
*
* @param context Application context.
* @param keyImpl Implementation of KeyInterface.
*/
public static void initHybrid(Context context, KeyInterface keyImpl) {
SalesforceSDKManager.init(context, keyImpl, SalesforceDroidGapActivity.class, LoginActivity.class);
}
/**
* Initializes required components. Hybrid apps must call one overload of
* this method before using the Salesforce Mobile SDK.
*
* @param context Application context.
* @param keyImpl Implementation of KeyInterface.
* @param loginActivity Login activity.
*/
public static void initHybrid(Context context, KeyInterface keyImpl, Class<? extends Activity> loginActivity) {
SalesforceSDKManager.init(context, keyImpl, SalesforceDroidGapActivity.class, loginActivity);
}
/**
* Initializes required components. Hybrid apps must call one overload of
* this method before using the Salesforce Mobile SDK.
*
* @param context Application context.
* @param keyImpl Implementation of KeyInterface.
* @param mainActivity Main activity.
* @param loginActivity Login activity.
*/
public static void initHybrid(Context context, KeyInterface keyImpl,
Class<? extends SalesforceDroidGapActivity> mainActivity, Class<? extends Activity> loginActivity) {
SalesforceSDKManager.init(context, keyImpl, mainActivity, loginActivity);
}
/**
* Initializes required components. Native apps must call one overload of
* this method before using the Salesforce Mobile SDK.
*
* @param context Application context.
* @param keyImpl Implementation of KeyInterface.
* @param mainActivity Activity that should be launched after the login flow.
*/
public static void initNative(Context context, KeyInterface keyImpl, Class<? extends Activity> mainActivity) {
SalesforceSDKManager.init(context, keyImpl, mainActivity, LoginActivity.class);
}
/**
* Initializes required components. Native apps must call one overload of
* this method before using the Salesforce Mobile SDK.
*
* @param context Application context.
* @param keyImpl Implementation of KeyInterface.
* @param mainActivity Activity that should be launched after the login flow.
* @param loginActivity Login activity.
*/
public static void initNative(Context context, KeyInterface keyImpl,
Class<? extends Activity> mainActivity, Class<? extends Activity> loginActivity) {
SalesforceSDKManager.init(context, keyImpl, mainActivity, loginActivity);
}
/**
* Sets a custom passcode activity class to be used instead of the default class.
* The custom class must subclass PasscodeActivity.
*
* @param activity Subclass of PasscodeActivity.
*/
public void setPasscodeActivity(Class<? extends PasscodeActivity> activity) {
if (activity != null) {
passcodeActivityClass = activity;
}
}
/**
* Returns the descriptor of the passcode activity class that's currently in use.
*
* @return Passcode activity class descriptor.
*/
public Class<? extends PasscodeActivity> getPasscodeActivity() {
return passcodeActivityClass;
}
/**
* Indicates whether the SDK should automatically log out when the
* access token is revoked. If you override this method to return
* false, your app is responsible for handling its own cleanup when the
* access token is revoked.
*
* @return True if the SDK should automatically logout.
*/
public boolean shouldLogoutWhenTokenRevoked() {
return true;
}
/**
* Returns the application context.
*
* @return Application context.
*/
public Context getAppContext() {
return context;
}
/**
* Returns the login server manager associated with SalesforceSDKManager.
*
* @return LoginServerManager instance.
*/
public synchronized LoginServerManager getLoginServerManager() {
if (loginServerManager == null) {
loginServerManager = new LoginServerManager(context);
}
return loginServerManager;
}
/**
* Sets a receiver that handles received push notifications.
*
* @param pnInterface Implementation of PushNotificationInterface.
*/
public synchronized void setPushNotificationReceiver(PushNotificationInterface pnInterface) {
pushNotificationInterface = pnInterface;
}
/**
* Returns the receiver that's configured to handle incoming push notifications.
*
* @return Configured implementation of PushNotificationInterface.
*/
public synchronized PushNotificationInterface getPushNotificationReceiver() {
return pushNotificationInterface;
}
/**
* Returns the passcode manager that's associated with SalesforceSDKManager.
*
* @return PasscodeManager instance.
*/
public PasscodeManager getPasscodeManager() {
synchronized (passcodeManagerLock) {
if (passcodeManager == null) {
passcodeManager = new PasscodeManager(context);
}
return passcodeManager;
}
}
/**
* Returns the user account manager that's associated with SalesforceSDKManager.
*
* @return UserAccountManager instance.
*/
public UserAccountManager getUserAccountManager() {
return UserAccountManager.getInstance();
}
/**
* Returns the administrator preferences manager that's associated with SalesforceSDKManager.
*
* @return AdminPrefsManager instance.
*/
public synchronized AdminPrefsManager getAdminPrefsManager() {
if (adminPrefsManager == null) {
adminPrefsManager = new AdminPrefsManager();
}
return adminPrefsManager;
}
/**
* Changes the passcode to a new value.
*
* @param oldPass Old passcode.
* @param newPass New passcode.
*/
public synchronized void changePasscode(String oldPass, String newPass) {
if (!isNewPasscode(oldPass, newPass)) {
return;
}
// Resets the cached encryption key, since the passcode has changed.
encryptionKey = null;
ClientManager.changePasscode(oldPass, newPass);
}
/**
* Indicates whether the new passcode is different from the old passcode.
*
* @param oldPass Old passcode.
* @param newPass New passcode.
* @return True if the new passcode is different from the old passcode.
*/
protected boolean isNewPasscode(String oldPass, String newPass) {
return !((oldPass == null && newPass == null)
|| (oldPass != null && newPass != null && oldPass.trim().equals(newPass.trim())));
}
/**
* Returns the encryption key being used.
*
* @param actualPass Passcode.
* @return Encryption key for passcode.
*/
public synchronized String getEncryptionKeyForPasscode(String actualPass) {
if (actualPass != null && !actualPass.trim().equals("")) {
return actualPass;
}
if (encryptionKey == null) {
encryptionKey = getPasscodeManager().hashForEncryption("");
}
return encryptionKey;
}
/**
* Returns the app display name used by the passcode dialog.
*
* @return App display string.
*/
public String getAppDisplayString() {
return DEFAULT_APP_DISPLAY_NAME;
}
/**
* Returns the passcode hash being used.
*
* @return The hashed passcode, or null if it's not required.
*/
public String getPasscodeHash() {
return getPasscodeManager().getPasscodeHash();
}
/**
* Returns the name of the application (as defined in AndroidManifest.xml).
*
* @return The name of the application.
*/
public String getApplicationName() {
return context.getPackageManager().getApplicationLabel(context.getApplicationInfo()).toString();
}
/**
* Checks if network connectivity exists.
*
* @return True if a network connection is available.
*/
public boolean hasNetwork() {
return HttpAccess.DEFAULT.hasNetwork();
}
/**
* Cleans up cached credentials and data.
*
* @param frontActivity Front activity.
* @param account Account.
*/
protected void cleanUp(Activity frontActivity, Account account) {
final List<UserAccount> users = getUserAccountManager().getAuthenticatedUsers();
// Finishes front activity if specified, and if this is the last account.
if (frontActivity != null && (users == null || users.size() <= 1)) {
frontActivity.finish();
}
/*
* Checks how many accounts are left that are authenticated. If only one
* account is left, this is the account that is being removed. In this
* case, we can safely reset passcode manager, admin prefs, and encryption keys.
* Otherwise, we don't reset passcode manager and admin prefs since
* there might be other accounts on that same org, and these policies
* are stored at the org level.
*/
if (users == null || users.size() <= 1) {
getAdminPrefsManager().resetAll();
adminPrefsManager = null;
getPasscodeManager().reset(context);
passcodeManager = null;
encryptionKey = null;
UUIDManager.resetUuids();
}
}
/**
* Starts login flow if user account has been removed.
*/
protected void startLoginPage() {
// Clears cookies.
CookieSyncManager.createInstance(context);
CookieManager.getInstance().removeAllCookie();
// Restarts the application.
final Intent i = new Intent(context, getMainActivityClass());
i.setPackage(getAppContext().getPackageName());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
/**
* Starts account switcher activity if an account has been removed.
*/
public void startSwitcherActivityIfRequired() {
// Clears cookies.
CookieSyncManager.createInstance(context);
CookieManager.getInstance().removeAllCookie();
/*
* If the number of accounts remaining is 0, shows the login page.
* If the number of accounts remaining is 1, switches to that user
* automatically. If there is more than 1 account logged in, shows
* the account switcher screen, so that the user can pick which
* account to switch to.
*/
final UserAccountManager userAccMgr = getUserAccountManager();
final List<UserAccount> accounts = userAccMgr.getAuthenticatedUsers();
if (accounts == null || accounts.size() == 0) {
startLoginPage();
} else if (accounts.size() == 1) {
userAccMgr.switchToUser(accounts.get(0));
} else {
final Intent i = new Intent(context, switcherActivityClass);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
/**
* Unregisters from push notifications for both GCM (Android) and SFDC, and waits either for
* unregistration to complete or for the operation to time out. The timeout period is defined
* in PUSH_UNREGISTER_TIMEOUT_MILLIS.
*
* If timeout occurs while the user is logged in, this method attempts to unregister the push
* unregistration receiver, and then removes the user's account.
*
* @param clientMgr ClientManager instance.
* @param showLoginPage True - if the login page should be shown, False - otherwise.
* @param refreshToken Refresh token.
* @param clientId Client ID.
* @param loginServer Login server.
* @param account Account instance.
* @param frontActivity Front activity.
*/
private void unregisterPush(final ClientManager clientMgr, final boolean showLoginPage,
final String refreshToken, final String clientId,
final String loginServer, final Account account, final Activity frontActivity) {
final IntentFilter intentFilter = new IntentFilter(PushMessaging.UNREGISTERED_ATTEMPT_COMPLETE_EVENT);
final BroadcastReceiver pushUnregisterReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(PushMessaging.UNREGISTERED_ATTEMPT_COMPLETE_EVENT)) {
postPushUnregister(this, clientMgr, showLoginPage,
refreshToken, clientId, loginServer, account, frontActivity);
}
}
};
getAppContext().registerReceiver(pushUnregisterReceiver, intentFilter);
// Unregisters from notifications on logout.
final UserAccount userAcc = getUserAccountManager().buildUserAccount(account);
PushMessaging.unregister(context, userAcc);
/*
* Starts a background thread to wait up to the timeout period. If
* another thread has already performed logout, we exit immediately.
*/
(new Thread() {
public void run() {
long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) < PUSH_UNREGISTER_TIMEOUT_MILLIS && !loggedOut) {
// Waits for half a second at a time.
SystemClock.sleep(500);
}
postPushUnregister(pushUnregisterReceiver, clientMgr, showLoginPage,
refreshToken, clientId, loginServer, account, frontActivity);
};
}).start();
}
/**
* This method is called either when unregistration for push notifications
* is complete and the user has logged out, or when a timeout occurs while waiting.
* If the user has not logged out, this method attempts to unregister the push
* notification unregistration receiver, and then removes the user's account.
*
* @param pushReceiver Broadcast receiver.
* @param clientMgr ClientManager instance.
* @param showLoginPage True - if the login page should be shown, False - otherwise.
* @param refreshToken Refresh token.
* @param clientId Client ID.
* @param loginServer Login server.
* @param account Account instance.
* @param frontActivity Front activity.
*/
private synchronized void postPushUnregister(BroadcastReceiver pushReceiver,
final ClientManager clientMgr, final boolean showLoginPage,
final String refreshToken, final String clientId,
final String loginServer, final Account account, Activity frontActivity) {
if (!loggedOut) {
try {
context.unregisterReceiver(pushReceiver);
} catch (Exception e) {
Log.e("SalesforceSDKManager:postPushUnregister", "Exception occurred while un-registering.", e);
}
removeAccount(clientMgr, showLoginPage, refreshToken, clientId, loginServer, account, frontActivity);
}
}
/**
* Destroys the stored authentication credentials (removes the account).
*
* @param frontActivity Front activity.
*/
public void logout(Activity frontActivity) {
logout(frontActivity, true);
}
/**
* Destroys the stored authentication credentials (removes the account).
*
* @param account Account.
* @param frontActivity Front activity.
*/
public void logout(Account account, Activity frontActivity) {
logout(account, frontActivity, true);
}
/**
* Destroys the stored authentication credentials (removes the account)
* and, if requested, restarts the app.
*
* @param frontActivity Front activity.
* @param showLoginPage If true, displays the login page after removing the account.
*/
public void logout(Activity frontActivity, final boolean showLoginPage) {
final ClientManager clientMgr = new ClientManager(context, getAccountType(),
null, shouldLogoutWhenTokenRevoked());
final Account account = clientMgr.getAccount();
logout(account, frontActivity, showLoginPage);
}
/**
* Destroys the stored authentication credentials (removes the account)
* and, if requested, restarts the app.
*
* @param account Account.
* @param frontActivity Front activity.
* @param showLoginPage If true, displays the login page after removing the account.
*/
public void logout(Account account, Activity frontActivity, final boolean showLoginPage) {
final ClientManager clientMgr = new ClientManager(context, getAccountType(),
null, shouldLogoutWhenTokenRevoked());
isLoggingOut = true;
final AccountManager mgr = AccountManager.get(context);
String refreshToken = null;
String clientId = null;
String loginServer = null;
if (account != null) {
String passcodeHash = getPasscodeHash();
refreshToken = SalesforceSDKManager.decryptWithPasscode(mgr.getPassword(account),
passcodeHash);
clientId = SalesforceSDKManager.decryptWithPasscode(mgr.getUserData(account,
AuthenticatorService.KEY_CLIENT_ID), passcodeHash);
loginServer = SalesforceSDKManager.decryptWithPasscode(mgr.getUserData(account,
AuthenticatorService.KEY_INSTANCE_URL), passcodeHash);
}
/*
* Makes a call to un-register from push notifications, only
* if the refresh token is available.
*/
final UserAccount userAcc = getUserAccountManager().buildUserAccount(account);
if (PushMessaging.isRegistered(context, userAcc) && refreshToken != null) {
loggedOut = false;
unregisterPush(clientMgr, showLoginPage, refreshToken, clientId,
loginServer, account, frontActivity);
} else {
removeAccount(clientMgr, showLoginPage, refreshToken, clientId,
loginServer, account, frontActivity);
}
}
/**
* Removes the account upon logout.
*
* @param clientMgr ClientManager instance.
* @param showLoginPage If true, displays the login page after removing the account.
* @param refreshToken Refresh token.
* @param clientId Client ID.
* @param loginServer Login server.
* @param account Account instance.
* @param frontActivity Front activity.
*/
private void removeAccount(ClientManager clientMgr, final boolean showLoginPage,
String refreshToken, String clientId, String loginServer,
Account account, Activity frontActivity) {
loggedOut = true;
cleanUp(frontActivity, account);
// Removes the exisiting account, if any.
if (account == null) {
EventsObservable.get().notifyEvent(EventType.LogoutComplete);
if (showLoginPage) {
startSwitcherActivityIfRequired();
}
} else {
clientMgr.removeAccountAsync(account, new AccountManagerCallback<Boolean>() {
@Override
public void run(AccountManagerFuture<Boolean> arg0) {
EventsObservable.get().notifyEvent(EventType.LogoutComplete);
if (showLoginPage) {
startSwitcherActivityIfRequired();
}
}
});
}
isLoggingOut = false;
// Revokes the existing refresh token.
if (shouldLogoutWhenTokenRevoked() && account != null && refreshToken != null) {
new RevokeTokenTask(refreshToken, clientId, loginServer).execute();
}
}
/**
* Returns a user agent string based on the Mobile SDK version. The user agent takes the following form:
* SalesforceMobileSDK/<salesforceSDK version> android/<android OS version> appName/appVersion <Native|Hybrid>
*
* @return The user agent string to use for all requests.
*/
public final String getUserAgent() {
return getUserAgent("");
}
public final String getUserAgent(String qualifier) {
String appName = "";
String appVersion = "";
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
appName = context.getString(packageInfo.applicationInfo.labelRes);
appVersion = packageInfo.versionName;
} catch (NameNotFoundException e) {
Log.w("SalesforceSDKManager:getUserAgent", e);
} catch (Resources.NotFoundException nfe) {
- // if your application doesn't have a name (like a test harness from Gradle)
+
+ // A test harness such as Gradle does NOT have an application name.
Log.w("SalesforceSDKManager:getUserAgent", nfe);
}
String nativeOrHybrid = (isHybrid() ? "Hybrid" : "Native") + qualifier;
return String.format("SalesforceMobileSDK/%s android mobile/%s (%s) %s/%s %s",
SDK_VERSION, Build.VERSION.RELEASE, Build.MODEL, appName, appVersion, nativeOrHybrid);
}
/**
* Indicates whether the application is a hybrid application.
*
* @return True if this is a hybrid application.
*/
public boolean isHybrid() {
return SalesforceDroidGapActivity.class.isAssignableFrom(getMainActivityClass());
}
/**
* Returns the authentication account type (which should match authenticator.xml).
*
* @return Account type string.
*/
public String getAccountType() {
return context.getString(getSalesforceR().stringAccountType());
}
/**
* Indicates whether the app is running on a tablet.
*
* @return True if the application is running on a tablet.
*/
public static boolean isTablet() {
if ((INSTANCE.context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
return true;
}
return false;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(this.getClass()).append(": {\n")
.append(" accountType: ").append(getAccountType()).append("\n")
.append(" userAgent: ").append(getUserAgent()).append("\n")
.append(" mainActivityClass: ").append(getMainActivityClass()).append("\n")
.append(" isFileSystemEncrypted: ").append(Encryptor.isFileSystemEncrypted()).append("\n");
if (passcodeManager != null) {
// passcodeManager may be null at startup if the app is running in debug mode.
sb.append(" hasStoredPasscode: ").append(passcodeManager.hasStoredPasscode(context)).append("\n");
}
sb.append("}\n");
return sb.toString();
}
/**
* Encrypts the given data using the given passcode as the encryption key.
*
* @param data Data to be encrypted.
* @param passcode Encryption key.
* @return Encrypted data.
*/
public static String encryptWithPasscode(String data, String passcode) {
return Encryptor.encrypt(data, SalesforceSDKManager.INSTANCE.getEncryptionKeyForPasscode(passcode));
}
/**
* Decrypts the given data using the given passcode as the decryption key.
*
* @param data Data to be decrypted.
* @param passcode Decryption key.
* @return Decrypted data.
*/
public static String decryptWithPasscode(String data, String passcode) {
return Encryptor.decrypt(data, SalesforceSDKManager.INSTANCE.getEncryptionKeyForPasscode(passcode));
}
/**
* Asynchronous task for revoking the refresh token on logout.
*
* @author bhariharan
*/
private class RevokeTokenTask extends AsyncTask<Void, Void, Void> {
private String refreshToken;
private String clientId;
private String loginServer;
public RevokeTokenTask(String refreshToken, String clientId, String loginServer) {
this.refreshToken = refreshToken;
this.clientId = clientId;
this.loginServer = loginServer;
}
@Override
protected Void doInBackground(Void... nothings) {
try {
OAuth2.revokeRefreshToken(HttpAccess.DEFAULT, new URI(loginServer), clientId, refreshToken);
} catch (Exception e) {
Log.w("SalesforceSDKManager:revokeToken", e);
}
return null;
}
}
/**
* Retrieves a property value that indicates whether the current run is a test run.
*
* @return True if the current run is a test run.
*/
public boolean getIsTestRun() {
return INSTANCE.isTestRun;
}
/**
* Sets a property that indicates whether the current run is a test run.
*
* @param isTestRun True if the current run is a test run.
*/
public void setIsTestRun(boolean isTestRun) {
INSTANCE.isTestRun = isTestRun;
}
/**
* Retrieves a property value that indicates whether logout is in progress.
*
* @return True if logout is in progress.
*/
public boolean isLoggingOut() {
return isLoggingOut;
}
/**
* @return ClientManager
*/
public ClientManager getClientManager() {
return new ClientManager(getAppContext(), getAccountType(), getLoginOptions(), true);
}
}
diff --git a/libs/SalesforceSDK/src/com/salesforce/androidsdk/phonegap/SDKInfoPlugin.java b/libs/SalesforceSDK/src/com/salesforce/androidsdk/phonegap/SDKInfoPlugin.java
index 38106840d..eba184a6f 100644
--- a/libs/SalesforceSDK/src/com/salesforce/androidsdk/phonegap/SDKInfoPlugin.java
+++ b/libs/SalesforceSDK/src/com/salesforce/androidsdk/phonegap/SDKInfoPlugin.java
@@ -1,171 +1,179 @@
/*
* Copyright (c) 2012, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software 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 salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.phonegap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.util.Log;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.BootConfig;
/**
* PhoneGap plugin for SDK info.
*/
public class SDKInfoPlugin extends ForcePlugin {
// Keys in sdk info map
private static final String SDK_VERSION = "sdkVersion";
private static final String APP_NAME = "appName";
private static final String APP_VERSION = "appVersion";
private static final String FORCE_PLUGINS_AVAILABLE = "forcePluginsAvailable";
private static final String BOOT_CONFIG = "bootConfig";
// Cached
private static List<String> forcePlugins;
/**
* Supported plugin actions that the client can take.
*/
enum Action {
getInfo
}
@Override
public boolean execute(String actionStr, JavaScriptPluginVersion jsVersion, JSONArray args, CallbackContext callbackContext) throws JSONException {
// Figure out action
Action action = null;
try {
action = Action.valueOf(actionStr);
switch(action) {
case getInfo: getInfo(args, callbackContext); return true;
default: return false;
}
}
catch (IllegalArgumentException e) {
return false;
}
}
/**
* Native implementation for "getInfo" action.
* @param callbackContext Used when calling back into Javascript.
* @throws JSONException
*/
protected void getInfo(JSONArray args, final CallbackContext callbackContext) throws JSONException {
Log.i("SalesforceOAuthPlugin.authenticate", "authenticate called");
try {
callbackContext.success(getSDKInfo(cordova.getActivity()));
}
catch (NameNotFoundException e) {
callbackContext.error(e.getMessage());
}
}
/**************************************************************************************************
*
* Helper methods for building js credentials
*
**************************************************************************************************/
/**
* @return sdk info as JSONObject
* @throws NameNotFoundException
* @throws JSONException
*/
public static JSONObject getSDKInfo(Context ctx) throws NameNotFoundException, JSONException {
- PackageInfo packageInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
- String appName = ctx.getString(packageInfo.applicationInfo.labelRes);
- String appVersion = packageInfo.versionName;
-
+ String appName = "";
+ String appVersion = "";
+ try {
+ final PackageInfo packageInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
+ appName = ctx.getString(packageInfo.applicationInfo.labelRes);
+ appVersion = packageInfo.versionName;
+ } catch (Resources.NotFoundException nfe) {
+
+ // A test harness such as Gradle does NOT have an application name.
+ Log.w("SalesforceSDKManager:getUserAgent", nfe);
+ }
JSONObject data = new JSONObject();
data.put(SDK_VERSION, SalesforceSDKManager.SDK_VERSION);
data.put(APP_NAME, appName);
data.put(APP_VERSION, appVersion);
data.put(FORCE_PLUGINS_AVAILABLE, new JSONArray(getForcePlugins(ctx)));
data.put(BOOT_CONFIG, BootConfig.getBootConfig(ctx).asJSON());
return data;
}
/**
* @param ctx
* @return list of force plugins (read from XML the first time, and stored in field afterwards)
*/
public static List<String> getForcePlugins(Context ctx) {
if (forcePlugins == null) {
forcePlugins = getForcePluginsFromXML(ctx);
}
return forcePlugins;
}
/**
* @param ctx
* @return list of force plugins (read from XML)
*/
public static List<String> getForcePluginsFromXML(Context ctx) {
List<String> services = new ArrayList<String>();
int id = ctx.getResources().getIdentifier("config", "xml", ctx.getPackageName());
if (id == 0) {
id = ctx.getResources().getIdentifier("plugins", "xml", ctx.getPackageName());
}
if (id != 0) {
XmlResourceParser xml = ctx.getResources().getXml(id);
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG && xml.getName().equals("feature")) {
String service = xml.getAttributeValue(null, "name");
if (service.startsWith("com.salesforce.")) {
services.add(service);
}
}
try {
eventType = xml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return services;
}
}
diff --git a/libs/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java b/libs/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java
index 21c1c146a..d87d3217e 100644
--- a/libs/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java
+++ b/libs/test/SalesforceSDKTest/src/com/salesforce/androidsdk/phonegap/SDKInfoPluginTest.java
@@ -1,104 +1,104 @@
/*
* Copyright (c) 2012, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software 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 salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.phonegap;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.BootConfig;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.test.InstrumentationTestCase;
/**
* Tests for SDKInfoPlugin
*
*/
public class SDKInfoPluginTest extends InstrumentationTestCase {
/**
* Test for getSDKInfo
*/
public void testGetSDKInfo() throws NameNotFoundException, JSONException {
Context ctx = getInstrumentation().getTargetContext();
JSONObject sdkInfo = SDKInfoPlugin.getSDKInfo(ctx);
BootConfig bootconfig = BootConfig.getBootConfig(ctx);
- assertEquals("Wrong app name", "SalesforceSDKTest", sdkInfo.getString("appName"));
- assertEquals("Wrong app version", "1.0", sdkInfo.getString("appVersion"));
+ assertEquals("Wrong app name", "", sdkInfo.getString("appName"));
+ assertEquals("Wrong app version", "", sdkInfo.getString("appVersion"));
List<String> sdkInfoPlugins = toList(sdkInfo.getJSONArray("forcePluginsAvailable"));
assertEquals("Wrong number of plugins", 3, sdkInfoPlugins.size());
assertTrue("oauth plugin should have been returned", sdkInfoPlugins.contains("com.salesforce.oauth"));
assertTrue("sdkinfo plugin should have been returned", sdkInfoPlugins.contains("com.salesforce.sdkinfo"));
assertTrue("sfaccountmanager plugin should have been returned", sdkInfoPlugins.contains("com.salesforce.sfaccountmanager"));
assertEquals("Wrong version", SalesforceSDKManager.SDK_VERSION, sdkInfo.getString("sdkVersion"));
JSONObject sdkInfoBootConfig = sdkInfo.getJSONObject("bootConfig");
assertEquals("Wrong bootconfig shouldAuthenticate", bootconfig.shouldAuthenticate(), sdkInfoBootConfig.getBoolean("shouldAuthenticate"));
assertEquals("Wrong bootconfig attemptOfflineLoad", bootconfig.attemptOfflineLoad(), sdkInfoBootConfig.getBoolean("attemptOfflineLoad"));
assertEquals("Wrong bootconfig isLocal", bootconfig.isLocal(), sdkInfoBootConfig.getBoolean("isLocal"));
List<String> sdkInfoOAuthScopes = toList(sdkInfoBootConfig.getJSONArray("oauthScopes"));
assertEquals("Wrong bootconfig oauthScopes", 1, sdkInfoOAuthScopes.size());
assertTrue("Wrong bootconfig oauthScopes", sdkInfoOAuthScopes.contains("api"));
assertEquals("Wrong bootconfig oauthRedirectURI", bootconfig.getOauthRedirectURI(), sdkInfoBootConfig.getString("oauthRedirectURI"));
assertEquals("Wrong bootconfig remoteAccessConsumerKey", bootconfig.getRemoteAccessConsumerKey(), sdkInfoBootConfig.getString("remoteAccessConsumerKey"));
assertEquals("Wrong bootconfig androidPushNotificationClientId", bootconfig.getPushNotificationClientId(), sdkInfoBootConfig.getString("androidPushNotificationClientId"));
assertEquals("Wrong bootconfig startPage", "", sdkInfoBootConfig.optString("startPage")); // this is a native app
assertEquals("Wrong bootconfig errorPage", "", sdkInfoBootConfig.optString("errorPage")); // this is a native app
}
/**
* Test for getForcePluginsFromXML
*/
public void testGetForcePluginsFromXML() {
List<String> plugins = SDKInfoPlugin.getForcePluginsFromXML(getInstrumentation().getTargetContext());
assertEquals("Wrong number of force plugins", 3, plugins.size());
assertTrue("oauth plugin should have been returned", plugins.contains("com.salesforce.oauth"));
assertTrue("sdkinfo plugin should have been returned", plugins.contains("com.salesforce.sdkinfo"));
assertTrue("sfaccountmanager plugin should have been returned", plugins.contains("com.salesforce.sfaccountmanager"));
}
/**
* Helper method
* @param jsonArray
* @return
* @throws JSONException
*/
private List<String> toList(JSONArray jsonArray) throws JSONException {
List<String> list = new ArrayList<String>(jsonArray.length());
for (int i=0; i<jsonArray.length(); i++) {
list.add(jsonArray.getString(i));
}
return list;
}
}
| false | false | null | null |
diff --git a/MonacaFramework/src/mobi/monaca/framework/bootloader/LocalFileBootloader.java b/MonacaFramework/src/mobi/monaca/framework/bootloader/LocalFileBootloader.java
index 636490d..f7a9021 100644
--- a/MonacaFramework/src/mobi/monaca/framework/bootloader/LocalFileBootloader.java
+++ b/MonacaFramework/src/mobi/monaca/framework/bootloader/LocalFileBootloader.java
@@ -1,411 +1,411 @@
package mobi.monaca.framework.bootloader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mobi.monaca.framework.util.MyAsyncTask;
import mobi.monaca.framework.util.MyLog;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
/** This class make Monaca application running on local file. */
public class LocalFileBootloader {
protected static final String BOOTLOADER_PREFERENCE_NAME = "bootloader";
protected static final String BOOTLOADER_FILES_PREFERENCE_NAME = "bootloader_files";
private static final String TAG = LocalFileBootloader.class.getSimpleName();
protected Context context;
protected Runnable success, fail;
protected String dataDirPath;
protected BootloaderPreferences bootloaderPreferences;
protected LocalFileBootloader(Context context, Runnable success,
Runnable fail) {
this.context = context;
this.success = success;
this.fail = fail;
this.bootloaderPreferences = new BootloaderPreferences(context);
dataDirPath = context.getApplicationInfo().dataDir;
}
/** Get application's version string. */
protected String getAppliationVersionCode() {
try {
return ""
+ context.getPackageManager().getPackageInfo(
context.getPackageName(),
PackageManager.GET_META_DATA).versionCode;
} catch (NameNotFoundException e) {
return "0";
}
}
protected void execute() {
MyLog.d(TAG, "using localFileBootloader");
new BootloaderTask().execute();
}
protected String getApplicationLocalFileListHash() {
return Md5Util.md5(join(getApplicationLocalFileList()));
}
public static void setup(Context context, Runnable runner, Runnable fail) {
MyLog.d(TAG, "using LocalFileBootloader");
new LocalFileBootloader(context, runner, fail).execute();
}
protected boolean validateAllFilesHash() {
Map<String, String> hashMap = bootloaderPreferences.getFileHashMap();
if (hashMap == null) {
MyLog.d(getClass().getSimpleName(), "all file hash validation: fail");
return false;
}
for (String path : getApplicationLocalFileList()) {
String assetHash = hashMap.get(path);
String localFileHash = Md5Util.getLocalFileHash(dataDirPath + "/"
+ path);
String assetFileHash;
try {
assetFileHash = Md5Util.getAssetFileHash(context, path);
} catch (RuntimeException e) {
MyLog.d(getClass().getSimpleName(),
"all file hash validation: fail." + e.getMessage());
return false;
}
MyLog.d(getClass().getSimpleName(), "file hash comparison: "
+ assetHash + " = " + localFileHash);
if (assetHash == null || localFileHash == null) {
MyLog.d(getClass().getSimpleName(),
"all file hash validation: fail");
return false;
}
if (!(assetHash.equals(localFileHash) && assetHash
.equals(assetFileHash))) {
MyLog.d(getClass().getSimpleName(),
"all file hash validation: fail");
return false;
}
}
MyLog.d(getClass().getSimpleName(), "all file hash validation: ok");
return true;
}
protected boolean validateFileListHash() {
boolean result = bootloaderPreferences.getFileListHash().equals(
Md5Util.md5(join(getApplicationLocalFileList())));
result = result
&& bootloaderPreferences.getFileListHash().equals(
Md5Util.md5(join(getAssetsFileList())));
MyLog.d(getClass().getSimpleName(), "filelist hash validation: "
+ (result ? "ok" : "fail"));
return result;
}
protected boolean validateAppVersion() {
boolean result = bootloaderPreferences.getAppVersionCode().equals(
getAppliationVersionCode());
MyLog.d(getClass().getSimpleName(), "app version validation: "
+ (result ? "ok" : "fail"));
return result;
}
protected boolean needInitialization() {
return !(validateAppVersion() && validateFileListHash() && validateAllFilesHash());
}
protected List<String> getAssetsFileList() {
ArrayList<String> result = new ArrayList<String>();
aggregateAssetsFileList("www", result);
Collections.sort(result);
return result;
}
public static boolean needToUseLocalFileBootloader() {
return Build.VERSION.SDK_INT == 14 || Build.VERSION.SDK_INT == 15;
}
/**
* returns new inputStream from assetPath.
* if ver4.0.x, uses LocalFileBootloader.
* else uses getAssets()
* @param path this method removes file:///android_asset/ and file://android_asset/
* @param context
* @return
* @throws IOException
*/
public static InputStream openAsset(Context context, String path) throws IOException {
Log.d(TAG, "getInputStream : " + path);
if (needToUseLocalFileBootloader()) {
String newPath = path.replaceFirst("(file:///android_asset/)|(file://android_asset/)", "");
MyLog.d(TAG, "need to use LocalFileBootloader(), getInputStream, newRelativePath :" + newPath);
- File localAssetFile = new File(context.getApplicationInfo().dataDir + "/" + path);
+ File localAssetFile = new File(context.getApplicationInfo().dataDir + "/" + newPath);
MyLog.d(TAG, "localAssetFile :" + localAssetFile);
if (localAssetFile.exists()) {
MyLog.d(TAG, "getInputStream, loading localFile succeed");
return new FileInputStream(localAssetFile);
} else {
MyLog.d(TAG, "getInputStream, loading localFile failed, get from assets");
- return context.getAssets().open(path);
+ return context.getAssets().open(newPath);
}
} else {
MyLog.d(TAG, "no need to use LocalFileBootloader");
String newPath = path.replaceFirst("(file:///android_asset/)|(file://android_asset/)", "");
return context.getAssets().open(newPath);
}
}
protected void aggregateAssetsFileList(String prefix,
ArrayList<String> result) {
try {
for (String path : context.getAssets().list(prefix)) {
MyLog.d(TAG, "pathCheck :" + prefix + "/" + path);
// if (!path.contains(".")) {
if (existAsset(prefix + "/" + path)) {
result.add(prefix + "/" + path);
} else {
// may be directory
aggregateAssetsFileList(prefix + "/" + path, result);
}
// } else {
// result.add(prefix + "/" + path);
// }
}
} catch (Exception e) {
MyLog.e(getClass().getSimpleName(), e.getMessage());
throw new RuntimeException(e);
}
}
protected List<String> getApplicationLocalFileList() {
ArrayList<String> temp = new ArrayList<String>();
File dir = new File(context.getApplicationInfo().dataDir + "/www");
dir.mkdir();
aggregateApplicationLocalFileList(new File(
context.getApplicationInfo().dataDir + "/www"), temp);
ArrayList<String> result = new ArrayList<String>();
int start = context.getApplicationInfo().dataDir.length() + 1;
for (String path : temp) {
result.add(path.substring(start));
}
Collections.sort(result);
return result;
}
protected void aggregateApplicationLocalFileList(File dir,
ArrayList<String> result) {
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
aggregateApplicationLocalFileList(file, result);
} else {
result.add(file.getAbsolutePath());
}
}
}
protected static String join(List<String> list) {
StringBuffer buffer = new StringBuffer();
for (String elt : list) {
buffer.append(elt);
buffer.append(":");
}
String temp = buffer.toString();
if(temp.length() == 0){
MyLog.e(TAG, "Warning: temp.length=0");
return "";
}
return temp.substring(0, temp.length() - 1);
}
protected boolean existAsset(String path) {
try {
InputStream stream = context.getAssets().open(path);
stream.close();
} catch (Exception e) {
MyLog.e(TAG, path + " not exist");
return false;
}
return true;
}
/** Copy assets to local data directory. */
protected void copyAssetToLocal(String path) {
MyLog.d(TAG, "copyAssetToLocal()");
byte[] buffer = new byte[1024 * 4];
File file = new File(context.getApplicationInfo().dataDir + "/" + path);
file.getParentFile().mkdirs();
try {
OutputStream output = new FileOutputStream(file);
InputStream input = context.getAssets().open(path);
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
input.close();
output.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new AbortException(e);
}
}
/** Clean local application files and the application preferences. */
protected void clean() {
bootloaderPreferences.clear();
cleanFiles(context.getApplicationInfo().dataDir + "/www");
}
protected void cleanFiles(String path) {
File file = new File(path);
if (file.isDirectory()) {
for (File child : file.listFiles()) {
cleanFiles(child.getAbsolutePath());
}
file.delete();
} else {
file.delete();
}
}
protected class BootloaderTask extends MyAsyncTask<Void, Void, Boolean> {
protected Handler handler = new Handler();
protected ProgressDialog loadingDialog = null;
@Override
protected Boolean doInBackground(Void ...a) {
boolean needInit = true;
showProgressDialog();
try {
needInit = needInitialization();
MyLog.v(TAG, "needInit = " + needInit);
} catch (AbortException e) {
MyLog.e(getClass().getSimpleName(), "bootloader task aborted." + e);
return false;
} catch (RuntimeException e) {
MyLog.e(getClass().getSimpleName(), "bootloader task fail." + e);
return false;
}
try {
if (needInit) {
clean();
MyLog.v(TAG, "assetFiles size=" + getAssetsFileList().size());
for (String path : getAssetsFileList()) {
copyAssetToLocal(path);
}
bootloaderPreferences
.saveAppVersionCode(getAppliationVersionCode());
bootloaderPreferences
.saveFileListHash(getApplicationLocalFileListHash());
HashMap<String, String> map = new HashMap<String, String>();
for (String path : getAssetsFileList()) {
map.put(path, Md5Util.getAssetFileHash(context, path));
}
bootloaderPreferences.saveFileHashMap(map);
}
} catch (AbortException e) {
MyLog.e(getClass().getSimpleName(),
"local file bootloader abort." + e.getMessage());
return false;
} catch (RuntimeException e) {
MyLog.e(getClass().getSimpleName(), "local file bootloader fail" + e.getMessage());
return false;
}
return true;
}
@Override
protected void onPostExecute(Boolean isSuccess) {
dismissProgressDialog();
if (isSuccess) {
success.run();
} else {
fail.run();
}
}
protected void showProgressDialog() {
handler.post(new Runnable() {
@Override
public void run() {
loadingDialog = new ProgressDialog(context);
loadingDialog.setMessage("Loading...");
loadingDialog.show();
loadingDialog.setCancelable(false);
}
});
}
protected void dismissProgressDialog() {
handler.post(new Runnable() {
@Override
public void run() {
if (loadingDialog != null) {
loadingDialog.dismiss();
loadingDialog = null;
}
}
});
}
protected void showAbortAlert() {
showAlert("インストールに失敗しました。ディスクの容量を増やして再度実行してください。");
}
protected void showAlert(final String message) {
handler.post(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(context).setTitle("")
.setMessage(message).setCancelable(true);
}
});
}
}
}
| false | false | null | null |
diff --git a/src/com/cyanogenmod/filemanager/ui/widgets/NavigationView.java b/src/com/cyanogenmod/filemanager/ui/widgets/NavigationView.java
index f17c645..61aa09e 100644
--- a/src/com/cyanogenmod/filemanager/ui/widgets/NavigationView.java
+++ b/src/com/cyanogenmod/filemanager/ui/widgets/NavigationView.java
@@ -1,1386 +1,1390 @@
/*
* Copyright (C) 2012 The CyanogenMod 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.cyanogenmod.filemanager.ui.widgets;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.storage.StorageVolume;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.cyanogenmod.filemanager.FileManagerApplication;
import com.cyanogenmod.filemanager.R;
import com.cyanogenmod.filemanager.adapters.FileSystemObjectAdapter;
import com.cyanogenmod.filemanager.adapters.FileSystemObjectAdapter.OnSelectionChangedListener;
import com.cyanogenmod.filemanager.console.ConsoleAllocException;
import com.cyanogenmod.filemanager.listeners.OnHistoryListener;
import com.cyanogenmod.filemanager.listeners.OnRequestRefreshListener;
import com.cyanogenmod.filemanager.listeners.OnSelectionListener;
import com.cyanogenmod.filemanager.model.Directory;
import com.cyanogenmod.filemanager.model.FileSystemObject;
import com.cyanogenmod.filemanager.model.ParentDirectory;
import com.cyanogenmod.filemanager.model.Symlink;
import com.cyanogenmod.filemanager.parcelables.NavigationViewInfoParcelable;
import com.cyanogenmod.filemanager.parcelables.SearchInfoParcelable;
import com.cyanogenmod.filemanager.preferences.AccessMode;
import com.cyanogenmod.filemanager.preferences.DisplayRestrictions;
import com.cyanogenmod.filemanager.preferences.FileManagerSettings;
import com.cyanogenmod.filemanager.preferences.NavigationLayoutMode;
import com.cyanogenmod.filemanager.preferences.ObjectIdentifier;
import com.cyanogenmod.filemanager.preferences.Preferences;
import com.cyanogenmod.filemanager.ui.ThemeManager;
import com.cyanogenmod.filemanager.ui.ThemeManager.Theme;
import com.cyanogenmod.filemanager.ui.policy.DeleteActionPolicy;
import com.cyanogenmod.filemanager.ui.policy.IntentsActionPolicy;
import com.cyanogenmod.filemanager.ui.widgets.FlingerListView.OnItemFlingerListener;
import com.cyanogenmod.filemanager.ui.widgets.FlingerListView.OnItemFlingerResponder;
import com.cyanogenmod.filemanager.util.CommandHelper;
import com.cyanogenmod.filemanager.util.DialogHelper;
import com.cyanogenmod.filemanager.util.ExceptionUtil;
import com.cyanogenmod.filemanager.util.ExceptionUtil.OnRelaunchCommandResult;
import com.cyanogenmod.filemanager.util.FileHelper;
import com.cyanogenmod.filemanager.util.StorageHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The file manager implementation view (contains the graphical representation and the input
* management for a file manager; shows the folders/files, the mode view, react touch events,
* navigate, ...).
*/
public class NavigationView extends RelativeLayout implements
AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener,
BreadcrumbListener, OnSelectionChangedListener, OnSelectionListener, OnRequestRefreshListener {
private static final String TAG = "NavigationView"; //$NON-NLS-1$
/**
* An interface to communicate selection changes events.
*/
public interface OnNavigationSelectionChangedListener {
/**
* Method invoked when the selection changed.
*
* @param navView The navigation view that generate the event
* @param selectedItems The new selected items
*/
void onSelectionChanged(NavigationView navView, List<FileSystemObject> selectedItems);
}
/**
* An interface to communicate a request for show the menu associated
* with an item.
*/
public interface OnNavigationRequestMenuListener {
/**
* Method invoked when a request to show the menu associated
* with an item is started.
*
* @param navView The navigation view that generate the event
* @param item The item for which the request was started
*/
void onRequestMenu(NavigationView navView, FileSystemObject item);
}
/**
* An interface to communicate a request when the user choose a file.
*/
public interface OnFilePickedListener {
/**
* Method invoked when a request when the user choose a file.
*
* @param item The item choose
*/
void onFilePicked(FileSystemObject item);
}
/**
* An interface to communicate a change of the current directory
*/
public interface OnDirectoryChangedListener {
/**
* Method invoked when the current directory changes
*
* @param item The newly active directory
*/
void onDirectoryChanged(FileSystemObject item);
}
/**
* The navigation view mode
* @hide
*/
public enum NAVIGATION_MODE {
/**
* The navigation view acts as a browser, and allow open files itself.
*/
BROWSABLE,
/**
* The navigation view acts as a picker of files
*/
PICKABLE,
}
/**
* A listener for flinging events from {@link FlingerListView}
*/
private final OnItemFlingerListener mOnItemFlingerListener = new OnItemFlingerListener() {
@Override
public boolean onItemFlingerStart(
AdapterView<?> parent, View view, int position, long id) {
try {
// Response if the item can be removed
FileSystemObjectAdapter adapter = (FileSystemObjectAdapter)parent.getAdapter();
FileSystemObject fso = adapter.getItem(position);
if (fso != null) {
if (fso instanceof ParentDirectory) {
return false;
}
return true;
}
} catch (Exception e) {
ExceptionUtil.translateException(getContext(), e, true, false);
}
return false;
}
@Override
public void onItemFlingerEnd(OnItemFlingerResponder responder,
AdapterView<?> parent, View view, int position, long id) {
try {
// Response if the item can be removed
FileSystemObjectAdapter adapter = (FileSystemObjectAdapter)parent.getAdapter();
FileSystemObject fso = adapter.getItem(position);
if (fso != null) {
DeleteActionPolicy.removeFileSystemObject(
getContext(),
fso,
NavigationView.this,
NavigationView.this,
responder);
return;
}
// Cancels the flinger operation
responder.cancel();
} catch (Exception e) {
ExceptionUtil.translateException(getContext(), e, true, false);
responder.cancel();
}
}
};
private int mId;
private String mCurrentDir;
private NavigationLayoutMode mCurrentMode;
/**
* @hide
*/
List<FileSystemObject> mFiles;
private FileSystemObjectAdapter mAdapter;
private boolean mChangingDir;
private final Object mSync = new Object();
private OnHistoryListener mOnHistoryListener;
private OnNavigationSelectionChangedListener mOnNavigationSelectionChangedListener;
private OnNavigationRequestMenuListener mOnNavigationRequestMenuListener;
private OnFilePickedListener mOnFilePickedListener;
private OnDirectoryChangedListener mOnDirectoryChangedListener;
private boolean mChRooted;
private NAVIGATION_MODE mNavigationMode;
// Restrictions
private Map<DisplayRestrictions, Object> mRestrictions;
/**
* @hide
*/
Breadcrumb mBreadcrumb;
/**
* @hide
*/
NavigationCustomTitleView mTitle;
/**
* @hide
*/
AdapterView<?> mAdapterView;
//The layout for icons mode
private static final int RESOURCE_MODE_ICONS_LAYOUT = R.layout.navigation_view_icons;
private static final int RESOURCE_MODE_ICONS_ITEM = R.layout.navigation_view_icons_item;
//The layout for simple mode
private static final int RESOURCE_MODE_SIMPLE_LAYOUT = R.layout.navigation_view_simple;
private static final int RESOURCE_MODE_SIMPLE_ITEM = R.layout.navigation_view_simple_item;
//The layout for details mode
private static final int RESOURCE_MODE_DETAILS_LAYOUT = R.layout.navigation_view_details;
private static final int RESOURCE_MODE_DETAILS_ITEM = R.layout.navigation_view_details_item;
//The current layout identifier (is shared for all the mode layout)
private static final int RESOURCE_CURRENT_LAYOUT = R.id.navigation_view_layout;
/**
* Constructor of <code>NavigationView</code>.
*
* @param context The current context
* @param attrs The attributes of the XML tag that is inflating the view.
*/
public NavigationView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Navigable);
try {
init(a);
} finally {
a.recycle();
}
}
/**
* Constructor of <code>NavigationView</code>.
*
* @param context The current context
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyle The default style to apply to this view. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
*/
public NavigationView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.Navigable, defStyle, 0);
try {
init(a);
} finally {
a.recycle();
}
}
/**
* Invoked when the instance need to be saved.
*
* @return NavigationViewInfoParcelable The serialized info
*/
public NavigationViewInfoParcelable onSaveState() {
//Return the persistent the data
NavigationViewInfoParcelable parcel = new NavigationViewInfoParcelable();
parcel.setId(this.mId);
parcel.setCurrentDir(this.mCurrentDir);
parcel.setChRooted(this.mChRooted);
parcel.setSelectedFiles(this.mAdapter.getSelectedItems());
parcel.setFiles(this.mFiles);
return parcel;
}
/**
* Invoked when the instance need to be restored.
*
* @param info The serialized info
* @return boolean If can restore
*/
public boolean onRestoreState(NavigationViewInfoParcelable info) {
synchronized (mSync) {
if (mChangingDir) {
return false;
}
}
//Restore the data
this.mId = info.getId();
this.mCurrentDir = info.getCurrentDir();
this.mChRooted = info.getChRooted();
this.mFiles = info.getFiles();
this.mAdapter.setSelectedItems(info.getSelectedFiles());
//Update the views
refresh();
return true;
}
/**
* Method that initializes the view. This method loads all the necessary
* information and create an appropriate layout for the view.
*
* @param tarray The type array
*/
private void init(TypedArray tarray) {
// Retrieve the mode
this.mNavigationMode = NAVIGATION_MODE.BROWSABLE;
int mode = tarray.getInteger(
R.styleable.Navigable_navigation,
NAVIGATION_MODE.BROWSABLE.ordinal());
if (mode >= 0 && mode < NAVIGATION_MODE.values().length) {
this.mNavigationMode = NAVIGATION_MODE.values()[mode];
}
// Initialize default restrictions (no restrictions)
this.mRestrictions = new HashMap<DisplayRestrictions, Object>();
//Initialize variables
this.mFiles = new ArrayList<FileSystemObject>();
// Is ChRooted environment?
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.PICKABLE) == 0) {
// Pick mode is always ChRooted
this.mChRooted = true;
} else {
this.mChRooted =
FileManagerApplication.getAccessMode().compareTo(AccessMode.SAFE) == 0;
}
//Retrieve the default configuration
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
SharedPreferences preferences = Preferences.getSharedPreferences();
int viewMode = preferences.getInt(
FileManagerSettings.SETTINGS_LAYOUT_MODE.getId(),
((ObjectIdentifier)FileManagerSettings.
SETTINGS_LAYOUT_MODE.getDefaultValue()).getId());
changeViewMode(NavigationLayoutMode.fromId(viewMode));
} else {
// Pick mode has always a details layout
changeViewMode(NavigationLayoutMode.DETAILS);
}
}
/**
* Method that returns the display restrictions to apply to this view.
*
* @return Map<DisplayRestrictions, Object> The restrictions to apply
*/
public Map<DisplayRestrictions, Object> getRestrictions() {
return this.mRestrictions;
}
/**
* Method that sets the display restrictions to apply to this view.
*
* @param mRestrictions The restrictions to apply
*/
public void setRestrictions(Map<DisplayRestrictions, Object> mRestrictions) {
this.mRestrictions = mRestrictions;
}
/**
* Method that returns the current file list of the navigation view.
*
* @return List<FileSystemObject> The current file list of the navigation view
*/
public List<FileSystemObject> getFiles() {
if (this.mFiles == null) {
return null;
}
return new ArrayList<FileSystemObject>(this.mFiles);
}
/**
* Method that returns the current file list of the navigation view.
*
* @return List<FileSystemObject> The current file list of the navigation view
*/
public List<FileSystemObject> getSelectedFiles() {
if (this.mAdapter != null && this.mAdapter.getSelectedItems() != null) {
return new ArrayList<FileSystemObject>(this.mAdapter.getSelectedItems());
}
return null;
}
/**
* Method that returns the custom title fragment associated with this navigation view.
*
* @return NavigationCustomTitleView The custom title view fragment
*/
public NavigationCustomTitleView getCustomTitle() {
return this.mTitle;
}
/**
* Method that associates the custom title fragment with this navigation view.
*
* @param title The custom title view fragment
*/
public void setCustomTitle(NavigationCustomTitleView title) {
this.mTitle = title;
}
/**
* Method that returns the breadcrumb associated with this navigation view.
*
* @return Breadcrumb The breadcrumb view fragment
*/
public Breadcrumb getBreadcrumb() {
return this.mBreadcrumb;
}
/**
* Method that associates the breadcrumb with this navigation view.
*
* @param breadcrumb The breadcrumb view fragment
*/
public void setBreadcrumb(Breadcrumb breadcrumb) {
this.mBreadcrumb = breadcrumb;
this.mBreadcrumb.addBreadcrumbListener(this);
}
/**
* Method that sets the listener for communicate history changes.
*
* @param onHistoryListener The listener for communicate history changes
*/
public void setOnHistoryListener(OnHistoryListener onHistoryListener) {
this.mOnHistoryListener = onHistoryListener;
}
/**
* Method that sets the listener which communicates selection changes.
*
* @param onNavigationSelectionChangedListener The listener reference
*/
public void setOnNavigationSelectionChangedListener(
OnNavigationSelectionChangedListener onNavigationSelectionChangedListener) {
this.mOnNavigationSelectionChangedListener = onNavigationSelectionChangedListener;
}
/**
* Method that sets the listener for menu item requests.
*
* @param onNavigationRequestMenuListener The listener reference
*/
public void setOnNavigationOnRequestMenuListener(
OnNavigationRequestMenuListener onNavigationRequestMenuListener) {
this.mOnNavigationRequestMenuListener = onNavigationRequestMenuListener;
}
/**
* @return the mOnFilePickedListener
*/
public OnFilePickedListener getOnFilePickedListener() {
return this.mOnFilePickedListener;
}
/**
* Method that sets the listener for picked items
*
* @param onFilePickedListener The listener reference
*/
public void setOnFilePickedListener(OnFilePickedListener onFilePickedListener) {
this.mOnFilePickedListener = onFilePickedListener;
}
/**
* Method that sets the listener for directory changes
*
* @param onDirectoryChangedListener The listener reference
*/
public void setOnDirectoryChangedListener(
OnDirectoryChangedListener onDirectoryChangedListener) {
this.mOnDirectoryChangedListener = onDirectoryChangedListener;
}
/**
* Method that sets if the view should use flinger gesture detection.
*
* @param useFlinger If the view should use flinger gesture detection
*/
public void setUseFlinger(boolean useFlinger) {
if (this.mCurrentMode.compareTo(NavigationLayoutMode.ICONS) == 0) {
// Not supported
return;
}
// Set the flinger listener (only when navigate)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
if (this.mAdapterView instanceof FlingerListView) {
if (useFlinger) {
((FlingerListView)this.mAdapterView).
setOnItemFlingerListener(this.mOnItemFlingerListener);
} else {
((FlingerListView)this.mAdapterView).setOnItemFlingerListener(null);
}
}
}
}
/**
* Method that forces the view to scroll to the file system object passed.
*
* @param fso The file system object
*/
public void scrollTo(FileSystemObject fso) {
if (fso != null) {
try {
int position = this.mAdapter.getPosition(fso);
this.mAdapterView.setSelection(position);
} catch (Exception e) {
this.mAdapterView.setSelection(0);
}
} else {
this.mAdapterView.setSelection(0);
}
}
/**
* Method that refresh the view data.
*/
public void refresh() {
refresh(false);
}
/**
* Method that refresh the view data.
*
* @param restore Restore previous position
*/
public void refresh(boolean restore) {
FileSystemObject fso = null;
// Try to restore the previous scroll position
if (restore) {
try {
if (this.mAdapterView != null && this.mAdapter != null) {
int position = this.mAdapterView.getFirstVisiblePosition();
fso = this.mAdapter.getItem(position);
}
} catch (Throwable _throw) {/**NON BLOCK**/}
}
refresh(fso);
}
/**
* Method that refresh the view data.
*
* @param scrollTo Scroll to object
*/
public void refresh(FileSystemObject scrollTo) {
//Check that current directory was set
if (this.mCurrentDir == null || this.mFiles == null) {
return;
}
//Reload data
changeCurrentDir(this.mCurrentDir, false, true, false, null, scrollTo);
}
/**
* Method that recycles this object
*/
public void recycle() {
if (this.mAdapter != null) {
this.mAdapter.dispose();
}
}
/**
* Method that change the view mode.
*
* @param newMode The new mode
*/
@SuppressWarnings("unchecked")
public void changeViewMode(final NavigationLayoutMode newMode) {
synchronized (this.mSync) {
//Check that it is really necessary change the mode
if (this.mCurrentMode != null && this.mCurrentMode.compareTo(newMode) == 0) {
return;
}
// If we should set the listview to response to flinger gesture detection
boolean useFlinger =
Preferences.getSharedPreferences().getBoolean(
FileManagerSettings.SETTINGS_USE_FLINGER.getId(),
((Boolean)FileManagerSettings.
SETTINGS_USE_FLINGER.
getDefaultValue()).booleanValue());
//Creates the new layout
AdapterView<ListAdapter> newView = null;
int itemResourceId = -1;
if (newMode.compareTo(NavigationLayoutMode.ICONS) == 0) {
newView = (AdapterView<ListAdapter>)inflate(
getContext(), RESOURCE_MODE_ICONS_LAYOUT, null);
itemResourceId = RESOURCE_MODE_ICONS_ITEM;
} else if (newMode.compareTo(NavigationLayoutMode.SIMPLE) == 0) {
newView = (AdapterView<ListAdapter>)inflate(
getContext(), RESOURCE_MODE_SIMPLE_LAYOUT, null);
itemResourceId = RESOURCE_MODE_SIMPLE_ITEM;
// Set the flinger listener (only when navigate)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
if (useFlinger && newView instanceof FlingerListView) {
((FlingerListView)newView).
setOnItemFlingerListener(this.mOnItemFlingerListener);
}
}
} else if (newMode.compareTo(NavigationLayoutMode.DETAILS) == 0) {
newView = (AdapterView<ListAdapter>)inflate(
getContext(), RESOURCE_MODE_DETAILS_LAYOUT, null);
itemResourceId = RESOURCE_MODE_DETAILS_ITEM;
// Set the flinger listener (only when navigate)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
if (useFlinger && newView instanceof FlingerListView) {
((FlingerListView)newView).
setOnItemFlingerListener(this.mOnItemFlingerListener);
}
}
}
//Get the current adapter and its adapter list
List<FileSystemObject> files = new ArrayList<FileSystemObject>(this.mFiles);
final AdapterView<ListAdapter> current =
(AdapterView<ListAdapter>)findViewById(RESOURCE_CURRENT_LAYOUT);
FileSystemObjectAdapter adapter =
new FileSystemObjectAdapter(
getContext(),
new ArrayList<FileSystemObject>(),
itemResourceId,
this.mNavigationMode.compareTo(NAVIGATION_MODE.PICKABLE) == 0);
adapter.setOnSelectionChangedListener(this);
//Remove current layout
if (current != null) {
if (current.getAdapter() != null) {
//Save selected items before dispose adapter
FileSystemObjectAdapter currentAdapter =
((FileSystemObjectAdapter)current.getAdapter());
adapter.setSelectedItems(currentAdapter.getSelectedItems());
currentAdapter.dispose();
}
removeView(current);
}
this.mFiles = files;
adapter.addAll(files);
//Set the adapter
this.mAdapter = adapter;
newView.setAdapter(this.mAdapter);
newView.setOnItemClickListener(NavigationView.this);
//Add the new layout
this.mAdapterView = newView;
addView(newView, 0);
this.mCurrentMode = newMode;
// Pick mode doesn't implements the onlongclick
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
this.mAdapterView.setOnItemLongClickListener(this);
} else {
this.mAdapterView.setOnItemLongClickListener(null);
}
//Save the preference (only in navigation browse mode)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
try {
Preferences.savePreference(
FileManagerSettings.SETTINGS_LAYOUT_MODE, newMode, true);
} catch (Exception ex) {
Log.e(TAG, "Save of view mode preference fails", ex); //$NON-NLS-1$
}
}
}
}
/**
* Method that removes a {@link FileSystemObject} from the view
*
* @param fso The file system object
*/
public void removeItem(FileSystemObject fso) {
// Delete also from internal list
if (fso != null) {
int cc = this.mFiles.size()-1;
for (int i = cc; i >= 0; i--) {
FileSystemObject f = this.mFiles.get(i);
if (f != null && f.compareTo(fso) == 0) {
this.mFiles.remove(i);
break;
}
}
}
this.mAdapter.remove(fso);
}
/**
* Method that removes a file system object from his path from the view
*
* @param path The file system object path
*/
public void removeItem(String path) {
FileSystemObject fso = this.mAdapter.getItem(path);
if (fso != null) {
this.mAdapter.remove(fso);
}
}
/**
* Method that returns the current directory.
*
* @return String The current directory
*/
public String getCurrentDir() {
return this.mCurrentDir;
}
/**
* Method that changes the current directory of the view.
*
* @param newDir The new directory location
*/
public void changeCurrentDir(final String newDir) {
changeCurrentDir(newDir, true, false, false, null, null);
}
/**
* Method that changes the current directory of the view.
*
* @param newDir The new directory location
* @param searchInfo The search information (if calling activity is {@link "SearchActivity"})
*/
public void changeCurrentDir(final String newDir, SearchInfoParcelable searchInfo) {
changeCurrentDir(newDir, true, false, false, searchInfo, null);
}
/**
* Method that changes the current directory of the view.
*
* @param newDir The new directory location
* @param addToHistory Add the directory to history
* @param reload Force the reload of the data
* @param useCurrent If this method must use the actual data (for back actions)
* @param searchInfo The search information (if calling activity is {@link "SearchActivity"})
* @param scrollTo If not null, then listview must scroll to this item
*/
private void changeCurrentDir(
final String newDir, final boolean addToHistory,
final boolean reload, final boolean useCurrent,
final SearchInfoParcelable searchInfo, final FileSystemObject scrollTo) {
// Check navigation security (don't allow to go outside the ChRooted environment if one
// is created)
final String fNewDir = checkChRootedNavigation(newDir);
// Wait to finalization
synchronized (this.mSync) {
if (mChangingDir) {
try {
mSync.wait();
} catch (InterruptedException iex) {
// Ignore
}
}
mChangingDir = true;
}
//Check that it is really necessary change the directory
if (!reload && this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0) {
+ synchronized (this.mSync) {
+ mChangingDir = false;
+ mSync.notify();
+ }
return;
}
final boolean hasChanged =
!(this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0);
final boolean isNewHistory = (this.mCurrentDir != null);
//Execute the listing in a background process
AsyncTask<String, Integer, List<FileSystemObject>> task =
new AsyncTask<String, Integer, List<FileSystemObject>>() {
/**
* {@inheritDoc}
*/
@Override
protected List<FileSystemObject> doInBackground(String... params) {
try {
//Reset the custom title view and returns to breadcrumb
if (NavigationView.this.mTitle != null) {
NavigationView.this.mTitle.post(new Runnable() {
@Override
public void run() {
try {
NavigationView.this.mTitle.restoreView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Start of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.startLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
//Get the files, resolve links and apply configuration
//(sort, hidden, ...)
List<FileSystemObject> files = NavigationView.this.mFiles;
if (!useCurrent) {
files = CommandHelper.listFiles(getContext(), fNewDir, null);
}
return files;
} catch (final ConsoleAllocException e) {
//Show exception and exists
NavigationView.this.post(new Runnable() {
@Override
public void run() {
Context ctx = getContext();
Log.e(TAG, ctx.getString(
R.string.msgs_cant_create_console), e);
DialogHelper.showToast(ctx,
R.string.msgs_cant_create_console,
Toast.LENGTH_LONG);
((Activity)ctx).finish();
}
});
return null;
} catch (Exception ex) {
//End of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex2) {
/**NON BLOCK**/
}
}
//Capture exception (attach task, and use listener to do the anim)
ExceptionUtil.attachAsyncTask(
ex,
new AsyncTask<Object, Integer, Boolean>() {
private List<FileSystemObject> mTaskFiles = null;
@Override
@SuppressWarnings({
"unchecked", "unqualified-field-access"
})
protected Boolean doInBackground(Object... taskParams) {
mTaskFiles = (List<FileSystemObject>)taskParams[0];
return Boolean.TRUE;
}
@Override
@SuppressWarnings("unqualified-field-access")
protected void onPostExecute(Boolean result) {
if (!result.booleanValue()) {
return;
}
onPostExecuteTask(
mTaskFiles, addToHistory,
isNewHistory, hasChanged,
searchInfo, fNewDir, scrollTo);
}
});
final OnRelaunchCommandResult exListener =
new OnRelaunchCommandResult() {
@Override
public void onSuccess() {
done();
}
@Override
public void onFailed(Throwable cause) {
done();
}
@Override
public void onCancelled() {
done();
}
private void done() {
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
};
ExceptionUtil.translateException(
getContext(), ex, false, true, exListener);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void onPreExecute() {
// Do animation
fadeEfect(true);
}
/**
* {@inheritDoc}
*/
@Override
protected void onPostExecute(List<FileSystemObject> files) {
// This means an exception. This method will be recalled then
if (files != null) {
onPostExecuteTask(
files, addToHistory, isNewHistory,
hasChanged, searchInfo, fNewDir, scrollTo);
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
}
/**
* Method that performs a fade animation.
*
* @param out Fade out (true); Fade in (false)
*/
void fadeEfect(final boolean out) {
Activity activity = (Activity)getContext();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Animation fadeAnim = out ?
new AlphaAnimation(1, 0) :
new AlphaAnimation(0, 1);
fadeAnim.setDuration(50L);
fadeAnim.setFillAfter(true);
fadeAnim.setInterpolator(new AccelerateInterpolator());
NavigationView.this.startAnimation(fadeAnim);
}
});
}
};
task.execute(fNewDir);
}
/**
* Method invoked when a execution ends.
*
* @param files The files obtains from the list
* @param addToHistory If add path to history
* @param isNewHistory If is new history
* @param hasChanged If current directory was changed
* @param searchInfo The search information (if calling activity is {@link "SearchActivity"})
* @param newDir The new directory
* @param scrollTo If not null, then listview must scroll to this item
* @hide
*/
void onPostExecuteTask(
List<FileSystemObject> files, boolean addToHistory, boolean isNewHistory,
boolean hasChanged, SearchInfoParcelable searchInfo,
String newDir, final FileSystemObject scrollTo) {
try {
//Check that there is not errors and have some data
if (files == null) {
return;
}
//Apply user preferences
List<FileSystemObject> sortedFiles =
FileHelper.applyUserPreferences(files, this.mRestrictions, this.mChRooted);
//Remove parent directory if we are in the root of a chrooted environment
if (this.mChRooted && StorageHelper.isStorageVolume(newDir)) {
if (files.size() > 0 && files.get(0) instanceof ParentDirectory) {
files.remove(0);
}
}
//Load the data
loadData(sortedFiles);
this.mFiles = sortedFiles;
if (searchInfo != null) {
searchInfo.setSuccessNavigation(true);
}
//Add to history?
if (addToHistory && hasChanged && isNewHistory) {
if (this.mOnHistoryListener != null) {
//Communicate the need of a history change
this.mOnHistoryListener.onNewHistory(onSaveState());
}
}
//Change the breadcrumb
if (this.mBreadcrumb != null) {
this.mBreadcrumb.changeBreadcrumbPath(newDir, this.mChRooted);
}
//Scroll to object?
if (scrollTo != null) {
scrollTo(scrollTo);
}
//The current directory is now the "newDir"
this.mCurrentDir = newDir;
if (this.mOnDirectoryChangedListener != null) {
FileSystemObject dir = FileHelper.createFileSystemObject(new File(newDir));
this.mOnDirectoryChangedListener.onDirectoryChanged(dir);
}
} finally {
//If calling activity is search, then save the search history
if (searchInfo != null) {
this.mOnHistoryListener.onNewHistory(searchInfo);
}
//End of loading data
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
}
/**
* Method that loads the files in the adapter.
*
* @param files The files to load in the adapter
* @hide
*/
@SuppressWarnings("unchecked")
private void loadData(final List<FileSystemObject> files) {
//Notify data to adapter view
final AdapterView<ListAdapter> view =
(AdapterView<ListAdapter>)findViewById(RESOURCE_CURRENT_LAYOUT);
FileSystemObjectAdapter adapter = (FileSystemObjectAdapter)view.getAdapter();
adapter.setNotifyOnChange(false);
adapter.clear();
adapter.addAll(files);
adapter.notifyDataSetChanged();
view.setSelection(0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// Different actions depending on user preference
// Get the adapter and the fso
FileSystemObjectAdapter adapter = ((FileSystemObjectAdapter)parent.getAdapter());
FileSystemObject fso = adapter.getItem(position);
// Parent directory hasn't actions
if (fso instanceof ParentDirectory) {
return false;
}
// Pick mode doesn't implements the onlongclick
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.PICKABLE) == 0) {
return false;
}
onRequestMenu(fso);
return true; //Always consume the event
}
/**
* Method that opens or navigates to the {@link FileSystemObject}
*
* @param fso The file system object
*/
public void open(FileSystemObject fso) {
open(fso, null);
}
/**
* Method that opens or navigates to the {@link FileSystemObject}
*
* @param fso The file system object
* @param searchInfo The search info
*/
public void open(FileSystemObject fso, SearchInfoParcelable searchInfo) {
// If is a folder, then navigate to
if (FileHelper.isDirectory(fso)) {
changeCurrentDir(fso.getFullPath(), searchInfo);
} else {
// Open the file with the preferred registered app
IntentsActionPolicy.openFileSystemObject(getContext(), fso, false, null, null);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
FileSystemObject fso = ((FileSystemObjectAdapter)parent.getAdapter()).getItem(position);
if (fso instanceof ParentDirectory) {
changeCurrentDir(fso.getParent(), true, false, false, null, null);
return;
} else if (fso instanceof Directory) {
changeCurrentDir(fso.getFullPath(), true, false, false, null, null);
return;
} else if (fso instanceof Symlink) {
Symlink symlink = (Symlink)fso;
if (symlink.getLinkRef() != null && symlink.getLinkRef() instanceof Directory) {
changeCurrentDir(
symlink.getLinkRef().getFullPath(), true, false, false, null, null);
return;
}
// Open the link ref
fso = symlink.getLinkRef();
}
// Open the file (edit or pick)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
// Open the file with the preferred registered app
IntentsActionPolicy.openFileSystemObject(getContext(), fso, false, null, null);
} else {
// Request a file pick selection
if (this.mOnFilePickedListener != null) {
this.mOnFilePickedListener.onFilePicked(fso);
}
}
} catch (Throwable ex) {
ExceptionUtil.translateException(getContext(), ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onRequestRefresh(Object o, boolean clearSelection) {
if (o instanceof FileSystemObject) {
refresh((FileSystemObject)o);
} else if (o == null) {
refresh();
}
if (clearSelection) {
onDeselectAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onRequestRemove(Object o, boolean clearSelection) {
if (o != null && o instanceof FileSystemObject) {
removeItem((FileSystemObject)o);
} else {
onRequestRefresh(null, clearSelection);
}
if (clearSelection) {
onDeselectAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onNavigateTo(Object o) {
// Ignored
}
/**
* {@inheritDoc}
*/
@Override
public void onBreadcrumbItemClick(BreadcrumbItem item) {
changeCurrentDir(item.getItemPath(), true, true, false, null, null);
}
/**
* {@inheritDoc}
*/
@Override
public void onSelectionChanged(final List<FileSystemObject> selectedItems) {
if (this.mOnNavigationSelectionChangedListener != null) {
this.mOnNavigationSelectionChangedListener.onSelectionChanged(this, selectedItems);
}
}
/**
* Method invoked when a request to show the menu associated
* with an item is started.
*
* @param item The item for which the request was started
*/
public void onRequestMenu(final FileSystemObject item) {
if (this.mOnNavigationRequestMenuListener != null) {
this.mOnNavigationRequestMenuListener.onRequestMenu(this, item);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onToggleSelection(FileSystemObject fso) {
if (this.mAdapter != null) {
this.mAdapter.toggleSelection(fso);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDeselectAll() {
if (this.mAdapter != null) {
this.mAdapter.deselectedAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onSelectAllVisibleItems() {
if (this.mAdapter != null) {
this.mAdapter.selectedAllVisibleItems();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDeselectAllVisibleItems() {
if (this.mAdapter != null) {
this.mAdapter.deselectedAllVisibleItems();
}
}
/**
* {@inheritDoc}
*/
@Override
public List<FileSystemObject> onRequestSelectedFiles() {
return this.getSelectedFiles();
}
/**
* {@inheritDoc}
*/
@Override
public List<FileSystemObject> onRequestCurrentItems() {
return this.getFiles();
}
/**
* {@inheritDoc}
*/
@Override
public String onRequestCurrentDir() {
return this.mCurrentDir;
}
/**
* Method that creates a ChRooted environment, protecting the user to break anything
* in the device
* @hide
*/
public void createChRooted() {
// If we are in a ChRooted environment, then do nothing
if (this.mChRooted) return;
this.mChRooted = true;
//Change to first storage volume
StorageVolume[] volumes =
StorageHelper.getStorageVolumes(getContext());
if (volumes != null && volumes.length > 0) {
changeCurrentDir(volumes[0].getPath(), false, true, false, null, null);
}
}
/**
* Method that exits from a ChRooted environment
* @hide
*/
public void exitChRooted() {
// If we aren't in a ChRooted environment, then do nothing
if (!this.mChRooted) return;
this.mChRooted = false;
// Refresh
refresh();
}
/**
* Method that ensures that the user don't go outside the ChRooted environment
*
* @param newDir The new directory to navigate to
* @return String
*/
private String checkChRootedNavigation(String newDir) {
// If we aren't in ChRooted environment, then there is nothing to check
if (!this.mChRooted) return newDir;
// Check if the path is owned by one of the storage volumes
if (!StorageHelper.isPathInStorageVolume(newDir)) {
StorageVolume[] volumes = StorageHelper.getStorageVolumes(getContext());
if (volumes != null && volumes.length > 0) {
return volumes[0].getPath();
}
}
return newDir;
}
/**
* Method that applies the current theme to the activity
*/
public void applyTheme() {
//- Breadcrumb
if (getBreadcrumb() != null) {
getBreadcrumb().applyTheme();
}
//- Redraw the adapter view
Theme theme = ThemeManager.getCurrentTheme(getContext());
theme.setBackgroundDrawable(getContext(), this, "background_drawable"); //$NON-NLS-1$
if (this.mAdapter != null) {
this.mAdapter.notifyThemeChanged();
}
if (this.mAdapterView instanceof ListView) {
((ListView)this.mAdapterView).setDivider(
theme.getDrawable(getContext(), "horizontal_divider_drawable")); //$NON-NLS-1$
}
refresh();
}
}
| true | true | private void changeCurrentDir(
final String newDir, final boolean addToHistory,
final boolean reload, final boolean useCurrent,
final SearchInfoParcelable searchInfo, final FileSystemObject scrollTo) {
// Check navigation security (don't allow to go outside the ChRooted environment if one
// is created)
final String fNewDir = checkChRootedNavigation(newDir);
// Wait to finalization
synchronized (this.mSync) {
if (mChangingDir) {
try {
mSync.wait();
} catch (InterruptedException iex) {
// Ignore
}
}
mChangingDir = true;
}
//Check that it is really necessary change the directory
if (!reload && this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0) {
return;
}
final boolean hasChanged =
!(this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0);
final boolean isNewHistory = (this.mCurrentDir != null);
//Execute the listing in a background process
AsyncTask<String, Integer, List<FileSystemObject>> task =
new AsyncTask<String, Integer, List<FileSystemObject>>() {
/**
* {@inheritDoc}
*/
@Override
protected List<FileSystemObject> doInBackground(String... params) {
try {
//Reset the custom title view and returns to breadcrumb
if (NavigationView.this.mTitle != null) {
NavigationView.this.mTitle.post(new Runnable() {
@Override
public void run() {
try {
NavigationView.this.mTitle.restoreView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Start of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.startLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
//Get the files, resolve links and apply configuration
//(sort, hidden, ...)
List<FileSystemObject> files = NavigationView.this.mFiles;
if (!useCurrent) {
files = CommandHelper.listFiles(getContext(), fNewDir, null);
}
return files;
} catch (final ConsoleAllocException e) {
//Show exception and exists
NavigationView.this.post(new Runnable() {
@Override
public void run() {
Context ctx = getContext();
Log.e(TAG, ctx.getString(
R.string.msgs_cant_create_console), e);
DialogHelper.showToast(ctx,
R.string.msgs_cant_create_console,
Toast.LENGTH_LONG);
((Activity)ctx).finish();
}
});
return null;
} catch (Exception ex) {
//End of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex2) {
/**NON BLOCK**/
}
}
//Capture exception (attach task, and use listener to do the anim)
ExceptionUtil.attachAsyncTask(
ex,
new AsyncTask<Object, Integer, Boolean>() {
private List<FileSystemObject> mTaskFiles = null;
@Override
@SuppressWarnings({
"unchecked", "unqualified-field-access"
})
protected Boolean doInBackground(Object... taskParams) {
mTaskFiles = (List<FileSystemObject>)taskParams[0];
return Boolean.TRUE;
}
@Override
@SuppressWarnings("unqualified-field-access")
protected void onPostExecute(Boolean result) {
if (!result.booleanValue()) {
return;
}
onPostExecuteTask(
mTaskFiles, addToHistory,
isNewHistory, hasChanged,
searchInfo, fNewDir, scrollTo);
}
});
final OnRelaunchCommandResult exListener =
new OnRelaunchCommandResult() {
@Override
public void onSuccess() {
done();
}
@Override
public void onFailed(Throwable cause) {
done();
}
@Override
public void onCancelled() {
done();
}
private void done() {
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
};
ExceptionUtil.translateException(
getContext(), ex, false, true, exListener);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void onPreExecute() {
// Do animation
fadeEfect(true);
}
/**
* {@inheritDoc}
*/
@Override
protected void onPostExecute(List<FileSystemObject> files) {
// This means an exception. This method will be recalled then
if (files != null) {
onPostExecuteTask(
files, addToHistory, isNewHistory,
hasChanged, searchInfo, fNewDir, scrollTo);
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
}
/**
* Method that performs a fade animation.
*
* @param out Fade out (true); Fade in (false)
*/
void fadeEfect(final boolean out) {
Activity activity = (Activity)getContext();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Animation fadeAnim = out ?
new AlphaAnimation(1, 0) :
new AlphaAnimation(0, 1);
fadeAnim.setDuration(50L);
fadeAnim.setFillAfter(true);
fadeAnim.setInterpolator(new AccelerateInterpolator());
NavigationView.this.startAnimation(fadeAnim);
}
});
}
};
task.execute(fNewDir);
}
| private void changeCurrentDir(
final String newDir, final boolean addToHistory,
final boolean reload, final boolean useCurrent,
final SearchInfoParcelable searchInfo, final FileSystemObject scrollTo) {
// Check navigation security (don't allow to go outside the ChRooted environment if one
// is created)
final String fNewDir = checkChRootedNavigation(newDir);
// Wait to finalization
synchronized (this.mSync) {
if (mChangingDir) {
try {
mSync.wait();
} catch (InterruptedException iex) {
// Ignore
}
}
mChangingDir = true;
}
//Check that it is really necessary change the directory
if (!reload && this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0) {
synchronized (this.mSync) {
mChangingDir = false;
mSync.notify();
}
return;
}
final boolean hasChanged =
!(this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0);
final boolean isNewHistory = (this.mCurrentDir != null);
//Execute the listing in a background process
AsyncTask<String, Integer, List<FileSystemObject>> task =
new AsyncTask<String, Integer, List<FileSystemObject>>() {
/**
* {@inheritDoc}
*/
@Override
protected List<FileSystemObject> doInBackground(String... params) {
try {
//Reset the custom title view and returns to breadcrumb
if (NavigationView.this.mTitle != null) {
NavigationView.this.mTitle.post(new Runnable() {
@Override
public void run() {
try {
NavigationView.this.mTitle.restoreView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Start of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.startLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
//Get the files, resolve links and apply configuration
//(sort, hidden, ...)
List<FileSystemObject> files = NavigationView.this.mFiles;
if (!useCurrent) {
files = CommandHelper.listFiles(getContext(), fNewDir, null);
}
return files;
} catch (final ConsoleAllocException e) {
//Show exception and exists
NavigationView.this.post(new Runnable() {
@Override
public void run() {
Context ctx = getContext();
Log.e(TAG, ctx.getString(
R.string.msgs_cant_create_console), e);
DialogHelper.showToast(ctx,
R.string.msgs_cant_create_console,
Toast.LENGTH_LONG);
((Activity)ctx).finish();
}
});
return null;
} catch (Exception ex) {
//End of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex2) {
/**NON BLOCK**/
}
}
//Capture exception (attach task, and use listener to do the anim)
ExceptionUtil.attachAsyncTask(
ex,
new AsyncTask<Object, Integer, Boolean>() {
private List<FileSystemObject> mTaskFiles = null;
@Override
@SuppressWarnings({
"unchecked", "unqualified-field-access"
})
protected Boolean doInBackground(Object... taskParams) {
mTaskFiles = (List<FileSystemObject>)taskParams[0];
return Boolean.TRUE;
}
@Override
@SuppressWarnings("unqualified-field-access")
protected void onPostExecute(Boolean result) {
if (!result.booleanValue()) {
return;
}
onPostExecuteTask(
mTaskFiles, addToHistory,
isNewHistory, hasChanged,
searchInfo, fNewDir, scrollTo);
}
});
final OnRelaunchCommandResult exListener =
new OnRelaunchCommandResult() {
@Override
public void onSuccess() {
done();
}
@Override
public void onFailed(Throwable cause) {
done();
}
@Override
public void onCancelled() {
done();
}
private void done() {
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
};
ExceptionUtil.translateException(
getContext(), ex, false, true, exListener);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void onPreExecute() {
// Do animation
fadeEfect(true);
}
/**
* {@inheritDoc}
*/
@Override
protected void onPostExecute(List<FileSystemObject> files) {
// This means an exception. This method will be recalled then
if (files != null) {
onPostExecuteTask(
files, addToHistory, isNewHistory,
hasChanged, searchInfo, fNewDir, scrollTo);
// Do animation
fadeEfect(false);
synchronized (mSync) {
mChangingDir = false;
mSync.notify();
}
}
}
/**
* Method that performs a fade animation.
*
* @param out Fade out (true); Fade in (false)
*/
void fadeEfect(final boolean out) {
Activity activity = (Activity)getContext();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Animation fadeAnim = out ?
new AlphaAnimation(1, 0) :
new AlphaAnimation(0, 1);
fadeAnim.setDuration(50L);
fadeAnim.setFillAfter(true);
fadeAnim.setInterpolator(new AccelerateInterpolator());
NavigationView.this.startAnimation(fadeAnim);
}
});
}
};
task.execute(fNewDir);
}
|
diff --git a/src/jrds/factories/ProbeFactory.java b/src/jrds/factories/ProbeFactory.java
index c3dcc369..539e24f2 100644
--- a/src/jrds/factories/ProbeFactory.java
+++ b/src/jrds/factories/ProbeFactory.java
@@ -1,180 +1,185 @@
/*##########################################################################
_##
_## $Id$
_##
_##########################################################################*/
package jrds.factories;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jrds.Probe;
import jrds.ProbeDesc;
import jrds.PropertiesManager;
import org.apache.log4j.Logger;
/**
* A class to find probe by their names
* @author Fabrice Bacchella
* @version $Revision$, $Date$
*/
public class ProbeFactory {
private final Logger logger = Logger.getLogger(ProbeFactory.class);
final private List<String> probePackages = new ArrayList<String>(5);
private Map<String, ProbeDesc> probeDescMap;
private GraphFactory gf;
private PropertiesManager pm;
/**
* Private constructor
* @param b
*/
public ProbeFactory(Map<String, ProbeDesc> probeDescMap, GraphFactory gf, PropertiesManager pm) {
this.probeDescMap = probeDescMap;
this.gf = gf;
this.pm = pm;
probePackages.add("");
}
/**
* Create an probe, provided his Class and a list of argument for a constructor
* for this object. It will be found using the default list of possible package
* @param className the probe name
* @param constArgs
* @return
*/
public Probe makeProbe(String className, List<?> constArgs) {
Probe retValue = null;
ProbeDesc pd = (ProbeDesc) probeDescMap.get(className);
if( pd != null) {
retValue = makeProbe(pd, constArgs);
}
else if(pm.legacymode ){
Class<?> probeClass = resolvClass(className, probePackages);
if (probeClass != null) {
Object o = null;
try {
Class<?>[] constArgsType = new Class[constArgs.size()];
Object[] constArgsVal = new Object[constArgs.size()];
int index = 0;
for (Object arg: constArgs) {
constArgsType[index] = arg.getClass();
constArgsVal[index] = arg;
index++;
}
Constructor<?> theConst = probeClass.getConstructor(constArgsType);
o = theConst.newInstance(constArgsVal);
retValue = (Probe) o;
}
catch (ClassCastException ex) {
logger.warn("didn't get a Probe but a " + o.getClass().getName());
}
catch (Exception ex) {
logger.warn("Error during probe creation of type " + className +
": " + ex, ex);
}
}
}
else {
logger.error("Probe named " + className + " not found");
}
//Now we finish the initialization of classes
if(retValue != null) {
retValue.initGraphList(gf);
}
return retValue;
}
/**
* Instanciate a probe using a probedesc
* @param constArgs
* @return
*/
public Probe makeProbe(ProbeDesc pd, List<?> constArgs) {
Class<? extends Probe> probeClass = pd.getProbeClass();
List<?> defaultsArgs = pd.getDefaultArgs();
Probe retValue = null;
if (probeClass != null) {
Object o = null;
try {
if(defaultsArgs != null && constArgs != null && constArgs.size() <= 0)
constArgs = defaultsArgs;
Class<?>[] constArgsType = new Class[constArgs.size()];
Object[] constArgsVal = new Object[constArgs.size()];
int index = 0;
for (Object arg: constArgs) {
constArgsType[index] = arg.getClass();
if(arg instanceof List) {
constArgsType[index] = List.class;
}
constArgsVal[index] = arg;
index++;
}
Constructor<? extends Probe> theConst = probeClass.getConstructor(constArgsType);
o = theConst.newInstance(constArgsVal);
retValue = (Probe) o;
retValue.setPd(pd);
}
catch (ClassCastException ex) {
logger.warn("didn't get a Probe but a " + o.getClass().getName());
+ return null;
}
catch (NoClassDefFoundError ex) {
logger.warn("Missing class for the creation of a probe " + pd.getName());
+ return null;
}
catch(InstantiationException ex) {
if(ex.getCause() != null)
logger.warn("Instantation exception : " + ex.getCause().getMessage(),
ex.getCause());
else {
logger.warn("Instantation exception : " + ex,
ex);
}
+ return null;
}
catch (NoSuchMethodException ex) {
logger.warn("ProbeDescription invalid " + pd.getName() + ": no constructor " + ex.getMessage() + " found");
+ return null;
}
catch (Exception ex) {
Throwable showException = ex;
Throwable t = ex.getCause();
if(t != null)
showException = t;
logger.warn("Error during probe creation of type " + pd.getName() + " with args " + constArgs +
": ", showException);
+ return null;
}
}
if(pm != null) {
logger.trace("Setting time step to " + pm.step + " for " + retValue);
retValue.setStep(pm.step);
}
return retValue;
}
private Class<?> resolvClass(String name, List<String> listPackages) {
Class<?> retValue = null;
for (String packageTry: listPackages) {
try {
retValue = Class.forName(packageTry + name);
}
catch (ClassNotFoundException ex) {
}
catch (NoClassDefFoundError ex) {
}
}
if (retValue == null)
logger.warn("Class " + name + " not found");
return retValue;
}
public ProbeDesc getProbeDesc(String name) {
return probeDescMap.get(name);
}
}
| false | true | public Probe makeProbe(ProbeDesc pd, List<?> constArgs) {
Class<? extends Probe> probeClass = pd.getProbeClass();
List<?> defaultsArgs = pd.getDefaultArgs();
Probe retValue = null;
if (probeClass != null) {
Object o = null;
try {
if(defaultsArgs != null && constArgs != null && constArgs.size() <= 0)
constArgs = defaultsArgs;
Class<?>[] constArgsType = new Class[constArgs.size()];
Object[] constArgsVal = new Object[constArgs.size()];
int index = 0;
for (Object arg: constArgs) {
constArgsType[index] = arg.getClass();
if(arg instanceof List) {
constArgsType[index] = List.class;
}
constArgsVal[index] = arg;
index++;
}
Constructor<? extends Probe> theConst = probeClass.getConstructor(constArgsType);
o = theConst.newInstance(constArgsVal);
retValue = (Probe) o;
retValue.setPd(pd);
}
catch (ClassCastException ex) {
logger.warn("didn't get a Probe but a " + o.getClass().getName());
}
catch (NoClassDefFoundError ex) {
logger.warn("Missing class for the creation of a probe " + pd.getName());
}
catch(InstantiationException ex) {
if(ex.getCause() != null)
logger.warn("Instantation exception : " + ex.getCause().getMessage(),
ex.getCause());
else {
logger.warn("Instantation exception : " + ex,
ex);
}
}
catch (NoSuchMethodException ex) {
logger.warn("ProbeDescription invalid " + pd.getName() + ": no constructor " + ex.getMessage() + " found");
}
catch (Exception ex) {
Throwable showException = ex;
Throwable t = ex.getCause();
if(t != null)
showException = t;
logger.warn("Error during probe creation of type " + pd.getName() + " with args " + constArgs +
": ", showException);
}
}
if(pm != null) {
logger.trace("Setting time step to " + pm.step + " for " + retValue);
retValue.setStep(pm.step);
}
return retValue;
}
| public Probe makeProbe(ProbeDesc pd, List<?> constArgs) {
Class<? extends Probe> probeClass = pd.getProbeClass();
List<?> defaultsArgs = pd.getDefaultArgs();
Probe retValue = null;
if (probeClass != null) {
Object o = null;
try {
if(defaultsArgs != null && constArgs != null && constArgs.size() <= 0)
constArgs = defaultsArgs;
Class<?>[] constArgsType = new Class[constArgs.size()];
Object[] constArgsVal = new Object[constArgs.size()];
int index = 0;
for (Object arg: constArgs) {
constArgsType[index] = arg.getClass();
if(arg instanceof List) {
constArgsType[index] = List.class;
}
constArgsVal[index] = arg;
index++;
}
Constructor<? extends Probe> theConst = probeClass.getConstructor(constArgsType);
o = theConst.newInstance(constArgsVal);
retValue = (Probe) o;
retValue.setPd(pd);
}
catch (ClassCastException ex) {
logger.warn("didn't get a Probe but a " + o.getClass().getName());
return null;
}
catch (NoClassDefFoundError ex) {
logger.warn("Missing class for the creation of a probe " + pd.getName());
return null;
}
catch(InstantiationException ex) {
if(ex.getCause() != null)
logger.warn("Instantation exception : " + ex.getCause().getMessage(),
ex.getCause());
else {
logger.warn("Instantation exception : " + ex,
ex);
}
return null;
}
catch (NoSuchMethodException ex) {
logger.warn("ProbeDescription invalid " + pd.getName() + ": no constructor " + ex.getMessage() + " found");
return null;
}
catch (Exception ex) {
Throwable showException = ex;
Throwable t = ex.getCause();
if(t != null)
showException = t;
logger.warn("Error during probe creation of type " + pd.getName() + " with args " + constArgs +
": ", showException);
return null;
}
}
if(pm != null) {
logger.trace("Setting time step to " + pm.step + " for " + retValue);
retValue.setStep(pm.step);
}
return retValue;
}
|
diff --git a/hot-deploy/opentaps-tests/src/org/opentaps/tests/financials/FinancialsTests.java b/hot-deploy/opentaps-tests/src/org/opentaps/tests/financials/FinancialsTests.java
index aad806bfa..09e6f376c 100644
--- a/hot-deploy/opentaps-tests/src/org/opentaps/tests/financials/FinancialsTests.java
+++ b/hot-deploy/opentaps-tests/src/org/opentaps/tests/financials/FinancialsTests.java
@@ -1,2943 +1,2943 @@
/*
* Copyright (c) 2006 - 2009 Open Source Strategies, Inc.
*
* Opentaps is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Opentaps is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Opentaps. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentaps.tests.financials;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import com.opensourcestrategies.financials.accounts.AccountsHelper;
import com.opensourcestrategies.financials.util.UtilCOGS;
import com.opensourcestrategies.financials.util.UtilFinancial;
import javolution.util.FastMap;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.opentaps.base.constants.AcctgTransTypeConstants;
import org.opentaps.base.constants.GlFiscalTypeConstants;
import org.opentaps.base.constants.InvoiceAdjustmentTypeConstants;
import org.opentaps.base.constants.InvoiceItemTypeConstants;
import org.opentaps.base.constants.InvoiceTypeConstants;
import org.opentaps.base.constants.PaymentMethodTypeConstants;
import org.opentaps.base.constants.PaymentTypeConstants;
import org.opentaps.base.constants.StatusItemConstants;
import org.opentaps.base.entities.AccountBalanceHistory;
import org.opentaps.base.entities.AcctgTransEntry;
import org.opentaps.base.entities.CustomTimePeriod;
import org.opentaps.base.entities.GlAccountHistory;
import org.opentaps.base.entities.GlAccountOrganization;
import org.opentaps.base.entities.InventoryItemValueHistory;
import org.opentaps.base.entities.InvoiceAdjustmentGlAccount;
import org.opentaps.base.entities.InvoiceAdjustmentType;
import org.opentaps.base.entities.SupplierProduct;
import org.opentaps.base.services.CreateQuickAcctgTransService;
import org.opentaps.base.services.PostAcctgTransService;
import org.opentaps.common.order.PurchaseOrderFactory;
import org.opentaps.domain.DomainsDirectory;
import org.opentaps.domain.DomainsLoader;
import org.opentaps.domain.billing.invoice.Invoice;
import org.opentaps.domain.billing.invoice.InvoiceRepositoryInterface;
import org.opentaps.domain.billing.payment.Payment;
import org.opentaps.domain.billing.payment.PaymentRepositoryInterface;
import org.opentaps.domain.inventory.InventoryDomainInterface;
import org.opentaps.domain.inventory.InventoryItem;
import org.opentaps.domain.inventory.InventoryRepositoryInterface;
import org.opentaps.domain.ledger.AccountingTransaction;
import org.opentaps.domain.ledger.AccountingTransaction.TagBalance;
import org.opentaps.domain.ledger.GeneralLedgerAccount;
import org.opentaps.domain.ledger.LedgerRepositoryInterface;
import org.opentaps.domain.order.Order;
import org.opentaps.domain.order.OrderRepositoryInterface;
import org.opentaps.domain.organization.Organization;
import org.opentaps.domain.organization.OrganizationRepositoryInterface;
import org.opentaps.domain.purchasing.PurchasingRepositoryInterface;
import org.opentaps.financials.domain.billing.invoice.InvoiceRepository;
import org.opentaps.foundation.entity.hibernate.Query;
import org.opentaps.foundation.entity.hibernate.Session;
import org.opentaps.foundation.infrastructure.Infrastructure;
import org.opentaps.foundation.infrastructure.User;
import org.opentaps.tests.analytics.tests.TestObjectGenerator;
import org.opentaps.tests.warehouse.InventoryAsserts;
/**
* General financial tests. If there is a large chunk of test cases that are related, please
* place them in a separate class.
*
* These tests are designed to run over and over again on the same database.
*/
public class FinancialsTests extends FinancialsTestCase {
private static final String MODULE = FinancialsTests.class.getName();
/** userLogin for inventory operations. */
private GenericValue demowarehouse1 = null;
/** Facility and inventory owner. */
private static final String facilityContactMechId = "9200";
private static final String testLedgerOrganizationPartyId = "LEDGER-TEST";
private static final String testLedgerTransId = "LEDGER-TEST-1"; // pre-stored transactions
private static final int LOOP_TESTS = 1000;
private TimeZone timeZone = TimeZone.getDefault();
private Locale locale = Locale.getDefault();
@Override
public void setUp() throws Exception {
super.setUp();
User = admin;
demowarehouse1 = delegator.findByPrimaryKeyCache("UserLogin", UtilMisc.toMap("userLoginId", "demowarehouse1"));
}
@Override
public void tearDown() throws Exception {
demowarehouse1 = null;
super.tearDown();
}
/**
* Test organizationRepository's getAllFiscalTimePeriods returns correct number of time periods.
* @throws GeneralException if an error occurs
*/
public void testGetAllCustomTimePeriods() throws GeneralException {
OrganizationRepositoryInterface orgRepository = organizationDomain.getOrganizationRepository();
List<CustomTimePeriod> timePeriods = orgRepository.getAllFiscalTimePeriods(testLedgerOrganizationPartyId);
// check that the number of time periods is same as that in LedgerPostingTestData.xml
assertEquals("Correct number of time periods found for [" + testLedgerOrganizationPartyId + "]", timePeriods.size(), 12);
}
/**
* Verify that the AccountingTransaction getDebitTotal() and getCreditTotal() methods are correct.
* @throws GeneralException if an error occurs
*/
public void testAccountingTransactionDebitCreditTotals() throws GeneralException {
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
AccountingTransaction ledgerTestTrans = ledgerRepository.getAccountingTransaction(testLedgerTransId);
assertEquals("Transaction [" + testLedgerTransId + "] debit total is not correct", ledgerTestTrans.getDebitTotal(), new BigDecimal("300.0"));
assertEquals("Transaction [" + testLedgerTransId + "] credit total is not correct", ledgerTestTrans.getCreditTotal(), new BigDecimal("300.0"));
}
/**
* Verify key ledger posting features:
* 1. transactions will not post before scheduled date
* 2. correct debit/credit balances will be set for all time periods
* 3. will not post transactions which have already been posted
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testLedgerPosting() throws GeneralException {
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
OrganizationRepositoryInterface organizationRepository = dd.getOrganizationDomain().getOrganizationRepository();
AccountingTransaction ledgerTestTrans = ledgerRepository.getAccountingTransaction(testLedgerTransId);
Map postToLedgerParams = UtilMisc.toMap("acctgTransId", testLedgerTransId, "userLogin", demofinadmin);
// verify that a transaction which is supposed to post in the future cannot be posted
ledgerTestTrans.setScheduledPostingDate(UtilDateTime.addDaysToTimestamp(UtilDateTime.nowTimestamp(), 10));
ledgerRepository.update(ledgerTestTrans);
runAndAssertServiceError("postAcctgTrans", postToLedgerParams);
// verify that it can post without the scheduled posting date
postToLedgerParams = UtilMisc.toMap("acctgTransId", testLedgerTransId, "userLogin", demofinadmin);
ledgerTestTrans.setScheduledPostingDate(null);
ledgerRepository.update(ledgerTestTrans);
runAndAssertServiceSuccess("postAcctgTrans", postToLedgerParams);
// verify AcctgTrans.getPostedAmount() is 300.00
ledgerTestTrans = ledgerRepository.getAccountingTransaction(testLedgerTransId);
assertEquals("AcctgTrans.getPostedAmount() should be 300.00", new BigDecimal("300.0"), ledgerTestTrans.getPostedAmount());
// the test transaction should only post to these time periods
List timePeriodsWithPosting = UtilMisc.toList("LT2008", "LT2008Q1", "LT2008FEB");
// verify that the GL Account History is correctly updated for each time period by checking each entry of the
// AcctgTrans and verifying that its GL account is correct for all available time periods
List<CustomTimePeriod> availableTimePeriods = organizationRepository.getAllFiscalTimePeriods(testLedgerOrganizationPartyId);
List<? extends AcctgTransEntry> transEntries = ledgerTestTrans.getAcctgTransEntrys();
for (AcctgTransEntry entry : transEntries) {
for (CustomTimePeriod period : availableTimePeriods) {
GlAccountHistory accountHistory = ledgerRepository.getAccountHistory(entry.getGlAccountId(), testLedgerOrganizationPartyId, period.getCustomTimePeriodId());
// verify that only the correct time periods were posted to
if (timePeriodsWithPosting.contains(period.getCustomTimePeriodId())) {
assertNotNull("Time period [" + period.getCustomTimePeriodId() + "] was posted to for gl account [" + entry.getGlAccountId(), accountHistory);
GeneralLedgerAccount glAccount = ledgerRepository.getLedgerAccount(entry.getGlAccountId(), testLedgerOrganizationPartyId);
if (glAccount.isDebitAccount()) {
assertEquals("Posted debits do not equal for " + accountHistory + " and " + entry, accountHistory.getPostedDebits(), entry.getAmount());
} else {
assertEquals("Posted credits do not equal for " + accountHistory + " and " + entry, accountHistory.getPostedCredits(), entry.getAmount());
}
} else {
assertNull("Time period [" + period.getCustomTimePeriodId() + "] was not posted to for gl account [" + entry.getGlAccountId(), accountHistory);
}
}
}
// verify that we cannot post it again
postToLedgerParams = UtilMisc.toMap("acctgTransId", testLedgerTransId, "userLogin", demofinadmin);
runAndAssertServiceError("postAcctgTrans", postToLedgerParams);
}
/**
* Tests posting a transaction that is globally balanced but unbalanced regarding tag1 because of a missing tag (which is configured for STATEMENT_DETAILS).
* Specifically one entry has a tag 1 debit 5000, and the corresponding credit entry has no tag 1.
* @throws GeneralException if an error occurs
*/
public void testLedgerPostingTagBalanceMissing() throws GeneralException {
// check the transaction cannot be posted
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("acctgTransId", "BAD-STATEMENT-TEST-1");
runAndAssertServiceError("postAcctgTrans", input);
// check the accounting transaction canPost() method
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
AccountingTransaction trans = ledgerRepository.getAccountingTransaction("BAD-STATEMENT-TEST-1");
assertFalse("Transaction BAD-STATEMENT-TEST-1 should not be marked as able to post.", trans.canPost());
// check the error is related to the unbalanced tag 1
TagBalance tagNotBalance = trans.accountingTagsBalance();
assertEquals("Transaction BAD-STATEMENT-TEST-1 tag 1 should be unbalanced", 1, tagNotBalance.getIndex());
assertEquals("Transaction BAD-STATEMENT-TEST-1 tag 1 should be unbalanced", new BigDecimal(5000), tagNotBalance.getBalance().abs());
}
/**
* tests posting a transaction that is globally balanced but unbalanced regarding tag1 because of a mismatched tag (which is configured for STATEMENT_DETAILS).
* Specifically the credit and debit entries both has a tag 1 but not the same tag value.
* @throws GeneralException if an error occurs
*/
public void testLedgerPostingTagBalanceMismatched() throws GeneralException {
// check the transaction cannot be posted
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("acctgTransId", "BAD-STATEMENT-TEST-2");
runAndAssertServiceError("postAcctgTrans", input);
// check the accounting transaction canPost() method
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
AccountingTransaction trans = ledgerRepository.getAccountingTransaction("BAD-STATEMENT-TEST-2");
assertFalse("Transaction BAD-STATEMENT-TEST-2 should not be marked as able to post.", trans.canPost());
// check the error is related to the unbalanced tag 1
TagBalance tagNotBalance = trans.accountingTagsBalance();
assertEquals("Transaction BAD-STATEMENT-TEST-2 tag 1 should be unbalanced", 1, tagNotBalance.getIndex());
assertEquals("Transaction BAD-STATEMENT-TEST-2 tag 1 should be unbalanced", new BigDecimal(1200), tagNotBalance.getBalance().abs());
}
/**
* Test getting the right GL Account for GlAccountTypeId and organization.
* @throws GeneralException if an error occurs
*/
public void testGlAccountTypeSetting() throws GeneralException {
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
GeneralLedgerAccount glAccount = ledgerRepository.getDefaultLedgerAccount("ACCOUNTS_RECEIVABLE", testLedgerOrganizationPartyId);
// this hardcoded gl account ID Needs to be the same as that defined in hot-deploy/opentaps-tests/data/financials/LedgerPostingTestData.xml
assertEquals("Incorrect Accounts Receivables account for [" + testLedgerOrganizationPartyId + "]", "120000", glAccount.getGlAccountId());
}
/**
* Test the sending of a paycheck [DEMOPAYCHECK1] and compares the resulting GL transaction
* to the reference transaction DEMOPAYCHECK1 in PayrollEntries.xml.
*
* Note that this is a test between an initial demo paycheck and an expected result set,
* so we are not testing the logic in creating a paycheck, but rather the ledger posting
* logic. The idea is to test the part of the system which is difficult for humans to
* validate immediately. Bugs in the posting process may surface after many months, so
* this makes for a perfect unit test subject.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testPaycheckTransactions() throws GeneralException {
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
GenericValue paycheck = delegator.findByPrimaryKey("Payment", UtilMisc.toMap("paymentId", "DEMOPAYCHECK1"));
assertNotNull("Paycheck with ID [DEMOPAYCHECK1] not found.", paycheck);
// set the status to "not paid" so we can send it
paycheck.set("statusId", "PMNT_NOT_PAID");
paycheck.store();
// mark the payment as sent
fa.updatePaymentStatus(paycheck.getString("paymentId"), "PMNT_SENT");
// get the transaction with the assistance of our start timestamp. Note that this requires the DEMOPAYCHECK1 not to have an effectiveDate of its own
// or it would be posted with transactionDate = payment.effectiveDate
Set transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paycheck.get("paymentId"))), start, delegator);
assertNotEmpty("Paycheck transaction not created.", transactions);
// assert transaction equivalence with the reference transaction
assertTransactionEquivalence(transactions, UtilMisc.toList("PAYCHECKTEST1"));
}
/**
* Test receives a few serialized and non-serialized items of product, write off
* some quantity of product as damaged and checks average cost after.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testProductAverageCost() throws GeneralException {
// create product for inventory operations
Map<String, Object> callContext = new HashMap<String, Object>();
callContext.put("productTypeId", "FINISHED_GOOD");
callContext.put("internalName", "Product for use in Average Cost Unit Tests");
callContext.put("isVirtual", "N");
callContext.put("isVariant", "N");
callContext.put("userLogin", demowarehouse1);
Map<String, Object> product = runAndAssertServiceSuccess("createProduct", callContext);
String productId = (String) product.get("productId");
assertEquals("Failed to create test product.", true, productId != null);
Timestamp startTime = UtilDateTime.nowTimestamp();
BigDecimal expectedAvgCost = null;
BigDecimal calculatedAvgCost = null;
InventoryAsserts inventoryAsserts = new InventoryAsserts(this, "WebStoreWarehouse", organizationPartyId, demowarehouse1);
final BigDecimal acceptedDelta = new BigDecimal("0.009");
// common parameters for receiveInventoryProduct service
Map<String, Object> commonParameters = new HashMap<String, Object>();
commonParameters.put("productId", productId);
commonParameters.put("facilityId", "WebStoreWarehouse");
commonParameters.put("currencyUomId", "USD");
commonParameters.put("datetimeReceived", startTime);
commonParameters.put("quantityRejected", BigDecimal.ZERO);
commonParameters.put("userLogin", demowarehouse1);
/*
* receives 10 products at $15, average cost = 15 [10 x 15$]
*/
Map<String, Object> input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM", "unitCost", new BigDecimal("15"), "quantityAccepted", new BigDecimal("10")));
Map output = runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("15");
assertEquals("After receipt 10 products [" + productId + "] at $15 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
// we'll write this inventory off later
String inventoryItemIdVar = (String) output.get("inventoryItemId");
pause("allow distinct product average cost timestamps");
/*
* receives 10 products at $20, average cost = 17.5 [10 x 15$ + 10 x 20$]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM", "unitCost", new BigDecimal("20"), "quantityAccepted", new BigDecimal("10")));
output = runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("17.5");
assertEquals("After receipt 10 products [" + productId + "] at $20 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
String inventoryItemIdForRevalue1 = (String) output.get("inventoryItemId");
pause("allow distinct product average cost timestamps");
/*
* receives 1 serialized product at $10, average cost = 17.142857 [10 x 15$ + 10 x 20$ + 1 x 10$]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "SERIALIZED_INV_ITEM", "unitCost", new BigDecimal("10"), "quantityAccepted", BigDecimal.ONE));
runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("17.142");
assertEquals("After receipt 1 serialized product [" + productId + "] at $10 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* receives 1 serialized product at $12, average cost = 16.909091 [10 x 15$ + 10 x 20$ + 1 x 10$ +1 x 12$]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "SERIALIZED_INV_ITEM", "unitCost", new BigDecimal("12"), "quantityAccepted", BigDecimal.ONE));
runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("16.909");
assertEquals("After receipt 1 serialized product [" + productId + "] at $12 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* Create variance -5 products from inventory item at $15, average cost = 16.909091 [10 x 15$ + 10 x 20$ + 1 x 10$ + 1 x 12$ - 5 x avg] doesn't change the average cost
*/
BigDecimal varianceQuantity = new BigDecimal("-5");
input = UtilMisc.<String, Object>toMap("userLogin", demowarehouse1, "inventoryItemId", inventoryItemIdVar, "quantityOnHandVar", varianceQuantity, "availableToPromiseVar", varianceQuantity, "varianceReasonId", "VAR_DAMAGED");
runAndAssertServiceSuccess("createPhysicalInventoryAndVariance", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("16.909");
assertEquals("After creating variance for -5 products [" + productId + "] calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* Create variance -3 products from inventory item at $15, average cost = 16.909091 [10 x 15$ + 10 x 20$ + 1 x 10$ + 1 x 12$ - 8 x avg] doesn't change the average cost
*/
varianceQuantity = new BigDecimal("-3");
input = UtilMisc.<String, Object>toMap("userLogin", demowarehouse1, "inventoryItemId", inventoryItemIdVar, "quantityOnHandVar", varianceQuantity, "availableToPromiseVar", varianceQuantity, "varianceReasonId", "VAR_DAMAGED");
runAndAssertServiceSuccess("createPhysicalInventoryAndVariance", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("16.909");
assertEquals("After creating variance for -3 products [" + productId + "] calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* receives 3 products at $11 average cost = 15.865882 [10 x 15$ + 10 x 20$ + 1 x 10$ + 1 x 12$ + 3 x 11$ - 8 x 16.91]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM", "unitCost", new BigDecimal("11"), "quantityAccepted", new BigDecimal("3")));
runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("15.866");
assertEquals("After receipt 3 products [" + productId + "] at $11 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* receives 1 serialized products at $22 average cost = 16.206667 [10 x 15$ + 10 x 20$ + 1 x 10$ + 1 x 12$ + 3 x 11$ + 1 x 22$ - 8 x 16.91]
*/
input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "SERIALIZED_INV_ITEM", "unitCost", new BigDecimal("22"), "quantityAccepted", new BigDecimal("1")));
output = runAndAssertServiceSuccess("receiveInventoryProduct", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("16.207");
assertEquals("After receipt 1 serialized product [" + productId + "] at $22 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
String inventoryItemIdForRevalue2 = (String) output.get("inventoryItemId");
pause("allow distinct product average cost timestamps");
/*
* revalue inventoryItemIdForRevalue1 to $10 average cost = 10.651111 [10 x 15$ + 10 x 10$ + 1 x 10$ + 1 x 12$ + 3 x 11$ + 1 x 22$ - 8 x 16.91]
*/
input = new HashMap<String, Object>();
input.put("inventoryItemId", inventoryItemIdForRevalue1);
input.put("productId", productId);
input.put("ownerPartyId", organizationPartyId);
input.put("userLogin", demowarehouse1);
input.put("unitCost", new BigDecimal("10.0"));
input.put("currencyUomId", "USD");
input.put("inventoryItemTypeId", "NON_SERIAL_INV_ITEM");
runAndAssertServiceSuccess("updateInventoryItem", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("10.651");
assertEquals("After revalue 10 products [" + productId + "] at $20 to $10 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
pause("allow distinct product average cost timestamps");
/*
* revalue inventoryItemIdForRevalue2 to $10
*/
input = new HashMap<String, Object>();
input.put("inventoryItemId", inventoryItemIdForRevalue2);
input.put("productId", productId);
input.put("ownerPartyId", organizationPartyId);
input.put("userLogin", demowarehouse1);
input.put("unitCost", new BigDecimal("10.0"));
input.put("currencyUomId", "USD");
input.put("inventoryItemTypeId", "SERIALIZED_INV_ITEM");
runAndAssertServiceSuccess("updateInventoryItem", input);
calculatedAvgCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
assertNotNull("The product [" + productId + "] average cost cannot be null", calculatedAvgCost);
calculatedAvgCost = calculatedAvgCost.setScale(DECIMALS, ROUNDING);
expectedAvgCost = new BigDecimal("9.984");
assertEquals("After revalue 1 serialized product [" + productId + "] at $22 to $10 calculated average cost doesn't equal expected one with inadmissible error.", expectedAvgCost, calculatedAvgCost, acceptedDelta);
inventoryAsserts.assertInventoryValuesEqual(productId);
}
/**
* This test verifies that products average cost will be correct after
* a large number of transactions in rapid succession of each other.
* @throws GeneralException if an error occurs
*/
public void testProductAverageCostLongRunning() throws GeneralException {
// Create a new product
Map<String, Object> callContext = new HashMap<String, Object>();
callContext.put("productTypeId", "FINISHED_GOOD");
callContext.put("internalName", "Product for use in Average Cost Long Running Tests");
callContext.put("isVirtual", "N");
callContext.put("isVariant", "N");
callContext.put("userLogin", demowarehouse1);
Map<String, Object> product = runAndAssertServiceSuccess("createProduct", callContext);
String productId = (String) product.get("productId");
// track two values: total quantity and total value of the product. Initially, both should be zero
BigDecimal totalQuantity = BigDecimal.ZERO;
BigDecimal totalValue = BigDecimal.ZERO;
// common parameters for receiveInventoryProduct service
Map<String, Object> commonParameters = new HashMap<String, Object>();
commonParameters.put("productId", productId);
commonParameters.put("facilityId", "WebStoreWarehouse");
commonParameters.put("currencyUomId", "USD");
commonParameters.put("quantityRejected", BigDecimal.ZERO);
commonParameters.put("userLogin", demowarehouse1);
// for i = 1 to 1000
for (int i = 1; i < LOOP_TESTS; i++) {
// q (quantity) = i, uc (unit cost) = i mod 1000
// receive q of product at unit cost = uc
BigDecimal q = new BigDecimal(i);
BigDecimal uc = new BigDecimal(i % 1000);
Map<String, Object> input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM"
, "unitCost", uc, "quantityAccepted" , q
, "datetimeReceived", UtilDateTime.nowTimestamp()));
runAndAssertServiceSuccess("receiveInventoryProduct", input);
// update total quantity (add q) and total value (add q*uc)
totalQuantity = totalQuantity.add(q);
totalValue = totalValue.add(q.multiply(uc));
// Verify that the average cost of the product from UtilCOGS.getProductAverageCost is equal to (total value)/(total quantity) to within 5 decimal places
BigDecimal productAverageCost = UtilCOGS.getProductAverageCost(productId, organizationPartyId, demowarehouse1, delegator, dispatcher);
BigDecimal expectedAvgCost = totalValue.divide(totalQuantity, DECIMALS, BigDecimal.ROUND_HALF_DOWN);
assertEquals("Product [" + productId + "] average cost should be " + expectedAvgCost + ".", expectedAvgCost, productAverageCost.setScale(DECIMALS, BigDecimal.ROUND_HALF_DOWN));
}
}
/**
* This test verifies that products average cost will be correct after
* a large number of transactions in rapid succession of each other.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testInventoryItemValueHistoryLongRunning() throws GeneralException {
// Create a new product
Map<String, Object> callContext = new HashMap<String, Object>();
callContext.put("productTypeId", "FINISHED_GOOD");
callContext.put("internalName", "Product for use in testInventoryItemValueHistoryLongRunning");
callContext.put("isVirtual", "N");
callContext.put("isVariant", "N");
callContext.put("userLogin", demowarehouse1);
Map<String, Object> product = runAndAssertServiceSuccess("createProduct", callContext);
String productId = (String) product.get("productId");
// receive 1 of the product at unit cost 0.1
Map<String, Object> commonParameters = new HashMap<String, Object>();
commonParameters.put("productId", productId);
commonParameters.put("facilityId", "WebStoreWarehouse");
commonParameters.put("currencyUomId", "USD");
commonParameters.put("quantityRejected", BigDecimal.ZERO);
commonParameters.put("userLogin", demowarehouse1);
Map<String, Object> input = new HashMap<String, Object>();
input.putAll(commonParameters);
input.putAll(UtilMisc.toMap("inventoryItemTypeId", "NON_SERIAL_INV_ITEM"
, "unitCost", new BigDecimal("0.1"), "quantityAccepted" , new BigDecimal("1.0")
, "datetimeReceived", UtilDateTime.nowTimestamp()));
Map output = runAndAssertServiceSuccess("receiveInventoryProduct", input);
String inventoryItemId = (String) output.get("inventoryItemId");
// track the previous inventory item unit cost
List<GenericValue> inventoryItems = delegator.findByAnd("InventoryItem", UtilMisc.toMap("inventoryItemId", inventoryItemId));
GenericValue firstInventoryItem = inventoryItems.get(0);
BigDecimal previousUnitCost = firstInventoryItem.getBigDecimal("unitCost");
Debug.logInfo("previousUnitCost : " + previousUnitCost, MODULE);
pause("allow distinct product average cost timestamps");
DomainsLoader dl = new DomainsLoader(new Infrastructure(dispatcher), new User(User));
InventoryDomainInterface inventoryDomain = dl.loadDomainsDirectory().getInventoryDomain();
InventoryRepositoryInterface inventoryRepository = inventoryDomain.getInventoryRepository();
// for i = 1 to 1000
// update the inventory item.unit cost to i
for (int i = 1; i < LOOP_TESTS; i++) {
firstInventoryItem.set("unitCost", new BigDecimal(i));
firstInventoryItem.store();
// Verify that the previous inventory item unit cost is the same as the one retrieved from InventoryItem
InventoryItem item = inventoryRepository.getInventoryItemById(firstInventoryItem.getString("inventoryItemId"));
InventoryItemValueHistory inventoryItemValueHistory = inventoryRepository.getLastInventoryItemValueHistoryByInventoryItem(item);
BigDecimal inventoryItemValueHistoryUnitCost = inventoryItemValueHistory.getUnitCost();
assertEquals("Product [" + productId + "] previous inventory item unit cost should be " + previousUnitCost + ".", previousUnitCost, inventoryItemValueHistoryUnitCost);
}
}
/**
* Test that the transactionDate of accounting transaction will be the invoice's invoiceDate, not the current timestamp.
* @throws GeneralException if an error occurs
*/
public void testInvoiceTransactionPostingDate() throws GeneralException {
// create a customer
String customerPartyId = createPartyFromTemplate("DemoAccount1", "account for testing invoice posting transaction date");
// create a sales invoice to the customer 30 days in the future
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Timestamp invoiceDate = UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale);
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", invoiceDate, null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
// set invoice to READY
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
// check that the accounting transaction's transactionDate is the same as the invoice's invoiceDate
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
List<AccountingTransaction> invoiceAcctgTransList = ledgerRepository.findList(AccountingTransaction.class, ledgerRepository.map(org.opentaps.base.entities.AcctgTrans.Fields.invoiceId, invoiceId));
assertNotNull("An accounting transaction was not found for invoice [" + invoiceId + "]", invoiceAcctgTransList);
AccountingTransaction acctgTrans = invoiceAcctgTransList.get(0);
// note: it is important to get the actual invoiceDate stored in the Invoice entity, not the invoiceDate from above
// for example, mysql might store 2009-06-12 12:46:30.309 as 2009-06-12 12:46:30.0, so your comparison won't equal
InvoiceRepositoryInterface repository = billingDomain.getInvoiceRepository();
Invoice invoice = repository.getInvoiceById(invoiceId);
assertEquals("Transaction date and invoice date do not equal", acctgTrans.getTransactionDate(), invoice.getInvoiceDate());
}
/**
* Test to verify that payments are posted to the effectiveDate of the payment.
* @throws GeneralException if an error occurs
*/
public void testPaymentTransactionPostingDate() throws GeneralException {
String customerPartyId = createPartyFromTemplate("DemoAccount1", "account for testing payment posting transaction date");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Timestamp paymentDate = UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale);
String paymentId = financialAsserts.createPayment(new BigDecimal("1.0"), customerPartyId, "CUSTOMER_PAYMENT", "CASH");
PaymentRepositoryInterface paymentRepository = billingDomain.getPaymentRepository();
Payment payment = paymentRepository.getPaymentById(paymentId);
payment.setEffectiveDate(paymentDate);
paymentRepository.createOrUpdate(payment);
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
List<AccountingTransaction> paymentAcctgTransList = ledgerRepository.findList(AccountingTransaction.class, ledgerRepository.map(org.opentaps.base.entities.AcctgTrans.Fields.paymentId, paymentId));
assertNotNull("An accounting transaction was not found for payment [" + paymentId + "]", paymentAcctgTransList);
AccountingTransaction acctgTrans = paymentAcctgTransList.get(0);
payment = paymentRepository.getPaymentById(paymentId);
assertEquals("Transaction date and invoice date do not equal", acctgTrans.getTransactionDate(), payment.getEffectiveDate());
}
/**
* Tests basic methods of Invoice class for sales invoice.
* @exception GeneralException if an error occurs
*/
public void testInvoiceMethodsForSalesInvoice() throws GeneralException {
//create a SALES_INVOICE from Company to another party
InvoiceRepositoryInterface repository = billingDomain.getInvoiceRepository();
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testInvoiceMethodsForSalesInvoice");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
// create invoice
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
// Check the Invoice.isReceivable() is true
Invoice invoice = repository.getInvoiceById(invoiceId);
assertTrue("Invoice with ID [" + invoiceId + "] should be receivable.", invoice.isReceivable());
// Check the Invoice.isPayable() is false
assertFalse("Invoice with ID [" + invoiceId + "] should not payable.", invoice.isPayable());
// Check the Invoice.getOrganizationPartyId() is Company
assertEquals("Invoice.getOrganizationPartyId() should be " + organizationPartyId, organizationPartyId, invoice.getOrganizationPartyId());
// Check the Invoice.getTransactionPartyId() is the other party
assertEquals("Invoice.getTransactionPartyId() should be " + customerPartyId, customerPartyId, invoice.getTransactionPartyId());
}
/**
* Tests basic methods of Invoice class for purchase invoice.
* @exception GeneralException if an error occurs
*/
public void testInvoiceMethodsForPurchaseInvoice() throws GeneralException {
InvoiceRepositoryInterface repository = billingDomain.getInvoiceRepository();
String supplierPartyId = createPartyFromTemplate("DemoSupplier", "Account for testInvoiceMethodsForPurchaseInvoice");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
// create a PURCHASE_INVOICE from another party to Company
String invoiceId = financialAsserts.createInvoice(supplierPartyId, "PURCHASE_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "PINV_FPROD_ITEM", "GZ-1000", new BigDecimal("100.0"), new BigDecimal("4.56"));
// Check the Invoice.isReceivable() is false
Invoice invoice = repository.getInvoiceById(invoiceId);
assertFalse("Invoice with ID [" + invoiceId + "] should not receivable.", invoice.isReceivable());
// Check the Invoice.isPayable() is true
assertTrue("Invoice with ID [" + invoiceId + "] should be payable.", invoice.isPayable());
// Check Invoice.getOrganizationPartyId() is Company
assertEquals("Invoice.getOrganizationPartyId() should be " + organizationPartyId, organizationPartyId, invoice.getOrganizationPartyId());
// Check the Invoice.getTransactionPartyId() is the other party
assertEquals("Invoice.getTransactionPartyId() should be " + supplierPartyId, supplierPartyId, invoice.getTransactionPartyId());
}
/**
* Test for sales invoice and payment.
* Note: this test relies on the status of previously created Invoices so it will fail if you run
* it a second time without rebuilding the DB
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testSalesInvoicePayment() throws GeneralException {
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
InvoiceRepositoryInterface repository = dd.getBillingDomain().getInvoiceRepository();
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
Timestamp now = start;
// note the initial balances
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testSalesInvoicePayment");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(start);
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
// create invoice and set it to ready
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_PROMOTION_ADJ", "GZ-1000", new BigDecimal("1.0"), new BigDecimal("-10.0"));
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1001", new BigDecimal("1.0"), new BigDecimal("45.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", null, null, new BigDecimal("12.95"));
// Check the invoice current status
Invoice invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_IN_PROCESS status", "INVOICE_IN_PROCESS", invoice.getString("statusId"));
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not increased by 77.95", balance2.subtract(new BigDecimal("77.95")), balance1);
Map halfBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "77.95");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, halfBalances, accountMap);
// create payment and set it to received
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("77.95"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_PAID status", "INVOICE_PAID", invoice.getString("statusId"));
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not decreased by 77.95", balance3.add(new BigDecimal("77.95")), balance2);
// get the transactions for the payment with the assistance of our start timestamp
Set<String> transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paymentId)), start, delegator);
assertNotEmpty(paymentId + " transaction not created.", transactions);
// assert transaction equivalence with the reference PMT_CUST_TEST-1 transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("PMT_CUST_TEST-1"));
Map finalBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "-77.95", "UNDEPOSITED_RECEIPTS", "77.95");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(halfBalances, finalBalances, accountMap);
}
/**
* These tests verify what happens when you void a payment.
* 1 - get the initial balance for the customer and financial balances
* 2 - create a payment and set status to PMNT_VOID
* 3 - get the new balance for the customer and financial balances
* 4 - verify that the balance for the customer has increased by 77.95
* 5 - verify that the balance for ACCOUNTS_RECEIVABLE has increased by 77.95, and the balance for UNDEPOSITED_RECEIPTS has decreased by 77.95
*
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testVoidPayment() throws GeneralException {
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
InvoiceRepositoryInterface repository = dd.getBillingDomain().getInvoiceRepository();
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
Timestamp now = start;
// note the initial balances
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testVoidPayment");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(start);
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
// create invoice and set it to ready
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_PROMOTION_ADJ", "GZ-1000", new BigDecimal("1.0"), new BigDecimal("-10.0"));
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1001", new BigDecimal("1.0"), new BigDecimal("45.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", null, null, new BigDecimal("12.95"));
// Update the Invoice status
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not increased by 77.95", balance2.subtract(new BigDecimal("77.95")), balance1);
Map afterSettingInvoiceReadyBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "77.95");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, afterSettingInvoiceReadyBalances, accountMap);
// create payment and set it to received
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("77.95"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
Invoice invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_PAID status", "INVOICE_PAID", invoice.getString("statusId"));
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not decrease by 77.95", balance3.add(new BigDecimal("77.95")), balance2);
// get the transactions for payment with the assistance of our start timestamp
Set<String> transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paymentId)), start, delegator);
assertNotEmpty(paymentId + " transaction not created.", transactions);
// assert transaction equivalence with the reference payment transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("PMT_CUST_TEST-2"));
Map afterSettingPaymentReceivedBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "-77.95", "UNDEPOSITED_RECEIPTS", "77.95");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(afterSettingInvoiceReadyBalances, afterSettingPaymentReceivedBalances, accountMap);
pause("avoid having two invoice status with same timestamp");
// void the payment
start = UtilDateTime.nowTimestamp();
Map<String, Object> input = UtilMisc.toMap("userLogin", demofinadmin, "paymentId", paymentId);
runAndAssertServiceSuccess("voidPayment", input);
// check that the reference invoice status changed back to INVOICE_READY
invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_READY status", "INVOICE_READY", invoice.getString("statusId"));
// verify that the balance for the customer has increased by 77.95
now = UtilDateTime.nowTimestamp();
BigDecimal balance4 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not increased by 77.95", balance3, balance4.subtract(new BigDecimal("77.95")));
// get the reversed transactions for payment, their date will be the same as the date of the reversed transaction
// so checking the created stamp field instead of the transaction date here
transactions = getAcctgTransCreatedSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paymentId)), start, delegator);
assertNotEmpty(paymentId + " payment void transactions not created.", transactions);
// assert transaction equivalence with the reference PMT_CUST_TEST-2R transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("PMT_CUST_TEST-2R"));
// verify that the balance for ACCOUNTS_RECEIVABLE has increased by 77.95, and the balance for UNDEPOSITED_RECEIPTS has decreased by 77.95
Map finalBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "77.95", "UNDEPOSITED_RECEIPTS", "-77.95");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(afterSettingPaymentReceivedBalances, finalBalances, accountMap);
}
/**
* This test verifies what happens when you write off an invoice.
* 1 - get the initial balance for the customer and financial balances
* 2 - create a invoice and set status to INVOICE_WRITEOFF
* 3 - get the new balance for customer DemoAccount1 and financial balances
* 4 - verify that the balance for the customer has decreased by 77.95
* 5 - verify that the balance for ACCOUNTS_RECEIVABLE has decreased by 77.95, and the balance for ACCTRECV_WRITEOFF has increased by 77.95
*
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testInvoiceWriteOff() throws GeneralException {
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testInvoiceWriteOff");
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
Timestamp now = start;
// note the initial balances
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(start);
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
// create invoice and set it to ready
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_PROMOTION_ADJ", "GZ-1000", new BigDecimal("1.0"), new BigDecimal("-10.0"));
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1001", new BigDecimal("1.0"), new BigDecimal("45.0"));
financialAsserts.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", null, null, new BigDecimal("12.95"));
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " should increase by 77.95", balance2.subtract(balance1), new BigDecimal("77.95"));
Map afterSettingInvoiceReadyBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "77.95");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, afterSettingInvoiceReadyBalances, accountMap);
// Update the Invoice status to INVOICE_WRITEOFF
start = UtilDateTime.nowTimestamp();
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_WRITEOFF");
// verify that the balance for the customer has decreased by 77.95
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + customerPartyId + " has not decrease by 77.95", balance3.subtract(balance2), new BigDecimal("-77.95"));
// get the transactions for INV_SALES_TEST-3 with the assistance of our start timestamp
Set<String> transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, invoiceId),
EntityCondition.makeCondition("acctgTransTypeId", EntityOperator.EQUALS, "WRITEOFF"),
EntityCondition.makeCondition("glFiscalTypeId", EntityOperator.NOT_EQUAL, "REFERENCE")), start, delegator);
assertNotEmpty(invoiceId + " invoice write off transactions not created.", transactions);
// assert transaction equivalence with the reference INV_SALES_TEST-3WO transaction
assertTransactionEquivalence(transactions, UtilMisc.toList("INV_SALES_TEST-3WO"));
// figure out what the sales invoice writeoff account is using the domain
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
LedgerRepositoryInterface ledgerRepository = dd.getLedgerDomain().getLedgerRepository();
InvoiceAdjustmentGlAccount writeoffGlAcct = ledgerRepository.getInvoiceAdjustmentGlAccount(organizationPartyId, "SALES_INVOICE", "WRITEOFF");
assertNotNull(writeoffGlAcct);
// verify that the balance for ACCOUNTS_RECEIVABLE has decreased by 77.95, and the balance for ACCTRECV_WRITEOFF has increased by 77.95
Map afterWritingOffInvoiceBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "-77.95");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(writeoffGlAcct.getGlAccountId(), "77.95");
assertMapDifferenceCorrect(afterSettingInvoiceReadyBalances, afterWritingOffInvoiceBalances, accountMap);
}
/**
* Test for purchase invoice and vendor payment.
* Note: this test relies on the status of previously created Invoices so it will fail if you run
* it a second time without rebuilding the DB
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testPurchaseInvoicePayment() throws GeneralException {
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
InvoiceRepositoryInterface repository = dd.getBillingDomain().getInvoiceRepository();
// before we begin, note the time so we can easily find the transaction
Timestamp start = UtilDateTime.nowTimestamp();
Timestamp now = start;
// note the initial balances
String supplierPartyId = createPartyFromTemplate("DemoSupplier", "Supplier for testPurchaseInvoicePayment");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(start);
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(supplierPartyId, organizationPartyId, "ACTUAL", now, delegator);
// create invoice
String invoiceId = financialAsserts.createInvoice(supplierPartyId, "PURCHASE_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "PINV_FPROD_ITEM", "GZ-1000", new BigDecimal("100.0"), new BigDecimal("4.56"));
financialAsserts.createInvoiceItem(invoiceId, "PITM_SHIP_CHARGES", new BigDecimal("1.0"), new BigDecimal("13.95"));
financialAsserts.createInvoiceItem(invoiceId, "PINV_SUPLPRD_ITEM", new BigDecimal("1.0"), new BigDecimal("56.78"));
// Check the invoice current status
Invoice invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_IN_PROCESS status", "INVOICE_IN_PROCESS", invoice.getString("statusId"));
// Update the Invoice status
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForVendorPartyId(supplierPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + supplierPartyId + " has not increase by 526.73", balance1, balance2.subtract(new BigDecimal("526.73")));
// get the transactions for INV_PURCH_TEST-1 with the assistance of our start timestamp
Set<String> transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, invoiceId)), start, delegator);
assertNotEmpty(invoiceId + " transaction not created.", transactions);
// assert transaction equivalence with the reference INV_PURCH_TEST-1 transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("INV_PURCH_TEST-1"));
Map halfBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_PAYABLE", "-526.73", "UNINVOICED_SHIP_RCPT", "456.0");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.putAll(UtilMisc.toMap("510000", "13.95", "650000", "56.78"));
assertMapDifferenceCorrect(initialBalances, halfBalances, accountMap);
// create payment and set it to sent
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("526.73"), organizationPartyId, supplierPartyId, "VENDOR_PAYMENT", "COMPANY_CHECK", "COCHECKING", invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId, "PMNT_SENT");
invoice = repository.getInvoiceById(invoiceId);
assertNotNull("Invoice with ID [" + invoiceId + "] not found.", invoice);
assertEquals("Invoice with ID [" + invoiceId + "] should have the INVOICE_PAID status", "INVOICE_PAID", invoice.getString("statusId"));
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForVendorPartyId(supplierPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + supplierPartyId + " has not decrease by 526.73", balance2, balance3.add(new BigDecimal("526.73")));
// get the transactions for PMT_VEND_TEST-1 with the assistance of our start timestamp
transactions = getAcctgTransSinceDate(UtilMisc.toList(EntityCondition.makeCondition("paymentId", EntityOperator.EQUALS, paymentId)), start, delegator);
assertNotEmpty(paymentId + " transaction not created.", transactions);
// assert transaction equivalence with the reference PMT_VEND_TEST-1 transaction
assertTransactionEquivalenceIgnoreParty(transactions, UtilMisc.toList("PMT_VEND_TEST-1"));
Map finalBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_PAYABLE", "526.73");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(halfBalances, finalBalances, accountMap);
}
/**
* Finance charges test:
* Setup
* 1. Create sales invoice (#1) from Company to customer1PartyId for 1 item of $100, invoiceDate = 60 days before today. Set invoice to ready.
* 2. Create sales invoice (#2) from Company to customer2PartyId for 2 items of $250 each, invoiceDate = 45 days before today. Set invoice to ready.
* 3. Create sales invoice (#3) from Company to customer1PartyId for 1 item of $250, invoiceDate = 20 days before today. Set invoice to ready.
* 4. Create sales invoice (#4) from Company to DemoPrivilegedCust for 2 items of $567.89 each, invoiceDate = 60 days before today. Set invoice to ready
* Verify basic interest calculations
* 5. Run AccountHelper.calculateFinanceCharges with grace period = 30 days and interest rate = 8.0 and verify that the results are:
* Invoice #1 - finance charge of $0.66 ((60 - 30) / 365.25 * 0.08 * 100)
* Invoice #2 - finance charge of $1.64 ((45 - 30) / 365.25 * 0.08 * 500)
* Invoice #4 - finance charge of $7.46 ((60 - 30) / 365.25 * 0.08 * 1135.78)
* Verify party classification filtering
* 6. Run AccountsHelper.calculateFinanceCharges with grace period = 30 days, interest rate = 8.0, and partyClassificationGroup = Prileged Customers, verify that:
* Only Invoice #4 shows up as before
* Verify party filtering
* 7. Run AccountsHelper.calculateFinanceCharges with grace period = 30 days, interest rate = 8.0, and partyId = DemoAccount1, verify that:
* Only Invoice #1 shows up as before
* Verify that writing off an invoice will not cause more finance charges to be collected
* 8. Set Invoice #1 status to INVOICE_WRITEOFF, Run AccountHelper.calculateFinanceCharges with grace period = 30 days and interest rate = 8.0 and verify that the results are:
* Verify only Invoice #2 and #4 show up now with amounts as above
* Verify that creating finance charges will create the right financial balance transactions
* 9. Get INTRSTINC_RECEIVABLE and INTEREST_INCOME balance for the Company and the Accounts balance for DemoCustCompany and DemoPrivilegedCust
* Run financials.createInterestInvoice on each of the invoice from step (8).
* Verify that INTRSTINC_RECEIVABLE and INTEREST_INCOME have both increased by $9.10, the balance of DemoCustCompany has increased by $1.64, the balance of DemoPrivilegedCust has increassed by $7.46
* Verify the next cycle's interest calculations are correct
* 10. Run AccountsHelper.calculateFinanceCharges 30 days further in the future (asOfDateTime parameter), and verify that the results are:
* Invoice #2 - previous finance charges = $1.64, new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $7.46, new finance charges of $7.47 ((90 - 30) * 365.25 * 0.08 * 1135.78 - 7.46)
* Verify that writing off a finance charge has the right effect on both accounting and on interest calculations
* 11. Get INTRSTINC_RECEIVABLE and the interest invoice writeoff account balances for Company and the Accounts balance for DemoPrivilegedCust.
* Write off the finance charge (invoice) created for DemoPrivilegedCust in step (9)
* Verify that both INTRSTINC_RECEIVABLE and invoice writeoff account balances have increased by $7.46
* 12. Run AccountsHelper.calculateFinanceCharges 30 days further in the future (asOfDateTime parameter), and verify that the results are:
* Invoice #2 - previous finance charges = $1.64, new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $0.00, new finance charges of $14.93 ((90 - 30) * 365.25 * 0.08 * 1135.78)
* Verify that payments would serve to reduce invoice finance charges //
* 13. Create customer payment for $250 from DemoPrivilegedCust to Company and apply it to invoice #4. Set the payment to RECEIVED.
* Run AccountsHelper.calculateFinanceCharges 30 days further in the future (asOfDateTime parameter), and verify that the results are:
* Invoice #2 - previous finance charges = $1.64, new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $0, new finance charges of $11.64 ((90 - 30) * 365.25 * 0.08 * 885.78)
*
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testFinanceCharges() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
/*
* Create sales invoice (#1) from Company to DemoAccount1
* for 1 item of $100, invoiceDate = 60 days before today.
* Set invoice to ready.
*/
String customer1PartyId = createPartyFromTemplate("DemoAccount1", "Account1 for testFinanceCharges");
String customer2PartyId = createPartyFromTemplate("DemoCustCompany", "Account2 for testFinanceCharges");
String invoiceId1 = fa.createInvoice(customer1PartyId, "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -60, timeZone, locale));
fa.createInvoiceItem(invoiceId1, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("100.0"));
// set invoice status to READY is successful
fa.updateInvoiceStatus(invoiceId1, "INVOICE_READY");
/*
* Create sales invoice (#2) from Company to DemoCustCompany
* for 2 items of $250 each, invoiceDate = 45 days before today.
* Set invoice to ready.
*/
String invoiceId2 = fa.createInvoice(customer2PartyId, "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -45, timeZone, locale));
fa.createInvoiceItem(invoiceId2, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("250.0"));
// set invoice status to READY is successful
fa.updateInvoiceStatus(invoiceId2, "INVOICE_READY");
/*
* Create sales invoice (#3) from Company to DemoAccount1
* for 1 item of $250, invoiceDate = 20 days before today.
* Set invoice to ready.
*/
String invoiceId3 = fa.createInvoice(customer1PartyId, "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -20, timeZone, locale));
fa.createInvoiceItem(invoiceId3, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("250.0"));
// set invoice status to READY is successful
fa.updateInvoiceStatus(invoiceId3, "INVOICE_READY");
/*
* Create sales invoice (#4) from Company to DemoPrivilegedCust
* for 2 items of $567.89 each, invoiceDate = 60 days before today.
* Set invoice to ready
*/
String invoiceId4 = fa.createInvoice("DemoPrivilegedCust", "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -60, timeZone, locale));
fa.createInvoiceItem(invoiceId4, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("567.89"));
// set invoice status to READY is successful
fa.updateInvoiceStatus(invoiceId4, "INVOICE_READY");
/*
* Verify basic interest calculations
* Run AccountHelper.calculateFinanceCharges with grace
* period = 30 days and interest rate = 8.0
*/
InvoiceRepository repository = new InvoiceRepository(delegator);
Map<Invoice, Map<String, BigDecimal>> financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"), UtilDateTime.nowTimestamp(), 30, timeZone, locale);
Invoice invoice1 = repository.getInvoiceById(invoiceId1);
Invoice invoice2 = repository.getInvoiceById(invoiceId2);
Invoice invoice4 = repository.getInvoiceById(invoiceId4);
// Note that these and all the tests below have a subtle test of the hashCode() function for the Invoice object, as
// the Invoices are not the same Java objects but are two objects of the same invoice, but if their hashCode() are
// equal, then they should be equal, and the Map get method should still work.
/*
* verify that the results are:
* Invoice #1 - finance charge of $0.66 ((60 - 30) / 365.25 * 0.08 * 100)
* Invoice #2 - finance charge of $1.64 ((45 - 30) / 365.25 * 0.08 * 500)
* Invoice #4 - finance charge of $7.46 ((60 - 30) / 365.25 * 0.08 * 1135.78)
*/
Map<String, BigDecimal> expectedFinanceCharges = UtilMisc.toMap(invoice1.getInvoiceId(), new BigDecimal("0.66"), invoice2.getInvoiceId(), new BigDecimal("1.64"), invoice4.getInvoiceId(), new BigDecimal("7.46"));
fa.assertFinanceCharges(financeCharges, expectedFinanceCharges);
/*
* Verify party classification filtering
* Run AccountsHelper.calculateFinanceCharges with grace
* period = 30 days, interest rate = 8.0, and
* partyClassificationGroup = Prileged Customers
*/
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, "PRIVILEGED_CUSTOMERS", new BigDecimal("8.0"), UtilDateTime.nowTimestamp(), 30, timeZone, locale);
/*
* verify that:
* Only Invoice #4 shows up as before
*/
expectedFinanceCharges = UtilMisc.toMap(invoice1.getInvoiceId(), null, invoice2.getInvoiceId(), null, invoice4.getInvoiceId(), new BigDecimal("7.46"));
fa.assertFinanceCharges(financeCharges, expectedFinanceCharges);
/*
* Verify party filtering
* Run AccountsHelper.calculateFinanceCharges with grace
* period = 30 days, interest rate = 8.0, and
* partyId = DemoAccount1
*/
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, customer1PartyId, null, new BigDecimal("8.0"), UtilDateTime.nowTimestamp(), 30, timeZone, locale);
/*
* verify that:
* Only Invoice #1 shows up as before
*/
expectedFinanceCharges = UtilMisc.toMap(invoice1.getInvoiceId(), new BigDecimal("0.66"), invoice2.getInvoiceId(), null, invoice4.getInvoiceId(), null);
fa.assertFinanceCharges(financeCharges, expectedFinanceCharges);
/*
* Verify that writing off an invoice will not
* cause more finance charges to be collected
* Set Invoice #1 status to INVOICE_WRITEOFF,
* Run AccountHelper.calculateFinanceCharges with grace
* period = 30 days and interest rate = 8.0
*/
fa.updateInvoiceStatus(invoiceId1, "INVOICE_WRITEOFF");
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"), UtilDateTime.nowTimestamp(), 30, timeZone, locale);
/*
* Verify only Invoice #2 and #4
* show up now with amounts as above
*/
expectedFinanceCharges = UtilMisc.toMap(invoice1.getInvoiceId(), null, invoice2.getInvoiceId(), new BigDecimal("1.64"), invoice4.getInvoiceId(), new BigDecimal("7.46"));
fa.assertFinanceCharges(financeCharges, expectedFinanceCharges);
/*
* Verify that creating finance charges will
* create the right financial balance transactions
* Get ACCOUNTS_RECEIVABLE and INTEREST_INCOME
* balance for the Company and the Accounts balance
* for DemoCustCompany and DemoPrivilegedCust
* Run financials.createInterestInvoice on each
* of the invoice from step (8).
*/
Timestamp now = UtilDateTime.nowTimestamp();
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
BigDecimal balance1_democustcompany = AccountsHelper.getBalanceForCustomerPartyId(customer2PartyId, organizationPartyId, "ACTUAL", now, delegator);
BigDecimal balance1_demoprivilegedcust = AccountsHelper.getBalanceForCustomerPartyId("DemoPrivilegedCust", organizationPartyId, "ACTUAL", now, delegator);
Map initialBalances = financialAsserts.getFinancialBalances(now);
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"), now, 30, timeZone, locale);
Map<String, BigDecimal> financeCharge = financeCharges.get(invoice2);
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("partyIdFrom", invoice2.get("partyIdFrom"));
input.put("partyIdTo", invoice2.get("partyId"));
input.put("amount", financeCharge.get("interestAmount"));
input.put("currencyUomId", invoice2.get("currencyUomId"));
input.put("invoiceDate", now);
input.put("dueDate", invoice2.get("dueDate"));
input.put("description", invoice2.get("description"));
input.put("parentInvoiceId", invoice2.get("invoiceId"));
Map<String, Object> output = runAndAssertServiceSuccess("financials.createInterestInvoice", input);
financeCharge = financeCharges.get(invoice4);
input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("partyIdFrom", invoice4.get("partyIdFrom"));
input.put("partyIdTo", invoice4.get("partyId"));
input.put("amount", financeCharge.get("interestAmount"));
input.put("currencyUomId", invoice4.get("currencyUomId"));
input.put("invoiceDate", now);
input.put("dueDate", invoice4.get("dueDate"));
input.put("description", invoice4.get("description"));
input.put("parentInvoiceId", invoice4.get("invoiceId"));
output = runAndAssertServiceSuccess("financials.createInterestInvoice", input);
String invoiceId4Interest = (String) output.get("invoiceId");
// reload invoices (to get the updated interest charged)
invoice2 = repository.getInvoiceById(invoiceId2);
invoice4 = repository.getInvoiceById(invoiceId4);
/*
* Verify that INTRSTINC_RECEIVABLE and INTEREST_INCOME
* have both increased by $9.10, the balance of
* DemoCustCompany has increased by $1.64, the
* balance of DemoPrivilegedCust has increassed by $7.46
*/
now = UtilDateTime.nowTimestamp();
BigDecimal balance2_democustcompany = AccountsHelper.getBalanceForCustomerPartyId(customer2PartyId, organizationPartyId, "ACTUAL", now, delegator);
BigDecimal balance2_demoprivilegedcust = AccountsHelper.getBalanceForCustomerPartyId("DemoPrivilegedCust", organizationPartyId, "ACTUAL", now, delegator);
assertEquals("the balance of DemoCustCompany should increased by $1.64",
balance2_democustcompany, balance1_democustcompany.add(new BigDecimal("1.64")));
assertEquals("the balance of DemoPrivilegedCust should increased by $7.46",
balance2_demoprivilegedcust, balance1_demoprivilegedcust.add(new BigDecimal("7.46")));
Map finalBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("INTRSTINC_RECEIVABLE", "9.10", "INTEREST_INCOME", "9.10");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
/*
* Verify the next cycle's interest calculations are
* correct. Run AccountsHelper.calculateFinanceCharges 30
* days further in the future (asOfDateTime parameter)
*/
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"),
UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), 30, timeZone, locale);
/*
* verify that the results are:
* Invoice #2 - previous finance charges = $1.64,
* new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $7.46,
* new finance charges of $7.47 ((90 - 30) * 365.25 * 0.08 * 1135.78 - 7.46)
*/
financeCharge = financeCharges.get(invoice2);
assertNotNull("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", new BigDecimal("3.29"), financeCharge.get("interestAmount"));
financeCharge = financeCharges.get(invoice4);
assertNotNull("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", new BigDecimal("7.47"), financeCharge.get("interestAmount"));
/*
* Verify that writing off a finance charge has the right
* effect on both accounting and on interest calculations
* Get INTRSTINC_RECEIVABLE and interest invoice writeoff
* account balances for Company and the Accounts balance
* for DemoPrivilegedCust. Write off the finance charge
* (invoice) created for DemoPrivilegedCust in step (9)
*/
now = UtilDateTime.nowTimestamp();
balance1_demoprivilegedcust = AccountsHelper.getBalanceForCustomerPartyId("DemoPrivilegedCust", organizationPartyId, "ACTUAL", now, delegator);
initialBalances = financialAsserts.getFinancialBalances(now);
fa.updateInvoiceStatus(invoiceId4Interest, "INVOICE_WRITEOFF");
/*
* Verify that both INTRSTINC_RECEIVABLE and interest invoice writeoff account
* balances have increased by $7.46
*/
now = UtilDateTime.nowTimestamp();
finalBalances = financialAsserts.getFinancialBalances(now);
// figure out what the interest invoice writeoff account is using the domain
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
LedgerRepositoryInterface ledgerRepository = dd.getLedgerDomain().getLedgerRepository();
InvoiceAdjustmentGlAccount writeoffGlAcct = ledgerRepository.getInvoiceAdjustmentGlAccount(organizationPartyId, "INTEREST_INVOICE", "WRITEOFF");
assertNotNull(writeoffGlAcct);
// interest income receivable is a debit account, so an increase is positive;
// interest income is a credit account, so an increase is negative
expectedBalanceChanges = UtilMisc.toMap("INTRSTINC_RECEIVABLE", "-7.46");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(writeoffGlAcct.getGlAccountId(), "7.46");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
/*
* Run AccountsHelper.calculateFinanceCharges 30 days further
* in the future (asOfDateTime parameter)
*/
invoice2 = repository.getInvoiceById(invoiceId2);
invoice4 = repository.getInvoiceById(invoiceId4);
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"),
UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), 30, timeZone, locale);
/*
* Verify that the results are:
* Invoice #2 - previous finance charges = $1.64,
* new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $0.00,
* new finance charges of $14.93 ((90 - 30) * 365.25 * 0.08 * 1135.78)
*/
financeCharge = financeCharges.get(invoice2);
assertNotNull("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", new BigDecimal("3.29"), financeCharge.get("interestAmount"));
financeCharge = financeCharges.get(invoice4);
assertNotNull("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", new BigDecimal("14.93"), financeCharge.get("interestAmount"));
/*
* Verify that payments would serve to reduce invoice finance charges
* Create customer payment for $250 from DemoPrivilegedCust to Company
* and apply it to invoice #4. Set the payment to RECEIVED.
* Run AccountsHelper.calculateFinanceCharges 30 days further in the
* future (asOfDateTime parameter)
*/
financialAsserts.createPaymentAndApplication(new BigDecimal("250.0"), "DemoPrivilegedCust", organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId4, "PMNT_RECEIVED");
invoice2 = repository.getInvoiceById(invoiceId2);
invoice4 = repository.getInvoiceById(invoiceId4);
financeCharges = AccountsHelper.calculateFinanceCharges(delegator, organizationPartyId, null, null, new BigDecimal("8.0"),
UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), 30, timeZone, locale);
/*
* Verify that the results are:
* Invoice #2 - previous finance charges = $1.64,
* new finance charges of $3.29 ((75 - 30) * 365.25 * 0.08 * 500 - 1.64)
* Invoice #4 - previous finance charges = $0,
* new finance charges of $11.64 ((90 - 30) * 365.25 * 0.08 * 885.78)
*/
financeCharge = financeCharges.get(invoice2);
assertNotNull("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #2 [" + invoice2.getInvoiceId() + "] basic interest calculations", new BigDecimal("3.29"), financeCharge.get("interestAmount"));
financeCharge = financeCharges.get(invoice4);
assertNotNull("invoice #4 [" + invoice4.getInvoiceId() + "] basic interest calculations", financeCharge);
assertEquals("invoice #4 [" + invoice2.getInvoiceId() + "] basic interest calculations", new BigDecimal("11.64"), financeCharge.get("interestAmount"));
}
/**
* Void invoice test:
* 1. Create a sales invoice to DemoCustCompany with 2 invoice items: (a) 2.0 x "Finished good" type for $50 and (b) 1.0 "Shipping and handling" for $9.95
* 2. Get the AccountsHelper customer receivable balance of DemoCustCompany
* 3. Get the initial financial balances
* 4. Set invoice to READY
* 5. Verify that the AccountsHelper customer balance of DemoCustCompany has increased by 109.95
* 6. Verify that the balance of gl accounts 120000 increased by 109.95, 400000 increased by 100, 408000 increased by 9.95
* 7. Verify AccountsHelper.getUnpaidInvoicesForCustomer returns this invoice of list of unpaid invoices
* 8. Set invoice to VOID using opentaps.VoidInvoice service
* 9. Verify that AccountsHelper customer balance of DemoCustCompany is back to value in #2
* 10. Verify that balance of gl accounts 120000, 400000, 408000 are backed to values of #3
* 11. Verify that AccountsHelper.getUnpaidInvoicesForCustomer no longer returns this invoice in list of unpaid invoices
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testVoidInvoice() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String companyPartyId = createPartyFromTemplate("DemoCustCompany", "Account for testVoidInvoice");
/*
* 1. Create a sales invoice to the Party with 2
* invoice items: (a) 2.0 x "Finished good" type for $50
* and (b) 1.0 "Shipping and handling" for $9.95
*/
String invoiceId = fa.createInvoice(companyPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("50.0"));
fa.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", new BigDecimal("1.0"), new BigDecimal("9.95"));
/*
* 2. Get the AccountsHelper customer receivable
* balance of the Party
*/
Timestamp now = UtilDateTime.nowTimestamp();
BigDecimal balance1 = AccountsHelper.getBalanceForCustomerPartyId(companyPartyId, organizationPartyId, "ACTUAL", now, delegator);
/*
* 3. Get the initial financial balances
*/
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(now);
/*
* 4. Set invoice to READY
*/
fa.updateInvoiceStatus(invoiceId, "INVOICE_READY");
/*
* 5. Verify that the AccountsHelper customer balance of
* the Party has increased by 109.95
*/
now = UtilDateTime.nowTimestamp();
BigDecimal balance2 = AccountsHelper.getBalanceForCustomerPartyId(companyPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + companyPartyId + " has not increased by 109.95", balance1, balance2.subtract(new BigDecimal("109.95")));
/*
* 6. Verify that the balance of gl accounts 120000 = ACCOUNTS_RECEIVABLE
* increased by 109.95, 400000 = SALES_ACCOUNT increased by 100,
* 408000 = ITM_SHIPPING_CHARGES increased by 9.95
*/
GenericValue invoiceItemTypeForShippingCharges = delegator.findByPrimaryKey("InvoiceItemType", UtilMisc.toMap("invoiceItemTypeId", "ITM_SHIPPING_CHARGES"));
String itemShippingChargesGlAccountId = invoiceItemTypeForShippingCharges.getString("defaultGlAccountId");
Map halfBalances = financialAsserts.getFinancialBalances(now);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "109.95", "SALES_ACCOUNT", "100");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(itemShippingChargesGlAccountId, "9.95");
assertMapDifferenceCorrect(initialBalances, halfBalances, accountMap);
/*
* 7. Verify AccountsHelper.getUnpaidInvoicesForCustomer returns this
* invoice of list of unpaid invoices
*/
Map invoices = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, UtilMisc.toList(new Integer(0)), now, delegator, timeZone, locale);
assertNotNull("Unpaid Invoices For Customers not found.", invoices);
List invoicesList = (List) invoices.get(0);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
Iterator invoicesIterator = invoicesList.iterator();
boolean isPresent = false;
while (invoicesIterator.hasNext()) {
Invoice invoice = (Invoice) invoicesIterator.next();
if (invoiceId.equals(invoice.getString("invoiceId"))) {
isPresent = true;
break;
}
}
assertTrue("Invoice [" + invoiceId + "] is not in the list of unpaid invoiced and shouldn't", isPresent);
/*
* 8. Set invoice to VOID using opentaps.VoidInvoice service
*/
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("invoiceId", invoiceId);
runAndAssertServiceSuccess("opentaps.voidInvoice", input);
/*
* 9. Verify that AccountsHelper customer balance of
* DemoCustCompany is back to value in #2
*/
now = UtilDateTime.nowTimestamp();
BigDecimal balance3 = AccountsHelper.getBalanceForCustomerPartyId(companyPartyId, organizationPartyId, "ACTUAL", now, delegator);
assertEquals("Balance for " + companyPartyId + " is not back to original value", balance1, balance3);
/*
* 10. Verify that balance of gl accounts 120000, 400000, 408000
* are backed to values of #3
*/
Map finalBalances = financialAsserts.getFinancialBalances(now);
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0", "SALES_ACCOUNT", "0");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(itemShippingChargesGlAccountId, "0");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
/*
* 11. Verify that AccountsHelper.getUnpaidInvoicesForCustomer no
* longer returns this invoice in list of unpaid invoices
*/
now = UtilDateTime.nowTimestamp();
invoices = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, UtilMisc.toList(new Integer(0)), now, delegator, timeZone, locale);
assertNotNull("Unpaid Invoices For Customers not found.", invoices);
invoicesList = (List) invoices.get(0);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
invoicesIterator = invoicesList.iterator();
isPresent = false;
while (invoicesIterator.hasNext()) {
Invoice invoice = (Invoice) invoicesIterator.next();
if (invoiceId.equals(invoice.getString("invoiceId"))) {
isPresent = true;
break;
}
}
assertFalse("Invoice [" + invoiceId + "] is in the list of unpaid invoiced and shouldn't", isPresent);
}
/**
* TestBasicInvoiceAdjustment
* 1. Create purchase invoice for $10
* 2. Set invoice to READY
* 3. Get financial balances and the balances
* 4. Create payment of type COMPANY_CHECK for $8 and apply payment to the invoice
* 5. Set payment to SENT
* 6. Verify that the outstanding amount of the invoice is $2 and the status of the invoice is still READY
* 7. Use createInvoiceAdjustment to create an adjustment of type EARLY_PAY_DISCT for -$2 for the invoice and call postAdjustmentToInvoice
* 8. Verify that the outstanding amount of the invoice is $0 and the status of the invoice is PAID
* 8. Find InvoiceAdjustmentGlAccount for PURCHASE_INVOICE and EARLY_PAY_DISCT and get the glAccountId
* 9. Get the financial balances
* 10. Verify the following changes in financial balances: ACCOUNTS_PAYABLE +10, BANK_STLMNT_ACCOUNT -8, InvoiceAdjustmentGlAccount.glAccountId -2
* 11. Verify that the vendor balance has decreased by $10 for the supplier since (4)
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testBasicInvoiceAdjustment() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
DomainsDirectory dd = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin)).loadDomainsDirectory();
String supplierPartyId = createPartyFromTemplate("DemoSupplier", "Supplier for testBasicInvoiceAdjustment");
// create the purchase invoice
String invoiceId = fa.createInvoice(supplierPartyId, "PURCHASE_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("10.0"));
fa.updateInvoiceStatus(invoiceId, "INVOICE_READY");
InvoiceRepositoryInterface repository = dd.getBillingDomain().getInvoiceRepository();
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal vendorBalance1 = AccountsHelper.getBalanceForVendorPartyId(supplierPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
fa.createPaymentAndApplication(new BigDecimal("8.0"), organizationPartyId, supplierPartyId, "VENDOR_PAYMENT", "COMPANY_CHECK", "COCHECKING", invoiceId, "PMNT_SENT");
Invoice invoice = repository.getInvoiceById(invoiceId);
assertEquals("Invoice [" + invoice.getInvoiceId() + "] is still ready", invoice.getStatusId(), "INVOICE_READY");
assertEquals("Invoice [" + invoice.getInvoiceId() + "] outstanding amt is $2", invoice.getOpenAmount(), new BigDecimal("2.0"));
// post an adjustment of -$2 of type EARLY_PAY_DISCT to the invoice
Map results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "adjustmentAmount", new BigDecimal("-2.0")));
String invoiceAdjustmentId = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId);
invoice = repository.getInvoiceById(invoiceId);
assertEquals("Invoice [" + invoice.getInvoiceId() + "] outstanding amt is $0", BigDecimal.ZERO, invoice.getOpenAmount());
assertEquals("Invoice [" + invoice.getInvoiceId() + "] is paid", "INVOICE_PAID", invoice.getStatusId());
GenericValue mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "PURCHASE_INVOICE", "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String glAccountId = mapping.getString("glAccountId");
assertNotNull(glAccountId);
// ensure the balances are correct
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_PAYABLE", "10.0", "BANK_STLMNT_ACCOUNT", "-8");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(glAccountId, "-2");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
BigDecimal vendorBalance2 = AccountsHelper.getBalanceForVendorPartyId(supplierPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
assertEquals("Vendor balance has decreased by $10", vendorBalance2.subtract(vendorBalance1), new BigDecimal("-10"));
}
/**
* TestInvoiceAdjustmentWithPayment
* 1. Create sales invoice for $10
* 2. Set invoice to READY
* 3. Get financial balances and customer balances
* 4. Create payment of type COMPANY_CHECK for $6 and apply payment to the invoice
* 5. Set payment to RECEIVED
* 6. Use createInvoiceAdjustment to create an adjustment of type CASH_DISCOUNT for -$2 for the invoice and call postAdjustmentToInvoice
* 7. Create payment of type CASH for $2 and apply payment to the invoice
* 8. Verify that the outstanding amount of the invoice is $0 and the status of the invoice is PAID
* 9. Find InvoiceAdjustmentGlAccount for SALES_INVOICE and CASH_DISCOUNT and get the glAccountId
* 10. Get the financial balances and customer balances
* 11. Verify the following changes in financial balances: ACCOUNTS_RECEIVABLE -10, UNDEPOSITED_RECEIPT +8, InvoiceAdjustmentGlAccount.glAccountId -2
* 12. Verify that the customer balance has decreased by $10 for the customer since (4)
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testInvoiceAdjustmentWithPayment() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustomer", "Customer for testInvoiceAdjustmentWithPayment");
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("10.0"));
fa.updateInvoiceStatus(invoiceId, "INVOICE_READY");
InvoiceRepository repository = new InvoiceRepository(delegator);
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalance1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// company check payment from customer of $6
fa.createPaymentAndApplication(new BigDecimal("6.0"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_RECEIVED");
Invoice invoice = repository.getInvoiceById(invoiceId);
assertEquals("Invoice [" + invoice.getInvoiceId() + "] is still ready", invoice.getStatusId(), "INVOICE_READY");
assertEquals("Invoice [" + invoice.getInvoiceId() + "] outstanding amt is $4", invoice.getOpenAmount(), new BigDecimal("4.0"));
// post an adjustment of -$2 of type CASH_DISCOUNT to the invoice
Map results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "CASH_DISCOUNT", "adjustmentAmount", new BigDecimal("-2.0")));
String invoiceAdjustmentId = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId);
// another customer payment for the remaining $2, which should pay off the invoice
fa.createPaymentAndApplication(new BigDecimal("2.0"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "CASH", null, invoiceId, "PMNT_RECEIVED");
invoice = repository.getInvoiceById(invoiceId);
assertEquals("Invoice [" + invoice.getInvoiceId() + "] is paid", "INVOICE_PAID", invoice.getStatusId());
assertEquals("Invoice [" + invoice.getInvoiceId() + "] outstanding amt is $0", BigDecimal.ZERO, invoice.getOpenAmount());
// get the cash discount gl account for sales invoices
GenericValue mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "SALES_INVOICE", "invoiceAdjustmentTypeId", "CASH_DISCOUNT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String glAccountId = mapping.getString("glAccountId");
assertNotNull(glAccountId);
// ensure the balances are correct
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "-10.0", "UNDEPOSITED_RECEIPTS", "+8");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(glAccountId, "+2");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
BigDecimal custBalance2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
assertEquals("Customer balance has decreased by $10", custBalance2.subtract(custBalance1), new BigDecimal("-10"));
}
/**
*This test checks that payment applications to an adjusted invoice is based on the invoice total including the adjusted amount
* @throws Exception
*/
public void testPaymentApplicationToAdjustedInvoice() throws Exception {
// create a customer party
String customerPartyId =
createPartyFromTemplate("DemoCustomer", "Customer for testPaymentApplicationToAdjustedInvoice");
// create sales invoice to the customer for $10
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String invoiceId = fa.createInvoice(customerPartyId, InvoiceTypeConstants.SALES_INVOICE);
fa.createInvoiceItem(invoiceId, InvoiceItemTypeConstants.INV_FPROD_ITEM, "WG-1111", new BigDecimal("1.0"), new BigDecimal("10.0"));
// set the invoice to READY
fa.updateInvoiceStatus(invoiceId, StatusItemConstants.InvoiceStatus.INVOICE_READY);
// create an adjustment of CASH_DISCOUNT of -2 for the invoice
Map<String, Object> results =
runAndAssertServiceSuccess("createInvoiceAdjustment",
UtilMisc.toMap(
"userLogin", demofinadmin,
"invoiceId", invoiceId,
"invoiceAdjustmentTypeId", InvoiceAdjustmentTypeConstants.CASH_DISCOUNT,
"adjustmentAmount", new BigDecimal("-2.0")
)
);
String invoiceAdjustmentId = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId);
InvoiceRepositoryInterface repository = getInvoiceRepository(demofinadmin);
Invoice invoice = repository.getInvoiceById(invoiceId);
// verify that the invoice adjusted total amount is $8
assertEquals(String.format("Invoice total amount for [%1$s] is incorrect.", invoiceId), new BigDecimal("8.0"), invoice.getInvoiceAdjustedTotal());
// verify that the invoice outstanding amount is $8
assertEquals(String.format("Invoice outstanding(open) amount for [%1$s] is incorrect.", invoiceId), new BigDecimal("8.0"), invoice.getOpenAmount());
// create a payment (paymentId1) of $4 and apply it to the invoice
String paymentId1 =
fa.createPayment(new BigDecimal("4.0"), customerPartyId, PaymentTypeConstants.Receipt.CUSTOMER_PAYMENT, PaymentMethodTypeConstants.CASH);
runAndAssertServiceSuccess("createPaymentApplication",
UtilMisc.<String, Object>toMap(
"paymentId", paymentId1,
"invoiceId", invoiceId,
"amountApplied", new BigDecimal("4.0"),
"userLogin", demofinadmin
)
);
fa.updatePaymentStatus(paymentId1, StatusItemConstants.PmntStatus.PMNT_RECEIVED);
// create a second payment (paymentId2) of $5 and apply $4 to the invoice
String paymentId2 =
fa.createPayment(new BigDecimal("5.0"), customerPartyId, PaymentTypeConstants.Receipt.CUSTOMER_PAYMENT, PaymentMethodTypeConstants.CASH);
runAndAssertServiceSuccess("createPaymentApplication",
UtilMisc.<String, Object>toMap(
"paymentId", paymentId2,
"invoiceId", invoiceId,
"amountApplied", new BigDecimal("4.0"),
"userLogin", demofinadmin
)
);
fa.updatePaymentStatus(paymentId2, StatusItemConstants.PmntStatus.PMNT_RECEIVED);
invoice = repository.getInvoiceById(invoiceId);
// verify that the invoice adjusted total is still $8 by the outstanding amount is $0
assertEquals(String.format("Invoice total amount for [%1$s] is incorrect.", invoiceId), new BigDecimal("8.0"), invoice.getInvoiceAdjustedTotal());
assertEquals(String.format("Invoice outstanding(open) amount for [%1$s] is incorrect.", invoiceId), BigDecimal.ZERO, invoice.getOpenAmount());
// verify the status of the invoice is PAID
assertEquals("Invoice status should be PAID in this point.", StatusItemConstants.InvoiceStatus.INVOICE_PAID, invoice.getStatusId());
}
/**
* TestAdjustmentToCancelledInvoice: this test should verify that adjustments to cancelled invoices are not posted to the ledger
* 1. Create sales invoice for $10 (do not set to ready)
* 2. Create adjustment of EARLY_PAY_DISCOUNT for $2 on invoice from (1)
* 3. Get financials balances
* 4. Get accounts receivable balances for customer of invoice from (1)
* 5. Set status of invoice from (1) to INVOICE_CANCELLED
* 6. Get financial balances
* 7. Get accounts receivable balances for customer of invoice from (1)
* 8. Verify that the changes in ACCOUNTS_RECEIVABLE and InvoiceAdjustmentGlAccount.glAccountId for Company, EARLY_PAY_DISCOUNT are both 0
* 9. Verify that the change in customer balance for customer is 0
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testAdjustmentToCancelledInvoice() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testAdjustmentToCancelledInvoice");
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("10.0"));
// post an adjustment of $2 of type EARLY_PAY_DISCT to the invoice
Map results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "adjustmentAmount", new BigDecimal("2.0")));
String invoiceAdjustmentId = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId);
// get balances, cancel
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
fa.updateInvoiceStatus(invoiceId, "INVOICE_CANCELLED");
// get the early pay discount gl account for sales invoices
GenericValue mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "SALES_INVOICE", "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String glAccountId = mapping.getString("glAccountId");
assertNotNull(glAccountId);
// the pause above should be sufficient to get the final balances
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// check balances are 0.0 throughout
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(glAccountId, "0.0");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
assertEquals("Customer balance has not changed", custBalances2.subtract(custBalances1), BigDecimal.ZERO);
}
/**
* TestAdjustPotVoidForInvoice: test alternate workflow: adjust invoice, post invoice, and void the invoice
* 1. Create sales invoice for $10
* 2. Create adjustment of CASH_DISCOUNT for -$2 on invoice
* 3. Create adjustment of EARLY_PAY_DISCOUNT of -$0.50 on invoice
* 4. Get financials balances
* 5. Get accounts receivables balance for customer of invoice from (1)
* 6. Get InvoiceAdjustmentGlAccount for Company, EARLY_PAY_DISCOUNT and Company, CASH_DISCOUNT
* 7. Set invoice to INVOICE_READY
* 8. Verify ACCOUNTS_RECEIVABLES +7.50, InvoiceAdjustmentGlAccount(Company, CASH_DISCOUNT) +2.0, InvoiceAdjustmentGlAccount(Company, EARLY_PAY_DISCOUNT) +0.50 since (4)
* 9. Verify that accounts receivable balance of customer has increased by 7.50
* 10. Set Invoice to INVOICE_VOID
* 11. Verify ACCOUNTS_RECEIVABLES +0, InvoiceAdjustmentGlAccount(Company, EARLY_PAY_DISCOUNT) +0, InvoiceAdjustmentGlAccount(Company, CASH_DISCOUNT) 0 since (4)
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testAdjustPostVoidForInvoice() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testAdjustPostVoidForInvoice");
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("10.0"));
// post an adjustment of $2 of type CASH_DISCOUNT to the invoice
Map results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "CASH_DISCOUNT", "adjustmentAmount", new BigDecimal("-2.0")));
String invoiceAdjustmentId1 = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId1);
// post an adjustment of $0.50 of type EARLY_PAY_DISCT to the invoice
results = runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "adjustmentAmount", new BigDecimal("-0.50")));
String invoiceAdjustmentId2 = (String) results.get("invoiceAdjustmentId");
assertNotNull(invoiceAdjustmentId2);
// get balances, set to ready
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances1 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
fa.updateInvoiceStatus(invoiceId, "INVOICE_READY");
// get the early pay discount and cash gl accounts for sales invoices (note: they might be the same account)
GenericValue mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "SALES_INVOICE", "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String earlyPayGlAccountId = mapping.getString("glAccountId");
assertNotNull(earlyPayGlAccountId);
mapping = delegator.findByPrimaryKey("InvoiceAdjustmentGlAccount", UtilMisc.toMap("invoiceTypeId", "SALES_INVOICE", "invoiceAdjustmentTypeId", "CASH_DISCOUNT", "organizationPartyId", organizationPartyId));
assertNotNull(mapping);
String cashGlAccountId = mapping.getString("glAccountId");
assertNotNull(cashGlAccountId);
// the pause above should be sufficient to get the final balances
Map middleBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances2 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// check balances are +7.50 to AR, +2 to early pay, -0.5 to cash and that the AR balance of customer is 7.50
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "7.50");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
if (cashGlAccountId.equals(earlyPayGlAccountId)) {
accountMap.put(cashGlAccountId, "2.50");
} else {
accountMap.put(cashGlAccountId, "2.0");
accountMap.put(earlyPayGlAccountId, "0.50");
}
assertMapDifferenceCorrect(initialBalances, middleBalances, accountMap);
assertEquals("Customer balance as expected", custBalances2.subtract(custBalances1), new BigDecimal("7.50"));
// void invoices and get balances again
fa.updateInvoiceStatus(invoiceId, "INVOICE_VOIDED");
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal custBalances3 = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// check balances are all 0 compared to initial
expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0");
accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
accountMap.put(earlyPayGlAccountId, "0.0");
accountMap.put(cashGlAccountId, "0");
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
assertEquals("Customer balance net 0", custBalances3.subtract(custBalances1), BigDecimal.ZERO);
}
/**
* Test for accounts receivable invoice aging and customer balances
*
* 1. Create parties Customer A, Customer B, Customer C
* 2. Create invoices:
* (a) Create sales invoice #1 from Company to Customer A for $100, invoice date 91 days before current date, due date 30 days after invoice date
* (b) Create sales invoice #2 from Company to Customer A for $50, invoice date 25 days before current date, due date 30 days after invoice date
* (c) Create sales invoice #3 from Company to Customer B for $150, invoice date 55 days before current date, due date 60 days after invoice date
* (d) Create sales invoice #4 from Company to Customer C for $170, invoice date 120 days before current date, due date 30 days after invoice date
* (e) Create sales invoice #5 from Company to Customer B for $210, invoice date 15 days before current date, due date 7 days after invoice date
* (f) Create sales invoice #6 from Company to Customer A for $500, invoice date 36 days before current date, due date 30 days after invoice date
* (g) Create sales invoice #7 from Company to Customer C for $228, invoice date 42 days before current date, due date 45 days after invoice date
* (h) Create sales invoice #8 from Company to Customer B for $65, invoice date 15 days before current date, due date 30 days after invoice date
* (i) Create sales invoice #9 from Company to Customer A for $156, invoice date 6 days before current date, due date 15 days after invoice date
* (j) Create sales invoice #10 from Company to Customer C for $550, invoice date 33 days before current date, due date 15 days after invoice date
* (k) Create sales invoice #11 from Company to Customer B for $90, invoice date 62 days before current date, due date 90 days after invoice date
* 3. Cancel invoice #2
* 4. Set all other invoices to READY
* 5. Set invoice #6 to VOID
* 6. Set invoice #10 to WRITEOFF
* 7. Receive a payment of $65 for invoice #8
* 8. Receive a payment of $65 for invoice #11
* 9. Create sales invoice #12 for Company to Customer A for $1000, invoice date now and due 30 days after invoicing, but do not set this invoice to READY
* 10. Run AccountsHelper.getBalancesForAllCustomers and verify the following:
* (a) balance of Customer A is $256
* (b) balance of Customer B is $385
* (c) balance of Customer C is $398
* 11. Run AccountsHelper.getUnpaidInvoicesForCustomers and verify:
* (a) 0-30 day bucket has invoices #5 and #9
* (b) 30-60 day bucket has invoices #3 and #7
* (c) 60-90 day bucket has invoice #11
* (d) 90+ day bucket has invoices #1 and #4
* 12. Create parties Customer D and Customer E
* 13. Create more sales invoices:
* (a) Invoice #13 from Company to Customer D for $200, invoice date today, due in 30 days after invoice date
* (b) Invoice #14 from Company to Customer D for $300, invoice date today, due in 60 days after invoice date
* (c) Invoice #15 from Company to Customer E for $155, invoice date 58 days before today, due in 50 days after invoice date
* (d) Invoice #16 from Company to Customer E for $266, invoice date 72 days before today, due in 30 days after invoice date
* (e) Invoice #17 from Company to Customer E for $377, invoice date 115 days before today, due in 30 days after invoice date
* (f) Invoice #18 from Company to Customer E for $488, invoice date 135 days before today, due in 30 days after invoice date
* (g) Invoice #19 from Company to Customer E for $599, invoice date 160 days before today, due in 30 days after invoice date
* (h) Invoice #20 from Company to Customer E for $44, invoice date 20 days before today, no due date (null)
* 14. Set all invoices from (13) to ready.
* 15. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=true and verify
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = $100, 90 - 120 days = 0, over 120 days = 0, total open amount = $256
* (b) Customer B: isPastDue = false, current = $385, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
* (c) Customer C: isPastDue = true, current = $228, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $170, over 120 days = 0, total open amount = $398
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
* (e) Customer E: isPastDue = true, current = $199, 30 - 60 days = 266, 60 - 90 days = 377, 90 - 120 days = 488, over 120 days = 599, total open amount = $1929
* 16. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=false and verify
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $100, over 120 days = 0, total open amount = $256
* (b) Customer B: isPastDue = true, current = $210, 30 - 60 days = 150, 60 - 90 days = 25, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
* (c) Customer C: isPastDue = true, current = 0, 30 - 60 days = 228, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = $170, total open amount = $398
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
* (e) Customer E: isPastDue = true, current = $44, 30 - 60 days = 155, 60 - 90 days = 266, 90 - 120 days = 377, over 120 days = 1087, total open amount = $1929
* @throws GeneralException if an error occurs
*/
public void testAccountsReceivableInvoiceAgingAndCustomerBalances() throws GeneralException {
/*
* 1. Create parties Customer A, Customer B, Customer C
*/
TestObjectGenerator generator = new TestObjectGenerator(delegator, dispatcher);
List<String> customerId = generator.getContacts(3);
assertNotNull("Three customers should be generated", customerId);
/*
* 2. Create invoices
*/
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
/*
* (a) Create sales invoice #1 from Company to Customer A for $100, invoice date 91 days before current date, due date 30 days after invoice date
*/
String invoiceId1 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -91, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -91 + 30, timeZone, locale), null, null, "invoiceId1");
fa.createInvoiceItem(invoiceId1, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("100.0"));
/*
* (b) Create sales invoice #2 from Company to Customer A for $50, invoice date 25 days before current date, due date 30 days after invoice date
*/
String invoiceId2 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -25, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -25 + 30, timeZone, locale), null, null, "invoiceId2");
fa.createInvoiceItem(invoiceId2, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("50.0"));
/*
* (c) Create sales invoice #3 from Company to Customer B for $150, invoice date 55 days before current date, due date 60 days after invoice date
*/
String invoiceId3 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -55, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -55 + 60, timeZone, locale), null, null, "invoiceId3");
fa.createInvoiceItem(invoiceId3, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("150.0"));
/*
* (d) Create sales invoice #4 from Company to Customer C for $170, invoice date 120 days before current date, due date 30 days after invoice date
*/
String invoiceId4 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -120, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -120 + 30, timeZone, locale), null, null, "invoiceId4");
fa.createInvoiceItem(invoiceId4, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("170.0"));
/*
* (e) Create sales invoice #5 from Company to Customer B for $210, invoice date 15 days before current date, due date 7 days after invoice date
*/
String invoiceId5 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15 + 7, timeZone, locale), null, null, "invoiceId5");
fa.createInvoiceItem(invoiceId5, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("210.0"));
/*
* (f) Create sales invoice #6 from Company to Customer A for $500, invoice date 36 days before current date, due date 30 days after invoice date
*/
String invoiceId6 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -36, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -36 + 30, timeZone, locale), null, null, "invoiceId6");
fa.createInvoiceItem(invoiceId6, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("500.0"));
/*
* (g) Create sales invoice #7 from Company to Customer C for $228, invoice date 42 days before current date, due date 45 days after invoice date
*/
String invoiceId7 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -42, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -42 + 45, timeZone, locale), null, null, "invoiceId7");
fa.createInvoiceItem(invoiceId7, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("228.0"));
/*
* (h) Create sales invoice #8 from Company to Customer B for $65, invoice date 15 days before current date, due date 30 days after invoice date
*/
String invoiceId8 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -15 + 30, timeZone, locale), null, null, "invoiceId8");
fa.createInvoiceItem(invoiceId8, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("65.0"));
/*
* (i) Create sales invoice #9 from Company to Customer A for $156, invoice date 6 days before current date, due date 15 days after invoice date
*/
String invoiceId9 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -6, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -6 + 15, timeZone, locale), null, null, "invoiceId9");
fa.createInvoiceItem(invoiceId9, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("156.0"));
/*
* (j) Create sales invoice #10 from Company to Customer C for $550, invoice date 33 days before current date, due date 15 days after invoice date
*/
String invoiceId10 = fa.createInvoice(customerId.get(2), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -33, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -33 + 15, timeZone, locale), null, null, "invoiceId10");
fa.createInvoiceItem(invoiceId10, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("550.0"));
/*
* (k) Create sales invoice #11 from Company to Customer B for $90, invoice date 62 days before current date, due date 90 days after invoice date
*/
String invoiceId11 = fa.createInvoice(customerId.get(1), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -62, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -62 + 90, timeZone, locale), null, null, "invoiceId11");
fa.createInvoiceItem(invoiceId11, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("90.0"));
/*
* 3. Cancel invoice #2
*/
fa.updateInvoiceStatus(invoiceId2, "INVOICE_CANCELLED");
/*
* 4. Set all other invoices to READY
*/
fa.updateInvoiceStatus(invoiceId1, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId3, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId4, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId5, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId6, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId7, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId8, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId9, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId10, "INVOICE_READY");
fa.updateInvoiceStatus(invoiceId11, "INVOICE_READY");
/*
* 5. Set invoice #6 to VOID
*/
Map<String, Object> input = new HashMap<String, Object>();
input.put("userLogin", demofinadmin);
input.put("invoiceId", invoiceId6);
runAndAssertServiceSuccess("opentaps.voidInvoice", input);
/*
* 6. Set invoice #10 to WRITEOFF
*/
fa.updateInvoiceStatus(invoiceId10, "INVOICE_WRITEOFF");
/*
* 7. Receive a payment of $65 for invoice #8
*/
fa.createPaymentAndApplication(new BigDecimal("65.0"), customerId.get(1), organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId8, "PMNT_RECEIVED");
/*
* 8. Receive a payment of $65 for invoice #11
*/
fa.createPaymentAndApplication(new BigDecimal("65.0"), customerId.get(1), organizationPartyId, "CUSTOMER_PAYMENT", "CREDIT_CARD", null, invoiceId11, "PMNT_RECEIVED");
/*
* 9. Create sales invoice #12 for Company to Customer A for $1000, invoice date now and due 30 days after invoicing, but do not set this invoice to READY
*/
String invoiceId12 = fa.createInvoice(customerId.get(0), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), null, null, "invoiceId12");
fa.createInvoiceItem(invoiceId12, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("1000.0"));
/*
* 10. Run AccountsHelper.getBalancesForAllCustomers and verify the following:
*/
Map<String, BigDecimal> balances = AccountsHelper.getBalancesForAllCustomers(organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
/*
* (a) balance of Customer A is $256
*/
assertEquals("balance of Customer " + customerId.get(0) + " is " + balances.get(customerId.get(0)) + " and not $256", balances.get(customerId.get(0)), new BigDecimal("256.00"));
/*
* (b) balance of Customer B is $385
*/
assertEquals("balance of Customer " + customerId.get(1) + " is " + balances.get(customerId.get(1)) + " and not $385", balances.get(customerId.get(1)), new BigDecimal("385.00"));
/*
* (c) balance of Customer C is $398
*/
assertEquals("balance of Customer " + customerId.get(2) + " is " + balances.get(customerId.get(0)) + " and not $398", balances.get(customerId.get(2)), new BigDecimal("398.00"));
/*
* 11. Run AccountsHelper.getUnpaidInvoicesForCustomers and verify:
*/
Map<Integer, List<Invoice>> invoices = AccountsHelper.getUnpaidInvoicesForCustomers(organizationPartyId, UtilMisc.toList(new Integer(30), new Integer(60), new Integer(90), new Integer(9999)), UtilDateTime.nowTimestamp(), delegator, timeZone, locale);
assertNotNull("Unpaid Invoices For Customers not found.", invoices);
/*
* (b) 0-30 day bucket has invoices #5 and #9
*/
List<Invoice> invoicesList = invoices.get(30);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent5 = false;
boolean isPresent9 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId5.equals(invoice.getString("invoiceId"))) {
isPresent5 = true;
}
if (invoiceId9.equals(invoice.getString("invoiceId"))) {
isPresent9 = true;
}
}
assertTrue("Invoice " + invoiceId5 + " is not present in 0-30 day bucket", isPresent5);
assertTrue("Invoice " + invoiceId9 + " is not present in 0-30 day bucket", isPresent9);
/*
* (c) 30-60 day bucket has invoice #3 and #7
*/
invoicesList = invoices.get(60);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent3 = false;
boolean isPresent7 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId3.equals(invoice.getString("invoiceId"))) {
isPresent3 = true;
}
if (invoiceId7.equals(invoice.getString("invoiceId"))) {
isPresent7 = true;
}
}
assertTrue("Invoice " + invoiceId3 + " is not present in 30-60 day bucket", isPresent3);
assertTrue("Invoice " + invoiceId7 + " is not present in 30-60 day bucket", isPresent7);
/*
* (d) 60-90 day bucket has invoices #11
*/
invoicesList = invoices.get(90);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent11 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId11.equals(invoice.getString("invoiceId"))) {
isPresent11 = true;
}
}
assertTrue("Invoice " + invoiceId11 + " is not present in 60-90 day bucket", isPresent11);
/*
* (d) 90+ day bucket has invoices #1 and #4
*/
invoicesList = invoices.get(9999);
assertNotNull("Unpaid Invoices For Customers not found.", invoicesList);
boolean isPresent1 = false;
boolean isPresent4 = false;
for (Invoice invoice : invoicesList) {
if (invoiceId1.equals(invoice.getString("invoiceId"))) {
isPresent1 = true;
}
if (invoiceId4.equals(invoice.getString("invoiceId"))) {
isPresent4 = true;
}
}
assertTrue("Invoice " + invoiceId1 + " is not present in 90+ day bucket", isPresent1);
assertTrue("Invoice " + invoiceId4 + " is not present in 90+ day bucket", isPresent4);
/*
* 12. Create parties Customer D and Customer E
*/
List<String> extraCustomerIds = generator.getContacts(2);
assertNotNull("Two customers should be generated", extraCustomerIds);
assertEquals(2, extraCustomerIds.size());
customerId.addAll(extraCustomerIds);
/*
* 13. Create more sales invoices
*
* (a) Invoice #13 from Company to Customer D for $200, invoice date today, due in 30 days after invoice date
*/
String invoice13 = fa.createInvoice(customerId.get(3), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale), null, null, "invoiceId13");
fa.createInvoiceItem(invoice13, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("2.0"), new BigDecimal("100.0"));
/*
* (b) Invoice #14 from Company to Customer D for $300, invoice date today, due in 60 days after invoice date
*/
String invoice14 = fa.createInvoice(customerId.get(3), "SALES_INVOICE", UtilDateTime.nowTimestamp(), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 60, timeZone, locale), null, null, "invoice14");
fa.createInvoiceItem(invoice14, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("3.0"), new BigDecimal("100.0"));
/*
* (c) Invoice #15 from Company to Customer E for $155, invoice date 58 days before today, due in 50 days after invoice date
*/
String invoice15 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -58, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -58 + 50, timeZone, locale), null, null, "invoice15");
fa.createInvoiceItem(invoice15, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("155.0"));
/*
* (d) Invoice #16 from Company to Customer E for $266, invoice date 72 days before today, due in 30 days after invoice date
*/
String invoice16 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -72, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -72 + 30, timeZone, locale), null, null, "invoice16");
fa.createInvoiceItem(invoice16, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("266.0"));
/*
* (e) Invoice #17 from Company to Customer E for $377, invoice date 115 days before today, due in 30 days after invoice date
*/
String invoice17 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -115, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -115 + 30, timeZone, locale), null, null, "invoice17");
fa.createInvoiceItem(invoice17, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("377.0"));
/*
* (f) Invoice #18 from Company to Customer E for $488, invoice date 135 days before today, due in 30 days after invoice date
*/
String invoice18 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -135, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -135 + 30, timeZone, locale), null, null, "invoice18");
fa.createInvoiceItem(invoice18, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("488.0"));
/*
* (g) Invoice #19 from Company to Customer E for $599, invoice date 160 days before today, due in 30 days after invoice date
*/
String invoice19 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -160, timeZone, locale), UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -160 + 30, timeZone, locale), null, null, "invoice19");
fa.createInvoiceItem(invoice19, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("599.0"));
/*
* (h) Invoice #20 from Company to Customer E for $44, invoice date 20 days before today, no due date (null)
*/
String invoice20 = fa.createInvoice(customerId.get(4), "SALES_INVOICE", UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, -20, timeZone, locale), null, null, null, "invoice20");
fa.createInvoiceItem(invoice20, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), new BigDecimal("44.0"));
/*
* 14. Set all invoices from (13) to ready.
*/
fa.updateInvoiceStatus(invoice13, "INVOICE_READY");
fa.updateInvoiceStatus(invoice14, "INVOICE_READY");
fa.updateInvoiceStatus(invoice15, "INVOICE_READY");
fa.updateInvoiceStatus(invoice16, "INVOICE_READY");
fa.updateInvoiceStatus(invoice17, "INVOICE_READY");
fa.updateInvoiceStatus(invoice18, "INVOICE_READY");
fa.updateInvoiceStatus(invoice19, "INVOICE_READY");
fa.updateInvoiceStatus(invoice20, "INVOICE_READY");
/*
* 15. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=true and verify
*/
DomainsLoader dl = new DomainsLoader(new Infrastructure(dispatcher), new User(demofinadmin));
Map<String, Object> partyData = FastMap.newInstance();
AccountsHelper.customerStatement(dl, organizationPartyId, UtilMisc.toSet(customerId), UtilDateTime.nowTimestamp(), 30, true, partyData, locale, timeZone);
assertNotNull("Failed to create customer statement.", partyData);
/*
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = $100, 90 - 120 days = 0, over 120 days = 0, total open amount = $256
*/
verifyCustomerStatement(customerId.get(0), partyData, true, new BigDecimal("156.0"), new BigDecimal("0.0"), new BigDecimal("100.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("256.0"));
/*
* (b) Customer B: isPastDue = false, current = $385, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
*/
verifyCustomerStatement(customerId.get(1), partyData, false, new BigDecimal("385.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("385.0"));
/*
* (c) Customer C: isPastDue = true, current = $228, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $170, over 120 days = 0, total open amount = $398
*/
verifyCustomerStatement(customerId.get(2), partyData, true, new BigDecimal("228.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("170.0"), new BigDecimal("0.0"), new BigDecimal("398.0"));
/*
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
*/
verifyCustomerStatement(customerId.get(3), partyData, false, new BigDecimal("500.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("500.0"));
/*
* (e) Customer E: isPastDue = true, current = $199, 30 - 60 days = 266, 60 - 90 days = 377, 90 - 120 days = 488, over 120 days = 599, total open amount = $1929
*/
verifyCustomerStatement(customerId.get(4), partyData, true, new BigDecimal("199.0"), new BigDecimal("266.0"), new BigDecimal("377.0"), new BigDecimal("488.0"), new BigDecimal("599.0"), new BigDecimal("1929.0"));
/*
* 16. Get customer statement (AccountsHelper.customerStatement) with useAgingDate=false and verify
*/
partyData = FastMap.newInstance();
AccountsHelper.customerStatement(dl, organizationPartyId, UtilMisc.toSet(customerId), UtilDateTime.nowTimestamp(), 30, false, partyData, locale, timeZone);
assertNotNull("Failed to create customer statement.", partyData);
/*
* (a) Customer A: isPastDue = true, current = $156, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = $100, over 120 days = 0, total open amount = $256
*/
verifyCustomerStatement(customerId.get(0), partyData, true, new BigDecimal("156.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("100.0"), new BigDecimal("0.0"), new BigDecimal("256.0"));
/*
* (b) Customer B: isPastDue = true, current = $210, 30 - 60 days = 150, 60 - 90 days = 25, 90 - 120 days = 0, over 120 days = 0, total open amount = $385
*/
verifyCustomerStatement(customerId.get(1), partyData, true, new BigDecimal("210.0"), new BigDecimal("150.0"), new BigDecimal("25.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("385.0"));
/*
* (c) Customer C: isPastDue = true, current = 0, 30 - 60 days = 228, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = $170, total open amount = $398
* Note that invoice #4 from above is in the over 120 day bucket because it is dated 120 days before current timestamp, but aging calculation start at beginning of today
*/
verifyCustomerStatement(customerId.get(2), partyData, true, new BigDecimal("0.0"), new BigDecimal("228.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("170.0"), new BigDecimal("398.0"));
/*
* (d) Customer D: isPastDue = false, current = $500, 30 - 60 days = 0, 60 - 90 days = 0, 90 - 120 days = 0, over 120 days = 0, total open amount = $500
*/
verifyCustomerStatement(customerId.get(3), partyData, false, new BigDecimal("500.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("0.0"), new BigDecimal("500.0"));
/*
* (e) Customer E: isPastDue = true, current = $44, 30 - 60 days = 155, 60 - 90 days = 266, 90 - 120 days = 377, over 120 days = 1087, total open amount = $1929
*/
verifyCustomerStatement(customerId.get(4), partyData, true, new BigDecimal("44.0"), new BigDecimal("155.0"), new BigDecimal("266.0"), new BigDecimal("377.0"), new BigDecimal("1087.0"), new BigDecimal("1929.0"));
}
private void verifyCustomerStatement(String partyId, Map<String, Object> partyData, boolean isPastDue, BigDecimal current, BigDecimal over30, BigDecimal over60, BigDecimal over90, BigDecimal over120, BigDecimal totalOpen) {
assertEquals("Customer " + partyId + " should have past due invoices but isPastDue flag incorrect.", Boolean.valueOf(isPastDue), partyData.get(partyId + "is_past_due"));
assertEquals("Current value for customer " + partyId + " is incorrect.", current, (BigDecimal) partyData.get(String.format("%1$scurrent", partyId)));
assertEquals("Over 30 days past due amount is wrong.", over30, (BigDecimal) partyData.get(String.format("%1$sover_1N", partyId)));
assertEquals("Over 60 days past due amount is wrong.", over60, (BigDecimal) partyData.get(String.format("%1$sover_2N", partyId)));
assertEquals("Over 90 days past due amount is wrong.", over90, (BigDecimal) partyData.get(String.format("%1$sover_3N", partyId)));
assertEquals("Over 120 days past due amount is wrong.", over120, (BigDecimal) partyData.get(String.format("%1$sover_4N", partyId)));
assertEquals("Total open amount is wrong.", totalOpen, (BigDecimal) partyData.get(String.format("%1$stotal_open", partyId)));
}
/**
* Tests setInvoiceReadyAndCheckIfPaid service on an in process invoice, verifying that it sets it to INVOICE_READY,
* and the GL and customer outstanding balance are increased.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testSetInvoiceReadyAndCheckIfPaidToInvoiceReady() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testSetInvoiceReadyAndCheckIfPaidToInvoiceReady");
BigDecimal invoiceAmount = new BigDecimal("10.0");
// create the invoice
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), invoiceAmount);
// get initial balances
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal initialCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// set to ready and check if paid
runAndAssertServiceSuccess("setInvoiceReadyAndCheckIfPaid", UtilMisc.toMap("invoiceId", invoiceId, "userLogin", demofinadmin));
// get final balances
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal finalCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// check customer outstanding balance is right
assertEquals("Customer balance has increased by the right amount", (finalCustomerBalance.subtract(initialCustomerBalance)).setScale(DECIMALS, ROUNDING), invoiceAmount);
// check AR has increased by $10
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "10.0");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
// check invoice is PAID
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
assertTrue("Invoice [" + invoiceId + "] is ready", invoice.isReady());
}
/**
* Tests setInvoiceReadyAndCheckIfPaid service on a cancelled invoice, verifying that it returns an error,
* and the GL and customer outstanding balance are unchanged.
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testSetInvoiceReadyAndCheckIfPaidForCancelledInvoice() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testSetInvoiceReadyAndCheckIfPaidForCancelledInvoice");
BigDecimal invoiceAmount = new BigDecimal("10.0");
// create the invoice
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), invoiceAmount);
// get initial balances
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal initialCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// now cancel the invoice
fa.updateInvoiceStatus(invoiceId, "INVOICE_CANCELLED");
// this should fail
runAndAssertServiceError("setInvoiceReadyAndCheckIfPaid", UtilMisc.toMap("invoiceId", invoiceId, "userLogin", demofinadmin));
// get the final balances
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal finalCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// but the customer balance and accounts receivable totals should not have changed
assertEquals("Customer balance is unchanged", (finalCustomerBalance.subtract(initialCustomerBalance)).setScale(DECIMALS, ROUNDING), BigDecimal.ZERO);
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0.0");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
// and the invoice should stay cancelled
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
assertTrue("Invoice [" + invoiceId + "] is cancelled", invoice.isCancelled());
}
/**
* Tests setInvoiceReadyAndCheckIfPaid service on an invoice with payments already applied, verifying that it causes invoice to be PAID
* and the GL and customer outstanding balance are unchanged, but there is now money received (in undeposited receipts).
* @throws GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testSetInvoiceReadyAndCheckIfPaidForInvoiceWithPayments() throws GeneralException {
FinancialAsserts fa = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String customerPartyId = createPartyFromTemplate("DemoCustCompany", "Customer for testSetInvoiceReadyAndCheckIfPaidForInvoiceWithPayments");
BigDecimal invoiceAmount = new BigDecimal("10.0");
// create the invoice
String invoiceId = fa.createInvoice(customerPartyId, "SALES_INVOICE");
fa.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "WG-1111", new BigDecimal("1.0"), invoiceAmount);
// get initial balances
Map initialBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal initialCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// now create a payment and apply it to the invoice
fa.createPaymentAndApplication(invoiceAmount, customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "PERSONAL_CHECK", null, invoiceId, "PMNT_RECEIVED");
// now set the invoice ready
runAndAssertServiceSuccess("setInvoiceReadyAndCheckIfPaid", UtilMisc.toMap("invoiceId", invoiceId, "userLogin", demofinadmin));
// get final balances
Map finalBalances = fa.getFinancialBalances(UtilDateTime.nowTimestamp());
BigDecimal finalCustomerBalance = AccountsHelper.getBalanceForCustomerPartyId(customerPartyId, organizationPartyId, "ACTUAL", UtilDateTime.nowTimestamp(), delegator);
// customer's balance should be unchanged
assertEquals("Customer balance is unchanged", (finalCustomerBalance.subtract(initialCustomerBalance)).setScale(DECIMALS, ROUNDING), BigDecimal.ZERO);
// AR should be unchanged (invoice is already paid), but we should have $10 in undeposited receipts
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_RECEIVABLE", "0.0", "UNDEPOSITED_RECEIPTS", "+10");
Map accountMap = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
assertMapDifferenceCorrect(initialBalances, finalBalances, accountMap);
// and invoice should be paid
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
assertTrue("Invoice [" + invoiceId + "] is paid", invoice.isPaid());
}
/**
* This test verifies that when the organization uses standard costing, the difference between the standard cost and
* purchase invoice price for the item is charged off as a purchase price variance. There should be no change to
* uninvoiced shipment receipt.
* @exception GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testPurchasingVarianceWithStandardCost() throws GeneralException {
// Set the organization costing method to standard costing
setStandardCostingMethod("STANDARD_COSTING");
// Get initial Financial balances
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Map initialBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
// Create a new product
GenericValue testProduct = createTestProduct("Test Purchasing Variance With Standard Cost Product", demowarehouse1);
String productId = testProduct.getString("productId");
// set its supplier product record for DemoSupplier to $10
createMainSupplierForProduct(productId, "DemoSupplier", new BigDecimal("10.0"), "USD", new BigDecimal("1.0"), admin);
// set its standard cost (EST_STD_MAT_COST) to $35
runAndAssertServiceSuccess("createCostComponent", UtilMisc.<String, Object>toMap("userLogin", admin, "productId", productId, "costComponentTypeId", "EST_STD_MAT_COST", "cost", new BigDecimal("35.0"), "costUomId", "USD"));
// Create a purchase order for 75 of this product from DemoSupplier
Map<GenericValue, BigDecimal> orderSpec = new HashMap<GenericValue, BigDecimal>();
orderSpec.put(testProduct, new BigDecimal("75.0"));
PurchaseOrderFactory pof = testCreatesPurchaseOrder(orderSpec, delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", "DemoSupplier")), facilityContactMechId);
String orderId = pof.getOrderId();
GenericValue pOrder = delegator.findByPrimaryKeyCache("OrderHeader", UtilMisc.toMap("orderId", orderId));
// approve the purchase order
pof.approveOrder();
// receive all 75 units of the product from the purchase order
runAndAssertServiceSuccess("warehouse.issueOrderItemToShipmentAndReceiveAgainstPO", createTestInputParametersForReceiveInventoryAgainstPurchaseOrder(pOrder, demowarehouse1));
// Find the invoice
OrderRepositoryInterface orderRepository = orderDomain.getOrderRepository();
Order order = orderRepository.getOrderById(orderId);
List<Invoice> invoices = order.getInvoices();
assertEquals("Should only have one invoice.", invoices.size(), 1);
Invoice invoice = invoices.get(0);
// set the amount of the product on the invoice to $11.25
GenericValue invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "productId", productId, "invoiceItemTypeId", "PINV_FPROD_ITEM")));
Map<String, Object> input = UtilMisc.<String, Object>toMap("userLogin", admin, "invoiceId", invoice.getInvoiceId(), "productId", productId, "invoiceItemTypeId", "PINV_FPROD_ITEM", "amount", new BigDecimal("11.25"));
input.put("invoiceItemSeqId", invoiceItem.get("invoiceItemSeqId"));
input.put("quantity", invoiceItem.get("quantity"));
runAndAssertServiceSuccess("updateInvoiceItem", input);
// add a second invoice item of "PITM_SHIP_CHARGES" for $58.39
input = UtilMisc.<String, Object>toMap("userLogin", admin, "invoiceId", invoice.getInvoiceId(), "invoiceItemTypeId", "PITM_SHIP_CHARGES", "amount", new BigDecimal("58.39"));
runAndAssertServiceSuccess("createInvoiceItem", input);
// set the invoice as ready
financialAsserts.updateInvoiceStatus(invoice.getInvoiceId(), "INVOICE_READY");
// Get the final financial balances
Map finalBalances = financialAsserts.getFinancialBalances(UtilDateTime.nowTimestamp());
// verify the following changes:
// ACCOUNTS_PAYABLE -902.14
// glAccountId=510000 58.39
// INVENTORY_ACCOUNT 2625.00
// PURCHASE_PRICE_VAR -1781.25
// UNINVOICED_SHIP_RCPT 0.00
Map expectedBalanceChanges = UtilMisc.toMap("ACCOUNTS_PAYABLE", "-902.14",
"INVENTORY_ACCOUNT", "2625.00",
"PURCHASE_PRICE_VAR", "-1781.25",
"UNINVOICED_SHIP_RCPT", "0.0");
expectedBalanceChanges = UtilFinancial.replaceGlAccountTypeWithGlAccountForOrg(organizationPartyId, expectedBalanceChanges, delegator);
expectedBalanceChanges.put("510000", "58.39");
printMapDifferences(initialBalances, finalBalances);
assertMapDifferenceCorrect(initialBalances, finalBalances, expectedBalanceChanges);
}
/**
* This test verifies that when creating an invoice item, if the productId is not null, then If invoiceItemTypeId is null, then use the ProductInvoiceItemType to fill in the invoiceItemTypeId (see below for this entity)
* If description is null, then use Product productName to fill in the description
* If amount is null, then call calculateProductPrice and fill in then amount.
* when updating an invoice item, if the new productId is different than the old productId
* @exception GeneralException if an error occurs
*/
@SuppressWarnings("unchecked")
public void testCreateAndUpdateInvoiceItem() throws GeneralException {
//create a SALES_INVOICE from Company to another party
InvoiceRepositoryInterface repository = billingDomain.getInvoiceRepository();
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testCreateAndUpdateInvoiceItem");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String productId1 = "GZ-1000";
String productId2 = "GZ-1001";
// 1 creating invoice item with productId but without invoiceItemTypeId, description, price gets the right values
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, null, productId1, new BigDecimal("1.0"), null);
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
GenericValue product1 = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId1));
String invoiceItemTypeId1 = repository.getInvoiceItemTypeIdForProduct(invoice, domainsDirectory.getProductDomain().getProductRepository().getProductById(productId1));
String description1 = product1.getString("productName");
String uomId = invoice.getCurrencyUomId();
Map results = dispatcher.runSync("calculateProductPrice", UtilMisc.toMap("product", product1, "currencyUomId", uomId));
BigDecimal price1 = (BigDecimal) results.get("price");
BigDecimal amount1 = price1.setScale(DECIMALS, ROUNDING);
GenericValue product2 = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId2));
String invoiceItemTypeId2 = repository.getInvoiceItemTypeIdForProduct(invoice, domainsDirectory.getProductDomain().getProductRepository().getProductById("GZ-1001"));
String description2 = product2.getString("productName");
results = dispatcher.runSync("calculateProductPrice", UtilMisc.toMap("product", product2, "currencyUomId", uomId));
BigDecimal price2 = (BigDecimal) results.get("price");
BigDecimal amount2 = price2.setScale(DECIMALS, ROUNDING);
GenericValue invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "productId", productId1)));
assertEquals("invoiceItemTypeId is wrong.", invoiceItemTypeId1, invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", description1, invoiceItem.getString("description"));
assertEquals("amount is wrong.", amount1, invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 2 you can also create invoice item with override invoiceItemTypeId, description, price
financialAsserts.createInvoiceItem(invoiceId, "ITM_SHIPPING_CHARGES", null, new BigDecimal("1.0"), new BigDecimal("45.0"), "testUpdateInvoiceItem description");
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "invoiceItemTypeId", "ITM_SHIPPING_CHARGES")));
assertEquals("invoiceItemTypeId is wrong.", "ITM_SHIPPING_CHARGES", invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", "testUpdateInvoiceItem description", invoiceItem.getString("description"));
assertEquals("amount is wrong.", new BigDecimal("45.0"), invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 3 updating invoice item causes the right values to be filled in
financialAsserts.updateInvoiceItem(invoiceId, invoiceItem.getString("invoiceItemSeqId"), null, productId2, new BigDecimal("2.0"), null, null, null);
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "productId", productId2)));
assertEquals("invoiceItemTypeId is wrong.", invoiceItemTypeId2, invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", description2, invoiceItem.getString("description"));
assertEquals("amount is wrong.", amount2, invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 4 you can update invoice item afterwards with override values
financialAsserts.updateInvoiceItem(invoiceId, invoiceItem.getString("invoiceItemSeqId"), "INV_FPROD_ITEM", productId2, new BigDecimal("2.0"), new BigDecimal("51.99"), "testUpdateInvoiceItem description", null);
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", invoice.getInvoiceId(), "productId", productId2)));
assertEquals("invoiceItemTypeId is wrong.", "INV_FPROD_ITEM", invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", "testUpdateInvoiceItem description", invoiceItem.getString("description"));
assertEquals("amount is wrong.", new BigDecimal("51.99"), invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// verify for PURCHASE_INVOICE
String supplierProductId1 = "SUPPLY-001";
String supplierProductId2 = "ASSET-001";
product1 = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", supplierProductId1));
product2 = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", supplierProductId2));
PurchasingRepositoryInterface purchasingRepository = purchasingDomain.getPurchasingRepository();
SupplierProduct demoSupplierProduct1 = purchasingRepository.getSupplierProduct("DemoSupplier", supplierProductId1, new BigDecimal("500.0"), "USD");
SupplierProduct demoSupplierProduct2 = purchasingRepository.getSupplierProduct("DemoSupplier", supplierProductId2, new BigDecimal("500.0"), "USD");
// 5 create a PURCHASE_INVOICE from Company to supplierParty
String purchaseInvoiceId = financialAsserts.createInvoice("DemoSupplier", "PURCHASE_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(purchaseInvoiceId, null, supplierProductId1, new BigDecimal("500.0"), null);
Invoice purchaseInvoice = repository.getInvoiceById(purchaseInvoiceId);
String purchaseInvoiceItemTypeId1 = repository.getInvoiceItemTypeIdForProduct(purchaseInvoice, domainsDirectory.getProductDomain().getProductRepository().getProductById(supplierProductId1));
String purchaseDescription1 = demoSupplierProduct1.getSupplierProductName()==null ? product1.getString("productName") : demoSupplierProduct1.getSupplierProductId() + " " + demoSupplierProduct1.getSupplierProductName();
BigDecimal purchaseAmount1 = demoSupplierProduct1.getLastPrice();
String purchaseInvoiceItemTypeId2 = repository.getInvoiceItemTypeIdForProduct(purchaseInvoice, domainsDirectory.getProductDomain().getProductRepository().getProductById(supplierProductId2));
String purchaseDescription2 = demoSupplierProduct2.getSupplierProductName()==null ? product2.getString("productName") : demoSupplierProduct2.getSupplierProductId() + " " + demoSupplierProduct2.getSupplierProductName();
BigDecimal purchaseAmount2 = demoSupplierProduct2.getLastPrice();
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", purchaseInvoice.getInvoiceId(), "productId", supplierProductId1)));
assertEquals("invoiceItemTypeId is wrong.", purchaseInvoiceItemTypeId1, invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", purchaseDescription1, invoiceItem.getString("description"));
assertEquals("amount is wrong.", purchaseAmount1, invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 6 you can also create invoice item with override invoiceItemTypeId, description, price
financialAsserts.createInvoiceItem(purchaseInvoiceId, "ITM_SHIPPING_CHARGES", null, new BigDecimal("1.0"), new BigDecimal("45.0"), "testUpdateInvoiceItem description");
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", purchaseInvoice.getInvoiceId(), "invoiceItemTypeId", "ITM_SHIPPING_CHARGES")));
assertEquals("invoiceItemTypeId is wrong.", "ITM_SHIPPING_CHARGES", invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", "testUpdateInvoiceItem description", invoiceItem.getString("description"));
assertEquals("amount is wrong.", new BigDecimal("45.0"), invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 7 updating invoice item causes the right values to be filled in
financialAsserts.updateInvoiceItem(purchaseInvoiceId, invoiceItem.getString("invoiceItemSeqId"), null, supplierProductId2, new BigDecimal("500.0"), null, null, null);
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", purchaseInvoice.getInvoiceId(), "productId", supplierProductId2)));
assertEquals("invoiceItemTypeId is wrong.", purchaseInvoiceItemTypeId2, invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", purchaseDescription2, invoiceItem.getString("description"));
assertEquals("amount is wrong.", purchaseAmount2, invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
// 8 you can update invoice item afterwards with override values
financialAsserts.updateInvoiceItem(purchaseInvoiceId, invoiceItem.getString("invoiceItemSeqId"), "PINV_FPROD_ITEM", supplierProductId2, new BigDecimal("2.0"), new BigDecimal("199.99"), "testUpdateInvoiceItem description", null);
invoiceItem = EntityUtil.getOnly(delegator.findByAnd("InvoiceItem", UtilMisc.toMap("invoiceId", purchaseInvoice.getInvoiceId(), "productId", supplierProductId2)));
assertEquals("invoiceItemTypeId is wrong.", "PINV_FPROD_ITEM", invoiceItem.getString("invoiceItemTypeId"));
assertEquals("description is wrong.", "testUpdateInvoiceItem description", invoiceItem.getString("description"));
assertEquals("amount is wrong.", new BigDecimal("199.99"), invoiceItem.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
}
/**
* This test verifies that transaction posted with a glFiscalTypeId not ACTUAL are not changing the GlAccountHistory
* or the GlAccountOrganization posted amount.
* @exception Exception if an error occurs
*/
public void testAccountHistoryUpdates() throws Exception {
// 1. create AcctgTrans of glFiscalTypeId = BUDGET
// with debitCreditFlag = D, amount = 100, glAccountId = 110000
// with debitCreditFlag = C, amount = 100, glAccountId = 300000
String debitAccount = "110000";
String creditAccount = "300000";
CreateQuickAcctgTransService service = new CreateQuickAcctgTransService();
service.setInUserLogin(admin);
service.setInAcctgTransTypeId(AcctgTransTypeConstants.BUDGET);
service.setInGlFiscalTypeId(GlFiscalTypeConstants.BUDGET);
service.setInAmount(100.0);
service.setInDebitGlAccountId(debitAccount);
service.setInCreditGlAccountId(creditAccount);
service.setInDescription("testAccountHistoryUpdates");
service.setInTransactionDate(UtilDateTime.nowTimestamp());
- service.setInOrganizationPartyId("LEDGER-TEST");
+ service.setInOrganizationPartyId(testLedgerOrganizationPartyId);
runAndAssertServiceSuccess(service);
String transId = service.getOutAcctgTransId();
// 2. get all GlAccountHistory records
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
List<String> orderBy = UtilMisc.toList(GlAccountHistory.Fields.glAccountId.name(),
GlAccountHistory.Fields.customTimePeriodId.name());
List<GlAccountHistory> creditHists = ledgerRepository.findList(GlAccountHistory.class,
ledgerRepository.map(GlAccountHistory.Fields.glAccountId, creditAccount,
- GlAccountHistory.Fields.organizationPartyId, "LEDGER-TEST"),
+ GlAccountHistory.Fields.organizationPartyId, testLedgerOrganizationPartyId),
orderBy);
List<GlAccountHistory> debitHists = ledgerRepository.findList(GlAccountHistory.class,
ledgerRepository.map(GlAccountHistory.Fields.glAccountId, debitAccount,
- GlAccountHistory.Fields.organizationPartyId, "LEDGER-TEST"),
+ GlAccountHistory.Fields.organizationPartyId, testLedgerOrganizationPartyId),
orderBy);
// 3. get the GlAccountOrganization record
GlAccountOrganization creditAcctOrg = ledgerRepository.findOneNotNull(GlAccountOrganization.class,
ledgerRepository.map(GlAccountOrganization.Fields.glAccountId, creditAccount,
- GlAccountOrganization.Fields.organizationPartyId, "LEDGER-TEST"));
+ GlAccountOrganization.Fields.organizationPartyId, testLedgerOrganizationPartyId));
GlAccountOrganization debitAcctOrg = ledgerRepository.findOneNotNull(GlAccountOrganization.class,
ledgerRepository.map(GlAccountOrganization.Fields.glAccountId, debitAccount,
- GlAccountOrganization.Fields.organizationPartyId, "LEDGER-TEST"));
+ GlAccountOrganization.Fields.organizationPartyId, testLedgerOrganizationPartyId));
// 4. postAcctgTrans
PostAcctgTransService postService = new PostAcctgTransService();
postService.setInUserLogin(admin);
postService.setInAcctgTransId(transId);
runAndAssertServiceSuccess(postService);
// 5. verify GlAccountHistory for 100000 and 300000 have not changed.
List<GlAccountHistory> creditHists2 = ledgerRepository.findList(GlAccountHistory.class,
ledgerRepository.map(GlAccountHistory.Fields.glAccountId, creditAccount,
- GlAccountHistory.Fields.organizationPartyId, "LEDGER-TEST"),
+ GlAccountHistory.Fields.organizationPartyId, testLedgerOrganizationPartyId),
orderBy);
List<GlAccountHistory> debitHists2 = ledgerRepository.findList(GlAccountHistory.class,
ledgerRepository.map(GlAccountHistory.Fields.glAccountId, debitAccount,
- GlAccountHistory.Fields.organizationPartyId, "LEDGER-TEST"),
+ GlAccountHistory.Fields.organizationPartyId, testLedgerOrganizationPartyId),
orderBy);
assertEquals("The GlAccountHistory for the debit account [" + debitAccount + "] should not have changed.", debitHists, debitHists2);
assertEquals("The GlAccountHistory for the credit account [" + creditAccount + "] should not have changed.", creditHists, creditHists2);
// 6. verify GlAccountOrganization for both accounts have not changed
GlAccountOrganization creditAcctOrg2 = ledgerRepository.findOneNotNull(GlAccountOrganization.class,
ledgerRepository.map(GlAccountOrganization.Fields.glAccountId, creditAccount,
- GlAccountOrganization.Fields.organizationPartyId, "LEDGER-TEST"));
+ GlAccountOrganization.Fields.organizationPartyId, testLedgerOrganizationPartyId));
GlAccountOrganization debitAcctOrg2 = ledgerRepository.findOneNotNull(GlAccountOrganization.class,
ledgerRepository.map(GlAccountOrganization.Fields.glAccountId, debitAccount,
- GlAccountOrganization.Fields.organizationPartyId, "LEDGER-TEST"));
+ GlAccountOrganization.Fields.organizationPartyId, testLedgerOrganizationPartyId));
assertEquals("The GlAccountOrganization for the debit account [" + debitAccount + "] should not have changed.", debitAcctOrg, debitAcctOrg2);
assertEquals("The GlAccountOrganization for the credit account [" + creditAccount + "] should not have changed.", creditAcctOrg, creditAcctOrg2);
}
/**
* This test verifies captureAccountBalancesSnapshot service can take snapshot for account balance.
* @exception Exception if an error occurs
*/
@SuppressWarnings("unchecked")
public void testAccountBalancesSnapshot() throws Exception {
// create a test party from DemoAccount1 template
String customerPartyId = createPartyFromTemplate("DemoAccount1", "Account for testAccountBalancesSnapshot");
Debug.logInfo("testAccountBalancesSnapshot method create partyId " + customerPartyId, MODULE);
// run captureAccountBalancesSnapshot
Map inputParams = UtilMisc.toMap("userLogin", demofinadmin);
runAndAssertServiceSuccess("captureAccountBalancesSnapshot", inputParams);
// verify that there is no account balance history record for test party
Session session = new Infrastructure(dispatcher).getSession();
String hql = "from AccountBalanceHistory eo where eo.partyId = :partyId order by eo.asOfDatetime desc";
Query query = session.createQuery(hql);
query.setString("partyId", customerPartyId);
List<AccountBalanceHistory> list = query.list();
assertEmpty("There is no account balance history record for " + customerPartyId, list);
// create a SALES_INVOICE from Company to test party for $100 and set it to READY
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", UtilDateTime.nowTimestamp(), null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("1.0"), new BigDecimal("100.0"));
financialAsserts.updateInvoiceStatus(invoiceId, "INVOICE_READY");
// run captureAccountBalancesSnapshot
inputParams = UtilMisc.toMap("userLogin", demofinadmin);
runAndAssertServiceSuccess("captureAccountBalancesSnapshot", inputParams);
// verify that there is a new account balance history record for test party and Company for 100
list = query.list();
assertEquals("There is a new account balance history record for Company and " + customerPartyId, 1, list.size());
AccountBalanceHistory accountBalanceHistory = list.get(0);
assertEquals("There is a new account balance history record for Company and " + customerPartyId + " for 100.0", new BigDecimal("100.0"), accountBalanceHistory.getTotalBalance());
pause("mysql timestamp pause");
// create a CUSTOMER_PAYMENT from Company to test party for $50 and set it to RECEIVED
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("50.0"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
// run captureAccountBalancesSnapshot
inputParams = UtilMisc.toMap("userLogin", demofinadmin);
runAndAssertServiceSuccess("captureAccountBalancesSnapshot", inputParams);
// verify that there is a new account balance history record for test party and Company for 50
list = query.list();
assertEquals("There are two account balance history records for Company and " + customerPartyId, 2, list.size());
accountBalanceHistory = list.get(0);
assertEquals("There is a new account balance history record for Company and " + customerPartyId + " for 50.0", new BigDecimal("50.0"), accountBalanceHistory.getTotalBalance());
}
/**
* This test verifies that an unbalanced transaction cannot be posted, this uses the unbalanced test transaction LEDGER-TEST-2.
* @exception Exception if an error occurs
*/
@SuppressWarnings("unchecked")
public void testCannotPostAcctgTrans() throws Exception {
LedgerRepositoryInterface ledgerRepository = ledgerDomain.getLedgerRepository();
AccountingTransaction transaction = ledgerRepository.getAccountingTransaction("LEDGER-TEST-2");
// check canPost()
assertFalse("canPost() should not return true for LEDGER-TEST-2.", transaction.canPost());
// check that the service returns an error
Map input = UtilMisc.toMap("userLogin", demofinadmin, "acctgTransId", "LEDGER-TEST-2");
runAndAssertServiceError("postAcctgTrans", input);
}
/**
* This test verifies that we can get correct InvoiceAdjustmentType by InvoiceRepository.getInvoiceAdjustmentTypes method.
* @exception Exception if an error occurs
*/
public void testGetInvoiceAdjustmentTypes() throws Exception {
// create a sales invoice
String customerPartyId = createPartyFromTemplate("DemoAccount1", "test for InvoiceRepository.getInvoiceAdjustmentTypes");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
Timestamp invoiceDate = UtilDateTime.adjustTimestamp(UtilDateTime.nowTimestamp(), Calendar.DAY_OF_YEAR, 30, timeZone, locale);
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE", invoiceDate, null, null, null);
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("15.0"));
//verify that the correct list (three rec) of invoice adjustment types are returned for Company
Organization organizationCompany = organizationRepository.getOrganizationById(organizationPartyId);
Organization organizationCompanySub2 = organizationRepository.getOrganizationById("CompanySub2");
InvoiceRepositoryInterface invoiceRepository = billingDomain.getInvoiceRepository();
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
List<InvoiceAdjustmentType> invoiceAdjustmentTypes = invoiceRepository.getInvoiceAdjustmentTypes(organizationCompany, invoice);
assertEquals("There should have three InvoiceAdjustmentType records for [" + organizationPartyId + "]", 3, invoiceAdjustmentTypes.size());
//verify none invoice adjustment types are returned for Company
invoiceAdjustmentTypes = invoiceRepository.getInvoiceAdjustmentTypes(organizationCompanySub2, invoice);
assertEquals("There should hasn't any InvoiceAdjustmentType record for [CompanySub2]", 0, invoiceAdjustmentTypes.size());
}
/**
* Test the Invoice fields calculation.
* @exception Exception if an error occurs
*/
public void testInvoiceFieldsCalculation() throws Exception {
// create a sales invoice
String customerPartyId = createPartyFromTemplate("DemoAccount1", "test for InvoiceFieldsCalculation");
FinancialAsserts financialAsserts = new FinancialAsserts(this, organizationPartyId, demofinadmin);
InvoiceRepositoryInterface invoiceRepository = billingDomain.getInvoiceRepository();
// create an invoice with one item and total 24
String invoiceId = financialAsserts.createInvoice(customerPartyId, "SALES_INVOICE");
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1000", new BigDecimal("2.0"), new BigDecimal("12.0"));
// check the invoice amounts at this point
Invoice invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("24"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("24"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), BigDecimal.ZERO);
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("24"));
// create a payment and application of 5
String paymentId = financialAsserts.createPaymentAndApplication(new BigDecimal("5"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
// check the invoice amounts at this point
// since an application is created but the payment was not received yet, it should only modify the pending amounts
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("24"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("19"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), BigDecimal.ZERO);
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("5"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("24"));
// create an invoice adjustment as a -2 discount
runAndAssertServiceSuccess("createInvoiceAdjustment", UtilMisc.toMap("userLogin", demofinadmin, "invoiceId", invoiceId, "invoiceAdjustmentTypeId", "EARLY_PAY_DISCT", "adjustmentAmount", new BigDecimal("-2.0")));
// check the invoice amounts at this point
// this modifies the adjusted amount, adjusted total and open amounts
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("22"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("17"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), BigDecimal.ZERO);
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("5"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("22"));
// create a second payment and application of 7
String paymentId2 = financialAsserts.createPaymentAndApplication(new BigDecimal("7"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("22"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("10"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), BigDecimal.ZERO);
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("12"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("22"));
// mark the first payment as received
financialAsserts.updatePaymentStatus(paymentId, "PMNT_RECEIVED");
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("24"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("17"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("10"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("5"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("7"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("22"));
// add an invoice item of 3x5 15
financialAsserts.createInvoiceItem(invoiceId, "INV_FPROD_ITEM", "GZ-1005", new BigDecimal("3.0"), new BigDecimal("5.0"));
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("39"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("32"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("25"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("5"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("7"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("37"));
// mark the second payment as received
financialAsserts.updatePaymentStatus(paymentId2, "PMNT_RECEIVED");
// set the invoice ready
runAndAssertServiceSuccess("setInvoiceReadyAndCheckIfPaid", UtilMisc.toMap("invoiceId", invoiceId, "userLogin", demofinadmin));
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("39"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("25"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("25"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("12"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("37"));
// create a payment and application of 8
String paymentId3 = financialAsserts.createPaymentAndApplication(new BigDecimal("8"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("39"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("25"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("17"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("12"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), new BigDecimal("8"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("37"));
// cancel the payment
financialAsserts.updatePaymentStatus(paymentId3, "PMNT_CANCELLED");
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("39"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), new BigDecimal("25"));
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), new BigDecimal("25"));
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("12"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("37"));
// create a final payment and application of 25, and receive it
String paymentId4 = financialAsserts.createPaymentAndApplication(new BigDecimal("25"), customerPartyId, organizationPartyId, "CUSTOMER_PAYMENT", "COMPANY_CHECK", null, invoiceId, "PMNT_NOT_PAID");
financialAsserts.updatePaymentStatus(paymentId4, "PMNT_RECEIVED");
// check the invoice amounts at this point
invoice = invoiceRepository.getInvoiceById(invoiceId);
assertEquals("Invoice total incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceTotal(), new BigDecimal("39"));
assertEquals("Open amount incorrect for invoice [" + invoiceId + "]", invoice.getOpenAmount(), BigDecimal.ZERO);
assertEquals("Pending Open amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingOpenAmount(), BigDecimal.ZERO);
assertEquals("Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getAppliedAmount(), new BigDecimal("37"));
assertEquals("Pending Applied amount incorrect for invoice [" + invoiceId + "]", invoice.getPendingAppliedAmount(), BigDecimal.ZERO);
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getAdjustedAmount(), new BigDecimal("-2"));
assertEquals("Adjusted amount incorrect for invoice [" + invoiceId + "]", invoice.getInvoiceAdjustedTotal(), new BigDecimal("37"));
// check that the invoice is marked as PAID
assertTrue("Invoice [" + invoiceId + "] is paid", invoice.isPaid());
}
}
| false | false | null | null |
diff --git a/src/main/java/com/alibaba/fastjson/parser/JSONScanner.java b/src/main/java/com/alibaba/fastjson/parser/JSONScanner.java
index 377c8f4..6f788a6 100644
--- a/src/main/java/com/alibaba/fastjson/parser/JSONScanner.java
+++ b/src/main/java/com/alibaba/fastjson/parser/JSONScanner.java
@@ -1,2539 +1,2543 @@
/*
* Copyright 1999-2101 Alibaba Group.
*
* 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.alibaba.fastjson.parser;
import static com.alibaba.fastjson.parser.JSONToken.COLON;
import static com.alibaba.fastjson.parser.JSONToken.COMMA;
import static com.alibaba.fastjson.parser.JSONToken.EOF;
import static com.alibaba.fastjson.parser.JSONToken.ERROR;
import static com.alibaba.fastjson.parser.JSONToken.LBRACE;
import static com.alibaba.fastjson.parser.JSONToken.LBRACKET;
import static com.alibaba.fastjson.parser.JSONToken.LITERAL_STRING;
import static com.alibaba.fastjson.parser.JSONToken.LPAREN;
import static com.alibaba.fastjson.parser.JSONToken.RBRACE;
import static com.alibaba.fastjson.parser.JSONToken.RBRACKET;
import static com.alibaba.fastjson.parser.JSONToken.RPAREN;
import java.lang.ref.SoftReference;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.TimeZone;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.util.Base64;
//这个类,为了性能优化做了很多特别处理,一切都是为了性能!!!
/**
* @author wenshao<[email protected]>
*/
public class JSONScanner implements JSONLexer {
public final static byte EOI = 0x1A;
private final char[] buf;
private int bp;
private final int buflen;
private int eofPos;
/**
* The current character.
*/
private char ch;
/**
* The token's position, 0-based offset from beginning of text.
*/
private int pos;
/**
* A character buffer for literals.
*/
private char[] sbuf;
private int sp;
/**
* number start position
*/
private int np;
/**
* The token, set by nextToken().
*/
private int token;
private Keywords keywods = Keywords.DEFAULT_KEYWORDS;
private final static ThreadLocal<SoftReference<char[]>> sbufRefLocal = new ThreadLocal<SoftReference<char[]>>();
private int features = JSON.DEFAULT_PARSER_FEATURE;
private Calendar calendar = null;
private boolean resetFlag = false;
public JSONScanner(String input){
this(input, JSON.DEFAULT_PARSER_FEATURE);
}
public JSONScanner(String input, int features){
this(input.toCharArray(), input.length(), features);
}
public JSONScanner(char[] input, int inputLength){
this(input, inputLength, JSON.DEFAULT_PARSER_FEATURE);
}
public JSONScanner(char[] input, int inputLength, int features){
this.features = features;
SoftReference<char[]> sbufRef = sbufRefLocal.get();
if (sbufRef != null) {
sbuf = sbufRef.get();
sbufRefLocal.set(null);
}
if (sbuf == null) {
sbuf = new char[64];
}
eofPos = inputLength;
if (inputLength == input.length) {
if (input.length > 0 && isWhitespace(input[input.length - 1])) {
inputLength--;
} else {
char[] newInput = new char[inputLength + 1];
System.arraycopy(input, 0, newInput, 0, input.length);
input = newInput;
}
}
buf = input;
buflen = inputLength;
buf[buflen] = EOI;
bp = -1;
ch = buf[++bp];
}
public boolean isResetFlag() {
return resetFlag;
}
public void setResetFlag(boolean resetFlag) {
this.resetFlag = resetFlag;
}
public final int getBufferPosition() {
return bp;
}
public void reset(int mark, char mark_ch, int token) {
this.bp = mark;
this.ch = mark_ch;
this.token = token;
resetFlag = true;
}
public boolean isBlankInput() {
for (int i = 0; i < buflen; ++i) {
if (!isWhitespace(buf[i])) {
return false;
}
}
return true;
}
public static final boolean isWhitespace(char ch) {
// 专门调整了判断顺序
return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b';
}
/**
* Report an error at the current token position using the provided arguments.
*/
private void lexError(String key, Object... args) {
token = ERROR;
}
/**
* Return the current token, set by nextToken().
*/
public final int token() {
return token;
}
public final String tokenName() {
return JSONToken.name(token);
}
private static boolean[] whitespaceFlags = new boolean[256];
static {
whitespaceFlags[' '] = true;
whitespaceFlags['\n'] = true;
whitespaceFlags['\r'] = true;
whitespaceFlags['\t'] = true;
whitespaceFlags['\f'] = true;
whitespaceFlags['\b'] = true;
}
public final void skipWhitespace() {
for (;;) {
if (whitespaceFlags[ch]) {
ch = buf[++bp];
continue;
} else {
break;
}
}
}
public final char getCurrent() {
return ch;
}
public final void nextTokenWithColon() {
for (;;) {
if (ch == ':') {
ch = buf[++bp];
nextToken();
return;
}
if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b') {
ch = buf[++bp];
continue;
}
throw new JSONException("not match ':' - " + ch);
}
}
public final void nextTokenWithColon(int expect) {
for (;;) {
if (ch == ':') {
ch = buf[++bp];
break;
}
if (isWhitespace(ch)) {
ch = buf[++bp];
continue;
}
throw new JSONException("not match ':', actual " + ch);
}
for (;;) {
if (expect == JSONToken.LITERAL_INT) {
if (ch >= '0' && ch <= '9') {
sp = 0;
pos = bp;
scanNumber();
return;
}
if (ch == '"') {
sp = 0;
pos = bp;
scanString();
return;
}
} else if (expect == JSONToken.LITERAL_STRING) {
if (ch == '"') {
sp = 0;
pos = bp;
scanString();
return;
}
if (ch >= '0' && ch <= '9') {
sp = 0;
pos = bp;
scanNumber();
return;
}
} else if (expect == JSONToken.LBRACE) {
if (ch == '{') {
token = JSONToken.LBRACE;
ch = buf[++bp];
return;
}
if (ch == '[') {
token = JSONToken.LBRACKET;
ch = buf[++bp];
return;
}
} else if (expect == JSONToken.LBRACKET) {
if (ch == '[') {
token = JSONToken.LBRACKET;
ch = buf[++bp];
return;
}
if (ch == '{') {
token = JSONToken.LBRACE;
ch = buf[++bp];
return;
}
}
if (isWhitespace(ch)) {
ch = buf[++bp];
continue;
}
nextToken();
break;
}
}
public final void incrementBufferPosition() {
ch = buf[++bp];
}
public final void resetStringPosition() {
this.sp = 0;
}
public void nextToken(int expect) {
for (;;) {
switch (expect) {
case JSONToken.LBRACE:
if (ch == '{') {
token = JSONToken.LBRACE;
ch = buf[++bp];
return;
}
if (ch == '[') {
token = JSONToken.LBRACKET;
ch = buf[++bp];
return;
}
break;
case JSONToken.COMMA:
if (ch == ',') {
token = JSONToken.COMMA;
ch = buf[++bp];
return;
}
if (ch == '}') {
token = JSONToken.RBRACE;
ch = buf[++bp];
return;
}
if (ch == ']') {
token = JSONToken.RBRACKET;
ch = buf[++bp];
return;
}
if (ch == EOI) {
token = JSONToken.EOF;
return;
}
break;
case JSONToken.LITERAL_INT:
if (ch >= '0' && ch <= '9') {
sp = 0;
pos = bp;
scanNumber();
return;
}
if (ch == '"') {
sp = 0;
pos = bp;
scanString();
return;
}
if (ch == '[') {
token = JSONToken.LBRACKET;
ch = buf[++bp];
return;
}
if (ch == '{') {
token = JSONToken.LBRACE;
ch = buf[++bp];
return;
}
break;
case JSONToken.LITERAL_STRING:
if (ch == '"') {
sp = 0;
pos = bp;
scanString();
return;
}
if (ch >= '0' && ch <= '9') {
sp = 0;
pos = bp;
scanNumber();
return;
}
if (ch == '[') {
token = JSONToken.LBRACKET;
ch = buf[++bp];
return;
}
if (ch == '{') {
token = JSONToken.LBRACE;
ch = buf[++bp];
return;
}
break;
case JSONToken.LBRACKET:
if (ch == '[') {
token = JSONToken.LBRACKET;
ch = buf[++bp];
return;
}
if (ch == '{') {
token = JSONToken.LBRACE;
ch = buf[++bp];
return;
}
break;
case JSONToken.RBRACKET:
if (ch == ']') {
token = JSONToken.RBRACKET;
ch = buf[++bp];
return;
}
case JSONToken.EOF:
if (ch == EOI) {
token = JSONToken.EOF;
return;
}
break;
default:
break;
}
if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b') {
ch = buf[++bp];
continue;
}
nextToken();
break;
}
}
public final void nextToken() {
sp = 0;
for (;;) {
pos = bp;
if (ch == '"') {
scanString();
return;
}
if (ch == ',') {
ch = buf[++bp];
token = COMMA;
return;
}
if (ch >= '0' && ch <= '9') {
scanNumber();
return;
}
if (ch == '-') {
scanNumber();
return;
}
switch (ch) {
case '\'':
if (!isEnabled(Feature.AllowSingleQuotes)) {
throw new JSONException("Feature.AllowSingleQuotes is false");
}
scanStringSingleQuote();
return;
case ' ':
case '\t':
case '\b':
case '\f':
case '\n':
case '\r':
ch = buf[++bp];
break;
case 't': // true
scanTrue();
return;
case 'T': // true
scanTreeSet();
return;
case 'S': // set
scanSet();
return;
case 'f': // false
scanFalse();
return;
case 'n': // new,null
scanNullOrNew();
return;
case 'D': // Date
scanIdent();
return;
case '(':
ch = buf[++bp];
token = LPAREN;
return;
case ')':
ch = buf[++bp];
token = RPAREN;
return;
case '[':
ch = buf[++bp];
token = LBRACKET;
return;
case ']':
ch = buf[++bp];
token = RBRACKET;
return;
case '{':
ch = buf[++bp];
token = LBRACE;
return;
case '}':
ch = buf[++bp];
token = RBRACE;
return;
case ':':
ch = buf[++bp];
token = COLON;
return;
default:
if (bp == buflen || ch == EOI && bp + 1 == buflen) { // JLS
if (token == EOF) {
throw new JSONException("EOF error");
}
token = EOF;
pos = bp = eofPos;
} else {
lexError("illegal.char", String.valueOf((int) ch));
ch = buf[++bp];
}
return;
}
}
}
boolean hasSpecial;
public final void scanStringSingleQuote() {
np = bp;
hasSpecial = false;
char ch;
for (;;) {
ch = buf[++bp];
if (ch == '\'') {
break;
}
if (ch == EOI) {
throw new JSONException("unclosed single-quote string");
}
if (ch == '\\') {
if (!hasSpecial) {
hasSpecial = true;
if (sp > sbuf.length) {
char[] newsbuf = new char[sp * 2];
System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length);
sbuf = newsbuf;
}
System.arraycopy(buf, np + 1, sbuf, 0, sp);
}
ch = buf[++bp];
switch (ch) {
case '"':
putChar('"');
break;
case '\\':
putChar('\\');
break;
case '/':
putChar('/');
break;
case '\'':
putChar('\'');
break;
case 'b':
putChar('\b');
break;
case 'f':
case 'F':
putChar('\f');
break;
case 'n':
putChar('\n');
break;
case 'r':
putChar('\r');
break;
case 't':
putChar('\t');
break;
case 'u':
char c1 = ch = buf[++bp];
char c2 = ch = buf[++bp];
char c3 = ch = buf[++bp];
char c4 = ch = buf[++bp];
int val = Integer.parseInt(new String(new char[] { c1, c2, c3, c4 }), 16);
putChar((char) val);
break;
default:
this.ch = ch;
throw new JSONException("unclosed single-quote string");
}
continue;
}
if (!hasSpecial) {
sp++;
continue;
}
if (sp == sbuf.length) {
putChar(ch);
} else {
sbuf[sp++] = ch;
}
}
token = LITERAL_STRING;
this.ch = buf[++bp];
}
public final void scanString() {
np = bp;
hasSpecial = false;
char ch;
for (;;) {
ch = buf[++bp];
if (ch == '\"') {
break;
}
if (ch == '\\') {
if (!hasSpecial) {
hasSpecial = true;
if (sp >= sbuf.length) {
int newCapcity = sbuf.length * 2;
if (sp > newCapcity) {
newCapcity = sp;
}
char[] newsbuf = new char[newCapcity];
System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length);
sbuf = newsbuf;
}
System.arraycopy(buf, np + 1, sbuf, 0, sp);
}
ch = buf[++bp];
switch (ch) {
case '"':
putChar('"');
break;
case '\\':
putChar('\\');
break;
case '/':
putChar('/');
break;
case 'b':
putChar('\b');
break;
case 'f':
case 'F':
putChar('\f');
break;
case 'n':
putChar('\n');
break;
case 'r':
putChar('\r');
break;
case 't':
putChar('\t');
break;
case 'x':
char x1 = ch = buf[++bp];
char x2 = ch = buf[++bp];
int x_val = digits[x1] * 16 + digits[x2];
char x_char = (char) x_val;
putChar(x_char);
break;
case 'u':
char u1 = ch = buf[++bp];
char u2 = ch = buf[++bp];
char u3 = ch = buf[++bp];
char u4 = ch = buf[++bp];
int val = Integer.parseInt(new String(new char[] { u1, u2, u3, u4 }), 16);
putChar((char) val);
break;
default:
this.ch = ch;
throw new JSONException("unclosed string : " + ch);
}
continue;
}
if (!hasSpecial) {
sp++;
continue;
}
if (sp == sbuf.length) {
putChar(ch);
} else {
sbuf[sp++] = ch;
}
}
token = LITERAL_STRING;
this.ch = buf[++bp];
}
public final String scanSymbolUnQuoted(final SymbolTable symbolTable) {
final boolean[] firstIdentifierFlags = CharTypes.firstIdentifierFlags;
final char first = ch;
final boolean firstFlag = ch >= firstIdentifierFlags.length || firstIdentifierFlags[first];
if (!firstFlag) {
throw new JSONException("illegal identifier : " + ch);
}
final boolean[] identifierFlags = CharTypes.identifierFlags;
int hash = first;
np = bp;
sp = 1;
char ch;
for (;;) {
ch = buf[++bp];
if (ch < identifierFlags.length) {
if (!identifierFlags[ch]) {
break;
}
}
hash = 31 * hash + ch;
sp++;
continue;
}
this.ch = buf[bp];
token = JSONToken.IDENTIFIER;
final int NULL_HASH = 3392903;
if (sp == 4 && hash == NULL_HASH && buf[np] == 'n' && buf[np + 1] == 'u' && buf[np + 2] == 'l'
&& buf[np + 3] == 'l') {
return null;
}
return symbolTable.addSymbol(buf, np, sp, hash);
}
public final static int NOT_MATCH = -1;
public final static int NOT_MATCH_NAME = -2;
public final static int UNKOWN = 0;
public final static int OBJECT = 1;
public final static int ARRAY = 2;
public final static int VALUE = 3;
public final static int END = 4;
private final static char[] typeFieldName = "\"@type\":\"".toCharArray();
public int scanType(String type) {
matchStat = UNKOWN;
final int fieldNameLength = typeFieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (typeFieldName[i] != buf[bp + i]) {
return NOT_MATCH_NAME;
}
}
int bp = this.bp + fieldNameLength;
final int typeLength = type.length();
for (int i = 0; i < typeLength; ++i) {
if (type.charAt(i) != buf[bp + i]) {
return NOT_MATCH;
}
}
bp += typeLength;
if (buf[bp] != '"') {
return NOT_MATCH;
}
this.ch = buf[++bp];
if (ch == ',') {
this.ch = buf[++bp];
this.bp = bp;
token = JSONToken.COMMA;
return VALUE;
} else if (ch == '}') {
ch = buf[++bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
return NOT_MATCH;
}
matchStat = END;
}
this.bp = bp;
return matchStat;
}
public boolean matchField(char[] fieldName) {
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
return false;
}
}
bp = bp + fieldNameLength;
ch = buf[bp];
if (ch == '{') {
ch = buf[++bp];
token = JSONToken.LBRACE;
} else if (ch == '[') {
ch = buf[++bp];
token = JSONToken.LBRACKET;
} else {
nextToken();
}
return true;
}
public int matchStat = UNKOWN;
public String scanFieldString(char[] fieldName) {
matchStat = UNKOWN;
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
matchStat = NOT_MATCH_NAME;
return null;
}
}
int index = bp + fieldNameLength;
char ch = buf[index++];
if (ch != '"') {
matchStat = NOT_MATCH;
return null;
}
String strVal;
int start = index;
for (;;) {
ch = buf[index++];
if (ch == '\"') {
bp = index;
this.ch = ch = buf[bp];
strVal = new String(buf, start, index - start - 1);
break;
}
if (ch == '\\') {
matchStat = NOT_MATCH;
return null;
}
}
if (ch == ',') {
this.ch = buf[++bp];
matchStat = VALUE;
return strVal;
} else if (ch == '}') {
ch = buf[++bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
matchStat = NOT_MATCH;
return null;
}
matchStat = END;
} else {
matchStat = NOT_MATCH;
return null;
}
return strVal;
}
public String scanFieldSymbol(char[] fieldName, final SymbolTable symbolTable) {
matchStat = UNKOWN;
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
matchStat = NOT_MATCH_NAME;
return null;
}
}
int index = bp + fieldNameLength;
char ch = buf[index++];
if (ch != '"') {
matchStat = NOT_MATCH;
return null;
}
String strVal;
int start = index;
int hash = 0;
for (;;) {
ch = buf[index++];
if (ch == '\"') {
bp = index;
this.ch = ch = buf[bp];
strVal = symbolTable.addSymbol(buf, start, index - start - 1, hash);
break;
}
hash = 31 * hash + ch;
if (ch == '\\') {
matchStat = NOT_MATCH;
return null;
}
}
if (ch == ',') {
this.ch = buf[++bp];
matchStat = VALUE;
return strVal;
} else if (ch == '}') {
ch = buf[++bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
matchStat = NOT_MATCH;
return null;
}
matchStat = END;
} else {
matchStat = NOT_MATCH;
return null;
}
return strVal;
}
public ArrayList<String> scanFieldStringArray(char[] fieldName) {
return (ArrayList<String>) scanFieldStringArray(fieldName, null);
}
@SuppressWarnings("unchecked")
public Collection<String> scanFieldStringArray(char[] fieldName, Class<?> type) {
matchStat = UNKOWN;
Collection<String> list;
if (type.isAssignableFrom(HashSet.class)) {
list = new HashSet<String>();
} else if (type.isAssignableFrom(ArrayList.class)) {
list = new ArrayList<String>();
} else {
try {
list = (Collection<String>) type.newInstance();
} catch (Exception e) {
throw new JSONException(e.getMessage(), e);
}
}
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
matchStat = NOT_MATCH_NAME;
return null;
}
}
int index = bp + fieldNameLength;
char ch = buf[index++];
if (ch != '[') {
matchStat = NOT_MATCH;
return null;
}
ch = buf[index++];
for (;;) {
if (ch != '"') {
matchStat = NOT_MATCH;
return null;
}
String strVal;
int start = index;
for (;;) {
ch = buf[index++];
if (ch == '\"') {
strVal = new String(buf, start, index - start - 1);
list.add(strVal);
ch = buf[index++];
break;
}
if (ch == '\\') {
matchStat = NOT_MATCH;
return null;
}
}
if (ch == ',') {
ch = buf[index++];
continue;
}
if (ch == ']') {
ch = buf[index++];
break;
}
matchStat = NOT_MATCH;
return null;
}
bp = index;
if (ch == ',') {
this.ch = buf[bp];
matchStat = VALUE;
return list;
} else if (ch == '}') {
ch = buf[bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
this.ch = ch;
} else {
matchStat = NOT_MATCH;
return null;
}
matchStat = END;
} else {
matchStat = NOT_MATCH;
return null;
}
return list;
}
public int scanFieldInt(char[] fieldName) {
matchStat = UNKOWN;
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
matchStat = NOT_MATCH_NAME;
return 0;
}
}
int index = bp + fieldNameLength;
char ch = buf[index++];
int value;
if (ch >= '0' && ch <= '9') {
value = digits[ch];
for (;;) {
ch = buf[index++];
if (ch >= '0' && ch <= '9') {
value = value * 10 + digits[ch];
} else if (ch == '.') {
matchStat = NOT_MATCH;
return 0;
} else {
bp = index - 1;
break;
}
}
if (value < 0) {
matchStat = NOT_MATCH;
return 0;
}
} else {
matchStat = NOT_MATCH;
return 0;
}
if (ch == ',') {
ch = buf[++bp];
matchStat = VALUE;
token = JSONToken.COMMA;
return value;
}
if (ch == '}') {
ch = buf[++bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
matchStat = NOT_MATCH;
return 0;
}
matchStat = END;
}
return value;
}
public boolean scanFieldBoolean(char[] fieldName) {
matchStat = UNKOWN;
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
matchStat = NOT_MATCH_NAME;
return false;
}
}
int index = bp + fieldNameLength;
char ch = buf[index++];
boolean value;
if (ch == 't') {
if (buf[index++] != 'r') {
matchStat = NOT_MATCH;
return false;
}
if (buf[index++] != 'u') {
matchStat = NOT_MATCH;
return false;
}
if (buf[index++] != 'e') {
matchStat = NOT_MATCH;
return false;
}
bp = index;
ch = buf[bp];
value = true;
} else if (ch == 'f') {
if (buf[index++] != 'a') {
matchStat = NOT_MATCH;
return false;
}
if (buf[index++] != 'l') {
matchStat = NOT_MATCH;
return false;
}
if (buf[index++] != 's') {
matchStat = NOT_MATCH;
return false;
}
if (buf[index++] != 'e') {
matchStat = NOT_MATCH;
return false;
}
bp = index;
ch = buf[bp];
value = false;
} else {
matchStat = NOT_MATCH;
return false;
}
if (ch == ',') {
ch = buf[++bp];
matchStat = VALUE;
token = JSONToken.COMMA;
} else if (ch == '}') {
ch = buf[++bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
matchStat = NOT_MATCH;
return false;
}
matchStat = END;
} else {
matchStat = NOT_MATCH;
return false;
}
return value;
}
public long scanFieldLong(char[] fieldName) {
matchStat = UNKOWN;
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
matchStat = NOT_MATCH_NAME;
return 0;
}
}
int index = bp + fieldNameLength;
char ch = buf[index++];
long value;
if (ch >= '0' && ch <= '9') {
value = digits[ch];
for (;;) {
ch = buf[index++];
if (ch >= '0' && ch <= '9') {
value = value * 10 + digits[ch];
} else if (ch == '.') {
token = NOT_MATCH;
return 0;
} else {
bp = index - 1;
break;
}
}
if (value < 0) {
matchStat = NOT_MATCH;
return 0;
}
} else {
matchStat = NOT_MATCH;
return 0;
}
if (ch == ',') {
ch = buf[++bp];
matchStat = VALUE;
token = JSONToken.COMMA;
return value;
} else if (ch == '}') {
ch = buf[++bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
matchStat = NOT_MATCH;
return 0;
}
matchStat = END;
} else {
matchStat = NOT_MATCH;
return 0;
}
return value;
}
public float scanFieldFloat(char[] fieldName) {
matchStat = UNKOWN;
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
matchStat = NOT_MATCH_NAME;
return 0;
}
}
int index = bp + fieldNameLength;
char ch = buf[index++];
float value;
if (ch >= '0' && ch <= '9') {
int start = index - 1;
for (;;) {
ch = buf[index++];
if (ch >= '0' && ch <= '9') {
continue;
} else {
break;
}
}
if (ch == '.') {
ch = buf[index++];
if (ch >= '0' && ch <= '9') {
for (;;) {
ch = buf[index++];
if (ch >= '0' && ch <= '9') {
continue;
} else {
break;
}
}
} else {
matchStat = NOT_MATCH;
return 0;
}
}
bp = index - 1;
String text = new String(buf, start, index - start - 1);
value = Float.parseFloat(text);
} else {
matchStat = NOT_MATCH;
return 0;
}
if (ch == ',') {
ch = buf[++bp];
matchStat = VALUE;
token = JSONToken.COMMA;
return value;
} else if (ch == '}') {
ch = buf[++bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
matchStat = NOT_MATCH;
return 0;
}
matchStat = END;
} else {
matchStat = NOT_MATCH;
return 0;
}
return value;
}
public byte[] scanFieldByteArray(char[] fieldName) {
matchStat = UNKOWN;
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
matchStat = NOT_MATCH_NAME;
return null;
}
}
int index = bp + fieldNameLength;
char ch = buf[index++];
byte[] value;
if (ch == '"' || ch == '\'') {
char sep = ch;
int startIndex = index;
int endIndex = index;
for (endIndex = index; endIndex < buf.length; ++endIndex) {
if (buf[endIndex] == sep) {
break;
}
}
int base64Len = endIndex - startIndex;
value = Base64.decodeFast(buf, startIndex, base64Len);
if (value == null) {
matchStat = NOT_MATCH;
return null;
}
bp = endIndex + 1;
ch = buf[bp];
} else {
matchStat = NOT_MATCH;
return null;
}
if (ch == ',') {
ch = buf[++bp];
matchStat = VALUE;
token = JSONToken.COMMA;
return value;
} else if (ch == '}') {
ch = buf[++bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
matchStat = NOT_MATCH;
return null;
}
matchStat = END;
} else {
matchStat = NOT_MATCH;
return null;
}
return value;
}
public byte[] bytesValue() {
return Base64.decodeFast(buf, np + 1, sp);
}
public double scanFieldDouble(char[] fieldName) {
matchStat = UNKOWN;
final int fieldNameLength = fieldName.length;
for (int i = 0; i < fieldNameLength; ++i) {
if (fieldName[i] != buf[bp + i]) {
matchStat = NOT_MATCH_NAME;
return 0;
}
}
int index = bp + fieldNameLength;
char ch = buf[index++];
double value;
if (ch >= '0' && ch <= '9') {
int start = index - 1;
for (;;) {
ch = buf[index++];
if (ch >= '0' && ch <= '9') {
continue;
} else {
break;
}
}
if (ch == '.') {
ch = buf[index++];
if (ch >= '0' && ch <= '9') {
for (;;) {
ch = buf[index++];
if (ch >= '0' && ch <= '9') {
continue;
} else {
break;
}
}
} else {
matchStat = NOT_MATCH;
return 0;
}
}
bp = index - 1;
String text = new String(buf, start, index - start - 1);
value = Double.parseDouble(text);
} else {
matchStat = NOT_MATCH;
return 0;
}
if (ch == ',') {
ch = buf[++bp];
matchStat = VALUE;
token = JSONToken.COMMA;
} else if (ch == '}') {
ch = buf[++bp];
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = buf[++bp];
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = buf[++bp];
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = buf[++bp];
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
matchStat = NOT_MATCH;
return 0;
}
matchStat = END;
} else {
matchStat = NOT_MATCH;
return 0;
}
return value;
}
// public int scanField2(char[] fieldName, Object object, FieldDeserializer fieldDeserializer) {
// return NOT_MATCH;
// }
public String scanSymbol(final SymbolTable symbolTable) {
skipWhitespace();
if (ch == '"') {
return scanSymbol(symbolTable, '"');
}
if (ch == '\'') {
if (!isEnabled(Feature.AllowSingleQuotes)) {
throw new JSONException("syntax error");
}
return scanSymbol(symbolTable, '\'');
}
if (ch == '}') {
ch = buf[++bp];
token = JSONToken.RBRACE;
return null;
}
if (ch == ',') {
ch = buf[++bp];
token = JSONToken.COMMA;
return null;
}
if (ch == EOI) {
token = JSONToken.EOF;
return null;
}
if (!isEnabled(Feature.AllowUnQuotedFieldNames)) {
throw new JSONException("syntax error");
}
return scanSymbolUnQuoted(symbolTable);
}
public final String scanSymbol(final SymbolTable symbolTable, final char quote) {
int hash = 0;
np = bp;
sp = 0;
boolean hasSpecial = false;
char ch;
for (;;) {
ch = buf[++bp];
if (ch == quote) {
break;
}
if (ch == EOI) {
throw new JSONException("unclosed.str");
}
if (ch == '\\') {
if (!hasSpecial) {
hasSpecial = true;
if (sp >= sbuf.length) {
int newCapcity = sbuf.length * 2;
if (sp > newCapcity) {
newCapcity = sp;
}
char[] newsbuf = new char[newCapcity];
System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length);
sbuf = newsbuf;
}
System.arraycopy(buf, np + 1, sbuf, 0, sp);
}
ch = buf[++bp];
switch (ch) {
case '"':
hash = 31 * hash + (int) '"';
putChar('"');
break;
case '\\':
hash = 31 * hash + (int) '\\';
putChar('\\');
break;
case '/':
hash = 31 * hash + (int) '/';
putChar('/');
break;
case 'b':
hash = 31 * hash + (int) '\b';
putChar('\b');
break;
case 'f':
case 'F':
hash = 31 * hash + (int) '\f';
putChar('\f');
break;
case 'n':
hash = 31 * hash + (int) '\n';
putChar('\n');
break;
case 'r':
hash = 31 * hash + (int) '\r';
putChar('\r');
break;
case 't':
hash = 31 * hash + (int) '\t';
putChar('\t');
break;
case 'u':
char c1 = ch = buf[++bp];
char c2 = ch = buf[++bp];
char c3 = ch = buf[++bp];
char c4 = ch = buf[++bp];
int val = Integer.parseInt(new String(new char[] { c1, c2, c3, c4 }), 16);
hash = 31 * hash + val;
putChar((char) val);
break;
default:
this.ch = ch;
throw new JSONException("unclosed.str.lit");
}
continue;
}
hash = 31 * hash + ch;
if (!hasSpecial) {
sp++;
continue;
}
if (sp == sbuf.length) {
putChar(ch);
} else {
sbuf[sp++] = ch;
}
}
token = LITERAL_STRING;
this.ch = buf[++bp];
if (!hasSpecial) {
return symbolTable.addSymbol(buf, np + 1, sp, hash);
} else {
return symbolTable.addSymbol(sbuf, 0, sp, hash);
}
}
public void scanTrue() {
if (buf[bp++] != 't') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'r') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'u') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'e') {
throw new JSONException("error parse true");
}
ch = buf[bp];
if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI
|| ch == '\f' || ch == '\b') {
token = JSONToken.TRUE;
} else {
throw new JSONException("scan true error");
}
}
public void scanSet() {
if (buf[bp++] != 'S') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'e') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 't') {
throw new JSONException("error parse true");
}
ch = buf[bp];
if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b' || ch == '[' || ch == '(') {
token = JSONToken.SET;
} else {
throw new JSONException("scan set error");
}
}
public void scanTreeSet() {
if (buf[bp++] != 'T') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'r') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'e') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'e') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'S') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'e') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 't') {
throw new JSONException("error parse true");
}
ch = buf[bp];
if (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t' || ch == '\f' || ch == '\b' || ch == '[' || ch == '(') {
token = JSONToken.TREE_SET;
} else {
throw new JSONException("scan set error");
}
}
public void scanNullOrNew() {
if (buf[bp++] != 'n') {
throw new JSONException("error parse null or new");
}
if (buf[bp] == 'u') {
bp++;
if (buf[bp++] != 'l') {
throw new JSONException("error parse true");
}
if (buf[bp++] != 'l') {
throw new JSONException("error parse true");
}
ch = buf[bp];
if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI
|| ch == '\f' || ch == '\b') {
token = JSONToken.NULL;
} else {
throw new JSONException("scan true error");
}
return;
}
if (buf[bp] != 'e') {
throw new JSONException("error parse e");
}
bp++;
if (buf[bp++] != 'w') {
throw new JSONException("error parse w");
}
ch = buf[bp];
if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI
|| ch == '\f' || ch == '\b') {
token = JSONToken.NEW;
} else {
throw new JSONException("scan true error");
}
}
public void scanFalse() {
if (buf[bp++] != 'f') {
throw new JSONException("error parse false");
}
if (buf[bp++] != 'a') {
throw new JSONException("error parse false");
}
if (buf[bp++] != 'l') {
throw new JSONException("error parse false");
}
if (buf[bp++] != 's') {
throw new JSONException("error parse false");
}
if (buf[bp++] != 'e') {
throw new JSONException("error parse false");
}
ch = buf[bp];
if (ch == ' ' || ch == ',' || ch == '}' || ch == ']' || ch == '\n' || ch == '\r' || ch == '\t' || ch == EOI
|| ch == '\f' || ch == '\b') {
token = JSONToken.FALSE;
} else {
throw new JSONException("scan false error");
}
}
public void scanIdent() {
np = bp - 1;
hasSpecial = false;
for (;;) {
sp++;
ch = buf[++bp];
if (Character.isLetterOrDigit(ch)) {
continue;
}
String ident = stringVal();
Integer tok = keywods.getKeyword(ident);
if (tok != null) {
token = tok;
} else {
token = JSONToken.IDENTIFIER;
}
return;
}
}
public void scanNumber() {
np = bp;
if (ch == '-') {
sp++;
ch = buf[++bp];
}
for (;;) {
if (ch >= '0' && ch <= '9') {
sp++;
} else {
break;
}
ch = buf[++bp];
}
boolean isDouble = false;
if (ch == '.') {
sp++;
ch = buf[++bp];
isDouble = true;
for (;;) {
if (ch >= '0' && ch <= '9') {
sp++;
} else {
break;
}
ch = buf[++bp];
}
}
if (ch == 'L') {
sp++;
ch = buf[++bp];
} else if (ch == 'S') {
sp++;
ch = buf[++bp];
} else if (ch == 'B') {
sp++;
ch = buf[++bp];
} else if (ch == 'F') {
sp++;
ch = buf[++bp];
isDouble = true;
} else if (ch == 'D') {
sp++;
ch = buf[++bp];
isDouble = true;
} else if (ch == 'e' || ch == 'E') {
sp++;
ch = buf[++bp];
if (ch == '+' || ch == '-') {
sp++;
ch = buf[++bp];
}
for (;;) {
if (ch >= '0' && ch <= '9') {
sp++;
} else {
break;
}
ch = buf[++bp];
}
+
+ if (ch == 'D' || ch == 'F') {
+ ch = buf[++bp];
+ }
isDouble = true;
}
if (isDouble) {
token = JSONToken.LITERAL_FLOAT;
} else {
token = JSONToken.LITERAL_INT;
}
}
/**
* Append a character to sbuf.
*/
private final void putChar(char ch) {
if (sp == sbuf.length) {
char[] newsbuf = new char[sbuf.length * 2];
System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length);
sbuf = newsbuf;
}
sbuf[sp++] = ch;
}
/**
* Return the current token's position: a 0-based offset from beginning of the raw input stream (before unicode
* translation)
*/
public final int pos() {
return pos;
}
/**
* The value of a literal token, recorded as a string. For integers, leading 0x and 'l' suffixes are suppressed.
*/
public final String stringVal() {
if (!hasSpecial) {
return new String(buf, np + 1, sp);
} else {
return new String(sbuf, 0, sp);
}
}
//
public boolean isRef() {
if (hasSpecial) {
return false;
}
if (sp != 4) {
return false;
}
return buf[np + 1] == '$' && buf[np + 2] == 'r' && buf[np + 3] == 'e' && buf[np + 4] == 'f';
}
public final String symbol(SymbolTable symbolTable) {
if (symbolTable == null) {
if (!hasSpecial) {
return new String(buf, np + 1, sp);
} else {
return new String(sbuf, 0, sp);
}
}
if (!hasSpecial) {
return symbolTable.addSymbol(buf, np + 1, sp);
} else {
return symbolTable.addSymbol(sbuf, 0, sp);
}
}
private static final long MULTMIN_RADIX_TEN = Long.MIN_VALUE / 10;
private static final long N_MULTMAX_RADIX_TEN = -Long.MAX_VALUE / 10;
private static final int INT_MULTMIN_RADIX_TEN = Integer.MIN_VALUE / 10;
private static final int INT_N_MULTMAX_RADIX_TEN = -Integer.MAX_VALUE / 10;
private final static int[] digits = new int[(int) 'f' + 1];
static {
for (int i = '0'; i <= '9'; ++i) {
digits[i] = i - '0';
}
for (int i = 'a'; i <= 'f'; ++i) {
digits[i] = (i - 'a') + 10;
}
for (int i = 'A'; i <= 'F'; ++i) {
digits[i] = (i - 'A') + 10;
}
}
public Number integerValue() throws NumberFormatException {
long result = 0;
boolean negative = false;
int i = np, max = np + sp;
long limit;
long multmin;
int digit;
char type = ' ';
if (max > 0) {
switch (buf[max - 1]) {
case 'L':
max--;
type = 'L';
break;
case 'S':
max--;
type = 'S';
break;
case 'B':
max--;
type = 'B';
break;
default:
break;
}
}
if (buf[np] == '-') {
negative = true;
limit = Long.MIN_VALUE;
i++;
} else {
limit = -Long.MAX_VALUE;
}
multmin = negative ? MULTMIN_RADIX_TEN : N_MULTMAX_RADIX_TEN;
if (i < max) {
digit = digits[buf[i++]];
result = -digit;
}
while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = digits[buf[i++]];
if (result < multmin) {
return new BigInteger(numberString());
}
result *= 10;
if (result < limit + digit) {
return new BigInteger(numberString());
}
result -= digit;
}
if (negative) {
if (i > np + 1) {
if (result >= Integer.MIN_VALUE && type != 'L') {
if (type == 'S') {
return (short) result;
}
if (type == 'B') {
return (byte) result;
}
return (int) result;
}
return result;
} else { /* Only got "-" */
throw new NumberFormatException(numberString());
}
} else {
result = -result;
if (result <= Integer.MAX_VALUE && type != 'L') {
if (type == 'S') {
return (short) result;
}
if (type == 'B') {
return (byte) result;
}
return (int) result;
}
return result;
}
}
public long longValue() throws NumberFormatException {
long result = 0;
boolean negative = false;
int i = np, max = np + sp;
long limit;
long multmin;
int digit;
if (buf[np] == '-') {
negative = true;
limit = Long.MIN_VALUE;
i++;
} else {
limit = -Long.MAX_VALUE;
}
multmin = negative ? MULTMIN_RADIX_TEN : N_MULTMAX_RADIX_TEN;
if (i < max) {
digit = digits[buf[i++]];
result = -digit;
}
while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
char ch = buf[i++];
if (ch == 'L' || ch == 'S' || ch == 'B') {
break;
}
digit = digits[ch];
if (result < multmin) {
throw new NumberFormatException(numberString());
}
result *= 10;
if (result < limit + digit) {
throw new NumberFormatException(numberString());
}
result -= digit;
}
if (negative) {
if (i > np + 1) {
return result;
} else { /* Only got "-" */
throw new NumberFormatException(numberString());
}
} else {
return -result;
}
}
public int intValue() {
int result = 0;
boolean negative = false;
int i = np, max = np + sp;
int limit;
int multmin;
int digit;
if (buf[np] == '-') {
negative = true;
limit = Integer.MIN_VALUE;
i++;
} else {
limit = -Integer.MAX_VALUE;
}
multmin = negative ? INT_MULTMIN_RADIX_TEN : INT_N_MULTMAX_RADIX_TEN;
if (i < max) {
digit = digits[buf[i++]];
result = -digit;
}
while (i < max) {
// Accumulating negatively avoids surprises near MAX_VALUE
char ch = buf[i++];
if (ch == 'L' || ch == 'S' || ch == 'B') {
break;
}
digit = digits[ch];
if (result < multmin) {
throw new NumberFormatException(numberString());
}
result *= 10;
if (result < limit + digit) {
throw new NumberFormatException(numberString());
}
result -= digit;
}
if (negative) {
if (i > np + 1) {
return result;
} else { /* Only got "-" */
throw new NumberFormatException(numberString());
}
} else {
return -result;
}
}
public final String numberString() {
char ch = buf[np + sp - 1];
int sp = this.sp;
if (ch == 'L' || ch == 'S' || ch == 'B' || ch == 'F' || ch == 'D') {
sp--;
}
return new String(buf, np, sp);
}
public float floatValue() {
return Float.parseFloat(numberString());
}
public double doubleValue() {
return Double.parseDouble(numberString());
}
public Number decimalValue(boolean decimal) {
char ch = buf[np + sp - 1];
if (ch == 'F') {
return Float.parseFloat(new String(buf, np, sp - 1));
}
if (ch == 'D') {
return Double.parseDouble(new String(buf, np, sp - 1));
}
if (decimal) {
return decimalValue();
} else {
return doubleValue();
}
}
public BigDecimal decimalValue() {
char ch = buf[np + sp - 1];
int sp = this.sp;
if (ch == 'L' || ch == 'S' || ch == 'B' || ch == 'F' || ch == 'D') {
sp--;
}
return new BigDecimal(buf, np, sp);
}
public void config(Feature feature, boolean state) {
features = Feature.config(features, feature, state);
}
public boolean isEnabled(Feature feature) {
return Feature.isEnabled(this.features, feature);
}
public final int ISO8601_LEN_0 = "0000-00-00".length();
public final int ISO8601_LEN_1 = "0000-00-00T00:00:00".length();
public final int ISO8601_LEN_2 = "0000-00-00T00:00:00.000".length();
public boolean scanISO8601DateIfMatch() {
int rest = buflen - bp;
if (rest < ISO8601_LEN_0) {
return false;
}
char y0 = buf[bp];
char y1 = buf[bp + 1];
char y2 = buf[bp + 2];
char y3 = buf[bp + 3];
if (y0 != '1' && y0 != '2') {
return false;
}
if (y1 < '0' || y1 > '9') {
return false;
}
if (y2 < '0' || y2 > '9') {
return false;
}
if (y3 < '0' || y3 > '9') {
return false;
}
if (buf[bp + 4] != '-') {
return false;
}
char M0 = buf[bp + 5];
char M1 = buf[bp + 6];
if (M0 == '0') {
if (M1 < '1' || M1 > '9') {
return false;
}
} else if (M0 == '1') {
if (M1 != '0' && M1 != '1' && M1 != '2') {
return false;
}
} else {
return false;
}
if (buf[bp + 7] != '-') {
return false;
}
char d0 = buf[bp + 8];
char d1 = buf[bp + 9];
if (d0 == '0') {
if (d1 < '1' || d1 > '9') {
return false;
}
} else if (d0 == '1' || d0 == '2') {
if (d1 < '0' || d1 > '9') {
return false;
}
} else if (d0 == '3') {
if (d1 != '0' && d1 != '1') {
return false;
}
} else {
return false;
}
Locale local = Locale.getDefault();
calendar = Calendar.getInstance(TimeZone.getDefault(), local);
int year = digits[y0] * 1000 + digits[y1] * 100 + digits[y2] * 10 + digits[y3];
int month = digits[M0] * 10 + digits[M1] - 1;
int day = digits[d0] * 10 + digits[d1];
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
char t = buf[bp + 10];
if (t == 'T') {
if (rest < ISO8601_LEN_1) {
return false;
}
} else if (t == '"' || t == EOI) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
ch = buf[bp += 10];
token = JSONToken.LITERAL_ISO8601_DATE;
return true;
} else {
return false;
}
char h0 = buf[bp + 11];
char h1 = buf[bp + 12];
if (h0 == '0') {
if (h1 < '0' || h1 > '9') {
return false;
}
} else if (h0 == '1') {
if (h1 < '0' || h1 > '9') {
return false;
}
} else if (h0 == '2') {
if (h1 < '0' || h1 > '4') {
return false;
}
} else {
return false;
}
if (buf[bp + 13] != ':') {
return false;
}
char m0 = buf[bp + 14];
char m1 = buf[bp + 15];
if (m0 >= '0' && m0 <= '5') {
if (m1 < '0' || m1 > '9') {
return false;
}
} else if (m0 == '6') {
if (m1 != '0') {
return false;
}
} else {
return false;
}
if (buf[bp + 16] != ':') {
return false;
}
char s0 = buf[bp + 17];
char s1 = buf[bp + 18];
if (s0 >= '0' && s0 <= '5') {
if (s1 < '0' || s1 > '9') {
return false;
}
} else if (s0 == '6') {
if (s1 != '0') {
return false;
}
} else {
return false;
}
int hour = digits[h0] * 10 + digits[h1];
int minute = digits[m0] * 10 + digits[m1];
int seconds = digits[s0] * 10 + digits[s1];
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, seconds);
char dot = buf[bp + 19];
if (dot == '.') {
if (rest < ISO8601_LEN_2) {
return false;
}
} else {
calendar.set(Calendar.MILLISECOND, 0);
ch = buf[bp += 19];
token = JSONToken.LITERAL_ISO8601_DATE;
return true;
}
char S0 = buf[bp + 20];
char S1 = buf[bp + 21];
char S2 = buf[bp + 22];
if (S0 < '0' || S0 > '9') {
return false;
}
if (S1 < '0' || S1 > '9') {
return false;
}
if (S2 < '0' || S2 > '9') {
return false;
}
int millis = digits[S0] * 100 + digits[S1] * 10 + digits[S2];
calendar.set(Calendar.MILLISECOND, millis);
ch = buf[bp += 23];
token = JSONToken.LITERAL_ISO8601_DATE;
return true;
}
public Calendar getCalendar() {
return this.calendar;
}
public boolean isEOF() {
switch (token) {
case JSONToken.EOF:
return true;
case JSONToken.ERROR:
return false;
case JSONToken.RBRACE:
return false;
default:
return false;
}
}
public void close() {
if (sbuf.length <= 1024 * 8) {
sbufRefLocal.set(new SoftReference<char[]>(sbuf));
}
this.sbuf = null;
}
}
| true | false | null | null |
diff --git a/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java b/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
index 29c475638..2a77d06f6 100644
--- a/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
+++ b/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
@@ -1,63 +1,63 @@
package org.drools.analytics;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.drools.StatelessSession;
import org.drools.analytics.components.AnalyticsRule;
import org.drools.analytics.dao.AnalyticsDataFactory;
import org.drools.analytics.dao.AnalyticsResult;
import org.drools.analytics.report.components.AnalyticsMessage;
import org.drools.analytics.report.components.AnalyticsMessageBase;
import org.drools.base.RuleNameMatchesAgendaFilter;
/**
*
* @author Toni Rikkola
*
*/
public class ConsequenceTest extends TestBase {
public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
- AnalyticsDataFactory.getAnalyticsData();
+ AnalyticsDataFactory.clearAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
}
| true | true | public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
AnalyticsDataFactory.getAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
| public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
AnalyticsDataFactory.clearAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
|
diff --git a/src/core/org/pathvisio/gpmldiff/PwyElt.java b/src/core/org/pathvisio/gpmldiff/PwyElt.java
index 43ccd400..5e13f3e3 100644
--- a/src/core/org/pathvisio/gpmldiff/PwyElt.java
+++ b/src/core/org/pathvisio/gpmldiff/PwyElt.java
@@ -1,118 +1,118 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// 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.pathvisio.gpmldiff;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.pathvisio.model.ObjectType;
import org.pathvisio.model.PathwayElement;
import org.pathvisio.model.PropertyType;
/**
Utility class for pathway element methods related to gpmldiff.
*/
class PwyElt
{
static String summary(PathwayElement elt)
{
if (elt == null) return "null"; // TODO, why is this necessary?
String result = "[" + ObjectType.getTagMapping (elt.getObjectType());
Set<PropertyType> props = elt.getStaticPropertyKeys();
if (props.contains(PropertyType.TEXTLABEL))
result += ",lbl=" + elt.getStaticProperty(PropertyType.TEXTLABEL);
if (props.contains(PropertyType.WIDTH))
result += ",w=" + elt.getStaticProperty(PropertyType.WIDTH);
if (props.contains(PropertyType.HEIGHT))
result += ",h=" + elt.getStaticProperty(PropertyType.HEIGHT);
if (props.contains(PropertyType.CENTERX))
result += ",cx=" + elt.getStaticProperty(PropertyType.CENTERX);
if (props.contains(PropertyType.CENTERY))
result += ",cy=" + elt.getStaticProperty(PropertyType.CENTERY);
if (props.contains(PropertyType.STARTX))
result += ",x1=" + elt.getStaticProperty(PropertyType.STARTX);
if (props.contains(PropertyType.STARTY))
result += ",y1=" + elt.getStaticProperty(PropertyType.STARTY);
if (props.contains(PropertyType.ENDX))
result += ",x2=" + elt.getStaticProperty(PropertyType.ENDX);
if (props.contains(PropertyType.ENDY))
result += ",y2=" + elt.getStaticProperty(PropertyType.ENDY);
if (props.contains(PropertyType.GRAPHID))
result += ",id=" + elt.getStaticProperty(PropertyType.GRAPHID);
if (props.contains(PropertyType.STARTGRAPHREF))
result += ",startref=" + elt.getStaticProperty(PropertyType.STARTGRAPHREF);
if (props.contains(PropertyType.ENDGRAPHREF))
result += ",endref=" + elt.getStaticProperty(PropertyType.ENDGRAPHREF);
if (props.contains(PropertyType.MAPINFONAME))
- result += ",name=" + elt.getStaticProperty(PropertyType.MAPINFONAME);
+ result += ",title=" + elt.getStaticProperty(PropertyType.MAPINFONAME);
if (props.contains(PropertyType.AUTHOR))
result += ",author=" + elt.getStaticProperty(PropertyType.AUTHOR);
result += "]";
return result;
}
static Map<String, String> getContents(PathwayElement elt)
{
Map<String, String> result = new HashMap<String, String>();
for (PropertyType prop : elt.getStaticPropertyKeys())
{
String attr = prop.tag();
String val = "" + elt.getStaticProperty (prop);
result.put (attr, val);
}
return result;
}
/**
Show detailed modifications compared to another elt
call on oldElt.
*/
static void writeModifications (PathwayElement oldElt, PathwayElement newElt, DiffOutputter outputter)
{
Map<String, String> oldContents = getContents (oldElt);
Map<String, String> newContents = getContents (newElt);
boolean opened = false; // indicates if modifyStart has been
// sent already for current PwyElt.
for (String key : oldContents.keySet())
{
if (key.equals ("BoardWidth") || key.equals ("BoardHeight"))
{
// ignore board width and height
continue;
}
if (newContents.containsKey(key))
{
if (!oldContents.get(key).equals(newContents.get(key)))
{
if (!opened)
{
outputter.modifyStart (oldElt, newElt);
opened = true;
}
outputter.modifyAttr (key, oldContents.get(key), newContents.get(key));
}
}
}
if (opened)
{
outputter.modifyEnd();
opened = false;
}
}
}
\ No newline at end of file
diff --git a/src/core/org/pathvisio/model/PropertyType.java b/src/core/org/pathvisio/model/PropertyType.java
index 4f4b826e..32273fad 100644
--- a/src/core/org/pathvisio/model/PropertyType.java
+++ b/src/core/org/pathvisio/model/PropertyType.java
@@ -1,180 +1,180 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// 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.
//
/*
* PropertyType.java
*
* Created on 6 december 2006, 9:50
*
*/
package org.pathvisio.model;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Martijn
*/
public enum PropertyType
{
// all
COMMENTS ("Comments", "Comments", PropertyClass.COMMENTS),
// line, shape, datanode, label
COLOR ("Color", "Color", PropertyClass.COLOR),
// shape, datanode, label
CENTERX ("CenterX", "Center X", PropertyClass.DOUBLE),
CENTERY ("CenterY", "Center Y", PropertyClass.DOUBLE),
// shape, datanode, label, modification
WIDTH ("Width", "Width", PropertyClass.DOUBLE),
HEIGHT ("Height", "Height", PropertyClass.DOUBLE),
// modification
RELX ("CenterX", "Center X", PropertyClass.DOUBLE),
RELY ("CenterY", "Center Y", PropertyClass.DOUBLE),
GRAPHREF ("GraphRef", "GraphRef", PropertyClass.STRING),
// shape, modification
TRANSPARENT ("Transparent", "Transparent", PropertyClass.BOOLEAN),
FILLCOLOR ("FillColor", "Fill Color", PropertyClass.COLOR),
SHAPETYPE ("ShapeType", "Shape Type", PropertyClass.SHAPETYPE),
// shape
ROTATION ("Rotation", "Rotation", PropertyClass.ANGLE),
// line
STARTX ("StartX", "Start X", PropertyClass.DOUBLE),
STARTY ("StartY", "Start Y", PropertyClass.DOUBLE),
ENDX ("EndX", "End X", PropertyClass.DOUBLE),
ENDY ("EndY", "End Y", PropertyClass.DOUBLE),
ENDLINETYPE ("EndLineType", "End Line Type", PropertyClass.LINETYPE),
STARTLINETYPE ("StartLineType", "Start Line Type", PropertyClass.LINETYPE),
// line, shape and modification
LINESTYLE ("LineStyle", "Line Style", PropertyClass.LINESTYLE),
// brace
ORIENTATION ("Orientation", "Orientation", PropertyClass.ORIENTATION),
// datanode
GENEID ("GeneID", "Database Identifier", PropertyClass.DB_ID),
DATASOURCE ("SystemCode", "Database Name", PropertyClass.DATASOURCE),
GENMAPP_XREF ("Xref", "Xref", PropertyClass.STRING), // deprecated, maintained for backward compatibility with GenMAPP.
BACKPAGEHEAD ("BackpageHead", "Backpage head", PropertyClass.STRING),
TYPE ("Type", "Type", PropertyClass.GENETYPE),
MODIFICATIONTYPE ("ModificationType", "ModificationType", PropertyClass.STRING),
// label, modification, datanode
TEXTLABEL ("TextLabel", "Text Label", PropertyClass.STRING),
// label
FONTNAME ("FontName", "Font Name", PropertyClass.FONT),
FONTWEIGHT ("FontWeight", "Bold", PropertyClass.BOOLEAN),
FONTSTYLE ("FontStyle", "Italic", PropertyClass.BOOLEAN),
FONTSIZE ("FontSize", "Font Size", PropertyClass.DOUBLE),
OUTLINE ("Outline", "Outline", PropertyClass.OUTLINETYPE),
// mappinfo
- MAPINFONAME ("MapInfoName", "Map Info Name", PropertyClass.STRING),
+ MAPINFONAME ("MapInfoName", "Title", PropertyClass.STRING),
ORGANISM ("Organism", "Organism", PropertyClass.ORGANISM),
MAPINFO_DATASOURCE ("Data-Source", "Data-Source", PropertyClass.STRING),
VERSION ("Version", "Version", PropertyClass.STRING),
AUTHOR ("Author", "Author", PropertyClass.STRING),
MAINTAINED_BY ("Maintained-By", "Maintainer", PropertyClass.STRING),
EMAIL ("Email", "Email", PropertyClass.STRING),
LAST_MODIFIED ("Last-Modified", "Last Modified", PropertyClass.STRING),
AVAILABILITY ("Availability", "Availability", PropertyClass.STRING),
BOARDWIDTH ("BoardWidth", "Board Width", PropertyClass.DOUBLE),
BOARDHEIGHT ("BoardHeight", "Board Height", PropertyClass.DOUBLE),
WINDOWWIDTH ("WindowWidth", "Window Width", PropertyClass.DOUBLE, true),
WINDOWHEIGHT ("WindowHeight", "Window Height", PropertyClass.DOUBLE, true),
// other
GRAPHID ("GraphId", "GraphId", PropertyClass.STRING),
STARTGRAPHREF ("StartGraphRef", "StartGraphRef", PropertyClass.STRING),
ENDGRAPHREF ("EndGraphRef", "EndGraphRef", PropertyClass.STRING),
GROUPID ("GroupId", "GroupId", PropertyClass.STRING),
GROUPREF ("GroupRef", "GroupRef", PropertyClass.STRING),
GROUPSTYLE ("GroupStyle", "Group style", PropertyClass.GROUPSTYLETYPE),
BIOPAXREF( "BiopaxRef", "BiopaxRef", PropertyClass.BIOPAXREF),
ZORDER ( "Z order", "ZOrder", PropertyClass.INTEGER);
private String tag, desc;
private PropertyClass type;
private boolean hidden;
PropertyType (String _tag, String _desc, PropertyClass _type, boolean _hidden)
{
tag = _tag;
type = _type;
desc = _desc;
hidden = _hidden;
}
PropertyType (String _tag, String _desc, PropertyClass _type)
{
this(_tag, _desc, _type, false);
}
public String tag()
{
return tag;
}
public String desc()
{
return desc;
}
public PropertyClass type()
{
return type;
}
public boolean isHidden()
{
return hidden;
}
public void setHidden(boolean hide) {
hidden = hide;
}
public static PropertyType getByTag(String value)
{
return tagMapping.get (value);
}
static private Map<String, PropertyType> tagMapping = initTagMapping();
static private Map<String, PropertyType> initTagMapping()
{
Map<String, PropertyType> result = new HashMap<String, PropertyType>();
for (PropertyType o : PropertyType.values())
{
result.put (o.tag(), o);
}
return result;
}
}
diff --git a/src/core/org/pathvisio/view/InfoBox.java b/src/core/org/pathvisio/view/InfoBox.java
index 7931987c..2d5f1bb7 100644
--- a/src/core/org/pathvisio/view/InfoBox.java
+++ b/src/core/org/pathvisio/view/InfoBox.java
@@ -1,146 +1,146 @@
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2007 BiGCaT Bioinformatics
//
// 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.pathvisio.view;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import org.pathvisio.model.PathwayElement;
/**
* //TODO: view.InfoBox corresponds in some ways to
* model.PathwayElement(ObjectType.MAPPINFO) and in some ways to
* model.PathwayElement(ObjectType.INFOBOX).
* This confusion is rooted in inconsistencies in GPML.
* This should be cleaned up one day.
*/
public class InfoBox extends Graphics {
static final int V_SPACING = 5;
static final int H_SPACING = 10;
static final int INITIAL_SIZE = 200;
//Elements not stored in gpml
String fontName = "Times New Roman";
String fontWeight = "regular";
static final double M_INITIAL_FONTSIZE = 10.0 * 15;
int sizeX = 1;
int sizeY = 1; //Real size is calculated on first call to draw()
public InfoBox (VPathway canvas, PathwayElement o) {
super(canvas, o);
canvas.setMappInfo(this);
}
//public Point getBoardSize() { return new Point((int)gdata.getMBoardWidth(), (int)gdata.getMBoardHeight()); }
int getVFontSize()
{
return (int)(vFromM(M_INITIAL_FONTSIZE));
}
protected void vMoveBy(double vdx, double vdy)
{
// markDirty();
gdata.setMTop (gdata.getMTop() + mFromV(vdy));
gdata.setMLeft (gdata.getMLeft() + mFromV(vdx));
// markDirty();
}
public void doDraw(Graphics2D g)
{
Font f = new Font(fontName, Font.PLAIN, getVFontSize());
Font fb = new Font(f.getFontName(), Font.BOLD, f.getSize());
if(isSelected()) {
g.setColor(selectColor);
}
//Draw Name, Organism, Data-Source, Version, Author, Maintained-by, Email, Availability and last modified
String[][] text = new String[][] {
- {"Name: ", gdata.getMapInfoName()},
+ {"Title: ", gdata.getMapInfoName()},
{"Maintained by: ", gdata.getMaintainer()},
{"Email: ", gdata.getEmail()},
{"Availability: ", gdata.getCopyright()},
{"Last modified: ", gdata.getLastModified()},
{"Organism: ", gdata.getOrganism()},
{"Data Source: ", gdata.getMapInfoDataSource()}
};
int shift = 0;
int vLeft = (int)vFromM(gdata.getMLeft());
int vTop = (int)vFromM(gdata.getMTop());
int newSizeX = sizeX;
int newSizeY = sizeY;
FontRenderContext frc = g.getFontRenderContext();
for(String[] s : text)
{
if(s[1] == null || s[1].equals("")) continue; //Skip empty labels
TextLayout tl0 = new TextLayout(s[0], fb, frc);
TextLayout tl1 = new TextLayout(s[1], f, frc);
Rectangle2D b0 = tl0.getBounds();
Rectangle2D b1 = tl1.getBounds();
shift += (int)Math.max(b0.getHeight(), b1.getHeight()) + V_SPACING;
g.setFont(fb);
tl0.draw(g, vLeft, vTop + shift);
g.setFont(f);
tl1.draw(g, vLeft + (int)b0.getWidth() + H_SPACING, vTop + shift);
// add 10 for safety
newSizeX = Math.max(
newSizeX,
(int)b0.getWidth() + (int)b1.getWidth() + H_SPACING + 10);
}
newSizeY = shift + 10; // add 10 for safety
// if the size was incorrect, mark dirty and draw again.
// note: we can't draw again right away because the clip rect
// is set to a too small region.
if (newSizeX != sizeX || newSizeY != sizeY)
{
sizeX = newSizeX;
sizeY = newSizeY;
markDirty();
canvas.redrawDirtyRect();
}
}
protected Shape getVShape(boolean rotate) {
double vLeft = vFromM(gdata.getMLeft());
double vTop = vFromM(gdata.getMTop());
double vW = sizeX;
double vH = sizeY;
if(vW == 1 && vH == 1) {
vW = INITIAL_SIZE;
vH = INITIAL_SIZE;
}
return new Rectangle2D.Double(vLeft, vTop, vW, vH);
}
protected void setVScaleRectangle(Rectangle2D r) {
//Do nothing, can't resize infobox
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/controllers/movement/MovementType.java b/AE-go_GameServer/src/com/aionemu/gameserver/controllers/movement/MovementType.java
index e8cfadda..795b54b2 100644
--- a/AE-go_GameServer/src/com/aionemu/gameserver/controllers/movement/MovementType.java
+++ b/AE-go_GameServer/src/com/aionemu/gameserver/controllers/movement/MovementType.java
@@ -1,87 +1,91 @@
/*
* This file is part of aion-emu <aion-emu.com>.
*
* aion-emu 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.
*
* aion-emu 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 aion-emu. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.controllers.movement;
/**
* Contains all possible movement types. Its used by CM_MOVE, SM_MOVE and controller.
*
* @author -Nemesiss-
*
*/
public enum MovementType
{
/**
* Movement by mouse.
*/
MOVEMENT_START_MOUSE(-32),
/**
* Movement by keyboard.
*/
MOVEMENT_START_KEYBOARD(-64),
/**
* Validation (movement by mouse).
*/
VALIDATE_MOUSE(-96),
/**
* Validation (movement by keyboard).
*/
VALIDATE_KEYBOARD(-128),
/**
* Validation (jump).
*/
VALIDATE_JUMP(8),
/**
+ * Validation (jump while moving).
+ */
+ VALIDATE_JUMP_WHILE_MOVING(72),
+ /**
* Movement stop.
*/
MOVEMENT_STOP(0);
private int typeId;
/**
* Constructor.
*
* @param typeId
*/
private MovementType(int typeId)
{
this.typeId = typeId;
}
/**
* Get id of this MovementType
* @return id.
*/
public int getMovementTypeId()
{
return typeId;
}
/**
* Return MovementType by id.
* @param id
* @return MovementType
*/
public static MovementType getMovementTypeById(int id)
{
for(MovementType mt : values())
{
if(mt.typeId == id)
return mt;
}
throw new IllegalArgumentException("Unsupported movement type: " + id);
}
}
\ No newline at end of file
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_EMOTION.java b/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_EMOTION.java
index 7379d68a..832220fb 100644
--- a/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_EMOTION.java
+++ b/AE-go_GameServer/src/com/aionemu/gameserver/network/aion/clientpackets/CM_EMOTION.java
@@ -1,100 +1,100 @@
/*
* This file is part of aion-emu <aion-emu.com>.
*
* aion-emu 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.
*
* aion-emu 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 aion-emu. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.network.aion.clientpackets;
import org.apache.log4j.Logger;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.AionClientPacket;
import com.aionemu.gameserver.network.aion.serverpackets.SM_EMOTION;
import com.aionemu.gameserver.utils.PacketSendUtility;
/**
* @author SoulKeeper
*/
public class CM_EMOTION extends AionClientPacket
{
/**
* Logger
*/
private static final Logger log = Logger.getLogger(CM_EMOTION.class);
/**
* Can 0x11 or 0x10
*/
int unknown;
/**
* Emotion number
*/
int emotion;
int ObjID;
private int monsterToAttackId;
/**
* Constructs new client packet instance.
* @param opcode
*/
public CM_EMOTION(int opcode)
{
super(opcode);
}
/**
* Read data
*/
@Override
protected void readImpl()
{
unknown = readC();
if(unknown == 0x01)
{
// jump
}
else if(unknown == 0x11)
{
// Nothing here
}
else if(unknown == 0x10)
{
emotion = readH();
}
else if(unknown == 0x13)
{
- emotion = readH();
+ //emotion = readH();
}
else
{
log.info("Unknown emotion type? 0x" + Integer.toHexString(unknown).toUpperCase());
}
}
/**
* Send emotion packet
*/
@Override
protected void runImpl()
{
Player player = getConnection().getActivePlayer();
PacketSendUtility.broadcastPacket(player, new SM_EMOTION(player.getObjectId(), unknown, emotion), true);
}
}
| false | false | null | null |
diff --git a/src/net/java/sip/communicator/impl/resources/ResourceManagementServiceImpl.java b/src/net/java/sip/communicator/impl/resources/ResourceManagementServiceImpl.java
index cd66625fd..8c7283aeb 100644
--- a/src/net/java/sip/communicator/impl/resources/ResourceManagementServiceImpl.java
+++ b/src/net/java/sip/communicator/impl/resources/ResourceManagementServiceImpl.java
@@ -1,676 +1,679 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.resources;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import org.osgi.framework.*;
/**
* A default implementation of the ResourceManagementService.
*
* @author Damian Minkov
* @author Yana Stamcheva
* @author Lubomir Marinov
*/
public class ResourceManagementServiceImpl
implements ResourceManagementService,
ServiceListener
{
private static Logger logger =
Logger.getLogger(ResourceManagementServiceImpl.class);
private Map<String, String> colorResources;
private ResourcePack colorPack = null;
private Map<String, String> imageResources;
private ResourcePack imagePack = null;
private Map<String, String> languageResources;
private LanguagePack languagePack = null;
/**
* The {@link Locale} of <code>languageResources</code> so that the caching
* of the latter can be used when a string with the same <code>Locale</code>
* is requested.
*/
private Locale languageLocale;
private Map<String, String> settingsResources;
private ResourcePack settingsPack = null;
private Map<String, String> soundResources;
private ResourcePack soundPack = null;
/**
* Initializes already registered default resource packs.
*/
ResourceManagementServiceImpl()
{
ResourceManagementActivator.bundleContext.addServiceListener(this);
colorPack =
getDefaultResourcePack(ColorPack.class.getName(),
ColorPack.RESOURCE_NAME_DEFAULT_VALUE);
if (colorPack != null)
colorResources = getResources(colorPack);
imagePack =
getDefaultResourcePack(ImagePack.class.getName(),
ImagePack.RESOURCE_NAME_DEFAULT_VALUE);
if (imagePack != null)
imageResources = getResources(imagePack);
// changes the default locale if set in the config
String defaultLocale = (String)ResourceManagementActivator.
getConfigurationService().getProperty(DEFAULT_LOCALE_CONFIG);
if(defaultLocale != null)
Locale.setDefault(
ResourceManagementServiceUtils.getLocale(defaultLocale));
languagePack =
(LanguagePack) getDefaultResourcePack(LanguagePack.class.getName(),
LanguagePack.RESOURCE_NAME_DEFAULT_VALUE);
if (languagePack != null)
{
languageLocale = Locale.getDefault();
languageResources = languagePack.getResources(languageLocale);
}
settingsPack =
getDefaultResourcePack(SettingsPack.class.getName(),
SettingsPack.RESOURCE_NAME_DEFAULT_VALUE);
if (settingsPack != null)
settingsResources = getResources(settingsPack);
soundPack =
getDefaultResourcePack(SoundPack.class.getName(),
SoundPack.RESOURCE_NAME_DEFAULT_VALUE);
if (soundPack != null)
soundResources = getResources(soundPack);
}
/**
* Searches for the <tt>ResourcePack</tt> corresponding to the given
* <tt>className</tt> and <tt></tt>.
* @param className The name of the resource class.
* @param typeName The name of the type we're looking for.
* For example: RESOURCE_NAME_DEFAULT_VALUE
* @return the <tt>ResourcePack</tt> corresponding to the given
* <tt>className</tt> and <tt></tt>.
*/
private ResourcePack getDefaultResourcePack(String className,
String typeName)
{
ServiceReference[] serRefs = null;
String osgiFilter =
"(" + ResourcePack.RESOURCE_NAME + "=" + typeName + ")";
try
{
serRefs = ResourceManagementActivator
.bundleContext.getServiceReferences(
className,
osgiFilter);
}
catch (InvalidSyntaxException exc)
{
logger.error("Could not obtain resource packs reference.", exc);
}
if ((serRefs != null) && (serRefs.length > 0))
{
return (ResourcePack)
ResourceManagementActivator.bundleContext.getService(serRefs[0]);
}
return null;
}
/**
* Returns the <tt>Map</tt> of (key, value) pairs contained in the given
* resource pack.
*
* @param resourcePack The <tt>ResourcePack</tt> from which we're obtaining
* the resources.
* @return the <tt>Map</tt> of (key, value) pairs contained in the given
* resource pack.
*/
private Map<String, String> getResources(ResourcePack resourcePack)
{
return resourcePack.getResources();
}
/**
* Handles all <tt>ServiceEvent</tt>s corresponding to <tt>ResourcePack</tt>
* being registered or unregistered.
*/
public void serviceChanged(ServiceEvent event)
{
Object sService = ResourceManagementActivator.bundleContext.getService(
event.getServiceReference());
if (!(sService instanceof ResourcePack))
{
return;
}
ResourcePack resourcePack = (ResourcePack) sService;
if (event.getType() == ServiceEvent.REGISTERED)
{
logger.info("Resource registered " + resourcePack);
Map<String, String> resources = getResources(resourcePack);
if(resourcePack instanceof ColorPack && colorPack == null)
{
colorPack = resourcePack;
colorResources = resources;
}
else if(resourcePack instanceof ImagePack && imagePack == null)
{
imagePack = resourcePack;
imageResources = resources;
}
else if(resourcePack instanceof LanguagePack && languagePack == null)
{
languagePack = (LanguagePack) resourcePack;
languageLocale = Locale.getDefault();
languageResources = resources;
}
else if(resourcePack instanceof SettingsPack && settingsPack == null)
{
settingsPack = resourcePack;
settingsResources = resources;
}
else if(resourcePack instanceof SoundPack && soundPack == null)
{
soundPack = resourcePack;
soundResources = resources;
}
}
else if (event.getType() == ServiceEvent.UNREGISTERING)
{
if(resourcePack instanceof ColorPack
&& colorPack.equals(resourcePack))
{
colorPack =
getDefaultResourcePack(ColorPack.class.getName(),
ColorPack.RESOURCE_NAME_DEFAULT_VALUE);
if (colorPack != null)
colorResources = getResources(colorPack);
}
else if(resourcePack instanceof ImagePack
&& imagePack.equals(resourcePack))
{
imagePack =
getDefaultResourcePack(ImagePack.class.getName(),
ImagePack.RESOURCE_NAME_DEFAULT_VALUE);
if (imagePack != null)
imageResources = getResources(imagePack);
}
else if(resourcePack instanceof LanguagePack
&& languagePack.equals(resourcePack))
{
languagePack =
(LanguagePack) getDefaultResourcePack(
LanguagePack.class.getName(),
LanguagePack.RESOURCE_NAME_DEFAULT_VALUE);
}
else if(resourcePack instanceof SettingsPack
&& settingsPack.equals(resourcePack))
{
settingsPack =
getDefaultResourcePack(SettingsPack.class.getName(),
SettingsPack.RESOURCE_NAME_DEFAULT_VALUE);
if (settingsPack != null)
settingsResources = getResources(settingsPack);
}
else if(resourcePack instanceof SoundPack
&& soundPack.equals(resourcePack))
{
soundPack =
getDefaultResourcePack(SoundPack.class.getName(),
SoundPack.RESOURCE_NAME_DEFAULT_VALUE);
if (soundPack != null)
soundResources = getResources(soundPack);
}
}
}
/**
* Returns the int representation of the color corresponding to the
* given key.
*
* @param key The key of the color in the colors properties file.
* @return the int representation of the color corresponding to the
* given key.
*/
public int getColor(String key)
{
String res = colorResources.get(key);
if(res == null)
{
logger.error("Missing color resource for key: " + key);
return 0xFFFFFF;
}
else
return Integer.parseInt(res, 16);
}
/**
* Returns the string representation of the color corresponding to the
* given key.
*
* @param key The key of the color in the colors properties file.
* @return the string representation of the color corresponding to the
* given key.
*/
public String getColorString(String key)
{
String res = colorResources.get(key);
if(res == null)
{
logger.error("Missing color resource for key: " + key);
return "0xFFFFFF";
}
else
return res;
}
/**
* Returns the <tt>InputStream</tt> of the image corresponding to the given
* path.
*
* @param path The path to the image file.
* @return the <tt>InputStream</tt> of the image corresponding to the given
* path.
*/
public InputStream getImageInputStreamForPath(String path)
{
return imagePack.getClass().getClassLoader().getResourceAsStream(path);
}
/**
* Returns the <tt>InputStream</tt> of the image corresponding to the given
* key.
*
* @param streamKey The identifier of the image in the resource properties
* file.
* @return the <tt>InputStream</tt> of the image corresponding to the given
* key.
*/
public InputStream getImageInputStream(String streamKey)
{
String path = imageResources.get(streamKey);
if (path == null || path.length() == 0)
{
logger.warn("Missing resource for key: " + streamKey);
return null;
}
return getImageInputStreamForPath(path);
}
/**
* Returns the <tt>URL</tt> of the image corresponding to the given key.
*
* @param urlKey The identifier of the image in the resource properties file.
* @return the <tt>URL</tt> of the image corresponding to the given key
*/
public URL getImageURL(String urlKey)
{
String path = imageResources.get(urlKey);
if (path == null || path.length() == 0)
{
logger.info("Missing resource for key: " + urlKey);
return null;
}
return getImageURLForPath(path);
}
/**
* Returns the image path corresponding to the given key.
*
* @param key The identifier of the image in the resource properties file.
* @return the image path corresponding to the given key.
*/
public String getImagePath(String key)
{
return imageResources.get(key);
}
/**
* Returns the <tt>URL</tt> of the image corresponding to the given path.
*
* @param path The path to the given image file.
* @return the <tt>URL</tt> of the image corresponding to the given path.
*/
public URL getImageURLForPath(String path)
{
return imagePack.getClass().getClassLoader().getResource(path);
}
// Language pack methods
/**
* All the locales in the language pack.
* @return all the locales this Language pack contains.
*/
public Iterator<Locale> getAvailableLocales()
{
return languagePack.getAvailableLocales();
}
/**
* Returns an internationalized string corresponding to the given key.
*
* @param key The identifier of the string in the resources properties file.
* @return An internationalized string corresponding to the given key.
*/
public String getI18NString(String key)
{
return getI18NString(key, Locale.getDefault());
}
/**
* Returns an internationalized string corresponding to the given key.
*
* @param key The identifier of the string in the resources properties file.
* @param locale The locale.
* @return An internationalized string corresponding to the given key and
* given locale.
*/
public String getI18NString(String key, Locale locale)
{
return getI18NString(key, null, locale);
}
/**
* Returns an internationalized string corresponding to the given key.
*
* @param key The identifier of the string.
* @return An internationalized string corresponding to the given key.
*/
public String getI18NString(String key, String[] params)
{
return getI18NString(key, params, Locale.getDefault());
}
/**
* Returns an internationalized string corresponding to the given key.
*
* @param key The identifier of the string in the resources properties
* file.
* @param locale The locale.
* @return An internationalized string corresponding to the given key.
*/
public String getI18NString(String key, String[] params, Locale locale)
{
Map<String, String> stringResources;
if ((locale != null) && locale.equals(languageLocale))
{
stringResources = languageResources;
}
else
{
stringResources = languagePack.getResources(locale);
}
String resourceString = stringResources.get(key);
if (resourceString == null)
{
logger.warn("Missing resource for key: " + key);
return '!' + key + '!';
}
int mnemonicIndex = resourceString.indexOf('&');
if (mnemonicIndex == 0
|| (mnemonicIndex > 0
&& resourceString.charAt(mnemonicIndex - 1) != '\\'))
{
String firstPart = resourceString.substring(0, mnemonicIndex);
String secondPart = resourceString.substring(mnemonicIndex + 1);
resourceString = firstPart.concat(secondPart);
}
if (resourceString.indexOf('\\') > -1)
{
resourceString = resourceString.replaceAll("\\\\", "");
}
if(params != null)
resourceString
= MessageFormat.format(resourceString, (Object[])params);
return resourceString;
}
/**
* Returns an internationalized string corresponding to the given key.
*
* @param key The identifier of the string in the resources properties file.
* @return An internationalized string corresponding to the given key.
*/
public char getI18nMnemonic(String key)
{
return getI18nMnemonic(key, Locale.getDefault());
}
/**
* Returns an internationalized string corresponding to the given key.
*
* @param key The identifier of the string in the resources properties file.
* @param locale The locale that we'd like to receive the result in.
* @return An internationalized string corresponding to the given key.
*/
public char getI18nMnemonic(String key, Locale locale)
{
Map<String, String> stringResources;
if ((locale != null) && locale.equals(languageLocale))
{
stringResources = languageResources;
}
else
{
stringResources = languagePack.getResources(locale);
}
String resourceString = stringResources.get(key);
if (resourceString == null)
{
logger.warn("Missing resource for key: " + key);
return 0;
}
int mnemonicIndex = resourceString.indexOf('&');
if (mnemonicIndex > -1)
{
return resourceString.charAt(mnemonicIndex + 1);
}
return 0;
}
/**
* Returns the int value of the corresponding configuration key.
*
* @param key The identifier of the string in the resources properties file.
* @return the int value of the corresponding configuration key.
*/
public String getSettingsString(String key)
{
return settingsResources.get(key);
}
/**
* Returns the int value of the corresponding configuration key.
*
* @param key The identifier of the string in the resources properties file.
* @return the int value of the corresponding configuration key.
*/
public int getSettingsInt(String key)
{
String resourceString = settingsResources.get(key);
if (resourceString == null)
{
logger.warn("Missing resource for key: " + key);
return 0;
}
return Integer.parseInt(resourceString);
}
/**
* Returns an <tt>URL</tt> from a given identifier.
*
* @param urlKey The identifier of the url.
* @return The url for the given identifier.
*/
public URL getSettingsURL(String urlKey)
{
String path = settingsResources.get(urlKey);
if (path == null || path.length() == 0)
{
logger.warn("Missing resource for key: " + urlKey);
return null;
}
return settingsPack.getClass().getClassLoader().getResource(path);
}
/**
* Returns a stream from a given identifier.
*
* @param streamKey The identifier of the stream.
* @return The stream for the given identifier.
*/
public InputStream getSettingsInputStream(String streamKey)
{
String path = settingsResources.get(streamKey);
if (path == null || path.length() == 0)
{
logger.warn("Missing resource for key: " + streamKey);
return null;
}
return settingsPack.getClass()
.getClassLoader().getResourceAsStream(path);
}
/**
* Returns the <tt>URL</tt> of the sound corresponding to the given
* property key.
*
* @return the <tt>URL</tt> of the sound corresponding to the given
* property key.
*/
public URL getSoundURL(String urlKey)
{
String path = soundResources.get(urlKey);
if (path == null || path.length() == 0)
{
logger.warn("Missing resource for key: " + urlKey);
return null;
}
return getSoundURLForPath(path);
}
/**
* Returns the <tt>URL</tt> of the sound corresponding to the given path.
*
* @return the <tt>URL</tt> of the sound corresponding to the given path.
*/
public URL getSoundURLForPath(String path)
{
return soundPack.getClass().getClassLoader().getResource(path);
}
/**
* Returns the path of the sound corresponding to the given
* property key.
*
* @return the path of the sound corresponding to the given
* property key.
*/
public String getSoundPath(String soundKey)
{
return soundResources.get(soundKey);
}
/**
* Loads an image from a given image identifier.
*
* @param imageID The identifier of the image.
* @return The image for the given identifier.
*/
public byte[] getImageInBytes(String imageID)
{
InputStream in = getImageInputStream(imageID);
if(in == null)
return null;
byte[] image = null;
try
{
image = new byte[in.available()];
in.read(image);
}
catch (IOException e)
{
logger.error("Failed to load image:" + imageID, e);
}
return image;
}
/**
* Loads an image from a given image identifier.
*
* @param imageID The identifier of the image.
* @return The image for the given identifier.
*/
public ImageIcon getImage(String imageID)
{
URL imageURL = getImageURL(imageID);
-
+ if (imageURL == null)
+ {
+ return null;
+ }
return new ImageIcon(imageURL);
}
}
| true | false | null | null |
diff --git a/src/main/java/org/unigram/docvalidator/parser/PlainTextParser.java b/src/main/java/org/unigram/docvalidator/parser/PlainTextParser.java
index b0492843..9e21f282 100644
--- a/src/main/java/org/unigram/docvalidator/parser/PlainTextParser.java
+++ b/src/main/java/org/unigram/docvalidator/parser/PlainTextParser.java
@@ -1,108 +1,110 @@
/**
* DocumentValidator
* Copyright (c) 2013-, Takahiko Ito, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 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.
*/
package org.unigram.docvalidator.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unigram.docvalidator.store.FileContent;
import org.unigram.docvalidator.store.Paragraph;
import org.unigram.docvalidator.store.Section;
import org.unigram.docvalidator.store.Sentence;
import org.unigram.docvalidator.util.DocumentValidatorException;
import org.unigram.docvalidator.util.StringUtils;
/**
* Parser for plain text file.
*/
public final class PlainTextParser extends BasicDocumentParser {
/**
* Constructor.
*/
public PlainTextParser() {
super();
}
public FileContent generateDocument(String fileName)
throws DocumentValidatorException {
InputStream iStream = this.loadStream(fileName);
FileContent content = this.generateDocument(iStream);
content.setFileName(fileName);
return content;
}
public FileContent generateDocument(InputStream is) {
BufferedReader br = createReader(is);
FileContent fileContent = new FileContent();
List<Sentence> headers = new ArrayList<Sentence>();
+ headers.add(new Sentence("", 0));
+
fileContent.appendSection(new Section(0, headers));
Section currentSection = fileContent.getLastSection();
currentSection.appendParagraph(new Paragraph());
try {
String remain = new String("");
String line;
int lineNum = 0;
while ((line = br.readLine()) != null) {
int periodPosition =
StringUtils.getSentenceEndPosition(line, this.period);
if (line.equals("")) {
currentSection.appendParagraph(new Paragraph());
} else if (periodPosition == -1) {
remain = remain + line;
} else {
remain =
this.extractSentences(lineNum, remain + line, currentSection);
}
lineNum++;
}
if (remain.length() > 0) {
currentSection.appendSentence(remain, lineNum);
}
} catch (IOException e) {
LOG.error("Failed to parse: " + e.getMessage());
return null;
}
return fileContent;
}
private String extractSentences(int lineNum, String line,
Section currentSection) {
int periodPosition = StringUtils.getSentenceEndPosition(line, this.period);
if (periodPosition == -1) {
return line;
} else {
while (true) {
currentSection.appendSentence(
line.substring(0, periodPosition + 1), lineNum);
line = line.substring(periodPosition + 1, line.length());
periodPosition = StringUtils.getSentenceEndPosition(line, this.period);
if (periodPosition == -1) {
return line;
}
}
}
}
private static Logger LOG = LoggerFactory.getLogger(PlainTextParser.class);
}
diff --git a/src/main/java/org/unigram/docvalidator/parser/WikiParser.java b/src/main/java/org/unigram/docvalidator/parser/WikiParser.java
index 32571536..312f446f 100644
--- a/src/main/java/org/unigram/docvalidator/parser/WikiParser.java
+++ b/src/main/java/org/unigram/docvalidator/parser/WikiParser.java
@@ -1,303 +1,306 @@
/**
l * DocumentValidator
* Copyright (c) 2013-, Takahiko Ito, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 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.
*/
package org.unigram.docvalidator.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import org.unigram.docvalidator.store.FileContent;
import org.unigram.docvalidator.store.Paragraph;
import org.unigram.docvalidator.store.Section;
import org.unigram.docvalidator.store.Sentence;
import org.unigram.docvalidator.util.DocumentValidatorException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Parser for wiki formatted file.
*/
public final class WikiParser extends BasicDocumentParser {
/**
* Constructor.
*/
public WikiParser() {
super();
}
public FileContent generateDocument(String fileName)
throws DocumentValidatorException {
InputStream inputStream = this.loadStream(fileName);
return this.generateDocument(inputStream);
}
public FileContent generateDocument(InputStream is) {
BufferedReader br = createReader(is);
if (br == null) {
LOG.error("Failed to create reader");
return null;
}
FileContent fileContent = new FileContent();
// for sentences right below the beginning of document
List<Sentence> headers = new ArrayList<Sentence>();
+ headers.add(new Sentence("", 0));
Section currentSection = new Section(0, headers);
fileContent.appendSection(currentSection);
+
+ // begin parsing
LinePattern prevPattern, currentPattern = LinePattern.VOID;
- String line;
+ String line = null;
int lineNum = 0;
String remain = "";
try {
while ((line = br.readLine()) != null) {
prevPattern = currentPattern;
Vector<String> head = new Vector<String>();
if (currentPattern == LinePattern.COMMENT) {
if (check(END_COMMENT_PATTERN, line, head)) {
currentPattern = LinePattern.VOID;
}
} else if (check(HEADER_PATTERN, line, head)) {
currentPattern = LinePattern.HEADER;
currentSection = appendSection(fileContent, currentSection, head,
lineNum);
} else if (check(LIST_PATTERN, line, head)) {
currentPattern = LinePattern.LIST;
appendListElement(currentSection, prevPattern, head, lineNum);
} else if (check(NUMBERED_LIST_PATTERN, line, head)) {
currentPattern = LinePattern.LIST;
appendListElement(currentSection, prevPattern, head, lineNum);
} else if (check(BEGIN_COMMENT_PATTERN, line, head)) {
if (!check(END_COMMENT_PATTERN, line, head)) { // skip comment
currentPattern = LinePattern.COMMENT;
}
} else if (line.equals("")) { // new paragraph content
currentSection.appendParagraph(new Paragraph());
} else { // usual sentence.
currentPattern = LinePattern.SENTENCE;
remain = appendSentencesIntoSection(lineNum, remain + line,
currentSection);
}
prevPattern = currentPattern;
lineNum++;
}
} catch (IOException e) {
LOG.error("Failed to parse input document: " + e.getMessage());
return null;
}
if (remain.length() > 0) {
appendLastSentence(fileContent, lineNum, remain);
}
return fileContent;
}
private void appendListElement(Section currentSection,
LinePattern prevPattern, Vector<String> head, int lineNum) {
if (prevPattern != LinePattern.LIST) {
currentSection.appendListBlock();
}
List<Sentence> outputSentences = new ArrayList<Sentence>();
String remainSentence= obtainSentences(0, head.get(1), outputSentences);
currentSection.appendListElement(extractListLevel(head.get(0)),
outputSentences);
// NOTE: for list content without period
if (remainSentence != null && remainSentence.length() > 0) {
outputSentences.add(new Sentence(remainSentence, lineNum));
}
}
private Section appendSection(FileContent fileContent,
Section currentSection, Vector<String> head, int lineNum) {
Integer level = Integer.valueOf(head.get(0));
List<Sentence> outputSentences = new ArrayList<Sentence>();
- String remainHeader = obtainSentences(0, head.get(1), outputSentences);
+ String remainHeader = obtainSentences(lineNum, head.get(1), outputSentences);
// NOTE: for header without period
if (remainHeader != null && remainHeader.length() > 0) {
outputSentences.add(new Sentence(remainHeader, lineNum));
}
Section tmpSection = new Section(level, outputSentences);
fileContent.appendSection(tmpSection);
if (!addChild(currentSection, tmpSection)) {
LOG.warn("Failed to add parent for a Seciotn: "
+ tmpSection.getHeaderContents().next());
}
currentSection = tmpSection;
return currentSection;
}
private void appendLastSentence(FileContent doc, int lineNum, String remain) {
Sentence sentence = new Sentence(remain, lineNum);
parseSentence(sentence); // extract inline elements
doc.getLastSection().appendSentence(sentence);
}
private void parseSentence(Sentence sentence) {
extractLinks(sentence);
removeTags(sentence);
}
private void removeTags(Sentence sentence) {
String content = sentence.content;
for (int i = 0; i< INLINE_PATTERNS.length; ++i) {
Matcher m = INLINE_PATTERNS[i].matcher(content);
content= m.replaceAll("$1");
}
sentence.content = content;
}
private void extractLinks(Sentence sentence) {
String modContent = "";
int start = 0;
Matcher m = LINK_PATTERN.matcher(sentence.content);
while (m.find()) {
String[] tagInternal = m.group(1).split("\\|");
String tagURL = tagInternal[0].trim();
if (tagInternal.length > 2) {
modContent += sentence.content.substring(
start, m.start()) + tagInternal[1].trim();
} else {
modContent += sentence.content.substring(start, m.start())
+ tagURL.trim();
}
sentence.links.add(tagURL);
start = m.end();
}
if (start > 0) {
modContent += sentence.content.substring(
start, sentence.content.length());
sentence.content = modContent;
}
}
private boolean addChild(Section candidate, Section child) {
if (candidate.getLevel() < child.getLevel()) {
candidate.appendSubSection(child);
child.setParentSection(candidate);
} else { // search parent
Section parent = candidate.getParentSection();
while (parent != null) {
if (parent.getLevel() < child.getLevel()) {
parent.appendSubSection(child);
child.setParentSection(parent);
candidate = child;
break;
}
parent = parent.getParentSection();
}
if (parent == null) {
return false;
}
}
return true;
}
private String obtainSentences(int lineNum, String line,
List<Sentence> outputSentences) {
String remain = ParseUtils.extractSentences(line, this.period,
outputSentences);
for (Sentence sentence : outputSentences) {
sentence.position = lineNum;
parseSentence(sentence); // extract inline elements
}
return remain;
}
private String appendSentencesIntoSection(int lineNum, String line,
Section currentSection) {
List<Sentence> outputSentences = new ArrayList<Sentence>();
String remain = obtainSentences(lineNum, line, outputSentences);
for (Sentence sentence : outputSentences) {
currentSection.appendSentence(sentence);
}
return remain;
}
private static boolean check(Pattern p, String target, Vector<String> head) {
Matcher m = p.matcher(target);
if (m.matches()) {
for (int i = 1; i <= m.groupCount(); i++) {
head.add(m.group(i));
}
return true;
} else {
return false;
}
}
private int extractListLevel(String listPrefix) {
return listPrefix.length();
}
private static Logger LOG = LoggerFactory.getLogger(WikiParser.class);
/**
* List of elements used in wiki format.
*/
private enum LinePattern {
SENTENCE, LIST, NUM_LIST, VOID, HEADER, COMMENT
}
/****************************************************************************
* patterns to handle wiki syntax
***************************************************************************/
private static final Pattern HEADER_PATTERN
= Pattern.compile("^h([1-6])\\. (.*)$");
private static final Pattern LIST_PATTERN = Pattern.compile("^(-+) (.*)$");
private static final Pattern NUMBERED_LIST_PATTERN =
Pattern.compile("^(#+) (.*)$");
private static final Pattern LINK_PATTERN =
Pattern.compile("\\[\\[(.+?)\\]\\]");
private static final Pattern BEGIN_COMMENT_PATTERN =
Pattern.compile("\\s*^\\[!--");
private static final Pattern END_COMMENT_PATTERN =
Pattern.compile("--\\]$\\s*");
private static final Pattern ITALIC_PATTERN =
Pattern.compile("//(.+?)//");
private static final Pattern UNDERLINE_PATTERN =
Pattern.compile("__(.+?)__");
private static final Pattern BOLD_PATTERN =
Pattern.compile("\\*\\*(.+?)\\*\\*");
private static final Pattern STRIKETHROUGH_PATTERN =
Pattern.compile("--(.+?)--");
private static final Pattern [] INLINE_PATTERNS = {
ITALIC_PATTERN,
BOLD_PATTERN,
UNDERLINE_PATTERN,
STRIKETHROUGH_PATTERN
};
}
diff --git a/src/test/java/org/unigram/docvalidator/parser/PlainTextParserTest.java b/src/test/java/org/unigram/docvalidator/parser/PlainTextParserTest.java
index a7eeb28a..0de4d2b8 100644
--- a/src/test/java/org/unigram/docvalidator/parser/PlainTextParserTest.java
+++ b/src/test/java/org/unigram/docvalidator/parser/PlainTextParserTest.java
@@ -1,151 +1,153 @@
/**
* DocumentValidator
* Copyright (c) 2013-, Takahiko Ito, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 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.
*/
package org.unigram.docvalidator.parser;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Vector;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.unigram.docvalidator.util.ValidationConfigurationLoader;
import org.unigram.docvalidator.store.FileContent;
import org.unigram.docvalidator.store.Paragraph;
import org.unigram.docvalidator.store.Section;
import org.unigram.docvalidator.util.DVResource;
import org.unigram.docvalidator.util.DocumentValidatorException;
public class PlainTextParserTest {
private Parser parser = null;
private DVResource resource;
private Vector<Paragraph> extractParagraphs(Section section) {
Iterator<Paragraph> paragraph = section.getParagraphs();
Vector<Paragraph> paragraphs = new Vector<Paragraph>();
while(paragraph.hasNext()) {
Paragraph p = paragraph.next();
paragraphs.add(p);
}
return paragraphs;
}
private int calcLineNum(Section section) {
Iterator<Paragraph> paragraph = section.getParagraphs();
int lineNum = 0;
while(paragraph.hasNext()) {
Paragraph p = paragraph.next();
lineNum += p.getNumberOfSentences();
}
return lineNum;
}
private FileContent generateDocument(String sampleText) {
InputStream is = null;
try {
is = new ByteArrayInputStream(sampleText.getBytes("utf-8"));
} catch (UnsupportedEncodingException e1) {
fail();
}
FileContent doc = null;
try {
doc = parser.generateDocument(is);
} catch (DocumentValidatorException e) {
fail();
}
return doc;
}
private String sampleConfiguraitonStr = new String(
"<?xml version=\"1.0\"?>" +
"<component name=\"Validator\">" +
" <component name=\"SentenceIterator\">" +
" <component name=\"LineLength\">"+
" <property name=\"max_length\" value=\"10\"/>" +
" </component>" +
" </component>" +
"</component>");
@Before
public void setup() {
InputStream stream = IOUtils.toInputStream(this.sampleConfiguraitonStr);
this.resource =
new DVResource(ValidationConfigurationLoader.loadConfiguraiton(stream));
if (this.resource == null) {
fail();
}
try {
parser = DocumentParserFactory.generate("plain", resource);
} catch (DocumentValidatorException e1) {
fail();
e1.printStackTrace();
}
}
@Test
public void testGenerateDocument() {
String sampleText = "";
sampleText += "This is a pen.\n";
sampleText += "That is a orange.\n";
sampleText += "\n";
sampleText += "However, pen is not oranges.\n";
sampleText += "We need to be peisient.\n";
sampleText += "\n";
sampleText += "Happ life.\n";
sampleText += "Happy home.\n";
sampleText += "Tama Home.\n";
FileContent doc = generateDocument(sampleText);
Section section = doc.getLastSection();
assertEquals(7 ,calcLineNum(section));
assertEquals(3, extractParagraphs(section).size());
}
@Test
public void testGenerateDocumentWithMultipleSentenceInOneLine() {
String sampleText = "Tokyu is a good railway company. ";
sampleText += "The company is reliable. In addition it is rich. ";
sampleText += "I like the company. Howerver someone does not like it.";
String[] expectedResult = {"Tokyu is a good railway company.",
" The company is reliable.", " In addition it is rich.",
" I like the company.", " Howerver someone does not like it."};
FileContent doc = generateDocument(sampleText);
Section section = doc.getLastSection();
Vector<Paragraph> paragraphs = extractParagraphs(section);
assertEquals(1, paragraphs.size());
assertEquals(5 ,calcLineNum(section));
Paragraph paragraph = paragraphs.lastElement();
for (int i=0; i<expectedResult.length; i++) {
assertEquals(expectedResult[i], paragraph.getSentence(i).content);
}
+ assertEquals(0, section.getHeaderContent(0).position);
+ assertEquals("", section.getHeaderContent(0).content);
}
@Test
public void testGenerateDocumentWithNoContent() {
String sampleText = "";
FileContent doc = generateDocument(sampleText);
Section section = doc.getLastSection();
Vector<Paragraph> paragraphs = extractParagraphs(section);
assertEquals(1, paragraphs.size());
assertEquals(0 ,calcLineNum(section));
}
}
diff --git a/src/test/java/org/unigram/docvalidator/parser/WikiParserTest.java b/src/test/java/org/unigram/docvalidator/parser/WikiParserTest.java
index 31d14322..9dd2d9ba 100644
--- a/src/test/java/org/unigram/docvalidator/parser/WikiParserTest.java
+++ b/src/test/java/org/unigram/docvalidator/parser/WikiParserTest.java
@@ -1,558 +1,563 @@
/**
* DocumentValidator
* Copyright (c) 2013-, Takahiko Ito, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 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.
*/
package org.unigram.docvalidator.parser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.unigram.docvalidator.util.ValidationConfigurationLoader;
import org.unigram.docvalidator.store.FileContent;
import org.unigram.docvalidator.store.ListBlock;
import org.unigram.docvalidator.store.Paragraph;
import org.unigram.docvalidator.store.Section;
import org.unigram.docvalidator.util.CharacterTable;
import org.unigram.docvalidator.util.CharacterTableLoader;
import org.unigram.docvalidator.util.ValidatorConfiguration;
import org.unigram.docvalidator.util.DVResource;
import org.unigram.docvalidator.util.DocumentValidatorException;
public class WikiParserTest {
@Before
public void setup() {
}
@Test
public void testBasicDocument() throws UnsupportedEncodingException {
String sampleText = "";
sampleText += "h1. About Gekioko.\n";
sampleText += "Gekioko pun pun maru means very very angry.\n";
sampleText += "\n";
sampleText += "The word also have posive meaning.\n";
sampleText += "h1. About Gunma.\n";
sampleText += "\n";
sampleText += "Gunma is located at west of Saitama.\n";
sampleText += "- Features\n";
sampleText += "-- Main City: Gumma City\n";
sampleText += "-- Capical: 200 Millon\n";
sampleText += "- Location\n";
sampleText += "-- Japan\n";
sampleText += "\n";
sampleText += "The word also have posive meaning. Hower it is a bit wired.";
FileContent doc = createFileContent(sampleText);
assertEquals(3, doc.getNumberOfSections());
Section lastSection = doc.getSection(doc.getNumberOfSections()-1);
assertEquals(1, lastSection.getNumberOfLists());
assertEquals(5, lastSection.getListBlock(0).getNumberOfListElements());
assertEquals(2,lastSection.getNumberOfParagraphs());
assertEquals(1, lastSection.getHeaderContentsListSize());
assertEquals("About Gunma.", lastSection.getHeaderContent(0).content);
}
@Test
public void testGenerateDocumentWithList() {
String sampleText =
"Threre are several railway companies in Japan as follows.\n";
sampleText += "- Tokyu\n";
sampleText += "-- Toyoko Line\n";
sampleText += "-- Denentoshi Line\n";
sampleText += "- Keio\n";
sampleText += "- Odakyu\n";
FileContent doc = createFileContent(sampleText);
assertEquals(5, doc.getSection(0).getListBlock(0).getNumberOfListElements());
}
@Test
public void testGenerateDocumentWithNumberedList() {
String sampleText =
"Threre are several railway companies in Japan as follows.\n";
sampleText += "# Tokyu\n";
sampleText += "## Toyoko Line\n";
sampleText += "## Denentoshi Line\n";
sampleText += "# Keio\n";
sampleText += "# Odakyu\n";
FileContent doc = createFileContent(sampleText);
assertEquals(5, doc.getSection(0).getListBlock(0).getNumberOfListElements());
}
@Test
public void testGenerateDocumentWithOneLineComment() {
String sampleText =
"There are various tests.\n";
sampleText += "[!-- The following should be exmples --]\n";
sampleText += "Most common one is unit test.\n";
sampleText += "Integration test is also common.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(3, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWithMultiLinesComment() {
String sampleText =
"There are various tests.\n";
sampleText += "[!-- \n";
sampleText += "The following should be exmples\n";
sampleText += "--]\n";
sampleText += "Most common one is unit test.\n";
sampleText += "Integration test is also common.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(3, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWithMultiLinesComment2() {
String sampleText =
"There are various tests.\n";
sampleText += "[!-- \n";
sampleText += "The following should be exmples\n";
sampleText += "In addition the histories should be described\n";
sampleText += "--]\n";
sampleText += "Most common one is unit test.\n";
sampleText += "Integration test is also common.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(3, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWithVoidComment() {
String sampleText =
"There are various tests.\n";
sampleText += "[!----]\n";
sampleText += "Most common one is unit test.\n";
sampleText += "Integration test is also common.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(3, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWithOnlySpaceComment() {
String sampleText =
"There are various tests.\n";
sampleText += "[!-- --]\n";
sampleText += "Most common one is unit test.\n";
sampleText += "Integration test is also common.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(3, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWithCommentHavingHeadSpace() {
String sampleText =
"There are various tests.\n";
sampleText += " [!-- BLAH BLAH --]\n";
sampleText += "Most common one is unit test.\n";
sampleText += "Integration test is also common.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(3, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWithCommentHavingTailingSpace() {
String sampleText =
"There are various tests.\n";
sampleText += "[!-- BLAH BLAH --] \n";
sampleText += "Most common one is unit test.\n";
sampleText += "Integration test is also common.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(3, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWithMultiLinesCommentHavingSpaces() {
String sampleText =
"There are various tests.\n";
sampleText += " [!-- \n";
sampleText += "The following should be exmples\n";
sampleText += "In addition the histories should be described\n";
sampleText += "--] \n";
sampleText += "Most common one is unit test.\n";
sampleText += "Integration test is also common.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(3, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWithMultipleSentenceInOneSentence() {
String sampleText =
"Tokyu is a good railway company. The company is reliable. In addition it is rich.";
String[] expectedResult = {"Tokyu is a good railway company.",
" The company is reliable.", " In addition it is rich."};
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(3, firstParagraph.getNumberOfSentences());
for (int i=0; i<expectedResult.length; i++) {
assertEquals(expectedResult[i], firstParagraph.getSentence(i).content);
}
}
@Test
public void testGenerateDocumentWithMultipleSentenceInMultipleSentences() {
String sampleText = "Tokyu is a good railway company. The company is reliable. In addition it is rich.\n";
sampleText += "I like the company. Howerver someone does not like it.";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(5, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWitVoidContent() {
String sampleText = "";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
assertEquals(false, firstSections.getParagraphs().hasNext());
}
@Test
public void testGenerateDocumentWithPeriodInSuccession() {
String sampleText = "...";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(1, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWitoutPeriodInLastSentence() {
String sampleText = "Hongo is located at the west of Tokyo. Saitama is located at the north";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(2, firstParagraph.getNumberOfSentences());
}
@Test
public void testGenerateDocumentWithSentenceLongerThanOneLine() {
String sampleText = "This is a good day.\n";
sampleText += "Hongo is located at the west of Tokyo ";
sampleText += "which is the capital of Japan ";
sampleText += "which is not located in the south of the earth.";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(2, firstParagraph.getNumberOfSentences());
}
@Test
public void testPlainLink() {
String sampleText = "this is not a [[pen]], but also this is not [[Google|http://google.com]] either.";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(1, firstParagraph.getNumberOfSentences());
assertEquals(2, firstParagraph.getSentence(0).links.size());
assertEquals("pen", firstParagraph.getSentence(0).links.get(0));
assertEquals("Google", firstParagraph.getSentence(0).links.get(1));
assertEquals("this is not a pen, but also this is not Google either.",
firstParagraph.getSentence(0).content);
}
@Test
public void testPlainLinkWithSpaces() {
String sampleText = "the url is not [[Google | http://google.com ]].";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(1, firstParagraph.getNumberOfSentences());
assertEquals(1, firstParagraph.getSentence(0).links.size());
assertEquals("Google", firstParagraph.getSentence(0).links.get(0));
assertEquals("the url is not Google.",
firstParagraph.getSentence(0).content);
}
@Test
public void testLinkWithoutTag() {
String sampleText = "url of google is [[http://google.com]].";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(1, firstParagraph.getNumberOfSentences());
assertEquals(1, firstParagraph.getSentence(0).links.size());
assertEquals("http://google.com", firstParagraph.getSentence(0).links.get(0));
assertEquals("url of google is http://google.com.",
firstParagraph.getSentence(0).content);
}
@Test
public void testIncompleteLink() {
String sampleText = "url of google is [[http://google.com.";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(1, firstParagraph.getNumberOfSentences());
assertEquals(0, firstParagraph.getSentence(0).links.size());
assertEquals("url of google is [[http://google.com.",
firstParagraph.getSentence(0).content);
}
@Test
public void testDocumentWithItalicWord() {
String sampleText = "This is a //good// day.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals("This is a good day.", firstParagraph.getSentence(0).content);
}
@Test
public void testDocumentWithMultipleItalicWords() {
String sampleText = "//This// is a //good// day.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals("This is a good day.", firstParagraph.getSentence(0).content);
}
@Test
public void testDocumentWithMultipleNearItalicWords() {
String sampleText = "This is //a// //good// day.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals("This is a good day.", firstParagraph.getSentence(0).content);
}
@Test
public void testDocumentWithItalicExpression() {
String sampleText = "This is //a good// day.\n";
FileContent doc = createFileContent(sampleText);
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals("This is a good day.", firstParagraph.getSentence(0).content);
}
@Test
public void testDocumentWithHeaderCotainingMultipleSentences()
throws UnsupportedEncodingException {
String sampleText = "";
sampleText += "h1. About Gunma. About Saitama.\n";
sampleText += "Gunma is located at west of Saitama.\n";
sampleText += "The word also have posive meaning. Hower it is a bit wired.";
FileContent doc = createFileContent(sampleText);
Section lastSection = doc.getSection(doc.getNumberOfSections()-1);
assertEquals(2, lastSection.getHeaderContentsListSize());
assertEquals("About Gunma.", lastSection.getHeaderContent(0).content);
assertEquals(" About Saitama.", lastSection.getHeaderContent(1).content);
}
@Test
public void testDocumentWithHeaderWitoutPeriod()
throws UnsupportedEncodingException {
String sampleText = "";
sampleText += "h1. About Gunma\n";
sampleText += "Gunma is located at west of Saitama.\n";
sampleText += "The word also have posive meaning. Hower it is a bit wired.";
FileContent doc = createFileContent(sampleText);
Section lastSection = doc.getSection(doc.getNumberOfSections()-1);
assertEquals(1, lastSection.getHeaderContentsListSize());
assertEquals("About Gunma", lastSection.getHeaderContent(0).content);
}
@Test
public void testDocumentWithList()
throws UnsupportedEncodingException {
String sampleText = "";
sampleText += "h1. About Gunma. About Saitama.\n";
sampleText += "- Gunma is located at west of Saitama.\n";
sampleText += "- The word also have posive meaning. Hower it is a bit wired.";
FileContent doc = createFileContent(sampleText);
Section lastSection = doc.getSection(doc.getNumberOfSections()-1);
ListBlock listBlock = lastSection.getListBlock(0);
assertEquals(2, listBlock.getNumberOfListElements());
assertEquals(1, listBlock.getListElement(0).getNumberOfSentences());
assertEquals("Gunma is located at west of Saitama.",
listBlock.getListElement(0).getSentence(0).content);
assertEquals("The word also have posive meaning.",
listBlock.getListElement(1).getSentence(0).content);
assertEquals(" Hower it is a bit wired.",
listBlock.getListElement(1).getSentence(1).content);
}
@Test
public void testDocumentWithListWithoutPeriod()
throws UnsupportedEncodingException {
String sampleText = "";
sampleText += "h1. About Gunma. About Saitama.\n";
sampleText += "- Gunma is located at west of Saitama\n";
FileContent doc = createFileContent(sampleText);
Section lastSection = doc.getSection(doc.getNumberOfSections()-1);
ListBlock listBlock = lastSection.getListBlock(0);
assertEquals(1, listBlock.getNumberOfListElements());
assertEquals(1, listBlock.getListElement(0).getNumberOfSentences());
assertEquals("Gunma is located at west of Saitama",
listBlock.getListElement(0).getSentence(0).content);
}
@Test
- public void testDocumentWithSections() throws UnsupportedEncodingException {
+ public void testDocumentWithMultipleSections()
+ throws UnsupportedEncodingException {
String sampleText = "h1. Prefectures in Japan.\n";
sampleText += "There are 47 prefectures in Japan.\n";
sampleText += "\n";
sampleText += "Each prefectures has its features.\n";
sampleText += "h2. Gunma \n";
sampleText += "Gumma is very beautiful";
FileContent doc = createFileContent(sampleText);
assertEquals(3, doc.getNumberOfSections());
Section rootSection = doc.getSection(0);
Section h1Section = doc.getSection(1);
Section h2Section = doc.getSection(2);
assertEquals(0, rootSection.getLevel());
assertEquals(1, h1Section.getLevel());
assertEquals(2, h2Section.getLevel());
assertEquals(rootSection.getSubSection(0), h1Section);
assertEquals(h1Section.getParentSection(), rootSection);
assertEquals(h2Section.getParentSection(), h1Section);
assertEquals(rootSection.getParentSection(), null);
+
+ assertEquals(0, rootSection.getHeaderContent(0).position);
+ assertEquals(0, h1Section.getHeaderContent(0).position);
+ assertEquals(4, h2Section.getHeaderContent(0).position);
}
@Test
public void testGenerateJapaneseDocument() {
String japaneseConfiguraitonStr = new String(
"<?xml version=\"1.0\"?>" +
"<component name=\"Validator\">" +
"</component>");
String japaneseCharTableStr = new String(
"<?xml version=\"1.0\"?>" +
"<character-table>" +
"<character name=\"FULL_STOP\" value=\"。\" />" +
"</character-table>");
String sampleText = "埼玉は東京の北に存在する。";
sampleText += "大きなベッドタウンであり、多くの人が住んでいる。";
FileContent doc = null;
try {
doc = createFileContent(sampleText, japaneseConfiguraitonStr,
japaneseCharTableStr);
} catch (DocumentValidatorException e1) {
e1.printStackTrace();
fail();
}
Section firstSections = doc.getSection(0);
Paragraph firstParagraph = firstSections.getParagraph(0);
assertEquals(2, firstParagraph.getNumberOfSentences());
}
private Parser loadParser(DVResource resource) {
Parser parser = null;
try {
parser = DocumentParserFactory.generate("wiki", resource);
} catch (DocumentValidatorException e1) {
fail();
e1.printStackTrace();
}
return parser;
}
private FileContent createFileContent(String inputDocumentString,
String configurationString,
String characterTableString) throws DocumentValidatorException {
InputStream configStream = IOUtils.toInputStream(configurationString);
ValidatorConfiguration conf =
ValidationConfigurationLoader.loadConfiguraiton(configStream);
CharacterTable characterTable = null;
if (characterTableString.length() > 0) {
InputStream characterTableStream =
IOUtils.toInputStream(characterTableString);
characterTable = CharacterTableLoader.load(characterTableStream);
}
return createFileContent(inputDocumentString, conf, characterTable);
}
private FileContent createFileContent(String inputDocumentString,
ValidatorConfiguration conf,
CharacterTable characterTable) {
InputStream inputDocumentStream = null;
try {
inputDocumentStream =
new ByteArrayInputStream(inputDocumentString.getBytes("utf-8"));
} catch (UnsupportedEncodingException e1) {
fail();
}
Parser parser = null;
if (characterTable != null) {
parser = loadParser(new DVResource(conf, characterTable));
} else {
parser = loadParser(new DVResource(conf));
}
try {
return parser.generateDocument(inputDocumentStream);
} catch (DocumentValidatorException e) {
e.printStackTrace();
return null;
}
}
private FileContent createFileContent(
String inputDocumentString) {
ValidatorConfiguration conf = new ValidatorConfiguration("dummy");
Parser parser = loadParser(new DVResource(conf));
InputStream is;
try {
is = new ByteArrayInputStream(inputDocumentString.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
FileContent doc = null;
try {
doc = parser.generateDocument(is);
} catch (DocumentValidatorException e) {
e.printStackTrace();
}
return doc;
}
}
| false | false | null | null |
diff --git a/xstream/src/test/com/thoughtworks/acceptance/ImplicitArrayTest.java b/xstream/src/test/com/thoughtworks/acceptance/ImplicitArrayTest.java
index 239b30ca..cbfcfaea 100644
--- a/xstream/src/test/com/thoughtworks/acceptance/ImplicitArrayTest.java
+++ b/xstream/src/test/com/thoughtworks/acceptance/ImplicitArrayTest.java
@@ -1,497 +1,497 @@
/*
* Copyright (C) 2011 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 29. July 2011 by Joerg Schaible
*/
package com.thoughtworks.acceptance;
import java.util.Arrays;
import java.util.List;
import com.thoughtworks.acceptance.objects.StandardObject;
import com.thoughtworks.xstream.InitializationException;
/**
* @author Jörg Schaible
*/
public class ImplicitArrayTest extends AbstractAcceptanceTest {
protected void setUp() throws Exception {
super.setUp();
xstream.alias("farm", Farm.class);
xstream.alias("animal", Animal.class);
xstream.alias("MEGA-farm", MegaFarm.class);
}
public static class Farm extends StandardObject {
private transient int idx;
Animal[] animals;
}
public static class Animal extends StandardObject implements Comparable {
String name;
public Animal(String name) {
this.name = name;
}
public int compareTo(Object o) {
return name.compareTo(((Animal)o).name);
}
}
public void testWithDirectType() {
Farm farm = new Farm();
farm.animals = new Animal[] {
new Animal("Cow"),
new Animal("Sheep")
};
String expected = "" +
"<farm>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
"</farm>";
xstream.addImplicitArray(Farm.class, "animals");
assertBothWays(farm, expected);
}
public static class MegaFarm extends Farm {
String[] names;
}
public void testInheritsImplicitArrayFromSuperclass() {
Farm farm = new MegaFarm(); // subclass
farm.animals = new Animal[] {
new Animal("Cow"),
new Animal("Sheep")
};
String expected = "" +
"<MEGA-farm>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
"</MEGA-farm>";
xstream.addImplicitCollection(Farm.class, "animals");
assertBothWays(farm, expected);
}
- public void testSupportsInheritedAndDirectDelcaredImplicitArraysAtOnce() {
+ public void testSupportsInheritedAndDirectDeclaredImplicitArraysAtOnce() {
MegaFarm farm = new MegaFarm(); // subclass
farm.animals = new Animal[] {
new Animal("Cow"),
new Animal("Sheep")
};
farm.names = new String[] {
"McDonald",
"Ponte Rosa"
};
String expected = "" +
"<MEGA-farm>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
" <name>McDonald</name>\n" +
" <name>Ponte Rosa</name>\n" +
"</MEGA-farm>";
xstream.addImplicitArray(Farm.class, "animals");
xstream.addImplicitArray(MegaFarm.class, "names", "name");
assertBothWays(farm, expected);
}
public void testAllowsSubclassToOverrideImplicitCollectionInSuperclass() {
Farm farm = new MegaFarm(); // subclass
farm.animals = new Animal[] {
new Animal("Cow"),
new Animal("Sheep")
};
String expected = "" +
"<MEGA-farm>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
"</MEGA-farm>";
xstream.addImplicitCollection(MegaFarm.class, "animals");
assertBothWays(farm, expected);
}
public static class House extends StandardObject {
private Room[] rooms;
private Person[] people;
public List getPeople() {
return Arrays.asList(people);
}
public List getRooms() {
return Arrays.asList(rooms);
}
}
public static class Room extends StandardObject {
private String name;
public Room(String name) {
this.name = name;
}
}
public static class Person extends StandardObject {
private String name;
private String[] emailAddresses;
public Person(String name) {
this.name = name;
}
}
public void testMultipleArraysBasedOnDifferentType() {
House house = new House();
house.rooms = new Room[] {
new Room("kitchen"),
new Room("bathroom")
};
Person joe = new Person("joe");
joe.emailAddresses = new String[]{
"[email protected]",
"[email protected]"
};
Person jaimie = new Person("jaimie");
jaimie.emailAddresses = new String[]{
"[email protected]",
"[email protected]",
"[email protected]"
};
house.people = new Person[]{
joe,
jaimie
};
String expected = ""
+ "<house>\n"
+ " <room>\n"
+ " <name>kitchen</name>\n"
+ " </room>\n"
+ " <room>\n"
+ " <name>bathroom</name>\n"
+ " </room>\n"
+ " <person>\n"
+ " <name>joe</name>\n"
+ " <email>[email protected]</email>\n"
+ " <email>[email protected]</email>\n"
+ " </person>\n"
+ " <person>\n"
+ " <name>jaimie</name>\n"
+ " <email>[email protected]</email>\n"
+ " <email>[email protected]</email>\n"
+ " <email>[email protected]</email>\n"
+ " </person>\n"
+ "</house>";
xstream.alias("room", Room.class);
xstream.alias("house", House.class);
xstream.alias("person", Person.class);
xstream.addImplicitArray(House.class, "rooms");
xstream.addImplicitArray(House.class, "people");
xstream.addImplicitArray(Person.class, "emailAddresses", "email");
House serializedHouse = (House)assertBothWays(house, expected);
assertEquals(house.getPeople(), serializedHouse.getPeople());
assertEquals(house.getRooms(), serializedHouse.getRooms());
}
public static class NumberedRoom extends Room {
private int number;
public NumberedRoom(int number) {
super("room");
this.number = number;
}
}
public void testArraysWithDerivedElements() {
House house = new House();
house.rooms = new Room[] {
new Room("kitchen"),
new NumberedRoom(13)
};
String expected = ""
+ "<house>\n"
+ " <room>\n"
+ " <name>kitchen</name>\n"
+ " </room>\n"
+ " <room class=\"chamber\" number=\"13\">\n"
+ " <name>room</name>\n"
+ " </room>\n"
+ "</house>";
xstream.alias("house", House.class);
xstream.alias("chamber", NumberedRoom.class);
xstream.addImplicitArray(House.class, "rooms", "room");
xstream.useAttributeFor(int.class);
House serializedHouse = (House)assertBothWays(house, expected);
assertEquals(house.getRooms(), serializedHouse.getRooms());
}
public static class Aquarium extends StandardObject {
private String name;
private String[] fish;
public Aquarium(String name) {
this.name = name;
}
}
public void testWithExplicitItemNameMatchingTheNameOfTheFieldWithTheArray() {
Aquarium aquarium = new Aquarium("hatchery");
aquarium.fish = new String[]{
"salmon",
"halibut",
"snapper"
};
String expected = "" +
"<aquarium>\n" +
" <name>hatchery</name>\n" +
" <fish>salmon</fish>\n" +
" <fish>halibut</fish>\n" +
" <fish>snapper</fish>\n" +
"</aquarium>";
xstream.alias("aquarium", Aquarium.class);
xstream.addImplicitArray(Aquarium.class, "fish", "fish");
assertBothWays(aquarium, expected);
}
public void testWithImplicitNameMatchingTheNameOfTheFieldWithTheArray() {
Aquarium aquarium = new Aquarium("hatchery");
aquarium.fish = new String[]{
"salmon",
"halibut",
"snapper"
};
String expected = "" +
"<aquarium>\n" +
" <name>hatchery</name>\n" +
" <fish>salmon</fish>\n" +
" <fish>halibut</fish>\n" +
" <fish>snapper</fish>\n" +
"</aquarium>";
xstream.alias("aquarium", Aquarium.class);
xstream.alias("fish", String.class);
xstream.addImplicitArray(Aquarium.class, "fish");
assertBothWays(aquarium, expected);
}
public void testWithAliasedItemNameMatchingTheAliasedNameOfTheFieldWithTheArray() {
Aquarium aquarium = new Aquarium("hatchery");
aquarium.fish = new String[]{
"salmon",
"halibut",
"snapper"
};
String expected = "" +
"<aquarium>\n" +
" <name>hatchery</name>\n" +
" <animal>salmon</animal>\n" +
" <animal>halibut</animal>\n" +
" <animal>snapper</animal>\n" +
"</aquarium>";
xstream.alias("aquarium", Aquarium.class);
xstream.aliasField("animal", Aquarium.class, "fish");
xstream.addImplicitArray(Aquarium.class, "fish", "animal");
assertBothWays(aquarium, expected);
}
public void testCanBeDeclaredOnlyForMatchingType() {
try {
xstream.addImplicitArray(Animal.class, "name");
fail("Thrown " + InitializationException.class.getName() + " expected");
} catch (final InitializationException e) {
assertTrue(e.getMessage().indexOf("declares no collection") >= 0);
}
}
public void testCanBeDeclaredOnlyForMatchingComponentType() {
try {
xstream.addImplicitArray(Aquarium.class, "fish", Farm.class);
fail("Thrown " + InitializationException.class.getName() + " expected");
} catch (final InitializationException e) {
assertTrue(e.getMessage().indexOf("array type is not compatible") >= 0);
}
}
public void testWithNullElement() {
Farm farm = new Farm();
farm.animals = new Animal[] {
new Animal("Cow"),
null,
new Animal("Sheep")
};
String expected = "" +
"<farm>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <null/>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
"</farm>";
xstream.addImplicitArray(Farm.class, "animals");
assertBothWays(farm, expected);
}
public void testWithNullElementAnsAlias() {
Farm farm = new Farm();
farm.animals = new Animal[] {
null,
new Animal("Sheep")
};
String expected = "" +
"<farm>\n" +
" <null/>\n" +
" <beast>\n" +
" <name>Sheep</name>\n" +
" </beast>\n" +
"</farm>";
xstream.addImplicitArray(Farm.class, "animals", "beast");
assertBothWays(farm, expected);
}
static class PrimitiveArray {
int[] ints;
};
public void testWithPrimitiveArray() {
PrimitiveArray pa = new PrimitiveArray();
pa.ints = new int[]{ 47, 11 };
String expected = "" +
"<primitives>\n" +
" <int>47</int>\n" +
" <int>11</int>\n" +
"</primitives>";
xstream.alias("primitives", PrimitiveArray.class);
xstream.addImplicitArray(PrimitiveArray.class, "ints");
assertBothWays(pa, expected);
}
static class MultiDimenstionalArrays {
Object[][] multiObject;
String[][] multiString;
int[][] multiInt;
};
public void testMultiDimensionalDirectArray() {
MultiDimenstionalArrays multiDim = new MultiDimenstionalArrays();
multiDim.multiString = new String[][]{
new String[]{ "1", "2" },
new String[]{ "a", "b", "c" }
};
String expected = "" +
"<N>\n" +
" <string-array>\n" +
" <string>1</string>\n" +
" <string>2</string>\n" +
" </string-array>\n" +
" <string-array>\n" +
" <string>a</string>\n" +
" <string>b</string>\n" +
" <string>c</string>\n" +
" </string-array>\n" +
"</N>";
xstream.alias("N", MultiDimenstionalArrays.class);
xstream.addImplicitArray(MultiDimenstionalArrays.class, "multiString");
assertBothWays(multiDim, expected);
}
public void testMultiDimensionalPrimitiveArray() {
MultiDimenstionalArrays multiDim = new MultiDimenstionalArrays();
multiDim.multiInt = new int[][]{
new int[]{ 1, 2 },
new int[]{ 0, -1, -2 }
};
String expected = "" +
"<N>\n" +
" <int-array>\n" +
" <int>1</int>\n" +
" <int>2</int>\n" +
" </int-array>\n" +
" <int-array>\n" +
" <int>0</int>\n" +
" <int>-1</int>\n" +
" <int>-2</int>\n" +
" </int-array>\n" +
"</N>";
xstream.alias("N", MultiDimenstionalArrays.class);
xstream.addImplicitArray(MultiDimenstionalArrays.class, "multiInt");
assertBothWays(multiDim, expected);
}
public void testMultiDimensionalArrayWithAlias() {
MultiDimenstionalArrays multiDim = new MultiDimenstionalArrays();
multiDim.multiObject = new Object[][]{
new String[]{ "1" },
new Object[]{ "a", Boolean.FALSE }
};
String expected = "" +
"<N>\n" +
" <M class=\"string-array\">\n" +
" <string>1</string>\n" +
" </M>\n" +
" <M>\n" +
" <string>a</string>\n" +
" <boolean>false</boolean>\n" +
" </M>\n" +
"</N>";
xstream.alias("N", MultiDimenstionalArrays.class);
xstream.addImplicitArray(MultiDimenstionalArrays.class, "multiObject", "M");
assertBothWays(multiDim, expected);
}
}
diff --git a/xstream/src/test/com/thoughtworks/acceptance/ImplicitCollectionTest.java b/xstream/src/test/com/thoughtworks/acceptance/ImplicitCollectionTest.java
index e83cb9c5..7455bfd8 100644
--- a/xstream/src/test/com/thoughtworks/acceptance/ImplicitCollectionTest.java
+++ b/xstream/src/test/com/thoughtworks/acceptance/ImplicitCollectionTest.java
@@ -1,458 +1,458 @@
/*
* Copyright (C) 2004, 2005 Joe Walnes.
* Copyright (C) 2006, 2007, 2008, 2009, 2011 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 14. August 2004 by Joe Walnes
*/
package com.thoughtworks.acceptance;
import com.thoughtworks.acceptance.objects.SampleLists;
import com.thoughtworks.acceptance.objects.StandardObject;
import com.thoughtworks.xstream.InitializationException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class ImplicitCollectionTest extends AbstractAcceptanceTest {
public static class Farm extends StandardObject {
int size;
List animals = new ArrayList();
public Farm(int size) {
this.size = size;
}
public void add(Animal animal) {
animals.add(animal);
}
}
public static class Animal extends StandardObject implements Comparable {
String name;
public Animal(String name) {
this.name = name;
}
public int compareTo(Object o) {
return name.compareTo(((Animal)o).name);
}
}
protected void setUp() throws Exception {
super.setUp();
xstream.alias("zoo", Zoo.class);
xstream.alias("farm", Farm.class);
xstream.alias("animal", Animal.class);
xstream.alias("room", Room.class);
xstream.alias("house", House.class);
xstream.alias("person", Person.class);
xstream.alias("sample", SampleLists.class);
}
public void testWithout() {
Farm farm = new Farm(100);
farm.add(new Animal("Cow"));
farm.add(new Animal("Sheep"));
String expected = "" +
"<farm>\n" +
" <size>100</size>\n" +
" <animals>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
" </animals>\n" +
"</farm>";
assertBothWays(farm, expected);
}
public void testWithList() {
Farm farm = new Farm(100);
farm.add(new Animal("Cow"));
farm.add(new Animal("Sheep"));
String expected = "" +
"<farm>\n" +
" <size>100</size>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
"</farm>";
xstream.addImplicitCollection(Farm.class, "animals");
assertBothWays(farm, expected);
}
public static class MegaFarm extends Farm {
List names;
public MegaFarm(int size) {
super(size);
}
}
public void testInheritsImplicitCollectionFromSuperclass() {
xstream.alias("MEGA-farm", MegaFarm.class);
Farm farm = new MegaFarm(100); // subclass
farm.add(new Animal("Cow"));
farm.add(new Animal("Sheep"));
String expected = "" +
"<MEGA-farm>\n" +
" <size>100</size>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
"</MEGA-farm>";
xstream.addImplicitCollection(Farm.class, "animals");
assertBothWays(farm, expected);
}
- public void testSupportsInheritedAndDirectDelcaredImplicitCollectionAtOnce() {
+ public void testSupportsInheritedAndDirectDeclaredImplicitCollectionAtOnce() {
xstream.alias("MEGA-farm", MegaFarm.class);
MegaFarm farm = new MegaFarm(100); // subclass
farm.add(new Animal("Cow"));
farm.add(new Animal("Sheep"));
farm.names = new ArrayList();
farm.names.add("McDonald");
farm.names.add("Ponte Rosa");
String expected = "" +
"<MEGA-farm>\n" +
" <size>100</size>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
" <name>McDonald</name>\n" +
" <name>Ponte Rosa</name>\n" +
"</MEGA-farm>";
xstream.addImplicitCollection(Farm.class, "animals");
xstream.addImplicitCollection(MegaFarm.class, "names", "name", String.class);
assertBothWays(farm, expected);
}
public void testAllowsSubclassToOverrideImplicitCollectionInSuperclass() {
xstream.alias("MEGA-farm", MegaFarm.class);
Farm farm = new MegaFarm(100); // subclass
farm.add(new Animal("Cow"));
farm.add(new Animal("Sheep"));
String expected = "" +
"<MEGA-farm>\n" +
" <size>100</size>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Sheep</name>\n" +
" </animal>\n" +
"</MEGA-farm>";
xstream.addImplicitCollection(MegaFarm.class, "animals");
assertBothWays(farm, expected);
}
public static class House extends StandardObject {
private List rooms = new ArrayList();
private List people = new ArrayList();
public void add(Room room) {
rooms.add(room);
}
public void add(Person person) {
people.add(person);
}
public List getPeople() {
return Collections.unmodifiableList(people);
}
public List getRooms() {
return Collections.unmodifiableList(rooms);
}
}
public static class Room extends StandardObject {
private String name;
public Room(String name) {
this.name = name;
}
}
public static class Person extends StandardObject {
private String name;
private LinkedList emailAddresses = new LinkedList();
public Person(String name) {
this.name = name;
}
public void addEmailAddress(String email) {
emailAddresses.add(email);
}
}
public void testDefaultCollectionBasedOnType() {
House house = new House();
house.add(new Room("kitchen"));
house.add(new Room("bathroom"));
Person joe = new Person("joe");
joe.addEmailAddress("[email protected]");
joe.addEmailAddress("[email protected]");
house.add(joe);
Person jaimie = new Person("jaimie");
jaimie.addEmailAddress("[email protected]");
jaimie.addEmailAddress("[email protected]");
jaimie.addEmailAddress("[email protected]");
house.add(jaimie);
String expected = ""
+ "<house>\n"
+ " <room>\n"
+ " <name>kitchen</name>\n"
+ " </room>\n"
+ " <room>\n"
+ " <name>bathroom</name>\n"
+ " </room>\n"
+ " <person>\n"
+ " <name>joe</name>\n"
+ " <email>[email protected]</email>\n"
+ " <email>[email protected]</email>\n"
+ " </person>\n"
+ " <person>\n"
+ " <name>jaimie</name>\n"
+ " <email>[email protected]</email>\n"
+ " <email>[email protected]</email>\n"
+ " <email>[email protected]</email>\n"
+ " </person>\n"
+ "</house>";
xstream.addImplicitCollection(House.class, "rooms", Room.class);
xstream.addImplicitCollection(House.class, "people", Person.class);
xstream.addImplicitCollection(Person.class, "emailAddresses", "email", String.class);
House serializedHouse = (House)assertBothWays(house, expected);
assertEquals(house.getPeople(), serializedHouse.getPeople());
assertEquals(house.getRooms(), serializedHouse.getRooms());
}
public static class Zoo extends StandardObject {
private Set animals;
public Zoo() {
this(new HashSet());
}
public Zoo(Set set) {
animals = set;
}
public void add(Animal animal) {
animals.add(animal);
}
}
public void testWithSet() {
Zoo zoo = new Zoo();
zoo.add(new Animal("Lion"));
zoo.add(new Animal("Ape"));
String expected = "" +
"<zoo>\n" +
" <animal>\n" +
" <name>Lion</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Ape</name>\n" +
" </animal>\n" +
"</zoo>";
xstream.addImplicitCollection(Zoo.class, "animals");
assertBothWaysNormalized(zoo, expected, "zoo", "animal", "name");
}
public void testWithDifferentDefaultImplementation() {
String xml = "" +
"<zoo>\n" +
" <animal>\n" +
" <name>Lion</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Ape</name>\n" +
" </animal>\n" +
"</zoo>";
xstream.addImplicitCollection(Zoo.class, "animals");
xstream.addDefaultImplementation(TreeSet.class, Set.class);
Zoo zoo = (Zoo)xstream.fromXML(xml);
assertTrue("Collection was a " + zoo.animals.getClass().getName(), zoo.animals instanceof TreeSet);
}
public void testWithSortedSet() {
Zoo zoo = new Zoo(new TreeSet());
zoo.add(new Animal("Lion"));
zoo.add(new Animal("Ape"));
String expected = "" +
"<zoo>\n" +
" <animal>\n" +
" <name>Ape</name>\n" +
" </animal>\n" +
" <animal>\n" +
" <name>Lion</name>\n" +
" </animal>\n" +
"</zoo>";
xstream.addImplicitCollection(Zoo.class, "animals");
xstream.addDefaultImplementation(TreeSet.class, Set.class);
assertBothWays(zoo, expected);
}
public static class Aquarium extends StandardObject {
private String name;
private List fish = new ArrayList();
public Aquarium(String name) {
this.name = name;
}
public void addFish(String fish) {
this.fish.add(fish);
}
}
public void testWithExplicitItemNameMatchingTheNameOfTheFieldWithTheCollection() {
Aquarium aquarium = new Aquarium("hatchery");
aquarium.addFish("salmon");
aquarium.addFish("halibut");
aquarium.addFish("snapper");
String expected = "" +
"<aquarium>\n" +
" <name>hatchery</name>\n" +
" <fish>salmon</fish>\n" +
" <fish>halibut</fish>\n" +
" <fish>snapper</fish>\n" +
"</aquarium>";
xstream.alias("aquarium", Aquarium.class);
xstream.addImplicitCollection(Aquarium.class, "fish", "fish", String.class);
assertBothWays(aquarium, expected);
}
public void testWithImplicitNameMatchingTheNameOfTheFieldWithTheCollection() {
Aquarium aquarium = new Aquarium("hatchery");
aquarium.addFish("salmon");
aquarium.addFish("halibut");
aquarium.addFish("snapper");
String expected = "" +
"<aquarium>\n" +
" <name>hatchery</name>\n" +
" <fish>salmon</fish>\n" +
" <fish>halibut</fish>\n" +
" <fish>snapper</fish>\n" +
"</aquarium>";
xstream.alias("aquarium", Aquarium.class);
xstream.alias("fish", String.class);
xstream.addImplicitCollection(Aquarium.class, "fish");
assertBothWays(aquarium, expected);
}
public void testWithAliasedItemNameMatchingTheAliasedNameOfTheFieldWithTheCollection() {
Aquarium aquarium = new Aquarium("hatchery");
aquarium.addFish("salmon");
aquarium.addFish("halibut");
aquarium.addFish("snapper");
String expected = "" +
"<aquarium>\n" +
" <name>hatchery</name>\n" +
" <animal>salmon</animal>\n" +
" <animal>halibut</animal>\n" +
" <animal>snapper</animal>\n" +
"</aquarium>";
xstream.alias("aquarium", Aquarium.class);
xstream.aliasField("animal", Aquarium.class, "fish");
xstream.addImplicitCollection(Aquarium.class, "fish", "animal", String.class);
assertBothWays(aquarium, expected);
}
public void testCanBeDeclaredOnlyForMatchingType() {
try {
xstream.addImplicitCollection(Animal.class, "name");
fail("Thrown " + InitializationException.class.getName() + " expected");
} catch (final InitializationException e) {
assertTrue(e.getMessage().indexOf("declares no collection") >= 0);
}
}
public void testWithNullElement() {
Farm farm = new Farm(100);
farm.add(null);
farm.add(new Animal("Cow"));
String expected = "" +
"<farm>\n" +
" <size>100</size>\n" +
" <null/>\n" +
" <animal>\n" +
" <name>Cow</name>\n" +
" </animal>\n" +
"</farm>";
xstream.addImplicitCollection(Farm.class, "animals");
assertBothWays(farm, expected);
}
public void testWithAliasAndNullElement() {
Farm farm = new Farm(100);
farm.add(null);
farm.add(new Animal("Cow"));
String expected = "" +
"<farm>\n" +
" <size>100</size>\n" +
" <null/>\n" +
" <beast>\n" +
" <name>Cow</name>\n" +
" </beast>\n" +
"</farm>";
xstream.addImplicitCollection(Farm.class, "animals", "beast", Animal.class);
assertBothWays(farm, expected);
}
}
| false | false | null | null |
diff --git a/document/fr.opensagres.xdocreport.document.docx/src/main/java/fr/opensagres/xdocreport/document/docx/preprocessor/sax/MergefieldBufferedRegion.java b/document/fr.opensagres.xdocreport.document.docx/src/main/java/fr/opensagres/xdocreport/document/docx/preprocessor/sax/MergefieldBufferedRegion.java
index 190d70d1..5591177a 100644
--- a/document/fr.opensagres.xdocreport.document.docx/src/main/java/fr/opensagres/xdocreport/document/docx/preprocessor/sax/MergefieldBufferedRegion.java
+++ b/document/fr.opensagres.xdocreport.document.docx/src/main/java/fr/opensagres/xdocreport/document/docx/preprocessor/sax/MergefieldBufferedRegion.java
@@ -1,225 +1,225 @@
/**
* Copyright (C) 2011 The XDocReport Team <[email protected]>
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package fr.opensagres.xdocreport.document.docx.preprocessor.sax;
import org.xml.sax.Attributes;
import fr.opensagres.xdocreport.core.document.DocumentKind;
import fr.opensagres.xdocreport.core.utils.StringUtils;
import fr.opensagres.xdocreport.document.preprocessor.sax.BufferedElement;
import fr.opensagres.xdocreport.document.preprocessor.sax.TransformedBufferedDocumentContentHandler;
import fr.opensagres.xdocreport.document.textstyling.ITransformResult;
import fr.opensagres.xdocreport.template.formatter.Directive;
import fr.opensagres.xdocreport.template.formatter.FieldMetadata;
import fr.opensagres.xdocreport.template.formatter.IDocumentFormatter;
public abstract class MergefieldBufferedRegion
extends BufferedElement
{
private static final String TEXTSTYLING = "_TEXTSTYLING";
private static final String W_P = "w:p";
private static final String MERGEFORMAT = "\\* MERGEFORMAT";
private static final String MERGEFIELD_FIELD_TYPE = "MERGEFIELD";
private static final String HYPERLINK_FIELD_TYPE = "HYPERLINK";
private final TransformedBufferedDocumentContentHandler handler;
private String fieldName;
private BufferedElement tRegion;
public MergefieldBufferedRegion( TransformedBufferedDocumentContentHandler handler, BufferedElement parent,
String uri, String localName, String name, Attributes attributes )
{
super( parent, uri, localName, name, attributes );
this.handler = handler;
}
public String getFieldName()
{
return fieldName;
}
public String setInstrText( String instrText, FieldMetadata fieldAsTextStyling )
{
// compute field name if it's MERGEFIELD
this.fieldName = getFieldName( this, instrText, fieldAsTextStyling, handler.getFormatter(), handler );
if ( fieldName == null )
{
// Not a MERGEFIELD, instrText must be decoded if it's an HYPERLINK
// and field is an interpolation
// ex : HYPERLINK "mailto:$%7bdeveloper.mail%7d"
// must be modified to
// ex : HYPERLINK "mailto:${developer.mail}"
return decodeInstrTextIfNeeded( instrText );
}
return instrText;
}
private String decodeInstrTextIfNeeded( String instrText )
{
// It's not a mergefield.
IDocumentFormatter formatter = handler.getFormatter();
if ( formatter == null )
{
return instrText;
}
// Test if it's HYPERLINK
// ex : HYPERLINK "mailto:$%7bdeveloper.mail%7d"
int index = instrText.indexOf( HYPERLINK_FIELD_TYPE );
if ( index != -1 )
{
// It's HYPERLINK, remove HYPERLINK prefix
// ex : "mailto:$%7bdeveloper.mail%7d"
String fieldName = instrText.substring( index + HYPERLINK_FIELD_TYPE.length(), instrText.length() ).trim();
if ( StringUtils.isNotEmpty( fieldName ) )
{
// remove double quote
// ex : mailto:$%7bdeveloper.mail%7d
if ( fieldName.startsWith( "\"" ) && fieldName.endsWith( "\"" ) )
{
fieldName = fieldName.substring( 1, fieldName.length() - 1 );
}
// decode it
// ex : mailto:${developer.mail}
fieldName = StringUtils.decode( fieldName );
if ( formatter.containsInterpolation( fieldName ) )
{
// It's an interpolation, returns the decoded field
return StringUtils.decode( instrText );
}
}
}
return instrText;
}
private static String getFieldName( MergefieldBufferedRegion mergefield, String instrText,
FieldMetadata fieldAsTextStyling, IDocumentFormatter formatter,
TransformedBufferedDocumentContentHandler handler )
{
if ( StringUtils.isEmpty( instrText ) )
{
return null;
}
int index = instrText.indexOf( MERGEFIELD_FIELD_TYPE );
if ( index != -1 )
{
// Extract field name and add it to the current buffer
String fieldName = instrText.substring( index + MERGEFIELD_FIELD_TYPE.length(), instrText.length() ).trim();
if ( StringUtils.isNotEmpty( fieldName ) )
{
// Test if fieldName ends with \* MERGEFORMAT
if ( fieldName.endsWith( MERGEFORMAT ) )
{
fieldName = fieldName.substring( 0, fieldName.length() - MERGEFORMAT.length() ).trim();
}
if ( StringUtils.isNotEmpty( fieldName ) )
{
// if #foreach is used w:fldSimple looks like this :
// <w:fldSimple w:instr="MERGEFIELD "#foreach($developer in
// $developers)" \\* MERGEFORMAT\"> to have
// foreach($developer in $developers)
// remove first " if needed
if ( fieldName.startsWith( "\"" ) && fieldName.endsWith( "\"" ) )
{
fieldName = fieldName.substring( 1, fieldName.length() - 1 );
}
// Fix bug
// http://code.google.com/p/xdocreport/issues/detail?id=29
// Replace \" with "
// ex : replace [#if \"a\" = \"one\"]1[#else]not 1[/#if]
// to have [#if "a" = "one"]1[#else]not 1[/#if]
fieldName = StringUtils.replaceAll( fieldName, "\\\"", "\"" );
// ex : remplace [#if 'a' = \"one\"]1[#else]not
// 1[/#if]
// to have [#if 'a' = "one"]1[#else]not 1[/#if]
fieldName = StringUtils.xmlUnescape( fieldName );
if ( fieldAsTextStyling != null )
{
// Find parent paragraph
BufferedElement parent = mergefield.findParent( W_P );
// Test if $___NoEscape0.TextBefore was already generated for the field.
String key = new StringBuilder( fieldName ).append( TEXTSTYLING ).toString();
- String directive = (String) parent.get( key );
+ String directive = parent.get( key );
if ( directive != null )
{
// The $___NoEscape0.TextBefore is already generated
// don't add it
return directive;
}
// register parent buffered element
long variableIndex = handler.getVariableIndex();
String elementId = handler.registerBufferedElement( variableIndex, parent );
// Set
String setVariableDirective =
formatter.formatAsCallTextStyling( variableIndex, fieldName, DocumentKind.DOCX.name(),
fieldAsTextStyling.getSyntaxKind(),
fieldAsTextStyling.isSyntaxWithDirective(), elementId,
handler.getEntryName() );
String textBefore =
formatter.formatAsTextStylingField( variableIndex, ITransformResult.TEXT_BEFORE_PROPERTY );
String textBody =
formatter.formatAsTextStylingField( variableIndex, ITransformResult.TEXT_BODY_PROPERTY );
String textEnd =
formatter.formatAsTextStylingField( variableIndex, ITransformResult.TEXT_END_PROPERTY );
parent.setContentBeforeStartTagElement( Directive.formatDirective( setVariableDirective + " "
+ textBefore, handler.getStartNoParse(), handler.getEndNoParse() ) );
parent.setContentAfterEndTagElement( Directive.formatDirective( textEnd,
handler.getStartNoParse(),
handler.getEndNoParse() ) );
directive =
Directive.formatDirective( textBody, handler.getStartNoParse(), handler.getEndNoParse() );
parent.put( key, directive );
return directive;
}
return Directive.formatDirective( fieldName, handler.getStartNoParse(), handler.getEndNoParse() );
}
}
}
return null;
}
public BufferedElement getTRegion()
{
if ( tRegion == null )
{
tRegion = super.findFirstChild( "w:t" );
}
return tRegion;
}
}
diff --git a/document/fr.opensagres.xdocreport.document/src/main/java/fr/opensagres/xdocreport/document/preprocessor/sax/BufferedElement.java b/document/fr.opensagres.xdocreport.document/src/main/java/fr/opensagres/xdocreport/document/preprocessor/sax/BufferedElement.java
index 84fa2a34..df6d4a9c 100644
--- a/document/fr.opensagres.xdocreport.document/src/main/java/fr/opensagres/xdocreport/document/preprocessor/sax/BufferedElement.java
+++ b/document/fr.opensagres.xdocreport.document/src/main/java/fr/opensagres/xdocreport/document/preprocessor/sax/BufferedElement.java
@@ -1,577 +1,598 @@
/**
* Copyright (C) 2011 The XDocReport Team <[email protected]>
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package fr.opensagres.xdocreport.document.preprocessor.sax;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import org.xml.sax.Attributes;
/**
* Buffered element which stores start Tag element (ex: <a>) and end Tag element (ex: </a>). The start Tag element
* stores too the {@link BufferedElement} children.
*/
-public class BufferedElement extends HashMap
+public class BufferedElement
implements IBufferedRegion
{
private final BufferedElement parent;
private final String name;
private final String startTagElementName;
private final String endTagElementName;
protected final BufferedStartTagElement startTagElement;
protected final BufferedEndTagElement endTagElement;
private BufferedTagElement currentTagElement;
private final Attributes attributes;
private Collection<BufferedAttribute> dynamicAttributes = null;
private boolean reseted;
+ private Map<String, String> data;
+
public BufferedElement( BufferedElement parent, String uri, String localName, String name, Attributes attributes )
{
this.parent = parent;
this.name = name;
this.startTagElementName = "<" + name + ">";
this.endTagElementName = "</" + name + ">";
this.attributes = attributes;
this.startTagElement = new BufferedStartTagElement( this );
this.endTagElement = new BufferedEndTagElement( this );
this.currentTagElement = startTagElement;
this.reseted = false;
}
/**
* Returns true if the given name match the name of this element and false otherwise.
*
* @param name
* @return
*/
public boolean match( String name )
{
if ( name == null )
{
return false;
}
return name.equals( this.name );
}
/**
* Returns the buffer of the start tag element.
*
* @return
*/
public BufferedStartTagElement getStartTagElement()
{
return startTagElement;
}
/**
* Returns the buffer of the end tag element.
*
* @return
*/
public BufferedEndTagElement getEndTagElement()
{
return endTagElement;
}
/**
* Set content on the before start tag element.
*
* @param before
*/
public void setContentBeforeStartTagElement( String before )
{
this.startTagElement.setBefore( before );
}
/**
* Set content on the after end tag element.
*
* @param before
*/
public void setContentAfterEndTagElement( String after )
{
this.endTagElement.setAfter( after );
}
/**
* Returns the parent buffered element of this element.
*/
public BufferedElement getParent()
{
return parent;
}
/**
* Returns the current tag element (start or end).
*
* @return
*/
private BufferedTagElement getCurrentTagElement()
{
return currentTagElement;
}
/**
* Write the content of this element in the given writer.
*/
public void save( Writer writer )
throws IOException
{
// Write start tag element content
getStartTagElement().save( writer );
// Write end tag element content
getEndTagElement().save( writer );
}
/**
* Add a savable region in the current tag element.
*/
public void addRegion( ISavable region )
{
getCurrentTagElement().addRegion( region );
}
/**
* Returns false
*/
public boolean isString()
{
return getCurrentTagElement().isString();
}
/**
* Append content in the current tag element.
*/
public void append( String content )
{
getCurrentTagElement().append( content );
}
/**
* Append content in the current tag element.
*/
public void append( char[] ch, int start, int length )
{
getCurrentTagElement().append( ch, start, length );
}
/**
* Append content in the current tag element.
*/
public void append( char c )
{
getCurrentTagElement().append( c );
}
/**
* Reset the whole content of the element.
*/
public void reset()
{
startTagElement.reset();
endTagElement.reset();
this.reseted = true;
}
public boolean isReseted()
{
return reseted;
}
/**
* Remove the collection of element.
*
* @param elements
*/
public void removeAll( Collection<BufferedElement> elements )
{
BufferedTagElement tagElement = null;
for ( BufferedElement element : elements )
{
// remove start tag element
tagElement = element.getStartTagElement();
if ( tagElement != null )
{
getStartTagElement().regions.remove( tagElement );
}
// remove end tag element
tagElement = element.getEndTagElement();
if ( tagElement != null )
{
getStartTagElement().regions.remove( tagElement );
}
}
}
@Override
public String toString()
{
StringWriter writer = new StringWriter();
try
{
save( writer );
}
catch ( IOException e )
{
// Do nothing
}
return writer.toString();
}
/**
* Returns the owner element.
*/
public BufferedElement getOwnerElement()
{
return this;
}
/**
* Returns the parent element of this element which match the given name.
*
* @param element
* @param name
* @return
*/
public BufferedElement findParent( String name )
{
return findParent( this, name );
}
/**
* Returns the parent element of the given element which match the given name.
*
* @param element
* @param name
* @return
*/
public BufferedElement findParent( BufferedElement element, String name )
{
if ( element == null )
{
return null;
}
if ( element.match( name ) )
{
return element;
}
return findParent( element.getParent(), name );
}
/**
* Returns the children element of this element which match the given name.
*
* @param name
* @return
*/
public List<BufferedElement> findChildren( String name )
{
return findChildren( this, name );
}
/**
* Returns the children element of the given element which match the given name.
*
* @param element
* @param name
* @return
*/
public List<BufferedElement> findChildren( BufferedElement element, String name )
{
List<BufferedElement> elements = new ArrayList<BufferedElement>();
List<ISavable> regions = element.getStartTagElement().regions;
findChildren( regions, name, elements );
return elements;
}
/**
* Returns the first child element of the given element which match the given name and null otherwise.
*
* @param name
* @return
*/
public BufferedElement findFirstChild( String name )
{
return findFirstChild( this, name );
}
/**
* Returns the first child element of this element which match the given name and null otherwise.
*
* @param name
* @return
*/
public BufferedElement findFirstChild( BufferedElement element, String name )
{
List<BufferedElement> elements = findChildren( element, name );
if ( elements.size() > 1 )
{
return elements.get( 0 );
}
return null;
}
/**
* Populate list elements with children element which match the given name.
*
* @param regions
* @param name
* @param elements
*/
private void findChildren( List<ISavable> regions, String name, List<BufferedElement> elements )
{
for ( ISavable region : regions )
{
if ( region instanceof IBufferedRegion )
{
IBufferedRegion r = (IBufferedRegion) region;
if ( r.getOwnerElement().match( name ) )
{
elements.add( r.getOwnerElement() );
}
if ( r instanceof BufferedRegion )
{
findChildren( ( (BufferedRegion) r ).regions, name, elements );
}
}
}
}
/**
* Set the current buffer with start tag element.
*/
public void start()
{
this.currentTagElement = startTagElement;
}
/**
* Set the current buffer with end tag element.
*/
public void end()
{
this.currentTagElement = endTagElement;
}
/**
* Returns true if current buffer is end tag element and false otherwise.
*
* @return
*/
public boolean isEnded()
{
return this.currentTagElement == endTagElement;
}
/**
* Returns the name of this start tag element (ex : <w:t>).
*
* @return
*/
public String getStartTagElementName()
{
return startTagElementName;
}
/**
* Returns the name of this end tag element (ex : </w:t>).
*
* @return
*/
public String getEndTagElementName()
{
return endTagElementName;
}
/**
* Set text content for this element.
*
* @param content
*/
public void setTextContent( String content )
{
if ( isEnded() )
{
// end tag element is parsed (ex: <w:t>XXXX</w:t>), reset the buffer
// and rebuild the buffer with the new content.
reset();
getStartTagElement().append( getStartTagElementName() );
getStartTagElement().append( content );
getEndTagElement().append( getEndTagElementName() );
}
else
{
// end tag element is not parsed (ex: <w:t>) append teh content.
getCurrentTagElement().append( content );
}
}
/**
* Returns the text content for this element.
*
* @return
*/
public String getTextContent()
{
// get content of the element (ex : <w:t>XXXX</w:t>)
StringWriter writer = new StringWriter();
try
{
save( writer );
}
catch ( IOException e )
{
e.printStackTrace();
}
// remove the start/end tag ex : XXXX)
String textContent = writer.toString();
if ( textContent.startsWith( getStartTagElementName() ) )
{
textContent = textContent.substring( getStartTagElementName().length(), textContent.length() );
}
if ( textContent.endsWith( getEndTagElementName() ) )
{
textContent = textContent.substring( 0, textContent.length() - getStartTagElementName().length() - 1 );
}
return textContent;
}
/**
* Returns the static SAX attributes.
*
* @return
*/
public Attributes getAttributes()
{
return attributes;
}
/**
* Register dynamic attributes if needed.
*/
public void registerDynamicAttributes()
{
if ( dynamicAttributes == null )
{
return;
}
for ( BufferedAttribute attribute : dynamicAttributes )
{
getCurrentTagElement().addRegion( attribute );
}
}
/**
* Set dynamic attribute.
*
* @param name
* @param value
* @return
*/
public BufferedAttribute setAttribute( String name, String value )
{
if ( dynamicAttributes == null )
{
dynamicAttributes = new ArrayList<BufferedAttribute>();
}
BufferedAttribute attribute = new BufferedAttribute( this, name, value );
dynamicAttributes.add( attribute );
return attribute;
}
public String getName()
{
return name;
}
public String getInnerText()
{
StringWriter writer = new StringWriter();
List<ISavable> regions = startTagElement.regions;
boolean startTagParsing = true;
for ( ISavable region : regions )
{
if ( startTagParsing )
{
if ( region instanceof BufferedStartTagElement )
{
startTagParsing = false;
}
}
if ( !startTagParsing )
{
try
{
region.save( writer );
}
catch ( IOException e )
{
// Should never thrown.
}
}
}
return writer.toString();
}
public void setInnerText( String innerText )
{
List<ISavable> regionsToAdd = new ArrayList<ISavable>();
List<ISavable> regions = startTagElement.regions;
boolean startTagParsing = true;
for ( ISavable region : regions )
{
startTagParsing = !( region instanceof BufferedStartTagElement );
if ( startTagParsing )
{
regionsToAdd.add( region );
}
else
{
break;
}
}
startTagElement.reset();
startTagElement.regions.addAll( regionsToAdd );
startTagElement.append( innerText );
}
+ public String get( String key )
+ {
+ if ( data == null )
+ {
+ return null;
+ }
+ return data.get( key );
+ }
+
+ public void put( String key, String value )
+ {
+ if ( data == null )
+ {
+ data = new HashMap<String, String>();
+ }
+ data.put( key, value );
+ }
+
}
| false | false | null | null |
diff --git a/src/br/edu/ifpr/ThiagoRomano/Camaleao/ArcadeLevelSelect.java b/src/br/edu/ifpr/ThiagoRomano/Camaleao/ArcadeLevelSelect.java
index a445d9a..8f4984e 100644
--- a/src/br/edu/ifpr/ThiagoRomano/Camaleao/ArcadeLevelSelect.java
+++ b/src/br/edu/ifpr/ThiagoRomano/Camaleao/ArcadeLevelSelect.java
@@ -1,313 +1,313 @@
package br.edu.ifpr.ThiagoRomano.Camaleao;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.region.ITextureRegion;
import android.view.KeyEvent;
public class ArcadeLevelSelect extends MenuScene implements
IOnMenuItemClickListener {
static final int MENU_LEVEL_1 = 0;
static final int MENU_LEVEL_2 = MENU_LEVEL_1 + 1;
static final int MENU_LEVEL_3 = MENU_LEVEL_2 + 1;
static final int MENU_LEVEL_4 = MENU_LEVEL_3 + 1;
static final int MENU_LEVEL_5 = MENU_LEVEL_4 + 1;
static final int MENU_BACK = MENU_LEVEL_5 + 1;
CamaleaotestActivity activity;
Sprite mBackground;
SpriteMenuItem[] mLevelCross = new SpriteMenuItem[5];
Sprite mCaminho[] = new Sprite[4];
Sprite mUnopen[] = new Sprite[9];
private SpriteMenuItem mBack;
public ArcadeLevelSelect() {
activity = CamaleaotestActivity.getSharedInstance();
this.mCamera = activity.mCamera;
mBackground = new Sprite(0, 0,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.MUNDO01_ID),
activity.getVertexBufferObjectManager());
this.attachChild(mBackground);
/*
* TiledTextureRegion crossTexture = new TiledTextureRegion(
* activity.mSpritesheetTexturePackTextureRegionLibrary.get(0)
* .getTexture(), activity.mSpritesheetTexturePackTextureRegionLibrary
* .get(posicoes.X_DISABLED_ID),
* activity.mSpritesheetTexturePackTextureRegionLibrary
* .get(posicoes.X_ATIVO_ID));
*/
ITextureRegion crossTexture = activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.X_ATIVO_ID);
mLevelCross[0] = new SpriteMenuItem(MENU_LEVEL_1, crossTexture,
activity.getVertexBufferObjectManager());
mLevelCross[0].setPosition(332, 87);
mLevelCross[1] = new SpriteMenuItem(MENU_LEVEL_2, crossTexture,
activity.getVertexBufferObjectManager());
mLevelCross[1].setPosition(286f, 351f);
mLevelCross[2] = new SpriteMenuItem(MENU_LEVEL_3, crossTexture,
activity.getVertexBufferObjectManager());
mLevelCross[2].setPosition(51f, 319f);
mLevelCross[3] = new SpriteMenuItem(MENU_LEVEL_4, crossTexture,
activity.getVertexBufferObjectManager());
mLevelCross[3].setPosition(330f, 571f);
mLevelCross[4] = new SpriteMenuItem(MENU_LEVEL_5, crossTexture,
activity.getVertexBufferObjectManager());
mLevelCross[4].setPosition(138f, 593f);
for (int i = activity.mLevel; i < 5; i++) {
mLevelCross[i].setVisible(false);
}
mUnopen[0] = new Sprite(332, 87,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.X_DISABLED_ID),
activity.getVertexBufferObjectManager());
mUnopen[1] = new Sprite(286, 351,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.X_DISABLED_ID),
activity.getVertexBufferObjectManager());
mUnopen[2] = new Sprite(51, 319,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.X_DISABLED_ID),
activity.getVertexBufferObjectManager());
mUnopen[3] = new Sprite(330, 571,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.X_DISABLED_ID),
activity.getVertexBufferObjectManager());
mUnopen[4] = new Sprite(138, 593,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.X_DISABLED_ID),
activity.getVertexBufferObjectManager());
mUnopen[5] = new Sprite(326, 152,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMINHO1_DISABLED_ID),
activity.getVertexBufferObjectManager());
mUnopen[6] = new Sprite(136, 336,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMINHO2_DISABLED_ID),
activity.getVertexBufferObjectManager());
mUnopen[7] = new Sprite(122, 397,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMINHO3_DISABLED_ID),
activity.getVertexBufferObjectManager());
mUnopen[8] = new Sprite(229, 603,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMINHO4_DISABLED_ID),
activity.getVertexBufferObjectManager());
mCaminho[0] = new Sprite(326, 152,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMINHO1_ID),
activity.getVertexBufferObjectManager());
mCaminho[1] = new Sprite(136, 336,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMINHO2_ID),
activity.getVertexBufferObjectManager());
mCaminho[2] = new Sprite(122, 397,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMINHO3_ID),
activity.getVertexBufferObjectManager());
mCaminho[3] = new Sprite(229, 603,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMINHO4_ID),
activity.getVertexBufferObjectManager());
for (int i = 0; i < mCaminho.length; i++) {
if (mLevelCross[i + 1].isVisible())
continue;
mCaminho[i].setVisible(false);
}
mBack = new SpriteMenuItem(MENU_BACK,
activity.mSpritesheetTexturePackTextureRegionLibrary2
.get(posicoes2.BACK_ID),
activity.getVertexBufferObjectManager());
mBack.setPosition(375, 678);
this.attachChild(mUnopen[0]);
this.attachChild(mUnopen[1]);
this.attachChild(mUnopen[2]);
this.attachChild(mUnopen[3]);
this.attachChild(mUnopen[4]);
this.attachChild(mUnopen[5]);
this.attachChild(mUnopen[6]);
this.attachChild(mUnopen[7]);
this.attachChild(mUnopen[8]);
this.addMenuItem(mLevelCross[0]);
this.addMenuItem(mLevelCross[1]);
this.addMenuItem(mLevelCross[2]);
this.addMenuItem(mLevelCross[3]);
this.addMenuItem(mLevelCross[4]);
this.attachChild(mCaminho[0]);
this.attachChild(mCaminho[1]);
this.attachChild(mCaminho[2]);
this.attachChild(mCaminho[3]);
this.addMenuItem(mBack);
setOnMenuItemClickListener(this);
}
@Override
public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
float pMenuItemLocalX, float pMenuItemLocalY) {
switch (pMenuItem.getID()) {
case MENU_LEVEL_1:
activity.setCurrentScene(new ArcadeModeScene(1, new int[] {
255, 255, 0,
0, 255, 0,
255, 0, 0,
255, 0, 255,
0, 0, 255,
255, 255, 255, }));
return true;
case MENU_LEVEL_2:
activity.setCurrentScene(new ArcadeModeScene(2, new int[] {
0, 255, 255,
0, 135, 255,
0, 135, 60,
135, 135, 60,
0, 150, 150,
150, 150, 150,
150, 255, 255, }) {
@Override
public void DiferenciadorDeFases() {
// TODO Auto-generated method stub
super.DiferenciadorDeFases();
final Sprite diferenciadorDeFases = new Sprite(
11,
235,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.FASE2_ID), activity
.getVertexBufferObjectManager());
attachChild(diferenciadorDeFases);
}
});
return true;
case MENU_LEVEL_3:
activity.setCurrentScene(new ArcadeModeScene(3, new int[] {
0, 120, 120,
255, 120, 120,
75, 120, 120,
75, 120, 0,
120, 60, 0,
0, 0, 0, }) {
@Override
public void DiferenciadorDeFases() {
// TODO Auto-generated method stub
super.DiferenciadorDeFases();
final Sprite diferenciadorDeFases = new Sprite(
0,
0,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.FASE3_ID), activity
.getVertexBufferObjectManager());
attachChild(diferenciadorDeFases);
}
});
return true;
case MENU_LEVEL_4:
activity.setCurrentScene(new ArcadeModeScene(4, new int[] {
180, 0, 0,
180, 0, 75,
255, 75, 0,
255, 75, 255,
105, 165, 0,
105, 0, 0, }) {
@Override
public void DiferenciadorDeFases() {
// TODO Auto-generated method stub
super.DiferenciadorDeFases();
final Sprite diferenciadorDeFases = new Sprite(
0,
158,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.FASE2_ID), activity
.getVertexBufferObjectManager());
attachChild(diferenciadorDeFases);
}
});
return true;
case MENU_LEVEL_5:
activity.setCurrentScene(new ArcadeModeScene(5, new int[] {
105, 45, 0,
255, 210, 150,
165, 135, 90,
165, 60, 60,
180, 45, 0,
255, 210, 165, }) {
@Override
public void DiferenciadorDeFases() {
// TODO Auto-generated method stub
super.DiferenciadorDeFases();
final Sprite diferenciadorDeFases = new Sprite(
0,
250,
activity.mSpritesheetTexturePackTextureRegionLibrary
- .get(posicoes.FASE2_ID), activity
+ .get(posicoes.FASE5_ID), activity
.getVertexBufferObjectManager());
attachChild(diferenciadorDeFases);
}
});
return true;
case MENU_BACK:
activity.setCurrentScene(new MainMenuScene());
return true;
default:
return false;
}
}
@Override
public boolean handleKeyDown(int pKeyCode, KeyEvent pEvent) {
if (pKeyCode == KeyEvent.KEYCODE_BACK
&& pEvent.getAction() == KeyEvent.ACTION_DOWN) {
activity.setCurrentScene(new MainMenuScene());
return true;
}
return false;
}
}
diff --git a/src/br/edu/ifpr/ThiagoRomano/Camaleao/ArcadeModeScene.java b/src/br/edu/ifpr/ThiagoRomano/Camaleao/ArcadeModeScene.java
index b9de179..c472034 100644
--- a/src/br/edu/ifpr/ThiagoRomano/Camaleao/ArcadeModeScene.java
+++ b/src/br/edu/ifpr/ThiagoRomano/Camaleao/ArcadeModeScene.java
@@ -1,484 +1,484 @@
package br.edu.ifpr.ThiagoRomano.Camaleao;
import java.util.Random;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.DelayModifier;
import org.andengine.entity.modifier.FadeOutModifier;
import org.andengine.entity.modifier.MoveModifier;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.sprite.TiledSprite;
import org.andengine.entity.sprite.batch.SpriteBatch;
import org.andengine.entity.text.Text;
import org.andengine.opengl.shader.constants.ShaderProgramConstants;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.util.color.ColorUtils;
import org.andengine.util.modifier.ease.EaseElasticOut;
import org.andengine.util.system.CPUUsage;
import android.graphics.Color;
import android.view.KeyEvent;
public class ArcadeModeScene extends GameScene {
public final float STARTING_TIME = 60f;
public int[] mCores;
CamaleaotestActivity activity;
Sprite mChamp;
Sprite mBlue;
Sprite mRed;
Sprite mGreen;
Sprite mLetraR;
Sprite mLetraG;
Sprite mLetraB;
SliderSprite mSliderBlue;
SliderSprite mSliderRed;
SliderSprite mSliderGreen;
Sprite mAdendo;
Sprite mChampShadow;
Sprite mPalco;
Sprite mFolhasFrente;
static final int X_PONTUACAO_INICIAL = 330;
static final int Y_PONTUACAO_INICIAL = 0;
TiledSprite mWisps[] = new TiledSprite[7];
Random rand;
// Text mTextRemainingTime;
Sprite mBackground;
Sprite mPlaca;
Sprite mPlacaSaindo;
Sprite mTronco;
int mPlacaColor;
int mActualColor = 0;
public int theColorLocation = ShaderProgramConstants.LOCATION_INVALID;
// public boolean mOverlayed = true;
int score = 0;
int mThisLevel;
private Sprite mBox;
private Pontuacao mPontuacao;
public ArcadeModeScene(int pThisLevel, int pCores[]) {
mCores = pCores;
mThisLevel = pThisLevel;
rand = new Random();
this.setOnAreaTouchTraversalFrontToBack();
colors = Color.rgb(255, 255, 255);
- mPlacaColor = 0xff00ffff;
+ mPlacaColor = Color.rgb(mCores[0], mCores[1], mCores[2]);
activity = CamaleaotestActivity.getSharedInstance();
createAssets();
createPauseMenu();
iniciando = false;
mConfirmExit = new ConfirmExitScene(this){
@Override
public void Quit() {
// TODO Auto-generated method stub
activity.setCurrentScene(new ArcadeLevelSelect());
}
};
mConfirmRestart = new ConfirmRestartScene(this);
setTouchAreaBindingOnActionDownEnabled(true);
registerUpdateHandler(new IUpdateHandler() {
@Override
public void onUpdate(float pSecondsElapsed) {
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
});
}
private void createAssets() {
/*
* mTextRemainingTime = new Text(10, 10, activity.mFont, "", 10,
* activity.getVertexBufferObjectManager());
*/
mBackground = new Sprite(0, 0,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.FUNDO_ID),
activity.getVertexBufferObjectManager());
mFolhasFrente = new Sprite(0, 0,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.FOLHAS_FRENTE_ID),
activity.getVertexBufferObjectManager());
mPalco = new Sprite(62, 365,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.PALCO_ID),
activity.getVertexBufferObjectManager());
mAdendo = new Sprite(-16, -15,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.NYLON_DETALHES_ID),
activity.getVertexBufferObjectManager());
mPlaca = new Sprite(83, 65,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.NYLON_TROCACOR_ID),
activity.getVertexBufferObjectManager());
mPlaca.setColor(colorIntToFloat(Color.red(mPlacaColor)),
colorIntToFloat(Color.green(mPlacaColor)),
colorIntToFloat(Color.blue(mPlacaColor)));
mTronco = new Sprite(0, 219,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.TRONCO_ID),
activity.getVertexBufferObjectManager());
mChampShadow = new Sprite(127, 68,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMALEAO_SOMBRA_ID),
activity.getVertexBufferObjectManager());
mChamp = new Sprite(127, 68,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMALEAO_MASK_TROCACOR_ID),
activity.getVertexBufferObjectManager());
mBox = new Sprite(45, 489,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.BOX_ID),
activity.getVertexBufferObjectManager());
mRed = new BarSprite(0, this, 112, 523, activity.mTextureBar,
activity.getVertexBufferObjectManager());
mGreen = new BarSprite(1, this, 112, 615, activity.mTextureBar,
activity.getVertexBufferObjectManager());
mBlue = new BarSprite(2, this, 112, 706, activity.mTextureBar,
activity.getVertexBufferObjectManager());
mLetraR = new Sprite(67, 492,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.R_ID),
activity.getVertexBufferObjectManager());
mLetraG = new Sprite(64, 587,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.G_ID),
activity.getVertexBufferObjectManager());
mLetraB = new Sprite(65, 685,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.B_ID),
activity.getVertexBufferObjectManager());
mSliderRed = new SliderSprite(16, 0, this, 372, 505,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.MARCADOR_ID),
activity.getVertexBufferObjectManager());
mSliderGreen = new SliderSprite(16, 1, this, 372, 597,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.MARCADOR_ID),
activity.getVertexBufferObjectManager());
mSliderBlue = new SliderSprite(16, 2, this, 372, 688,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.MARCADOR_ID),
activity.getVertexBufferObjectManager());
mBlackBehind = new Sprite(0, 0,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.BLACK_BEHIND_ID),
activity.getVertexBufferObjectManager());
mPontuacao = new Pontuacao(X_PONTUACAO_INICIAL, Y_PONTUACAO_INICIAL, 2,
this, activity.getVertexBufferObjectManager());
for (int i = 0; i < mWisps.length; i++) {
mWisps[i] = new TiledSprite(-100, -100, new TiledTextureRegion(
activity.mSpritesheetTexturePackTextureRegionLibrary.get(
posicoes.POEIRA1_ID).getTexture(),
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.POEIRA1_ID),
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.POEIRA2_ID),
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.POEIRA3_ID),
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.POEIRA4_ID)),
activity.getVertexBufferObjectManager());
RestartWisp(mWisps[i]);
}
this.attachChild(mBackground);
DiferenciadorDeFases();
this.attachChild(mPalco);
this.attachChild(mPlaca);
mPlaca.attachChild(mAdendo);
this.attachChild(mTronco);
this.attachChild(mFolhasFrente);
this.attachChild(mChamp);
this.attachChild(mChampShadow);
this.attachChild(mBox);
this.attachChild(mRed);
this.attachChild(mGreen);
this.attachChild(mBlue);
this.attachChild(mLetraR);
this.attachChild(mLetraG);
this.attachChild(mLetraB);
this.attachChild(mSliderRed);
registerTouchArea(mSliderRed);
this.attachChild(mSliderGreen);
registerTouchArea(mSliderGreen);
this.attachChild(mSliderBlue);
registerTouchArea(mSliderBlue);
// this.attachChild(mTextRemainingTime);
this.attachChild(mPontuacao);
updateScore();
this.attachChild(mBlackBehind);
mBlackBehind.setVisible(false);
for (int i = 0; i < mWisps.length; i++) {
this.attachChild(mWisps[i]);
}
movements = new MoveModifier(2f, -mPlaca.getWidth(), mPlaca.getX(),
mPlaca.getY(), mPlaca.getY(), EaseElasticOut.getInstance());
mPlaca.registerEntityModifier(movements);
movements.setAutoUnregisterWhenFinished(false);
// setTouchAreaBindingOnActionMoveEnabled(true);
}
public void DiferenciadorDeFases() {
}
private void RestartWisp(TiledSprite pWisp) {
pWisp.setCurrentTileIndex(rand.nextInt(4));
if (rand.nextBoolean()) {
pWisp.registerEntityModifier(new MoveModifier(rand.nextInt(10) + 5,
-60, 660, rand.nextInt(600), rand.nextInt(600)) {
@Override
protected void onModifierFinished(IEntity pItem) {
super.onModifierFinished(pItem);
RestartWisp((TiledSprite) pItem);
}
@Override
protected void onSetValues(final IEntity pEntity,
final float pPercentageDone, final float pX,
final float pY) {
super.onSetValues(pEntity, pPercentageDone, pX, pY);
pEntity.setPosition(
pEntity.getX()
+ (float) Math.cos(pPercentageDone * 20)
* 20,
pEntity.getY()
+ (float) Math.sin(pPercentageDone * 20)
* 20);
// pEntity.setPosition(pEntity.getX() + rand.nextInt(20) -
// 10,
// pEntity.getY() + rand.nextInt(10) - 5);
}
});
} else {
pWisp.registerEntityModifier(new MoveModifier(rand.nextInt(10) + 5,
660, -60, rand.nextInt(600), rand.nextInt(600)) {
@Override
protected void onModifierFinished(IEntity pItem) {
super.onModifierFinished(pItem);
RestartWisp((TiledSprite) pItem);
}
@Override
protected void onSetValues(final IEntity pEntity,
final float pPercentageDone, final float pX,
final float pY) {
super.onSetValues(pEntity, pPercentageDone, pX, pY);
pEntity.setPosition(
pEntity.getX()
+ (float) Math.cos(pPercentageDone * 20)
* 20,
pEntity.getY()
+ (float) Math.sin(pPercentageDone * 20)
* 20);
// pEntity.setPosition(pEntity.getX() + rand.nextInt(20) -
// 10,
// pEntity.getY() + rand.nextInt(10) - 5);
}
});
}
}
@Override
public void restart() {
score = -1;
mActualColor = -1;
updateScore();
this.reset();
nextColor();
}
private void createPauseMenu() {
mMenuScene = new PauseMenu(this);
}
@Override
public void ChangeColors(float newColor, int index) {
int iNewColor = (int) (newColor * 255);
// colors = (0xff00ffff >> (2*index))&((int)Math.floor(newColor*255));
int mask = (0xff00ffff >> (8 * index));
iNewColor <<= 16;
iNewColor >>= index * 8;
// a.setColor(pColor)
colors = (colors & mask);
colors |= iNewColor;
mChamp.setColor(Color.red(colors) / 256f, Color.green(colors) / 256f,
Color.blue(colors) / 256f);
int redStepsDiference = Math.abs(Color.red(colors)
- Color.red(mPlacaColor));
int greenStepsDiference = Math.abs(Color.green(colors)
- Color.green(mPlacaColor));
int blueStepsDiference = Math.abs(Color.blue(colors)
- Color.blue(mPlacaColor));
/*
* mTextRemainingTime.setText(Integer.toString(redStepsDiference +
* greenStepsDiference + blueStepsDiference));
*/
// mChampShadow
// .setAlpha(Math
// .min(((redStepsDiference + greenStepsDiference + blueStepsDiference)
// / 765f) * 7f + 0.1f,
// 1f));
if (redStepsDiference < 25
&& greenStepsDiference < 25
&& blueStepsDiference < 25
&& redStepsDiference + blueStepsDiference + greenStepsDiference < 50) {
if (mChamp.getEntityModifierCount() == 0) {
mChampShadow.registerEntityModifier(new FadeOutModifier(2f) {
@Override
protected void onModifierStarted(IEntity pItem) {
iniciando = true;
mSliderRed.setPosition(SliderSprite.MIN_X
+ colorIntToFloat(Color.red(mPlacaColor))
* (SliderSprite.MAX_X - SliderSprite.MIN_X),
mSliderRed.getY());
mSliderGreen.setPosition(SliderSprite.MIN_X
+ colorIntToFloat(Color.green(mPlacaColor))
* (SliderSprite.MAX_X - SliderSprite.MIN_X),
mSliderGreen.getY());
mSliderBlue.setPosition(SliderSprite.MIN_X
+ colorIntToFloat(Color.blue(mPlacaColor))
* (SliderSprite.MAX_X - SliderSprite.MIN_X),
mSliderBlue.getY());
mSliderRed.updateValue(false);
mSliderGreen.updateValue(false);
mSliderBlue.updateValue(false);
};
@Override
protected void onManagedUpdate(float pSecondsElapsed,
IEntity pItem) {
super.onManagedUpdate(pSecondsElapsed, pItem);
}
@Override
protected void onSetValue(IEntity pEntity,
float pPercentageDone, float pAlpha) {
// TODO Auto-generated method stub
super.onSetValue(pEntity, pPercentageDone, pAlpha);
if (pAlpha < 0.24f) {
pEntity.setAlpha(0.24f);
}
}
@Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
super.onModifierFinished(pItem);
nextColor();
}
});
}
}
}
MoveModifier movements;
public void nextColor() {
movements.reset();
score++;
updateScore();
mActualColor++;
mChampShadow.setAlpha(1f);
iniciando = false;
if (mActualColor * 3 + 2 < mCores.length)
mPlacaColor = Color.rgb(mCores[mActualColor * 3],
mCores[mActualColor * 3 + 1], mCores[mActualColor * 3 + 2]);
else {
if (activity.mLevel <= mThisLevel) {
activity.mLevel = mThisLevel + 1;
}
activity.setCurrentScene(new ArcadeLevelSelect());
}
setPlacaColor(mPlacaColor);
/*
* if (rand.nextBoolean()) { Sounds.getSharedInstace().mYay.play();
* }else{ Sounds.getSharedInstace().mUhul.play(); }
*/
// mPlaca.setX(-mPlaca.getX());
// animacao entrando
}
private void updateScore() {
mPontuacao.updateScore(score);
}
public int colorFloatToInt(float number) {
return (int) (number * 255);
}
public float colorIntToFloat(int number) {
return number / 255f;
}
public void setPlacaColor(int color) {
mPlaca.setColor(colorIntToFloat(Color.red(mPlacaColor)),
colorIntToFloat(Color.green(mPlacaColor)),
colorIntToFloat(Color.blue(mPlacaColor)));
}
@Override
public void clearChildScenes() {
this.mMenuScene.back();
this.mConfirmExit.back();
}
}
diff --git a/src/br/edu/ifpr/ThiagoRomano/Camaleao/NinjaModeScene.java b/src/br/edu/ifpr/ThiagoRomano/Camaleao/NinjaModeScene.java
index e3e04cb..66b5291 100644
--- a/src/br/edu/ifpr/ThiagoRomano/Camaleao/NinjaModeScene.java
+++ b/src/br/edu/ifpr/ThiagoRomano/Camaleao/NinjaModeScene.java
@@ -1,401 +1,403 @@
package br.edu.ifpr.ThiagoRomano.Camaleao;
import java.util.Random;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.modifier.MoveModifier;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.shader.constants.ShaderProgramConstants;
import org.andengine.util.modifier.ease.EaseElasticOut;
import android.graphics.Color;
import android.view.KeyEvent;
public class NinjaModeScene extends GameScene {
static final float STARTING_TIME = 30f;
static final float TIME_CORRECT = 4f;
public final int[] CORES = { 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0,
255, 255, 255, 255, 0, 100, 100, 100, };
static final int X_PONTUACAO_INICIAL = 330;
static final int Y_PONTUACAO_INICIAL = 0;
CamaleaotestActivity activity;
Sprite mChamp;
Sprite mBlue;
Sprite mRed;
Sprite mGreen;
Sprite mLetraR;
Sprite mLetraG;
Sprite mLetraB;
SliderSprite mSliderBlue;
SliderSprite mSliderRed;
SliderSprite mSliderGreen;
Sprite mAdendo;
Sprite mChampShadow;
Sprite mPalco;
Sprite mFolhasFrente;
Chronometer mChronometer;
Random rand;
// Text mTextRemainingTime;
Sprite mBackground;
Sprite mPlaca;
Sprite mPlacaSaindo;
Sprite mTronco;
Pontuacao mPontuacao;
int mPlacaColor;
int mActualColor = 0;
public int theColorLocation = ShaderProgramConstants.LOCATION_INVALID;
// public boolean mOverlayed = true;
float remainingTime = STARTING_TIME;
int score = 0;
private Sprite mBox;
private PlacaNinjaScreen mPlacaStart;
public NinjaModeScene() {
rand = new Random();
this.setOnAreaTouchTraversalFrontToBack();
colors = Color.rgb(255, 255, 255);
mPlacaColor = 0xff00ffff;
activity = CamaleaotestActivity.getSharedInstance();
createAssets();
createPauseMenu();
mConfirmExit = new ConfirmExitScene(this);
mConfirmRestart = new ConfirmRestartScene(this);
setTouchAreaBindingOnActionDownEnabled(true);
registerUpdateHandler(new IUpdateHandler() {
@Override
public void onUpdate(float pSecondsElapsed) {
if (!iniciando) {
remainingTime -= pSecondsElapsed;
updateTime();
}
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
});
}
private void createAssets() {
/*
* mTextRemainingTime = new Text(10, 10, activity.mFont, "", 10,
* activity.getVertexBufferObjectManager());
*/
updateTime();
mBackground = new Sprite(0, 0,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.FUNDO_ID),
activity.getVertexBufferObjectManager());
mFolhasFrente = new Sprite(0, 0,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.FOLHAS_FRENTE_ID),
activity.getVertexBufferObjectManager());
mPalco = new Sprite(62, 365,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.PALCO_ID),
activity.getVertexBufferObjectManager());
mAdendo = new Sprite(-16, -15,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.NYLON_DETALHES_ID),
activity.getVertexBufferObjectManager());
mPlaca = new Sprite(83, 65,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.NYLON_TROCACOR_ID),
activity.getVertexBufferObjectManager());
mPlaca.setColor(colorIntToFloat(Color.red(mPlacaColor)),
colorIntToFloat(Color.green(mPlacaColor)),
colorIntToFloat(Color.blue(mPlacaColor)));
mTronco = new Sprite(0, 219,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.TRONCO_ID),
activity.getVertexBufferObjectManager());
mChampShadow = new Sprite(127, 68,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMALEAO_SOMBRA_ID),
activity.getVertexBufferObjectManager());
mChamp = new Sprite(127, 68,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.CAMALEAO_MASK_TROCACOR_ID),
activity.getVertexBufferObjectManager());
mBox = new Sprite(45, 489,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.BOX_ID),
activity.getVertexBufferObjectManager());
mRed = new BarSprite(0, this, 112, 523, activity.mTextureBar,
activity.getVertexBufferObjectManager());
mGreen = new BarSprite(1, this, 112, 615, activity.mTextureBar,
activity.getVertexBufferObjectManager());
mBlue = new BarSprite(2, this, 112, 706, activity.mTextureBar,
activity.getVertexBufferObjectManager());
mLetraR = new Sprite(67, 492,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.R_ID),
activity.getVertexBufferObjectManager());
mLetraG = new Sprite(64, 587,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.G_ID),
activity.getVertexBufferObjectManager());
mLetraB = new Sprite(65, 685,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.B_ID),
activity.getVertexBufferObjectManager());
- mSliderRed = new SliderSprite(16, 0, this, 372, 505,
+ mSliderRed = new SliderSprite(0, this, 372, 505,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.MARCADOR_ID),
activity.getVertexBufferObjectManager());
- mSliderGreen = new SliderSprite(16, 1, this, 372, 597,
+ mSliderGreen = new SliderSprite(1, this, 372, 597,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.MARCADOR_ID),
activity.getVertexBufferObjectManager());
- mSliderBlue = new SliderSprite(16, 2, this, 372, 688,
+ mSliderBlue = new SliderSprite(
+
+ 2, this, 372, 688,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.MARCADOR_ID),
activity.getVertexBufferObjectManager());
mBlackBehind = new Sprite(0, 0,
activity.mSpritesheetTexturePackTextureRegionLibrary
.get(posicoes.BLACK_BEHIND_ID),
activity.getVertexBufferObjectManager());
mChronometer = new Chronometer(this,
activity.getVertexBufferObjectManager());
mPontuacao = new Pontuacao(X_PONTUACAO_INICIAL, Y_PONTUACAO_INICIAL, 2,
this, activity.getVertexBufferObjectManager());
this.attachChild(mBackground);
this.attachChild(mPalco);
this.attachChild(mPlaca);
mPlaca.attachChild(mAdendo);
this.attachChild(mTronco);
this.attachChild(mFolhasFrente);
this.attachChild(mChamp);
this.attachChild(mChampShadow);
this.attachChild(mBox);
this.attachChild(mRed);
this.attachChild(mGreen);
this.attachChild(mBlue);
this.attachChild(mLetraR);
this.attachChild(mLetraG);
this.attachChild(mLetraB);
this.attachChild(mSliderRed);
registerTouchArea(mSliderRed);
this.attachChild(mSliderGreen);
registerTouchArea(mSliderGreen);
this.attachChild(mSliderBlue);
registerTouchArea(mSliderBlue);
// this.attachChild(mTextRemainingTime);
this.attachChild(mPontuacao);
movements = new MoveModifier(2f, -mPlaca.getWidth(), mPlaca.getX(),
mPlaca.getY(), mPlaca.getY(), EaseElasticOut.getInstance());
this.attachChild(mBlackBehind);
mBlackBehind.setVisible(false);
mPlaca.registerEntityModifier(movements);
movements.setAutoUnregisterWhenFinished(false);
mPlacaStart = new PlacaNinjaScreen(
activity.mSpritesheetTexturePackTextureRegionLibrary.get(
posicoes.TABUAPAUSA_ID).getTexture(), this);
registerTouchArea(mPlacaStart.goMenuItem);
this.attachChild(mPlacaStart);
this.attachChild(mChronometer);
mChronometer.updateTime(STARTING_TIME);
// setTouchAreaBindingOnActionMoveEnabled(true);
// this.setChildScene(new PlacaNinjaScreen(this), false, true, true);
}
@Override
public void restart() {
remainingTime = STARTING_TIME;
score = 0;
mActualColor = 0;
updateTime();
updateScore();
this.reset();
registerTouchArea(mPlacaStart.goMenuItem);
mChronometer.restart();
iniciando = true;
// this.setChildScene(new PlacaNinjaScreen(this),false,true,true);
}
private void createPauseMenu() {
mMenuScene = new PauseMenu(this);
}
@Override
public void ChangeColors(float newColor, int index) {
int iNewColor = (int) (newColor * 255);
// colors = (0xff00ffff >> (2*index))&((int)Math.floor(newColor*255));
int mask = (0xff00ffff >> (8 * index));
iNewColor <<= 16;
iNewColor >>= index * 8;
// a.setColor(pColor)
colors = (colors & mask);
colors |= iNewColor;
mChamp.setColor(Color.red(colors) / 256f, Color.green(colors) / 256f,
Color.blue(colors) / 256f);
int redStepsDiference = Math.abs(Color.red(colors) / mSliderRed.mStep
- Color.red(mPlacaColor) / mSliderRed.mStep);
int greenStepsDiference = Math.abs(Color.green(colors)
/ mSliderGreen.mStep - Color.green(mPlacaColor)
/ mSliderGreen.mStep);
int blueStepsDiference = Math.abs(Color.blue(colors)
/ mSliderBlue.mStep - Color.blue(mPlacaColor)
/ mSliderBlue.mStep);
/*
* mTextRemainingTime.setText(Integer.toString(redStepsDiference +
* greenStepsDiference + blueStepsDiference));
*/
if (redStepsDiference < 50
&& greenStepsDiference < 50
&& blueStepsDiference < 50
&& redStepsDiference + blueStepsDiference + greenStepsDiference < 80)
nextColor();
}
MoveModifier movements;
public void nextColor() {
remainingTime += TIME_CORRECT;
mPlacaColor = Color.rgb(rand.nextInt(255), rand.nextInt(255),
rand.nextInt(255));
setPlacaColor(mPlacaColor);
// mPlaca.setX(-mPlaca.getX());
// animacao entrando
movements.reset();
score++;
updateScore();
mActualColor++;
}
private void updateScore() {
mPontuacao.updateScore(score);
}
private void updateTime() {
if (mChronometer != null) {
mChronometer.updateTime(remainingTime);
}
}
public int colorFloatToInt(float number) {
return (int) (number * 255);
}
public float colorIntToFloat(int number) {
return number / 255f;
}
public void setPlacaColor(int color) {
mPlaca.setColor(colorIntToFloat(Color.red(mPlacaColor)),
colorIntToFloat(Color.green(mPlacaColor)),
colorIntToFloat(Color.blue(mPlacaColor)));
}
@Override
public boolean handleKeyDown(int pKeyCode, KeyEvent pEvent) {
if (pKeyCode == KeyEvent.KEYCODE_MENU
&& pEvent.getAction() == KeyEvent.ACTION_DOWN) {
if (this.hasChildScene()) {
/* Remove the menu and reset it. */
this.mMenuScene.back();
this.mConfirmExit.back();
this.mConfirmRestart.back();
if (!this.hasChildScene()) {
toggleEscuro(false);
}
} else {
/* Attach the menu. */
if (!mPlacaStart.isVisible()) {
this.setChildScene(this.mMenuScene, false, true, true);
toggleEscuro(true);
}
}
return true;
} else if (pKeyCode == KeyEvent.KEYCODE_BACK
&& pEvent.getAction() == KeyEvent.ACTION_DOWN) {
if (this.hasChildScene()) {
/* Remove the menu and reset it. */
clearChildScenes();
if (!this.hasChildScene()) {
toggleEscuro(false);
}
} else {
/* Attach the confirm. */
this.setChildScene(this.mConfirmExit, false, true, true);
toggleEscuro(true);
}
return true;
} else {
return false;
}
}
@Override
public void clearChildScenes() {
this.mMenuScene.back();
this.mConfirmExit.back();
}
StatsScreen stats;
public void endTime() {
// TODO tocaFimDeJogo
// TODO showScore
// mChronometer.registerEntityModifier(new FadeOutModifier(3));
if (stats == null)
stats = new StatsScreen(this);
mBlackBehind.setVisible(true);
stats.updateText(score);
this.setChildScene(stats, false, true, true);
}
}
| false | false | null | null |
diff --git a/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareChildContracts.java b/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareChildContracts.java
index fbd6dfca..e3f84511 100644
--- a/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareChildContracts.java
+++ b/src/java/se/idega/idegaweb/commune/childcare/presentation/ChildCareChildContracts.java
@@ -1,489 +1,491 @@
/*
* Created on 27.3.2003
*/
package se.idega.idegaweb.commune.childcare.presentation;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import javax.ejb.FinderException;
import se.idega.idegaweb.commune.care.business.PlacementHelper;
import se.idega.idegaweb.commune.care.data.ChildCareContract;
import se.idega.idegaweb.commune.childcare.business.ChildCareConstants;
import com.idega.block.school.data.School;
import com.idega.block.school.data.SchoolClass;
import com.idega.block.school.data.SchoolClassMember;
import com.idega.block.school.data.SchoolClassMemberLog;
import com.idega.core.contact.data.Email;
import com.idega.core.contact.data.Phone;
import com.idega.core.location.data.Address;
import com.idega.presentation.IWContext;
import com.idega.presentation.Table;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.CloseButton;
import com.idega.presentation.ui.Form;
import com.idega.presentation.ui.GenericButton;
import com.idega.presentation.ui.HiddenInput;
import com.idega.presentation.ui.SubmitButton;
import com.idega.user.data.User;
import com.idega.util.IWTimestamp;
import com.idega.util.PersonalIDFormatter;
import com.idega.util.TimePeriod;
import com.idega.util.text.Name;
/**
* @author laddi
*/
public class ChildCareChildContracts extends ChildCareBlock {
public static final String PARAMETER_APPLICATION_ID = "ccc_application_id";
private boolean insideWindow = false;
private boolean useFuturePayment = false;
/**
* @see se.idega.idegaweb.commune.childcare.presentation.ChildCareBlock#init(com.idega.presentation.IWContext)
*/
public void init(IWContext iwc) throws Exception {
Table table = new Table();
table.setCellpadding(0);
table.setCellspacing(0);
table.setWidth(getWidth());
GenericButton back = null;
if(insideWindow){
CloseButton close = new CloseButton(localize("close","Close"));
close = (CloseButton)getStyledInterface(close);
back = close;
}
else{
back = (GenericButton) getStyledInterface(new GenericButton("back",localize("back","Back")));
back.setPageToOpen(getResponsePage());
}
if (getChildID(iwc) != -1) {
parse(iwc);
int row = 1;
if (useStyleNames()) {
table.setCellpaddingLeft(1, row, 12);
table.setCellpaddingRight(1, row, 12);
}
table.add(getInformationTable(iwc), 1, row++);
table.setHeight(row++, 12);
table.setAlignment(1, row, Table.HORIZONTAL_ALIGN_RIGHT);
if (useStyleNames()) {
table.setCellpaddingLeft(1, row, 12);
table.setCellpaddingRight(1, row, 12);
}
table.add(getRemoveContractsForm(iwc), 1, row++);
table.setHeight(row++, 6);
table.add(getContractsTable(iwc), 1, row++);
table.setHeight(row++, 12);
if (useStyleNames()) {
table.setCellpaddingLeft(1, row, 12);
table.setCellpaddingRight(1, row, 12);
}
table.add(back, 1, row);
}
else {
table.add(getLocalizedHeader("child_care.no_child_or_application_found","No child or application found."), 1, 1);
table.setHeight(2, 12);
table.add(back, 1, 3);
if (useStyleNames()) {
table.setCellpaddingLeft(1, 1, 12);
table.setCellpaddingLeft(1, 3, 12);
}
}
add(table);
}
protected Table getContractsTable(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setWidth(getWidth());
table.setCellpadding(getCellpadding());
table.setCellspacing(getCellspacing());
table.setColumns(6);
if (useStyleNames()) {
table.setRowStyleClass(1, getHeaderRowClass());
}
else {
table.setRowColor(1, getHeaderColor());
}
int column = 1;
int row = 1;
if (useStyleNames()) {
table.setCellpaddingLeft(1, row, 12);
table.setCellpaddingRight(table.getColumns(), row, 12);
}
table.add(getLocalizedSmallHeader("child_care.provider","Provider"), column++, row);
table.add(getLocalizedSmallHeader("child_care.group","Group"), column++, row);
table.add(getLocalizedSmallHeader("child_care.created","Created"), column++, row);
table.add(getLocalizedSmallHeader("child_care.valid_from","Valid from"), column++, row);
table.add(getLocalizedSmallHeader("child_care.terminated","Terminated"), column++, row);
table.add(getLocalizedSmallHeader("child_care.care_time","Care time"), column++, row++);
ChildCareContract contract;
School provider;
SchoolClass group;
SchoolClassMember member;
Collection logs = null;
IWTimestamp created;
IWTimestamp validFrom;
IWTimestamp terminated = null;
Link viewContract;
String careTime;
boolean isActive = false;
IWTimestamp stampNow = new IWTimestamp();
Collection contracts = null;
// preventing overruling the child parameter when session got application reference
if(iwc.isParameterSet(ChildCareConstants.PARAMETER_CHILD_ID)){
contracts = getBusiness().getContractsByChild(getChildID(iwc));
}
else if (getSession().getApplicationID() != -1) {
contracts = getBusiness().getContractsByApplication(getSession().getApplicationID());
}
else {
contracts = getBusiness().getContractsByChild(getChildID(iwc));
}
int contractCount = 0;
Iterator iter = contracts.iterator();
while (iter.hasNext()) {
column = 1;
contract = (ChildCareContract) iter.next();
contractCount++;
Link viewCancelFile = null;
provider = contract.getApplication().getProvider();
created = new IWTimestamp(contract.getCreatedDate());
member = contract.getSchoolClassMember();
group = member.getSchoolClass();
if (contract.getTerminatedDate() != null) {
terminated = new IWTimestamp(contract.getTerminatedDate());
}
else {
terminated = null;
}
if (contract.getValidFromDate() != null) {
if (!iter.hasNext()) {
validFrom = new IWTimestamp(member.getRegisterDate());
}
else {
validFrom = new IWTimestamp(contract.getValidFromDate());
}
try {
logs = getBusiness().getSchoolBusiness().getSchoolClassMemberLogHome().findAllByPlacementAndDates(member, validFrom.getDate(), terminated != null ? terminated.getDate() : null);
if (logs.isEmpty()) {
SchoolClassMemberLog log = getBusiness().getSchoolBusiness().getSchoolClassMemberLogHome().findByPlacementAndDate(member, validFrom.getDate());
logs.add(log);
}
}
catch (FinderException fe) {
group = member.getSchoolClass();
}
}
else {
validFrom = null;
}
careTime = getCareTime(contract.getCareTime());
if (stampNow.isLaterThanOrEquals(validFrom)) {
isActive = true;
if (contract.getTerminatedDate() != null) {
if (terminated.isLaterThanOrEquals(stampNow)) {
isActive = true;
}
else {
isActive = false;
}
}
}
viewContract = getPDFLink(contract.getContractFileID(),localize("child_care.view_contract","View contract"));
if (contractCount == 1) {
int fileId = contract.getApplication().getCancelFormFileID();
if (fileId > 0) {
viewCancelFile = getPDFLink(fileId, localize("child_care.view_cancel_file", "View cancel contract document"));
}
}
if (logs != null && !logs.isEmpty()) {
Iterator iterator = logs.iterator();
boolean first = true;
while (iterator.hasNext()) {
SchoolClassMemberLog log = (SchoolClassMemberLog) iterator.next();
IWTimestamp startDate = null;
IWTimestamp endDate = null;
if (!iterator.hasNext()) {
startDate = new IWTimestamp(contract.getValidFromDate());
}
else {
startDate = new IWTimestamp(log.getStartDate());
}
if (first) {
if (contract.getTerminatedDate() != null) {
endDate = contract.getTerminatedDate() != null ? new IWTimestamp(contract.getTerminatedDate()) : null;
}
else {
endDate = log.getEndDate() != null ? new IWTimestamp(log.getEndDate()) : null;
}
first = false;
}
else {
endDate = log.getEndDate() != null ? new IWTimestamp(log.getEndDate()) : null;
}
row = addToTable(iwc, table, row, isActive, provider, log.getSchoolClass(), created, startDate, endDate, careTime, viewContract, viewCancelFile);
}
}
else {
row = addToTable(iwc, table, row, isActive, provider, group, created, validFrom, terminated, careTime, viewContract, viewCancelFile);
}
}
table.setColumnAlignment(2, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(3, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(4, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(5, Table.HORIZONTAL_ALIGN_CENTER);
return table;
}
private int addToTable(IWContext iwc, Table table, int row, boolean isActive, School provider, SchoolClass group, IWTimestamp created, IWTimestamp validFrom, IWTimestamp terminated, String careTime, Link viewContract, Link viewCancelFile) {
int column = 1;
table.add(getText(provider.getSchoolName(), isActive), column++, row);
table.add(getText(group.getName(), isActive), column++, row);
table.add(getText(created.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT), isActive), column++, row);
if (validFrom != null) {
table.add(getText(validFrom.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT), isActive), column++, row);
}
else {
table.add(getText("-", isActive), column++, row);
}
if (terminated != null) {
table.add(getText(terminated.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT), isActive), column++, row);
}
else {
table.add(getText("-", isActive), column++, row);
}
table.add(getText(careTime, isActive), column++, row);
table.setWidth(column, row, 12);
table.add(viewContract, column++, row);
if (viewCancelFile != null) {
table.add(viewCancelFile, column++, row);
}
if (useStyleNames()) {
if (row % 2 == 0) {
table.setRowStyleClass(row, getDarkRowClass());
}
else {
table.setRowStyleClass(row, getLightRowClass());
}
table.setCellpaddingLeft(1, row, 12);
table.setCellpaddingRight(table.getColumns(), row, 12);
}
else {
if (row % 2 == 0)
table.setRowColor(row, getZebraColor1());
else
table.setRowColor(row, getZebraColor2());
}
row++;
return row;
}
protected Table getInformationTable(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setWidth(Table.HUNDRED_PERCENT);
table.setCellpadding(0);
table.setCellspacing(0);
table.setColumns(3);
table.setWidth(1, "100");
table.setWidth(2, "6");
int row = 1;
User child = getBusiness().getUserBusiness().getUser(getChildID(iwc));
if (child != null) {
Address address = getBusiness().getUserBusiness().getUsersMainAddress(child);
Collection parents = getBusiness().getUserBusiness().getParentsForChild(child);
table.add(getLocalizedSmallHeader("child_care.child","Child"), 1, row);
Name name = new Name(child.getFirstName(), child.getMiddleName(), child.getLastName());
table.add(getSmallText(name.getName(iwc.getApplicationSettings().getDefaultLocale(), true)), 3, row);
table.add(getSmallText(" - "), 3, row);
table.add(getSmallText(PersonalIDFormatter.format(child.getPersonalID(), iwc.getCurrentLocale())), 3, row++);
if (address != null) {
table.add(getLocalizedSmallHeader("child_care.address","Address"), 1, row);
table.add(getSmallText(address.getStreetAddress()), 3, row);
if (address.getPostalAddress() != null) {
table.add(getSmallText(", "+address.getPostalAddress()), 3, row);
}
row++;
}
table.setHeight(row++, 12);
if (parents != null) {
table.add(getLocalizedSmallHeader("child_care.parents","Parents"), 1, row);
- Phone phone;
- Email email;
+ Phone phone = null;
+ Email email= null;
Iterator iter = parents.iterator();
while (iter.hasNext()) {
User parent = (User) iter.next();
address = getBusiness().getUserBusiness().getUsersMainAddress(parent);
email = getBusiness().getUserBusiness().getEmail(parent);
phone = getBusiness().getUserBusiness().getHomePhone(parent);
name = new Name(parent.getFirstName(), parent.getMiddleName(), parent.getLastName());
table.add(getSmallText(name.getName(iwc.getApplicationSettings().getDefaultLocale(), true)), 3, row);
table.add(getSmallText(" - "), 3, row);
table.add(getSmallText(PersonalIDFormatter.format(parent.getPersonalID(), iwc.getCurrentLocale())), 3, row++);
if (address != null) {
table.add(getSmallText(address.getStreetAddress()), 3, row);
if (address.getPostalAddress() != null)
table.add(getSmallText(", "+address.getPostalAddress()), 3, row);
row++;
}
if (phone != null && phone.getNumber() != null) {
table.add(getSmallText(localize("child_care.phone","Phone")+": "), 3, row);
table.add(getSmallText(phone.getNumber()), 3, row++);
}
if (email != null && email.getEmailAddress() != null) {
Link link = getSmallLink(email.getEmailAddress());
link.setURL("mailto:"+email.getEmailAddress(), false, false);
table.add(link, 3, row++);
}
+ phone = null;
+ email= null;
table.setHeight(row++, 12);
}
}
}
return table;
}
protected Form getRemoveContractsForm(IWContext iwc) throws RemoteException {
Form form = new Form();
int applicationId = getSession().getApplicationID();
form.add(new HiddenInput(PARAMETER_APPLICATION_ID, String.valueOf(applicationId)));
SubmitButton removeContracts = (SubmitButton) getStyledInterface(new SubmitButton("remove", localize("child_care.remove_future_contracts","Remove future contracts")));
form.add(removeContracts);
if (!getBusiness().hasFutureContracts(applicationId) && !getBusiness().hasFutureLogs(applicationId, new java.sql.Date(System.currentTimeMillis()))) {
removeContracts.setDisabled(true);
} else {
java.sql.Date earliestPossibleRemoveDate = new java.sql.Date(getEarliestPossibleContractRemoveDate().getTime());
IWTimestamp futureDate = new IWTimestamp(earliestPossibleRemoveDate);
if (getBusiness().getNumberOfFutureContracts(applicationId, futureDate.getDate()) > 0 ||
getBusiness().hasFutureLogs(applicationId, futureDate.getDate())) {
removeContracts.setSingleSubmitConfirm(localize("child_care.submit_contract_delete", "Are you sure you want to remove future contracts for this application?"));
} else {
removeContracts.setOnSubmitFunction("removeContract", "function removeContract() { alert('" + localize("child_care.only_admin_delete_future_contract", "Earliest possible date to remove contract is") +
" " + new IWTimestamp(earliestPossibleRemoveDate).getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT) + "'); return false; }");
}
}
return form;
}
private Date getEarliestPossibleContractRemoveDate() throws RemoteException {
Date earliestPossibleRemoveDate = null;
if (useFuturePayment) {
IWTimestamp t = new IWTimestamp();
t.setDay(1);
t.addMonths(3);
t.addDays(-1);
earliestPossibleRemoveDate = t.getDate();
} else {
PlacementHelper helper = getBusiness().getPlacementHelper(new Integer(getSession().getApplicationID()));
TimePeriod period = helper.getValidPeriod();
if (period != null) {
IWTimestamp stamp = new IWTimestamp(period.getFirstTimestamp().getDate());
stamp.addDays(-1);
earliestPossibleRemoveDate = stamp.getDate();
}
else {
IWTimestamp stamp = new IWTimestamp();
stamp.addDays(-1);
earliestPossibleRemoveDate = stamp.getDate();
}
}
return earliestPossibleRemoveDate;
}
protected Text getText(String text, boolean isActive) {
if (isActive) {
return getSmallHeader(text);
}
else {
return getSmallText(text);
}
}
protected Link getLink(String text, boolean isActive) {
if (isActive) {
return getSmallHeaderLink(text);
}
else {
return getSmallLink(text);
}
}
private void parse(IWContext iwc) {
if (iwc.isParameterSet(PARAMETER_APPLICATION_ID)) {
int applicationID = Integer.parseInt(iwc.getParameter(PARAMETER_APPLICATION_ID));
try {
getBusiness().removeLatestFutureContract(applicationID, new java.sql.Date(getEarliestPossibleContractRemoveDate().getTime()), iwc.getCurrentUser());
}
catch (RemoteException e) {
e.printStackTrace();
}
}
}
private int getChildID(IWContext iwc) throws RemoteException {
if(iwc.isParameterSet(ChildCareConstants.PARAMETER_CHILD_ID)) {
return Integer.parseInt(iwc.getParameter(ChildCareConstants.PARAMETER_CHILD_ID));
}
else {
return getSession().getChildID();
}
}
/**
* @return
*/
public boolean isInsideWindow() {
return insideWindow;
}
/**
* @param insideWindow
*/
public void setInsideWindow(boolean insideWindow) {
this.insideWindow = insideWindow;
}
public boolean getUseFuturePayment() {
return useFuturePayment;
}
public void setUseFuturePayment(boolean b) {
useFuturePayment = b;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/hw1/Nuke2.java b/hw1/Nuke2.java
new file mode 100644
index 0000000..6536711
--- /dev/null
+++ b/hw1/Nuke2.java
@@ -0,0 +1,27 @@
+/* OpenCommercial.java */
+
+import java.net.*;
+import java.io.*;
+
+/** a class called Nuke2 whose main method reads a string from the keyboard
+ * and prints the same string, with its second character removed.
+ */
+
+class Nuke2 {
+
+ public static void main(String[] arg) throws Exception {
+
+ BufferedReader keyboard;
+ String inputString;
+
+ /* read from keyboard */
+ keyboard = new BufferedReader(new InputStreamReader(System.in));
+ inputString = keyboard.readLine();
+
+ String outString;
+ /* concatenate 1st character and characters from 3rd to end */
+ outString = inputString.substring(0,1) + inputString.substring(2);
+ System.out.println(outString);
+
+ }
+}
| true | false | null | null |
diff --git a/sahi/src/main/java/com/redhat/qe/jon/sahi/tasks/SahiTasks.java b/sahi/src/main/java/com/redhat/qe/jon/sahi/tasks/SahiTasks.java
index 0bef676b..57384432 100644
--- a/sahi/src/main/java/com/redhat/qe/jon/sahi/tasks/SahiTasks.java
+++ b/sahi/src/main/java/com/redhat/qe/jon/sahi/tasks/SahiTasks.java
@@ -1,2739 +1,2744 @@
package com.redhat.qe.jon.sahi.tasks;
import com.redhat.qe.jon.sahi.base.ExtendedSahi;
import com.redhat.qe.Assert;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.sahi.client.ElementStub;
import org.testng.annotations.Optional;
public class SahiTasks extends ExtendedSahi {
public static final String ADMIN_USER = "rhqadmin";
public static final String ADMIN_PASSWORD = "rhqadmin";
private static Logger _logger = Logger.getLogger(SahiTasks.class.getName());
private Navigator navigator;
public SahiTasks(String browserPath, String browserName, String browserOpt, String sahiBaseDir, String sahiUserdataDir) {
super(browserPath, browserName, browserOpt, sahiBaseDir, sahiUserdataDir);
}
public Navigator getNavigator() {
return navigator;
}
@Override
public void open() {
// initialize navigator in
this.navigator = new Navigator(this);
super.open();
}
// ***************************************************************************
// Login/Logout
// ***************************************************************************
public boolean login(String userName, String password) {
if(this.waitForElementExists(this, this.link("Logout"), "Link: Logout", 1000*3)){
this.link("Logout").click();
}
if(!this.waitForElementExists(this, this.textbox("user"), "user", 1000*180)){
return false;
}
this.textbox("user").setValue(userName);
this.password("password").setValue(password);
this.cell("Login").click();
return true;
}
public void logout() {
this.link("Logout").click();
}
public String getCurrentLogin(){
return this.cell(1).near(this.cell("|").in(this.div("toolStrip"))).getText();
}
public void relogin(String userName, String password) {
String currentLogin = this.getCurrentLogin();
if(userName.equals(currentLogin)){
_logger.log(Level.FINE, "User["+userName+"] already logged in");
}else{
_logger.log(Level.FINE, "Currently logged in as ["+currentLogin+"], Changing login to ["+userName+"]");
logout();
login(userName, password);
}
}
//LDAP login check with first time login
public boolean ldapLogin(String userName, String password, String firstName, String lastName, String email, String phoneNumber, String department) {
if(this.login(userName, password)){
//check:: Is LDAP user logged in first time?
if(this.cell("Register User").exists()){
_logger.log(Level.INFO, "user["+userName+"] logged in first time, registeration required...");
//Set First Name
this.textbox("first").setValue(firstName);
//set Last Name
this.textbox("last").setValue(lastName);
//set email
this.textbox("email").setValue(email);
//set phone number
this.textbox("phone").setValue(phoneNumber);
//set Department
this.textbox("department").setValue(department);
//Click OK
this.cell("OK").click();
return true;
}
return true;
}
return false;
}
//-----------------------------------------------------------------------------------------------------------
// Register LDAP
//-----------------------------------------------------------------------------------------------------------
public boolean registerLdapServer(String ldapUrl, String ldapSearchBase, String ldapLoginProperty, boolean enableSSL, boolean enableLdap){
if(this.selectPage("Administration-->System Settings", this.cell("Server Details"), 1000*5, 3)){
this.selectComboBoxes("Jump to Section-->LDAP Configuration Properties");
// Enable/Disable LDAP
if(enableLdap){
this.radio("CAM_JAAS_PROVIDER[0]").click();
}else{
this.radio("CAM_JAAS_PROVIDER[1]").click();
}
//Set Search base
this.textbox("CAM_LDAP_BASE_DN").setValue(ldapSearchBase);
//Set username
this.textbox("CAM_LDAP_BIND_DN").setValue("");
//Set password
this.password("CAM_LDAP_BIND_PW").setValue("");
//Search Filter
this.textbox("CAM_LDAP_FILTER").setValue("");
//Group Search Filter
this.textbox("CAM_LDAP_GROUP_FILTER").setValue("");
//Group Member filter
this.textbox("CAM_LDAP_GROUP_MEMBER").setValue("");
//Is PosixGroup enabled/disabled
//Disabled
this.radio("CAM_LDAP_GROUP_USE_POSIX[1]").click();
// Login Property
this.textbox("CAM_LDAP_LOGIN_PROPERTY").setValue(ldapLoginProperty);
//LDAP URL
this.textbox("CAM_LDAP_NAMING_PROVIDER_URL").setValue(ldapUrl);
//Enable/Disable SSL
if(enableSSL){
this.radio("CAM_LDAP_PROTOCOL[0]").click();
}else{
this.radio("CAM_LDAP_PROTOCOL[1]").click();
}
this.cell("Save").near(this.cell("Dump System Info")).click();
return true;
}else{
return false;
}
}
/**
* Method which add column Last Modified Time and sort descending the table by this column
*
*/
public void sortChildResources() {
if (!this.cell("Last Modified Time").isVisible()) {
// 1. Add column Last Modified Time
this.xy(this.cell("Name").near(this.cell("Ancestry")), 3, 3).rightClick();
this.xy(this.cell("Columns"), 3, 3).mouseOver();
this.xy(this.cell("Last Modified Time"), 3, 3).click();
// 2. Set Auto Fit All Columns
this.xy(this.cell("Auto Fit All Columns"), 3, 3).click();
// 3. Sort the table by Last Modified Time descending
// sort by Last Modified Time
this.xy(this.cell("Last Modified Time"), 3, 3).click();
this.waitFor(Timing.WAIT_TIME);
this.xy(this.cell("Last Modified Time"), 3, 3).click();
this.waitFor(Timing.WAIT_TIME);
}
}
// ***************************************************************************
// Inventory
// ***************************************************************************
public void createGroup(String groupPanelName, String groupName, String groupDesc) {
this.link("Inventory").click();
this.waitFor(5000);
this.cell(groupPanelName).click();
if(!this.div(groupName).in(this.div("gridBody")).exists()){
this.cell("New").click();
this.textbox("name").setValue(groupName);
this.textarea("description").setValue(groupDesc);
this.cell("Next").click();
this.cell("Finish").click();
}else{
_logger.log(Level.WARNING, "Group["+groupName+"] already available!!");
}
checkInfo();
}
private boolean checkInfo(){
if(this.cell("OK").under(this.cell("An empty group is always considered as mixed.")).exists()){
this.cell("OK").under(this.cell("An empty group is always considered as mixed.")).click();
return true;
}
_logger.log(Level.FINE, "Info Message is not available to click!");
return false;
}
private void selectResourceOnGroup(String resourceName, int maxIndex){
for(int i=maxIndex; i>=0; i--){
if(this.textbox("search["+i+"]").exists()){
this.textbox("search["+i+"]").setValue(resourceName);
_logger.log(Level.INFO, "Value set on: search["+i+"]: "+resourceName);
break;
}
}
this.waitFor(5*1000);
if(!this.byText(resourceName, "nobr").exists()){
_logger.log(Level.WARNING, "Resource["+resourceName+"] not available to select..");
}
this.xy(this.byText(resourceName, "nobr"), 3,3).doubleClick();
this.waitFor(2*1000);
}
public void createGroup(String groupPanelName, String groupName, String groupDesc, ArrayList<String> resourceList) {
this.selectPage("Inventory-->Compatible Groups", this.textbox("search"), 1000*5, 3);
this.cell("New").click();
this.textbox("name").setValue(groupName);
this.textarea("description").setValue(groupDesc);
this.cell("Next").click();
for (String resource : resourceList) {
selectResourceOnGroup(resource.trim(), 2);
}
this.cell("Finish").click();
checkInfo();
}
public void createDynaGroup(String groupName, String groupDesc, ArrayList<String> preloadExpressions, String otherExpressions) {
this.link("Inventory").click();
this.waitFor(5000);
this.cell("Dynagroup Definitions").click();
this.cell("New").click();
this.textbox("name").setValue(groupName);
this.textarea("description").setValue(groupDesc);
this.textarea("expression").setValue(otherExpressions);
// TODO: Commented out below because we can't locate the elements via. sahi atm.
/*
for (String exp : preloadExpressions) {
//this.image("isc_HU").click();
this.image("Saved Expression").click();
this.cell(exp).click();
}
this.cell("isc_I7").click(); // recursive
this.image("isc_I9").click(); // refresh timer set to 1m
*/
this.cell("Save").click();
this.cell("Back to List").click();
}
public boolean verifyGroup(String groupPanelName, String groupName) {
this.link("Inventory").click();
this.waitFor(5000);
this.cell(groupPanelName).click();
return this.div(groupName).exists();
}
public void deleteGroup(String groupPanelName, String groupName) {
this.link("Inventory").click();
this.waitFor(5000);
this.cell(groupPanelName).click();
selectDivElement(groupName);
this.cell("Delete").click();
this.cell("Yes").click();
}
/*
public void uninventoryResourcethroughGroup(String groupName, String groupDesc){
createCompatibleGroup(groupName, groupDesc);
this.link("Inventory").click();
this.waitFor(5000);
this.cell("Compatible Groups").click();
this.link(groupName).click();
this.image("Inventory_grey_16.png").click();
this.div("RHQ Agent").click();
this.cell("Uninventory").click();
this.cell("Yes").click();
this.link("Inventory").click();
}
public void inventoryResource(){
this.link("Inventory").click();
this.cell("Discovery Queue").click();
this.cell("Refresh").click();
this.image("opener_closed.png").click();
this.image("unchecked.png").click();
this.cell("Import").click();
this.link("Inventory").click();
}
*/
// ***************************************************************************
// Bundle
// ***************************************************************************
public void createBundleURL(String bundleURL) {
this.link("Bundles").click();
this.cell("New").near(this.cell("Deploy")).click();
this.radio("URL").click();
this.textbox("url").setValue(bundleURL);
this.cell("Next").click();
this.cell("Next").click();
this.waitFor(1000*3);
this.cell("Finish").click();
this.waitFor(1000*3);
}
public void deleteBundle(String bundleName) {
this.link("Bundles").click();
this.waitFor(5000);
this.div(bundleName).click();
this.cell("Delete").click();
this.cell("Yes").click();
}
// ***************************************************************************
// Menus
// ***************************************************************************
public void topLevelMenuDashboardExist() {
Assert.assertTrue(this.link("Dashboard").exists());
Assert.assertTrue(this.link("Inventory").exists());
Assert.assertTrue(this.link("Reports").exists());
Assert.assertTrue(this.link("Bundles").exists());
Assert.assertTrue(this.link("Administration").exists());
Assert.assertTrue(this.link("Help").exists());
Assert.assertTrue(this.link("Logout").exists());
}
public void topLevelMenuInventoryExist() {
Assert.assertTrue(this.link("Dashboard").exists());
Assert.assertTrue(this.link("Inventory").exists());
Assert.assertTrue(this.link("Reports").exists());
Assert.assertTrue(this.link("Bundles").exists());
Assert.assertTrue(this.link("Administration").exists());
Assert.assertTrue(this.link("Help").exists());
Assert.assertTrue(this.link("Logout").exists());
}
public void topLevelMenuReportExist() {
Assert.assertTrue(this.link("Dashboard").exists());
Assert.assertTrue(this.link("Inventory").exists());
Assert.assertTrue(this.link("Reports").exists());
Assert.assertTrue(this.link("Bundles").exists());
Assert.assertTrue(this.link("Administration").exists());
Assert.assertTrue(this.link("Help").exists());
Assert.assertTrue(this.link("Logout").exists());
}
public void topLevelMenuBundlesExist() {
Assert.assertTrue(this.link("Dashboard").exists());
Assert.assertTrue(this.link("Inventory").exists());
Assert.assertTrue(this.link("Reports").exists());
Assert.assertTrue(this.link("Bundles").exists());
Assert.assertTrue(this.link("Administration").exists());
Assert.assertTrue(this.link("Help").exists());
Assert.assertTrue(this.link("Logout").exists());
}
public void topLevelMenuAdministrationExist() {
Assert.assertTrue(this.link("Dashboard").exists());
Assert.assertTrue(this.link("Inventory").exists());
Assert.assertTrue(this.link("Reports").exists());
Assert.assertTrue(this.link("Bundles").exists());
Assert.assertTrue(this.link("Administration").exists());
Assert.assertTrue(this.link("Help").exists());
Assert.assertTrue(this.link("Logout").exists());
}
public void topLevelMenuHelpExist() {
Assert.assertTrue(this.link("Dashboard").exists());
Assert.assertTrue(this.link("Inventory").exists());
Assert.assertTrue(this.link("Reports").exists());
Assert.assertTrue(this.link("Bundles").exists());
Assert.assertTrue(this.link("Administration").exists());
Assert.assertTrue(this.link("Help").exists());
Assert.assertTrue(this.link("Logout").exists());
}
public void topLevelMenuLogoutExist() {
Assert.assertTrue(this.link("Dashboard").exists());
Assert.assertTrue(this.link("Inventory").exists());
Assert.assertTrue(this.link("Reports").exists());
Assert.assertTrue(this.link("Bundles").exists());
Assert.assertTrue(this.link("Administration").exists());
Assert.assertTrue(this.link("Help").exists());
Assert.assertTrue(this.link("Logout").exists());
}
public void scondLevelMandatoryMenuLinksExist() {
Assert.assertTrue(this.cell("Summary").exists());
Assert.assertTrue(this.cell("Inventory").exists());
Assert.assertTrue(this.cell("Alerts").exists());
Assert.assertTrue(this.cell("Monitoring").exists());
}
// ***************************************************************************
// Users and Groups
// ***************************************************************************
public void createDeleteUser() {
selectPage("Administration-->Users", this.cell("User Name"), 1000*5, 2);
this.cell("New").click();
this.textbox("name").setValue("test1");
this.password("password").setValue("password");
this.textbox("firstName").setValue("testfirstName");
this.textbox("emailAddress").setValue("[email protected]");
this.textbox("department").setValue("testdepartment");
this.password("passwordVerify").setValue("password");
this.textbox("lastName").setValue("testlastname");
this.textbox("phoneNumber").setValue("999 999-9999");
this.cell("Save").click();
this.div("test1").click();
this.cell("Delete").click();
this.cell("Yes").click();
}
public void createDeleteRole() {
this.link("Administration").click();
this.cell("Roles").click();
this.cell("New").click();
this.textbox("name").setValue("testrole");
this.textbox("description").setValue("testdescription");
this.cell("Save").click();
this.div("testrole").click();
this.cell("Delete").click();
this.cell("Yes").click();
}
// ***************************************************************************
// Reports
// ***************************************************************************
public void inventoryReport() {
this.link("Reports").click();
this.cell("Inventory Summary").click();
}
public void platformUtilization() {
this.link("Reports").click();
this.cell("Platform Utilization").click();
}
public void suspectMetrics() {
this.link("Reports").click();
this.cell("Suspect Metrics").click();
}
public void configurationHistory() {
this.link("Reports").click();
this.cell("Configuration History").click();
}
public void recentOperations() {
this.link("Reports").click();
this.cell("Recent Operations").click();
}
public void recentAlerts() {
this.link("Reports").click();
this.cell("Recent Alerts").click();
}
public void alertDefinitions() {
this.link("Reports").click();
this.cell("Alert Definitions").click();
}
public void expandCollapseSections() {
this.image("opener_closed.png").click();
this.image("opener_opened.png[1]").click();
this.image("opener_closed.png").click();
this.image("opener_opened.png").click();
}
//******************************************************************
//Resource
//******************************************************************
public void checkResourceBrowserAvailabilityColumnsInGroupDef() {
org.testng.Assert.assertTrue(selectPage("Inventory-->Dynagroup Definitions", this.cell("Expression Set"), 1000*5, 3));
org.testng.Assert.assertTrue(this.cell("Name").exists());
org.testng.Assert.assertTrue(this.cell("Description").exists());
org.testng.Assert.assertTrue(this.cell("Expression Set").exists());
org.testng.Assert.assertTrue(this.cell("Last Calculation Time").exists());
org.testng.Assert.assertTrue(this.cell("Next Calculation Time").exists());
}
public void checkResourceBrowserAvailabilityColumnsInEachGroup() {
this.link("Inventory").click();
this.cell("All Groups").click();
org.testng.Assert.assertTrue(this.cell("Name").exists());
org.testng.Assert.assertTrue(this.cell("Description").exists());
org.testng.Assert.assertTrue(this.cell("Type").exists());
org.testng.Assert.assertTrue(this.cell("Name").exists());
org.testng.Assert.assertTrue(this.cell("Plugin").exists());
org.testng.Assert.assertTrue(this.cell("Descendants").exists());
this.cell("Compatible Groups").click();
org.testng.Assert.assertTrue(this.cell("Name").exists());
org.testng.Assert.assertTrue(this.cell("Description").exists());
org.testng.Assert.assertTrue(this.cell("Type").exists());
org.testng.Assert.assertTrue(this.cell("Name").exists());
org.testng.Assert.assertTrue(this.cell("Plugin").exists());
org.testng.Assert.assertTrue(this.cell("Descendants").exists());
this.cell("Mixed Groups").click();
org.testng.Assert.assertTrue(this.cell("Name").exists());
org.testng.Assert.assertTrue(this.cell("Description").exists());
org.testng.Assert.assertTrue(this.cell("Type").exists());
org.testng.Assert.assertTrue(this.cell("Name").exists());
org.testng.Assert.assertTrue(this.cell("Plugin").exists());
org.testng.Assert.assertTrue(this.cell("Descendants").exists());
this.cell("Problem Groups").click();
org.testng.Assert.assertTrue(this.cell("Name").exists());
org.testng.Assert.assertTrue(this.cell("Description").exists());
org.testng.Assert.assertTrue(this.cell("Type").exists());
org.testng.Assert.assertTrue(this.cell("Name").exists());
org.testng.Assert.assertTrue(this.cell("Plugin").exists());
org.testng.Assert.assertTrue(this.cell("Descendants").exists());
this.link("Inventory").click();
}
private void checkSearchBox(){
if(this.textbox("SearchPatternField").exists()){
_logger.log(Level.FINE, "'SearchPatternField' is avaialble");
}else{
org.testng.Assert.assertTrue(this.textbox("search").exists());
}
}
public void checkSearchTextBoxInEachResourceBrowserGroup() {
this.link("Inventory").click();
this.cell("All Groups").click();
checkSearchBox();
this.cell("Compatible Groups").click();
checkSearchBox();
this.cell("Mixed Groups").click();
checkSearchBox();
this.cell("Problem Groups").click();
checkSearchBox();
this.link("Inventory").click();
}
public void createDyanGroup(String groupName, String groupDesc) {
this.link("Inventory").click();
this.cell("Dynagroup Definitions").click();
this.cell("New").click();
this.textbox("name").setValue(groupName);
this.textarea("description").setValue(groupDesc);
this.textarea("expression").setValue("" +
"groupby resource.trait[jboss.system:type=Server:VersionName] \n\r" +
"resource.type.plugin = JBossAS \n\r" +
"resource.type.name = JBossAS Server");
this.cell("Save & Recalculate").click();
org.testng.Assert.assertTrue(this.waitForElementExists(this, this.cell("You have successfully recalculated this group definition"), "Cell: You have successfully recalculated this group definition", 1000*20), "Successful message check"); //Wait 20 seconds
this.bold("Back to List").click();
this.link(groupName).click();
this.bold("Back to List").click();
}
public void deleteDynaGroup(String groupDesc) {
selectPage("Inventory-->Dynagroup Definitions", this.cell("Name"), 1000*5, 2);
this.div(groupDesc).click();
this.cell("Delete").click();
this.cell("Yes").click();
}
public void resourceSearch(String searchTestuser, String password, String firstName, String secondName, String emailId, String searchRoleName, String desc, String compGroupName, String searchQueryName) {
//createCompatibleGroup(compGroupName, desc);
createUser(searchTestuser, password, firstName, secondName, emailId);
createRoleWithoutMangeInvetntory(searchRoleName, desc, compGroupName, searchTestuser);
loginNewUser(searchTestuser, password);
navigateToAllGroups();
setSearchBox(compGroupName="="+searchQueryName);
this.cell("name").click();
}
public void createRoleWithoutMangeInvetntory(String roleName, String desc, String compGroupName, String searchTestuser) {
this.link("Administration").click();
this.cell("Roles").click();
this.cell("New").click();
this.textbox("name").setValue(roleName);
this.textbox("description").setValue(desc);
this.cell("Resource Groups").click();
this.div("compGroupName").click();
this.image("right.png").click();
this.cell("users").click();
this.div(searchTestuser).click();
this.image("right.png").click();
this.cell("Save").click();
}
public void loginNewUser(String newUser, String password) {
this.textbox("user").setValue(newUser);
this.password("password").setValue(password);
this.cell("Login").click();
}
public void navigateToAllGroups() {
this.link("Inventory").click();
this.waitFor(5000);
this.cell("All Groups").click();
}
public void checkPlatform(){
this.link("Inventory").click();
Assert.assertTrue(this.cell("Platforms").exists());
this.cell("Platforms").click();
Assert.assertTrue(this.div("Linux").exists());
this.div("Linux").doubleClick();
}
public void checkAutoGroupResourceMenues(){
this.link("Inventory").click();
Assert.assertTrue(this.cell("Platforms").exists());
this.cell("Platforms").click();
Assert.assertTrue(this.div("Linux").exists());
this.div("Linux").doubleClick();
Assert.assertTrue(this.image("folder_group_closed.png[0]").exists());
Assert.assertTrue(this.image("folder_group_closed.png[1]").exists());
Assert.assertTrue(this.image("folder_group_closed.png[2]").exists());
scondLevelMandatoryMenuLinksExist();
this.image("folder_group_closed.png[2]").click();
this.image("folder_group_closed.png[1]").click();
this.image("folder_group_closed.png[0]").click();
this.cell("Alerts").click();
this.cell("CPUs").click();
Assert.assertTrue(this.cell("tabTitleSelected").near(this.cell("Alerts")).exists());
this.cell("File Systems").click();
Assert.assertTrue(this.cell("tabTitleSelected").near(this.cell("Alerts")).exists());
this.cell("CPUs").click();
Assert.assertTrue(this.cell("tabTitleSelected").near(this.cell("Alerts")).exists());
}
// ***************************************************************************
// Dashboard
// ***************************************************************************
public void clickDashboardTopLevelMenu() {
this.link("Dashboard").click();
}
public void editDashboard() {
this.cell("Edit Mode").click();
this.cell("View Mode").click();
}
public void newDashboard() {
this.link("Dashboard").click();
this.cell("New Dashboard").click();
this.textbox("name").setValue("test");
this.image("close.png[1]").click();
this.cell("Yes").click();
}
// ***************************************************************************
// Administration
// ***************************************************************************
public void createUser(String userName, String password, String firstName, String lastName, String email) {
selectPage("Administration-->Users", this.cell("User Name"), 1000*5, 2);
this.cell("New").click();
this.textbox("name").setValue(userName);
this.password("password").setValue(password);
this.password("passwordVerify").setValue(password);
this.textbox("firstName").setValue(firstName);
this.textbox("lastName").setValue(lastName);
this.textbox("emailAddress").setValue(email);
this.cell("Save").click();
}
public void deleteUser(String userName) {
selectPage("Administration-->Users", this.cell("User Name"), 1000*5, 2);
this.div(userName).click();
this.cell("Delete").click();
this.cell("Yes").click();
}
public void createRole(String roleName, String roleDesc) {
selectPage("Administration-->Roles", this.cell("Name"), 1000*5, 2);
this.cell("New").click();
this.textbox("name").setValue(roleName);
this.textbox("description").setValue("Description");
// TODO: Can't automate permission because we have no good
// way to associate the permission name and the checkbox
// that's next to it.
// One workaround is to hard code the permission list.
this.cell("Save").click();
}
public void deleteRole(String roleName) throws SahiTasksException {
this.link("Administration").click();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/*if(!this.waitForElementExists(this, this.cell("Roles"), "Roles", 1000*30)){ //wait time up to 30 seconds
throw new SahiTasksException("Element is not available [element name: Roles]");
}*/
this.cell("Roles").click();
if(this.span("Administration").exists()){
this.cell("Roles").click();
}
this.div(roleName).click();
this.cell("Delete").click();
this.cell("Yes").click();
}
public void addRolesToUser(String userName, ArrayList<String> roleNames) {
selectPage("Administration-->Users", this.cell("User Name"), 1000*5, 2);
this.link(userName).click();
for (String role : roleNames) {
this.div(role).click();
this.image("right.png").click();
}
this.cell("Save").click();
}
public boolean verifyUserRole(String userName, String password, ArrayList<String> roleNames) {
relogin(userName, password);
// TODO: Verification of role still needs to be done, however this
// hinges on whether we can create a role w/ specific permission
// by specifying only the permission name.
relogin("rhqadmin", "rhqadmin"); // reset
return true;
}
//******************************************************************
//Help
//******************************************************************
public void helpAbout() {
this.link("Help").click();
this.cell("About").click();
this.cell("Close").click();
}
public void helpFAQ() {
this.link("Help").click();
this.cell("Frequently Asked Questions (FAQ)").click();
}
public void helpDocumentation() {
this.link("Help").click();
this.cell("Documentation Set").click();
}
public void helpAPI() {
this.link("Help").click();
this.cell("API Javadoc").click();
}
public void helpDemoAllDemos() {
this.link("Help").click();
this.cell("Demo: All Demos").click();
}
public void helpDemoBundles() {
this.link("Help").click();
this.cell("Demo: Bundle Provisioning").click();
}
public void helpHowToGroupDefinitions() {
this.link("Help").click();
this.cell("How to build Group Definitions").click();
}
public void helpHowToSearchBar() {
this.link("Help").click();
this.cell("How to use the Search Bar").click();
}
public void collapseExpandProduct() {
this.cell("Product").click();
this.cell("Product").click();
}
public void collapseExpandDocumentation() {
this.cell("Documentation").click();
this.cell("Documentation").click();
}
public void collapseExpandTutorial() {
this.cell("Tutorial").click();
this.cell("Tutorial").click();
}
//************************************************************
// Recent Operations
//************************************************************
public void gotoReportRecentOperationsPage() {
this.selectPage("Reports-->Recent Operations", this.cell("Date Submitted"), 1000*5, 3);
}
public void gotoOperationsSchedulesPage(String resourceName, boolean selectSchedules) {
selectResource(resourceName);
this.cell("Operations").click();
if (selectSchedules) {
this.xy(this.cell("Schedules"), 3, 3).click();
} else {
this.xy(this.cell("History"), 3, 3).click();
}
}
public boolean createRecentOperationsSchedule() {
this.gotoOperationsSchedulesPage("Servers=RHQ Agent", true);
this.cell("New").click();
this.div("selectItemText").click();
this.div("Get Info On All Plugins").click();
this.radio("now");
this.cell("Schedule").click();
this.gotoOperationsSchedulesPage("Servers=RHQ Agent", true);
if(!this.div("Get Info On All Plugins").exists()){
_logger.log(Level.WARNING, "[Get Info On All Plugins] is not available!");
return false;
}
return true;
}
public boolean deleteRecentOperationsSchedule() {
this.gotoReportRecentOperationsPage();
this.div("Get Info On All Plugins").click();
this.cell("Delete").click();
this.cell("Yes").click();
if(this.div("Get Info On All Plugins").exists()){
_logger.log(Level.WARNING, "[Get Info On All Plugins] is available!");
return false;
}
return true;
}
public boolean recentOperationsForceDelete() {
if(createRecentOperationsSchedule()){
this.gotoReportRecentOperationsPage();
this.div("Get Info On All Plugins").click();
this.cell("Force Delete").click();
this.cell("Yes").click();
if(this.div("Get Info On All Plugins").exists()){
_logger.log(Level.WARNING, "[Get Info On All Plugins] is available! Deletion failed...");
return false;
}
return true;
}
return false;
}
public boolean recentOperationsQuickLinks() {
this.gotoReportRecentOperationsPage();
this.link("RHQ Agent").click();
ElementStub expandElement = this.image("row_collapsed.png").near(this.bold("Tags:"));
ElementStub collapsedElement = this.image("row_expanded.png").near(this.bold("Tags:"));
if(!expandElement.exists()){
expandElement.click();
}
int formTitleCoint = this.cell("formTitle").countSimilar();
HashMap<String, String> formDetail = new HashMap<String, String>();
for(int i=0; i<formTitleCoint; i++){
formDetail.put(this.cell("formTitle["+i+"]").getText(), this.cell("formCell["+i+"]").getText());
}
_logger.log(Level.INFO, "Form Data: "+formDetail);
if(!collapsedElement.exists()){
_logger.log(Level.WARNING, "Collapsed Image not found!");
return false;
}
return true;
}
public boolean opreationsWithRefreshButtonFunctionality() {
this.gotoReportRecentOperationsPage();
this.cell("Refresh").click();
this.div("Get Info On All Plugins").click();
if(!this.div("Get Info On All Plugins").exists()){
_logger.log(Level.WARNING, "[Get Info On All Plugins] is available!");
return false;
}
return true;
}
//************************************************************
// Dashboard
//*************************************************************
public boolean messagePortletExists() {
return this.cell("Message").isVisible();
}
public boolean inventorySummaryPortletExists() {
return this.cell("Inventory Summary").isVisible();
}
public boolean mashupPortletExists() {
return this.cell("Mashup").isVisible();
}
public boolean recentAlertsPortletExists() {
return this.cell("Recent Alerts").isVisible();
}
public boolean alertedOrUnavailableResourcesPortletExists() {
return this.cell("Alerted or Unavailable Resources").isVisible();
}
public boolean recentOperationsPortletExists() {
return this.cell("Recent Operations").isVisible();
}
public void messagePortletRefresh() {
this.image("refresh.png").click();
}
public void messagePortletMinimizeMaximize() {
this.image("cascade_Disabled.png").click();
this.image("minimize_Disabled.png").click();
}
public boolean verifyInventorySummaryPortlet() {
return this.cell("Platform Total :").isVisible()
&& this.cell("Server Total :").isVisible()
&& this.cell("Service Total :").isVisible()
&& this.cell("Compatible Group Total :").isVisible()
&& this.cell("Mixed Group Total :").isVisible()
&& this.cell("Group Definition Total :").isVisible()
&& this.cell("Average Metrics per Minute :").isVisible();
}
public boolean verifyDefaultTabName() {
return this.cell("Default").isVisible();
}
//************************************
//* Favourite
//*************************************
public void createFavourite() {
selectResource("Servers=RHQ Agent");
this.image("Favorite_24.png").click();
}
public void removeFavourite() {
selectResource("Servers=RHQ Agent");
this.image("Favorite_24_Selected.png").click();
}
public boolean checkFavouriteBadgeForAgent() {
return this.image("Favorite_24_Selected.png").isVisible();
}
public boolean checkBadgeAfterRmovingFavourite() {
return this.image("Favorite_24.png").isVisible();
}
//********************************************************
// Plugins Verification
//********************************************************
public void locatePluginPage(boolean selectAgentPluginPage){
if(selectAgentPluginPage){
selectPage("Administration-->Agent Plugins", this.cell("Name"), 1000*5, 2);
}else{
selectPage("Administration-->Server Plugins", this.cell("Name"), 1000*5, 2);
}
}
public boolean getAgentServerPluginsStaus(String pluginsName, boolean redirectPage, boolean isAgentPlugins){
if(redirectPage){
locatePluginPage(isAgentPlugins);
}
return this.link(pluginsName).exists();
}
//*********************************************************************************
//* Redirect pages, main menu display page should be on span
//*********************************************************************************
public boolean selectPage(String pageLocation, ElementStub elementReference, int waitTime, int retryCount){
String[] pageLocations = pageLocation.split("-->");
for(int i=1;i<=retryCount;i++){
this.link(pageLocations[0].trim()).click();
this.waitForElementExists(this, this.span(pageLocations[0].trim()), "SPAN: "+pageLocations[0].trim(), waitTime);
this.cell(pageLocations[1].trim()).click();
if(!this.waitForElementExists(this, elementReference, "Element: "+elementReference.toString(), waitTime)){
_logger.log(Level.INFO, "Filed to load : "+pageLocation+", Retry Count: ["+i+" of "+retryCount+"]");
}else{
_logger.log(Level.FINE, "Loaded Successfully: "+pageLocation);
return true;
}
}
return false;
}
public boolean selectDivElement(String elementName){
//Set max div count on dynamic
int divMaxIndex = this.div(elementName).countSimilar();
for(int i=divMaxIndex; i>=0; i--){
if(this.div(elementName+"["+i+"]").exists()){
this.div(elementName+"["+i+"]").click();
_logger.log(Level.INFO, "Clciked on the element: "+elementName+"["+i+"]");
return true;
}
}
_logger.log(Level.WARNING, "There is no div element["+elementName+"] found!, Input MaxIndex:"+divMaxIndex);
return false;
}
//*********************************************************************************
//* About and build versions
//*********************************************************************************
public HashMap<String, String> getBuildVersion(){
selectPage("Help-->About", this.span("DisplayLabel[0]"), 1000*5, 3);
HashMap<String, String> version = new HashMap<String, String>();
version.put("version", this.span("DisplayLabel[0]").getText());
version.put("build.number", this.span("DisplayLabel[1]").getText());
version.put("gwt.version", this.span("DisplayLabel[2]").getText());
version.put("smartgwt.version", this.span("DisplayLabel[3]").getText());
_logger.log(Level.INFO, "Version Information: "+version);
this.row("Close").click();
return version;
}
//*********************************************************************************
//* Alert Definition Creation
//*********************************************************************************
public void selectResource(String resourceName){
String[] resourceType = resourceName.split("=");
if (resourceType.length > 1) {
selectPage("Inventory-->"+resourceType[0], this.textbox("search"), 1000*5, 3);
setSearchBox(resourceType[1].trim());
} else {
_logger.log(Level.WARNING, "Invalid parameter passed --> "+resourceName);
return;
}
this.link(resourceType[1].trim()).click();
}
public void gotoAlertDefinationPage(String resourceName, boolean definitionsPage) {
selectResource(resourceName);
this.cell("Alerts").click();
if (definitionsPage) {
this.xy(this.cell("Definitions"), 3, 3).click();
} else {
this.xy(this.cell("History"), 3, 3).click();
}
}
/**
*
* @param fileInputIdent indentify file input field (name,id)
* @param path to file to be uploaded - relative to /automatjon/jon/sahi/resources/
*/
public void setFileToUpload(String fileInputIdent, String path) {
URL resource = SahiTasks.class.getResource(path);
if (resource==null) {
throw new RuntimeException("Unable to find resource ["+path+"] on classpath");
}
String fullPath = resource.getPath();
this.file(fileInputIdent).setFile(fullPath);
this.execute("_sahi._call(_sahi._file(\""+fileInputIdent+"\").type = \"text\");");
this.textbox(fileInputIdent).setValue(fullPath);
}
public void selectComboBoxes(String options, String nearElement, String optionElementType){
if (options != null) {
if (options.trim().length() > 0) {
String[] optionArray = this.getCommaToArray(options);
for (String option : optionArray) {
String[] optionTmp = option.split("-->");
if(optionTmp[0].contains("|")){
String[] nearDrop = optionTmp[0].split("\\|");
nearElement = nearDrop[0];
optionTmp[0] = nearDrop[1];
}
if(nearElement == null){
if (this.div(optionTmp[0].trim() + "[1]").exists()) {
_logger.info("\"" + optionTmp[0].trim() + "[1]\" is available to select");
optionTmp[0] = optionTmp[0].trim()+"[1]";
//this.selectComboBoxDivRow(this, optionTmp[0].trim() + "[1]", optionTmp[1].trim());
}
}
//int maxCount = 1;
if(optionElementType == null){
optionElementType = "row";
}
optionElementType = optionElementType.toLowerCase();
if(optionElementType.equals("row")){
//maxCount = this.row(optionTmp[1].trim()).countSimilar();
//optionTmp[1] = optionTmp[1].trim()+"["+(maxCount-1)+"]";
if(nearElement != null){
this.selectComboBoxByNearCellOptionByRow(this, optionTmp[0].trim(), nearElement, optionTmp[1].trim());
}else{
this.selectComboBoxDivRow(this, optionTmp[0].trim(), optionTmp[1].trim());
}
}else if(optionElementType.equals("div")){
//maxCount = this.div(optionTmp[1].trim()).countSimilar();
//optionTmp[1] = optionTmp[1].trim()+"["+(maxCount-1)+"]";
if(nearElement != null){
this.selectComboBoxByNearCellOptionByDiv(this, optionTmp[0].trim(), nearElement, optionTmp[1].trim());
}else{
this.selectComboBoxDivDiv(this, optionTmp[0].trim(), optionTmp[1].trim());
}
}
}
}
}
}
public void selectComboBoxes(String options) {
selectComboBoxes(options, null, null);
}
public void selectComboBoxes(String options, String nearElement) {
selectComboBoxes(options, null, nearElement);
}
private void updateSystemUserNotification(String users) {
String[] usersArray = this.getCommaToArray(users);
for (String user : usersArray) {
this.byText(user.trim(), "nobr").doubleClick();
}
}
private int getNumberAlert(String alertName) {
return this.link(alertName).countSimilar();
}
private void updateTextBoxValues(String textBoxKeyValue) {
if (textBoxKeyValue != null) {
if (textBoxKeyValue.trim().length() > 0) {
HashMap<String, String> keyValueMap = this.getKeyValueMap(textBoxKeyValue);
Set<String> keys = keyValueMap.keySet();
for (String key : keys) {
try{
this.textbox(Integer.parseInt(key)).setValue(keyValueMap.get(key));
}catch(Exception ex){
this.textbox(key).setValue(keyValueMap.get(key));
}
_logger.log(Level.INFO, "Updated textbox:["+key+"="+keyValueMap.get(key)+"]");
}
}
}
}
private void updateRadioButtons(String radioButtons){
String[] radioButtonsArray = this.getCommaToArray(radioButtons);
for(int i=0; radioButtonsArray.length > i; i++){
this.radio(radioButtonsArray[i].trim()).check();
_logger.log(Level.INFO, "Radio Button \""+radioButtonsArray[i].trim()+"\" selected");
}
}
private void selectYesNoradioButtons(String buttonKeyValue) {
if (buttonKeyValue != null) {
if (buttonKeyValue.trim().length() > 0) {
HashMap<String, String> keyValueMap = this.getKeyValueMap(buttonKeyValue);
Set<String> keys = keyValueMap.keySet();
for (String key : keys) {
if (keyValueMap.get(key).equalsIgnoreCase("yes")) {
this.radio(key).check();
} else {
this.radio(key + "[1]").check();
}
}
}
}
}
public int createAlert(@Optional String resourceName, String alertName, @Optional String alertDescription, String conditionsDropDown, @Optional String conditionTextBox, String notificationType, String notificationData, @Optional String dampeningDropDown, @Optional String dampeningTextBoxData, @Optional String recoveryAlertDropDown, @Optional String disableWhenFired) {
//Select Resource to define alert
if (resourceName != null) {
gotoAlertDefinationPage(resourceName, true);
}
//Take current status
int similarAlert = getNumberAlert(alertName);
_logger.info("pre-status of Alert definition [" + alertName + "]: " + similarAlert + " definition(s)");
//Define new alert name and Description(if any)
this.cell("New").click();
_logger.log(Level.INFO, "Alert Name Text Box Status: "+this.textbox("/textItem/").near(this.row("Name :")).exists());
this.textbox("/textItem/").near(this.row("Name :")).click();
this.textbox("/textItem/").near(this.row("Name :")).setValue(alertName);
if (alertDescription != null) {
this.textarea("textItem").near(this.row("Description :")).setValue(alertDescription);
}
//Add conditions
this.cell("Conditions").click();
this.cell("Add").click();
//selectComboBoxes(conditionsDropDown); //Disabled, not stable with this
selectComboBoxes(conditionsDropDown, "row");
updateTextBoxValues(conditionTextBox);
this.cell("OK").click();
//Add notifications
this.cell("Notifications").click();
this.cell("Add[1]").click();
//Select Notification type
selectComboBoxes(notificationType, "row");
if (notificationType.contains("System Users")) {
updateSystemUserNotification(notificationData);
} else {
_logger.log(Level.WARNING, "Undefined notification type: " + notificationType);
}
this.cell("OK").click();
//Recovery
this.cell("Recovery").click();
selectComboBoxes(recoveryAlertDropDown);
selectYesNoradioButtons(disableWhenFired);
//Dampening
this.cell("Dampening").click();
selectComboBoxes(dampeningDropDown);
updateTextBoxValues(dampeningTextBoxData);
//Final step
this.xy(this.cell("Save"), 3, 3).click();
this.bold("Back to List").click();
return getNumberAlert(alertName) - similarAlert;
}
//*********************************************************************************
//* Alert History Validation
//*********************************************************************************
public int validateAlertHistory(@Optional String resourceName, String alertName) {
//Select Resource to define alert
if (resourceName != null) {
gotoAlertDefinationPage(resourceName, false);
}
//Get Number count from Alert History history
return this.link(alertName).countSimilar();
}
//*********************************************************************************
//* Alert Definition Deletion
//*********************************************************************************
public boolean deleteAlertDefinition(@Optional String resourceName, String alertName) {
if (resourceName != null) {
gotoAlertDefinationPage(resourceName, true);
}
int numberOfDefinitions = this.link(alertName).countSimilar();
_logger.log(Level.INFO, "[Before Deletion] \""+alertName+"\" definition count: "+numberOfDefinitions);
if(this.div(alertName+"[1]").exists()){
this.div(alertName+"[1]").click(); //Selecting the definition
}else{
this.div(alertName).click(); //Selecting the definition
}
this.cell("Delete[4]").click();
this.cell("Yes").click();
int numberOfDefinitionsUpdated = this.link(alertName).countSimilar();
_logger.log(Level.INFO, "[After Deletion] \""+alertName+"\" definition count: "+numberOfDefinitionsUpdated);
if((numberOfDefinitions - numberOfDefinitionsUpdated) == 1){
return true;
}else{
return false;
}
}
//*********************************************************************************
//* Alert History Deletion
//*********************************************************************************
public boolean deleteAlertHistory(@Optional String resourceName, String alertName) {
if (resourceName != null) {
gotoAlertDefinationPage(resourceName, false);
}
int numberOfHistory = this.link(alertName).countSimilar();
_logger.log(Level.INFO, "[Before Deletion] \""+alertName+"\" history count: "+numberOfHistory);
if(this.div(alertName+"[1]").exists()){
this.div(alertName+"[1]").click(); //Selecting the history
}else{
this.div(alertName).click(); //Selecting the history
}
this.cell("Delete[3]").click();
this.cell("Yes").click();
int numberOfHistoryUpdated = this.link(alertName).countSimilar();
_logger.log(Level.INFO, "[After Deletion] \""+alertName+"\" history count: "+numberOfHistoryUpdated);
if((numberOfHistory - numberOfHistoryUpdated) == 1){
return true;
}else{
return false;
}
}
//**************************************************************************************************
//* Get GWT table information
//**************************************************************************************************
public LinkedList<HashMap<String, String>> getRHQgwtTableFullDetails(String tableName, int tableCountOffset, String columnsCSV, String replacementKeyValue) {
return getRHQgwtTableDetails(tableName, tableCountOffset, columnsCSV, replacementKeyValue, false, 0, false, null);
}
public LinkedList<HashMap<String, String>> getRHQgwtTableConditionalDetails(String tableName, int tableCountOffset, String columnsCSV, String replacementKeyValue, String condition) {
return getRHQgwtTableDetails(tableName, tableCountOffset, columnsCSV, replacementKeyValue, false, 0, true, condition);
}
public HashMap<String, String> getRHQgwtTableRowDetails(String tableName, int tableCountOffset, String columnsCSV, String replacementKeyValue, int rowNo) {
LinkedList<HashMap<String, String>> rowDetails = getRHQgwtTableDetails(tableName, tableCountOffset, columnsCSV, replacementKeyValue, true, rowNo, false, null);
if(rowDetails.size() == 1){
return rowDetails.get(0);
}else{
return new HashMap<String, String>();
}
}
@SuppressWarnings("unchecked")
public LinkedList<HashMap<String, String>> getRHQgwtTableDetails(String tableName, int tableCountOffset, String columnsCSV, String replacementKeyValue, boolean singleRow, int rowNo, boolean conditional, String condition) {
int noListTables = this.table(tableName).countSimilar()-tableCountOffset;
LinkedList<HashMap<String, String>> rows = new LinkedList<HashMap<String,String>>();
HashMap<String, String> row = new HashMap<String, String>();
String[] columns = getCommaToArray(columnsCSV);
HashMap<String, String> replacement = getKeyValueMap(replacementKeyValue);
String innerHTMLstring;
String textString;
String columnName = null;
String columnValue = null;
if(conditional){
String[] columnValueTmp = condition.split("=");
columnName = columnValueTmp[0].trim();
columnValue = columnValueTmp[1].trim();
}
for(int i=0; ;i++){
if(singleRow){
i=rowNo;
}
try{
for(int c=0; c<columns.length; c++){
ElementStub categoryElement = cell(table(tableName+"["+(noListTables-1)+"]"),i, c);
innerHTMLstring = categoryElement.fetch("innerHTML");
textString = categoryElement.getText();
if(innerHTMLstring.contains("src=") && (textString.length() == 0)){
innerHTMLstring = innerHTMLstring.substring(innerHTMLstring.indexOf("src=\"")+5, innerHTMLstring.indexOf('"', innerHTMLstring.indexOf("src=\"")+5));
row.put(columns[c], innerHTMLstring.substring(innerHTMLstring.lastIndexOf('/')+1));
}else{
row.put(columns[c], textString);
}
if(replacement.get(row.get(columns[c])) != null){
row.put(columns[c], replacement.get(row.get(columns[c])));
}
}
}catch (Exception ex){
_logger.log(Level.FINER, "Known Exception: "+ex.getMessage());
break;
}
rows.addLast((HashMap<String, String>) row.clone());
if(singleRow){
return rows;
}
if(conditional){
if(row.get(columnName).equalsIgnoreCase(columnValue)){
return rows;
}
}
row.clear();
}
_logger.log(Level.FINEST, "Table Details: "+rows);
return rows;
}
//*********************************************************************************
//* Drift Management Add Drift on GUI
//*********************************************************************************
public void gotoDriftDefinationPage(String resourceName, boolean definitionsPage) {
if (definitionsPage) {
selectResource(resourceName);
this.cell("Drift").click();
//this.xy(this.cell("Definitions"), 3, 3).click();
} else {
this.link("Reports").click();
this.cell("Recent Drift").click();
//this.xy(this.cell("History"), 3, 3).click();
}
}
private void byPassConfirmationBox(){
if(this.cell("Yes").near(this.cell("No")).exists()){
this.cell("Yes").near(this.cell("No")).click();
}else{
_logger.log(Level.FINE, "Unable to find 'Confirmation' box!!");
_logger.log(Level.FINE, "Trying with 'Yes' button");
this.cell("Yes").click();
}
}
public boolean clickDriftDetectNowOrDelete(String driftName, int divMaxIndex, long waitTime, boolean deleteDrift) throws InterruptedException{
for(int i=divMaxIndex; i>=0; i--){
if(this.div(driftName+"["+i+"]").exists()){
this.div(driftName+"["+i+"]").click();
_logger.log(Level.INFO, "Clciked on, Drift Name: "+driftName+"["+i+"]");
break;
}
}
if(deleteDrift){
this.cell("Delete").near(this.cell("Delete All")).click();
//this.row("Delete[2]").click();
this.cell("Yes").near(this.cell("No")).click();
return this.link(driftName).exists();
}else{
if(this.cell("Detect Now").near(this.cell("Delete All")).exists()){
this.cell("Detect Now").near(this.cell("Delete All")).click();
}else{
this.cell("DetectNow").near(this.cell("Delete All")).click();
}
//This line added as a work-around for the issue --> Bug 949471
byPassConfirmationBox();
_logger.log(Level.INFO, "Waiting "+(waitTime/1000)+" Second(s) for agent/server drift actions...");
Thread.sleep(waitTime); //Give X second(s) for agent/server actions
return true;
}
}
public boolean addDrift(String baseDir, String resourceName, String templateName, String driftName, String textBoxKeyValue, String radioButtons, String fileIncludes, String fileExcludes ) throws InterruptedException, IOException {
//Remove old file History If any
DriftManagementSSH driftSSH = new DriftManagementSSH();
driftSSH.getConnection(System.getenv().get("AGENT_NAME"), System.getenv().get("AGENT_HOST_USER"), System.getenv().get("AGENT_HOST_PASSWORD"));
if(!driftSSH.deleteFilesDirs(baseDir)){
return false;
}
if(!driftSSH.createFileDir(baseDir)){
return false;
}
driftSSH.closeConnection();
//Select Resource
if (resourceName != null) {
gotoDriftDefinationPage(resourceName, true);
}
this.cell("New").click();
this.waitFor(1000*1);
//This line added as a work-around for the issue --> Bug 949471
byPassConfirmationBox();
//Select Template
if(templateName != null){
selectComboBoxes(templateName);
}
this.cell("Next").click();
//Update Drift Name
this.textbox("name").setValue(driftName.trim());
//Update text Boxes
updateTextBoxValues(textBoxKeyValue);
//Select Radio Buttons
updateRadioButtons(radioButtons);
int addImgCount = this.image("add.png").countSimilar();
_logger.log(Level.INFO, "Number of add.png images: "+addImgCount);
//File name Includes
if(fileIncludes != null){
String[] files = this.getCommaToArray(fileIncludes);
for(String fileName : files){
this.image("add.png["+(addImgCount-2)+"]").focus();
this.execute("_sahi._keyPress(_sahi._image('add.png["+(addImgCount-2)+"]'), 32);"); //32 - Space bar
if(this.image("checked.png").near(this.bold("Path")).exists()){
this.image("checked.png").near(this.bold("Path")).click();
_logger.log(Level.INFO, "Path Check/uncheck available to select and selected...");
}else{
_logger.log(Level.INFO, "Path Check/uncheck not available...");
}
this.textbox("path").setValue(fileName.trim());
_logger.log(Level.INFO, "File Name added [Includes]: "+fileName);
this.cell("OK").click();
}
}
//File Excludes
if(fileExcludes != null){
String[] files = this.getCommaToArray(fileExcludes);
for(String fileName : files){
this.image("add.png["+(addImgCount-1)+"]").focus();
this.execute("_sahi._keyPress(_sahi._image('add.png["+(addImgCount-1)+"]'), 32);"); //32 - Space bar
this.textbox("path").setValue(fileName.trim());
_logger.log(Level.INFO, "File Name added [Excludes]: "+fileName);
this.cell("OK").click();
}
}
this.cell("Finish").click();
if(this.link(driftName.trim()).exists()){
_logger.log(Level.INFO, "Drift Name ["+driftName.trim()+"] added successfully.");
//Do Manual 'Detect Now'
clickDriftDetectNowOrDelete(driftName, 2, 1000*65, false);
return true;
}
return false;
}
//***************************************************************************************
//* Get Drift History tables
//***************************************************************************************
public LinkedList<HashMap<String, String>> getDriftManagementHistory(String resource, int tableCountOffset) throws InterruptedException{
if(resource != null){
gotoDriftDefinationPage(resource, false);
}
Thread.sleep(1000);
return getRHQgwtTableFullDetails("listTable", tableCountOffset, "CreationTime,Definition,Snapshot,Category,Path,Resource,Ancestry", "Drift_add_16.png=added,Drift_change_16.png=changed,Drift_remove_16.png=removed");
}
//*********************************************************************************
//* Drift Management add/change/remove Files
//*********************************************************************************
private boolean fileAdditionDeletionChangeOnDrift(String baseDir, HashMap<String, String>files, Set<String> fileKeys, String fileAction, DriftManagementSSH driftSSH){
for (String key : fileKeys) {
_logger.info("File: "+key);
if(fileAction.equalsIgnoreCase("added")){
if(!driftSSH.createFileDir(baseDir+key.substring(0,key.lastIndexOf("/")))){
return false;
}
if(!driftSSH.addLineOnFile(baseDir+key, files.get(key), false)){
return false;
}
}else if(fileAction.equalsIgnoreCase("changed")){
if(!driftSSH.createFileDir(baseDir+key.substring(0,key.lastIndexOf("/")))){
return false;
}
if(!driftSSH.addLineOnFile(baseDir+key, files.get(key), true)){
return false;
}
}else if(fileAction.equalsIgnoreCase("removed")){
if(!driftSSH.deleteFilesDirs(baseDir+key)){
return false;
}
}
}
return true;
}
private boolean checkAvailabilityOnDriftHistory(Set<String> fileKeys, LinkedList<HashMap<String, String>> driftHistory, String category){
for(String key : fileKeys){
boolean status = false;
for(HashMap<String, String> singleRow : driftHistory){
if(singleRow.get("Path").equals(key)){
if(singleRow.get("Category").equalsIgnoreCase(category)){
_logger.log(Level.INFO, "Drift Change available on History[include File: "+key+"]: "+singleRow.get("Path"));
status = true;
break;
}
}
}
if(!status){
return false;
}
}
return true;
}
public boolean addChangeRemoveDriftFile(String resourceName, String driftName, String baseDir, String fileIncludes, String fileExcludes, String fileAction ) throws InterruptedException, IOException {
if(!baseDir.endsWith("/")){
baseDir += "/";
}
//Add files on back-end
DriftManagementSSH driftSSH = new DriftManagementSSH();
driftSSH.getConnection(System.getenv().get("AGENT_NAME"), System.getenv().get("AGENT_HOST_USER"), System.getenv().get("AGENT_HOST_PASSWORD"));
// Include files action
HashMap<String, String>filesInclude = new HashMap<String,String>();
filesInclude = getKeyValueMap(fileIncludes);
Set<String> includeFileKeys = filesInclude.keySet();
if(!fileAdditionDeletionChangeOnDrift(baseDir, filesInclude, includeFileKeys, fileAction, driftSSH)){
return false;
}
// Exclude files action
HashMap<String, String>filesExclude = new HashMap<String,String>();
filesExclude = getKeyValueMap(fileExcludes);
Set<String> excludeFileKeys = filesExclude.keySet();
if(!fileAdditionDeletionChangeOnDrift(baseDir, filesExclude, excludeFileKeys, fileAction, driftSSH)){
return false;
}
driftSSH.closeConnection();
//Select Resource
if (resourceName != null) {
gotoDriftDefinationPage(resourceName, true);
}else{
this.xy(this.cell("Definitions"), 3, 3).click();
}
//Do Manual 'Detect Now'
clickDriftDetectNowOrDelete(driftName, 3, 1000*65, false);
// Redirect to history Page
//this.xy(this.cell("History"), 3, 3).click();
LinkedList<HashMap<String, String>> driftHistory = getDriftManagementHistory(resourceName, 2);
//IncludeFile Test
if(!checkAvailabilityOnDriftHistory(includeFileKeys, driftHistory, fileAction)){
return false;
}
//ExcludeFile Test
if(checkAvailabilityOnDriftHistory(excludeFileKeys, driftHistory, fileAction)){
return false;
}
return true;
}
//***************************************************************************************************
//* Delete Drift
//***************************************************************************************************
public boolean deleteDrift(String resourceName, String driftName, String baseDir) throws InterruptedException, IOException{
//Select Resource
if (resourceName != null) {
gotoDriftDefinationPage(resourceName, true);
}else{
this.xy(this.cell("Definitions"), 3, 3).click();
}
//Delete files on back-end
DriftManagementSSH driftSSH = new DriftManagementSSH();
driftSSH.getConnection(System.getenv().get("AGENT_NAME"), System.getenv().get("AGENT_HOST_USER"), System.getenv().get("AGENT_HOST_PASSWORD"));
if(!driftSSH.deleteFilesDirs(baseDir)){
return false;
}
driftSSH.closeConnection();
return clickDriftDetectNowOrDelete(driftName, 7, 0, true);
}
//***********************************************************************
// Individual Config
//***************************************************************************
public void navigationToConfiguration(){
this.link("Inventory").click();
this.waitFor(5000);
this.cell("Servers").click();
this.link("RHQ Agent").click();
this.cell("Configuration").click();
}
public void navigationToConfigurationSubtabs(){
navigationToConfiguration();
this.xy(cell("History"), 3,3).click();
this.xy(cell("Current"),3,3).click();
}
public boolean editAndSaveConfiguration(){
this.link("Inventory").click();
this.waitFor(5000);
this.cell("Servers").click();
this.link("RHQ Agent").click();
this.cell("Configuration").click();
if(!this.waitForElementExists(this, this.textbox("rhq.agent.plugins.availability-scan.initial-delay-secs"), "rhq.agent.plugins.availability-scan.initial-delay-secs", 1000*5)){
return false;
}
String defaultDelay = this.textbox("rhq.agent.plugins.availability-scan.initial-delay-secs").getValue();
this.textbox("rhq.agent.plugins.availability-scan.initial-delay-secs").setValue(defaultDelay + "1");
this.cell("Save").click();
return true;
}
public void settingToOriginalValues(String defaultValue){
this.link("Inventory").click();
this.waitFor(5000);
this.cell("Servers").click();
this.link("RHQ Agent").click();
this.cell("Configuration").click();
this.textbox("rhq.agent.plugins.availability-scan.initial-delay-secs").setValue(defaultValue);
this.cell("Save").click();
}
//******************************************************************************
//Configuration History
//*******************************************************************************
public void navigationToConfigurationHistoryTab(){
this.link("Reports").click();
this.waitFor(5000);
this.cell("Configuration History").click();
}
public void deleteConfigurationFromList(){
this.link("Reports").click();
this.waitFor(5000);
this.cell("Configuration History").click();
this.div("Individual").click();
this.cell("Delete").click();
this.cell("Yes").click();
}
//************************************************************************************************
//* Metric Collection Schedules For Resources [enable/disable/update]
//************************************************************************************************
public void selectRowOnTable(String divName){
//Auto fix the max count of DIV
int divMaxIndex = this.div("divName").countSimilar();
for(int i=divMaxIndex; i>=0; i--){
if(this.div(divName+"["+i+"]").exists()){
this.div(divName+"["+i+"]").click();
_logger.log(Level.INFO, "Clicked, DIV Name: "+divName+"["+i+"]");
break;
}
}
}
public void selectSchedules(String resourceName){
selectResource(resourceName);
this.cell("Monitoring").click();
this.xy(cell("Schedules"), 3,3).click();
}
public int getMetricTableOffset(String resourceName){
if(resourceName != null){
selectSchedules(resourceName);
}
String tableName = "listTable";
int numberTableAvailable = this.table(tableName).countSimilar();
_logger.log(Level.FINE, "OffSet - TABLE COUNT ("+tableName+"): "+numberTableAvailable);
return numberTableAvailable;
}
public int adjustMetricTableOffset(int orgOffset, int newOffest){
/*if(orgOffset >= newOffest){
return newOffest - orgOffset;
}else{
return 0;
}*/
return 0;
}
public LinkedList<HashMap<String, String>> getMetricTableDetails(String resourceName, int tableOffset){
if(resourceName != null){
selectSchedules(resourceName);
}
String tableName = "listTable";
String tableColumns = "Metric,Description,Type,Enabled?,Collection Interval";
String replaceColumnValues = "permission_enabled_11.png=Enabled,permission_disabled_11.png=Disabled";
int numberTableAvailable = this.table(tableName).countSimilar();
_logger.log(Level.FINE, "TABLE COUNT ("+tableName+"): "+numberTableAvailable);
int tableOffsetNew = adjustMetricTableOffset(numberTableAvailable, tableOffset);
LinkedList<HashMap<String, String>> metricDetails = getRHQgwtTableFullDetails(tableName, tableOffsetNew, tableColumns, replaceColumnValues);
_logger.log(Level.INFO,"Number of Row: "+metricDetails.size());
return metricDetails;
}
public boolean enableDisableUpdateMetric(String resourceName, String metricName, String descrition, LinkedList<HashMap<String, String>> metricDetails, boolean updateCollectionInterval, String collectionIntervalValue, boolean enable, int tableOffset){
if(resourceName != null){
selectSchedules(resourceName);
}
String[] collectionInterval = null;
String collectionIntervalStr = null;
int rowNo=-1;
String tableName = "listTable";
String tableColumns = "Metric,Description,Type,Enabled?,Collection Interval";
String replaceColumnValues = "permission_enabled_11.png=Enabled,permission_disabled_11.png=Disabled";
int tableOffsetNew = 0;
int numberTableAvailable = 0;
if(metricDetails == null){
_logger.log(Level.INFO, "Metric table Details - NULL, reading metric table...");
numberTableAvailable= this.table(tableName).countSimilar();
_logger.log(Level.FINE, "TABLE COUNT ("+tableName+"): "+numberTableAvailable);
tableOffsetNew = adjustMetricTableOffset(numberTableAvailable, tableOffset);
metricDetails = getRHQgwtTableConditionalDetails(tableName, tableOffsetNew, tableColumns, replaceColumnValues, "Metric="+metricName);
_logger.log(Level.INFO,"Number of Row: "+metricDetails.size());
}
for(int i=0; i<metricDetails.size(); i++){
if(metricDetails.get(i).get("Metric").equalsIgnoreCase(metricName)){
_logger.log(Level.INFO, "Metric Details: Row ("+(i+1)+"): "+metricDetails.get(i));
rowNo = i;
break;
}
}
if(rowNo == -1){
_logger.log(Level.WARNING, "Metric: "+metricName+" not found on the metric table!");
return false;
}
numberTableAvailable = this.table(tableName).countSimilar();
_logger.log(Level.FINE, "TABLE COUNT ("+tableName+"): "+numberTableAvailable);
tableOffsetNew = adjustMetricTableOffset(numberTableAvailable, tableOffset);
HashMap<String, String> metricDetail = getRHQgwtTableRowDetails(tableName, tableOffsetNew, tableColumns, replaceColumnValues, rowNo);
_logger.log(Level.INFO, "Metric: [Old Status: "+metricDetail+"] Table Offset: "+tableOffsetNew);
if(updateCollectionInterval){
collectionInterval = collectionIntervalValue.split(" ");
int hours = 0;
int minutes = 0;
int seconds = 0;
int rawValue = Integer.parseInt(collectionInterval[0].trim());
if(collectionInterval[1].equalsIgnoreCase("seconds")){
hours = rawValue / (60*60);
minutes = rawValue / 60;
seconds = rawValue % 60;
}else if(collectionInterval[1].equalsIgnoreCase("minutes")){
hours = rawValue / 60;
minutes = rawValue % 60;
}else{
hours = rawValue;
}
if(hours > 0){
collectionIntervalStr = hours +" hours";
}
if(minutes > 0){
if(collectionIntervalStr != null){
collectionIntervalStr += ", "+minutes+" minutes";
}else{
collectionIntervalStr = minutes+" minutes";
}
}
if(seconds > 0){
if(collectionIntervalStr != null){
collectionIntervalStr += ", "+seconds+" seconds";
}else{
collectionIntervalStr = seconds+" seconds";
}
}
_logger.log(Level.FINE, "Reference Collection Value: "+collectionIntervalStr);
if(metricDetail.get("Collection Interval").equalsIgnoreCase(collectionIntervalStr)){
_logger.log(Level.WARNING, "Metric: "+metricName+" collection interval already defined as "+metricDetail.get("Collection Interval")+". Nothing to do..");
return true;
}
}else{
if(metricDetail.get("Enabled?").equalsIgnoreCase("Enabled") == enable){
_logger.log(Level.WARNING, "Metric: "+metricName+" already in "+metricDetail.get("Enabled?")+" state. Nothing to do..");
return true;
}
}
//selectRowOnTable(metricName);
this.div(metricName).near(this.div(descrition)).click();
if(updateCollectionInterval){
this.textbox("interval").setValue(collectionInterval[0].trim());
if(!collectionInterval[1].trim().equalsIgnoreCase("minutes")){
selectComboBoxes("minutes --> "+collectionInterval[1].trim());
}
- this.xy(cell("Set[1]"),3,3).click();
+ if(this.cell("Set[1]").exists()){
+ this.xy(cell("Set[1]"),3,3).click();
+ }else{
+ this.xy(cell("Set"),3,3).click();
+ }
+
if(!collectionInterval[1].trim().equalsIgnoreCase("minutes")){
selectComboBoxes(collectionInterval[1].trim()+" --> minutes");
}
}else{
if(enable){
this.cell("Enable").click();
}else{
this.cell("Disable").click();
}
}
this.waitFor(1000*2); //wait 2 seconds to get load table details
numberTableAvailable = this.table(tableName).countSimilar();
_logger.log(Level.FINE, "TABLE COUNT ("+tableName+"): "+numberTableAvailable);
tableOffsetNew = adjustMetricTableOffset(numberTableAvailable, tableOffset);
metricDetail = getRHQgwtTableRowDetails(tableName, tableOffsetNew, tableColumns, replaceColumnValues, rowNo);
_logger.log(Level.INFO, "Metric: New Status: "+metricDetail);
if(metricDetail.get("Metric").equalsIgnoreCase(metricName)){
if(updateCollectionInterval){
if(metricDetail.get("Collection Interval").equalsIgnoreCase(collectionIntervalStr)){
return true;
}
}else{
if(metricDetail.get("Enabled?").equalsIgnoreCase("Enabled") == enable){
return true;
}
}
}
return false;
}
//************************************************************************************************
// Group Configuration
//***************************************************************************************************
public void navigationToGroupConfigurtion(String panelName, String compatibleGroup, String groupDesc, ArrayList<String> resourceList){
createGroup(panelName, compatibleGroup, groupDesc, resourceList);
this.link(compatibleGroup).click();
this.cell("Configuration").click();
}
public void navigationToGroupConfigurationSubtabs(){
this.xy(cell("History"), 3,3).click();
this.xy(cell("Current"),3,3).click();
}
public void editAndSaveGroupConfiguration(){
this.waitForElementExists(this, this.textbox("rhq.agent.plugins.availability-scan.initial-delay-secs"), "rhq.agent.plugins.availability-scan.initial-delay-secs", 1000*5);
String defaultDelay = this.textbox("rhq.agent.plugins.availability-scan.initial-delay-secs").getValue();
this.textbox("rhq.agent.plugins.availability-scan.initial-delay-secs").setValue(defaultDelay + "1");
this.cell("Save").click();
}
//************************************************************************************************
// Metric Collection Schedules For Groups
//*********************************************************************************************
public void scheduleDisableForGroup(String panelName, String compatibleGroup, String groupDesc, ArrayList<String> resourceList){
createGroup(panelName, compatibleGroup, groupDesc, resourceList);
this.link(compatibleGroup).click();
this.cell("Monitoring").click();
this.xy(cell("Schedules"), 3,3).click();
this.div("JVM Total Memory[1]").click();
this.cell("Disable").click();
}
public void enableScheduleGroup(){
this.div("JVM Total Memory[1]").click();
this.cell("Enable").click();
}
public void refreshScheduledGroup(){
this.div("JVM Total Memory[1]").click();
this.cell("Refresh").click();
}
public void setCollectionIntervalForScheduledGroup(int value){
this.div("JVM Total Memory[1]").click();
this.textbox("interval").setValue(Integer.toString(value));
this.cell("Set").click();
}
public void deleteCompatibilityGroup(String panelName, String groupName){
deleteGroup(panelName, groupName);
}
//***********************************************************************************************
//* Administration Page(s) validation [NON-JSP pages] - added on 08-Mar-2013
//***********************************************************************************************
//***********************************************************************************************
//* Administration Page(s) validation [JSP pages]
//***********************************************************************************************
public void navigateToAdministrationPage(String pageLocation, String tableName){
this.link("Administration").click();
this.waitForElementExists(this, this.span("Administration"), "Administration", 1000*20);
this.cell(pageLocation).click();
this.waitForElementExists(this, this.table(tableName), tableName, 1000*20); //JSP pages are not a AJAX pages, hence waiting for an element (table name) on JSP page
_logger.log(Level.FINE, "Page redirected to: Administration-->"+pageLocation);
}
public boolean validatePage(String page, String tableName, String tableColumns, int columnIndexFrom, int minRowCount, boolean jsp){
navigateToAdministrationPage(page, tableName);
LinkedList<String> header = null;
LinkedList<LinkedList<String>> tableContent = null;
if(jsp){
header = getTableHeader(columnIndexFrom);
tableContent = getJSPtable(tableName, header.size(), columnIndexFrom);
}else{
String headerReference = "/headerButton/";
String cellReference = "/tallCell/";
header = getTableHeader(headerReference, columnIndexFrom);
tableContent = getTable(cellReference, header.size());
}
StringBuffer tableDetails = new StringBuffer("***********Friendly Tabele Details***************\n");
tableDetails.append("Table Name: ").append(tableName).append("\n");
tableDetails.append("Header Count: ").append(header.size()).append("\n");
tableDetails.append("Row Count: ").append(tableContent.size()).append("\n");
tableDetails.append("Header(s): ").append(header).append("\n");
for(int i=0;i<tableContent.size();i++){
tableDetails.append("Row [").append((i+1)).append(" of ").append(tableContent.size()).append("]: ").append(tableContent.get(i)).append("\n");
}
tableDetails.append("*********************************************************");
_logger.log(Level.INFO, tableDetails.toString());
String[] columns = getCommaToArray(tableColumns);
for(String column: columns){
header.remove(column.trim());
}
return ((minRowCount <= tableContent.size()) && (header.size() == 0));
}
public LinkedList<String> getTableHeader(String columnReference, int columnIndexFrom){
LinkedList<String> header = new LinkedList<String>();
int tableHeaderCount = this.cell(columnReference).countSimilar();
_logger.log(Level.FINE, "Table Header Count: "+tableHeaderCount);
for(int i=columnIndexFrom; i<tableHeaderCount;i++){
header.addLast((this.cell(columnReference+"["+i+"]")).getText());
}
return header;
}
public LinkedList<String> getTableHeader(int columnIndexFrom){
LinkedList<String> header = new LinkedList<String>();
String tableHeadertext = "/rich-table-subheadercell/";
String headerText = "headerText";
int tableHeaderCount = this.tableHeader(tableHeadertext).countSimilar();
_logger.log(Level.FINE, "Table Header Count: "+tableHeaderCount);
for(int i=columnIndexFrom; i<tableHeaderCount;i++){
header.addLast(this.span(headerText).in(this.tableHeader(tableHeadertext+"["+i+"]")).getText());
}
return header;
}
@SuppressWarnings("unchecked")
public LinkedList<LinkedList<String>> getJSPtable(String tableName, int headerSize, int columnIndexFrom){
LinkedList<LinkedList<String>> table = new LinkedList<LinkedList<String>>();
LinkedList<String> row = new LinkedList<String>();
for(int i=1; ;i++){
try{
if(columnIndexFrom == 0){
headerSize -=1;
}
for(int h=columnIndexFrom; h<=headerSize; h++){
row.addLast(cell(table(tableName), i, h).getText());
}
table.addLast((LinkedList<String>) row.clone());
row.clear();
}catch (Exception ex){
_logger.log(Level.FINER, "Known Exception: "+ex.getMessage());
break;
}
}
return table;
}
@SuppressWarnings("unchecked")
public LinkedList<LinkedList<String>> getTable(String cellReference, int columnSize){
LinkedList<LinkedList<String>> table = new LinkedList<LinkedList<String>>();
LinkedList<String> row = new LinkedList<String>();
int noCell = this.cell(cellReference).countSimilar();
for(int cell=0;cell<noCell;cell++){
for(int col=0; col<columnSize; col++){
row.addLast(this.cell(cellReference+"["+cell+"]").getText());
}
table.addLast((LinkedList<String>) row.clone());
row.clear();
}
return table;
}
//*************************************************************************************
//* Get Agent status
//*************************************************************************************
public boolean isAgentRunning(String agentName) {
this.link("Inventory").click();
this.cell("Platforms").click();
this.setSearchBox(agentName.trim());
LinkedList<HashMap<String, String>> agents = getRHQgwtTableFullDetails("listTable", 2, "Resource Type,Name,Ancestry,Description,Type,Version,Availability", "availability_red_16.png=Down,availability_green_16.png=Up");
if(agents.size() != 1){
if(agents.get(0).get("Availability").equalsIgnoreCase("Up")){
return true;
}
}else{
_logger.log(Level.INFO, "Agent Status: "+agents);
}
return false;
}
//*************************************************************************************
//* GUI installation - RHQ/JON
//*************************************************************************************
public boolean guiInstallationRHQ(String dataBaseType, String databaseDetails, String databasePassword, String databaseMaintanceType, String registeredServerSelection, String serverDetails, String embeddedAgentEnabled){
long maximunWaitTime = 1000*60*10;
//Check the installation status, return true if already installed
if(this.heading1("The Server Is Installed!").exists()){
if(this.link("Click here to get started!").exists()){
_logger.log(Level.INFO, "Installation process completed already!, Nothing to do!!");
return true;
}
}
if(!this.waitForElementExists(this, this.link("Click here to continue the installation"), "Link: Click here to continue the installation", 1000*30)){
return false;
}
this.link("Click here to continue the installation").click();
//Select Database Type
this.select("propForm:databasetype").choose(dataBaseType);
//Update text fields on database [DB Connection URL, DB JDBC Driver class, DB XA dataStore Class, DB User Name]
updateTextBoxValues(databaseDetails);
//Update database password
this.password("propForm:databasepassword").setValue(databasePassword);
//Test Connection
this.submit("Test Connection").click();
//validate Database connection works correctly
if(!this.waitForElementExists(this, this.image("OK"), "Image: OK, database validatition check", 1000*30)){
if(this.waitForElementExists(this, this.image("Error"), "Image: Error, database validatition check", 1000*30)){
return false;
}
return false;
}
if(databaseMaintanceType != null){
if(this.span("A database schema already exists. What do you want to do?").exists()){
this.select(1).choose(databaseMaintanceType);
}else{
_logger.log(Level.WARNING, "There no Database exists! Not able to select '"+databaseMaintanceType+"'. Continuing fresh DB installation...");
}
}
//Registered server Selection
if(registeredServerSelection != null){
this.select(2).choose(registeredServerSelection);
}
//Update Server details
updateTextBoxValues(serverDetails);
//Embedded Agent Enabled
if(embeddedAgentEnabled.equalsIgnoreCase("true")){
this.radio("true").click();
}else{
this.radio("false").click();
}
//Update database password
this.password("propForm:databasepassword").setValue(databasePassword);
this.submit("Install Server!").click();
//Starting up, please wait...
//Modified "Starting up, please wait..." to "Starting up, please wait... (this may take several minutes)" from 03-June-2012 build.
if(!this.waitForElementExists(this, this.span("Starting up, please wait... (this may take several minutes)"), "Span: Starting up, please wait... (this may take several minutes)", 1000*30)){
//return false;
//Adding manual wait due to issue with sahi proxy server
//Bug: https://bugzilla.redhat.com/show_bug.cgi?id=765670
//JBOSS AS7 Plug-in's are taking long minutes...
_logger.log(Level.WARNING, "[Starting up, please wait...] not found, hence will wait here "+(maximunWaitTime/1000)+" Second(s)");
this.waitFor(maximunWaitTime);
}
if(!this.waitForElementExists(this, this.link("Done! Click here to get started!"), "Link: Done! Click here to get started!", (int)(maximunWaitTime - (1000*60*4)))){
this.navigateTo("/installer/start.jsf", true);
if(this.heading1("The Server Is Installed!").exists()){
if(this.link("Click here to get started!").exists()){
this.link("Click here to get started!").click();
return true;
}
}
return false;
}
this.link("Done! Click here to get started!").click();
return true;
}
//*************************************************************************************
//* Import Resources
//*************************************************************************************
public boolean importResources(String resourceName) throws InterruptedException{
this.link("Inventory").click();
this.cell("Discovery Queue").click();
if(this.waitForElementRowExists(this, "No items to show", 1000*5)){
_logger.log(Level.INFO, "Do not find any resources in Discovery Queue, Clicking Refresh button and checking again...");
Thread.sleep(1000*60*5); //Hold on 5 minutes, there will be an agent and server communication may be going on..
this.cell("Refresh").near(this.cell("Deselect All")).click();
if(this.waitForElementRowExists(this, "No items to show", 1000*5)){
_logger.log(Level.WARNING, "No items to import!");
return false;
}
}
if(resourceName != null){
LinkedList<HashMap<String, String>> discoveryQueue = getRHQgwtTableFullDetails("listTable", 2, "Resource Name, Resource Key, Resource Type, Description, Inventory Status, Discovery Time", null);
_logger.log(Level.INFO, "Table Details: Number of Row(s): "+discoveryQueue.size());
for(int i=0; i<discoveryQueue.size(); i++){
if(resourceName.equalsIgnoreCase(discoveryQueue.get(i).get("Resource Name"))){
_logger.log(Level.INFO, "Row: ["+(i+1)+"]: "+discoveryQueue.get(i));
this.image("unchecked.png["+i+"]").click();
}
}
}else{
this.cell("Select All").click();
}
this.cell("Yes").click();
this.cell("Import").click();
if(!this.waitForElementExists(this, this.cell("You have successfully imported the selected Resources."), "Cell: You have successfully imported the selected Resources.", 1000*10)){
return false;
}
return true;
}
//************************************************************************************************
// Search Tests
//***************************************************************************************************
// TEXT search for Groups
public boolean searchComaptibilityGroupWithText(String groupPanelName, String groupName, String groupDesc, ArrayList<String> resourceList){
//'SearchPatternField' is on JBOSS ON and 'search' is on RHQ 4.5 and above
selectPage("Inventory-->"+groupPanelName, this.textbox("search"), 1000*5, 3);
setSearchBox(groupName);
if(!this.link(groupName.trim()).exists()){
_logger.log(Level.INFO, "Group ["+groupName+"] unavailable, Creating new one...");
createGroup(groupPanelName, groupName, groupDesc, resourceList);
}else{
return true;
}
setSearchBox(groupName);
return this.link(groupName.trim()).exists();
}
public boolean searchAllGroupWithText(String groupPanelName, String groupName, String groupDesc, ArrayList<String> resourceList){
return searchComaptibilityGroupWithText(groupPanelName, groupName, groupDesc, resourceList);
}
public boolean searchMixedGroupWithText(String groupPanelName, String groupName, String groupDesc, ArrayList<String> resourceList){
return searchComaptibilityGroupWithText(groupPanelName, groupName, groupDesc, resourceList);
}
//************************************************************************************************
// AlertDefinitionTemplate Tests
//***************************************************************************************************
public void createAlertDefinitionTemplate(String groupPanelName, String templateName){
this.link("Administration").click();
this.cell(groupPanelName).click();
this.image("edit.png[3]").click();
this.cell("New").click();
this.textbox("textItem").setValue(templateName);
this.textarea("textItem").setValue("Desc");
this.cell("Save").click();
}
public boolean verifyDefinitionTemplateExists(String groupPanelName, String templateName) {
/*this.cell("Administration").click();
this.waitFor(5000);*/
this.bold("Back to List").click();
/* this.cell(groupPanelName).click();
this.image("edit.png[3]");*/
return this.div(templateName).exists();
}
public void navigationThruConditionsTabAlertDefTemplate(String groupPanelName, String templateName){
/*this.cell("Administration").click();
this.waitFor(5000);
this.cell(groupPanelName).click();
this.image("edit.png[3]");*/
this.link(templateName).click();
this.cell("Edit").click();
this.cell("Conditions").click();
this.cell("Add").click();
//this.div("selectItemText[2]").click();
this.cell("OK").click();
this.cell("Save").click();
this.bold("Back to List").click();
}
public void navigationThruNotificationsTabAlertDefTemplate(String groupPanelName, String templateName){
/*this.cell("Administration").click();
this.waitFor(5000);
this.cell(groupPanelName).click();
this.image("edit.png[3]");*/
this.link(templateName).click();
this.cell("Edit").click();
this.cell("Notifications").click();
this.cell("Add").click();
// this.div("selectItemText[2]").click();
// this.div(templateName).click();
//this.image("right.png").click();
this.div("right_all.png").click();
this.cell("OK").click();
this.cell("Save").click();
this.bold("Back to List").click();
}
public void navigationThruRecoveryTabAlertDefTemplate(String groupPanelName, String templateName){
/*this.cell("Administration").click();
this.link("Administration").click();
this.waitFor(5000);
this.cell(groupPanelName).click();
this.image("edit.png[3]");*/
this.link(templateName).click();
this.cell("Edit").click();
this.cell("Recovery").click();
// this.div("selectItemText[2]").click();
this.radio("yes[1]").click();
this.radio("no[1]").click();
this.cell("Save").click();
this.bold("Back to List").click();
}
public void navigationThruDampeningTabAlertDefTemplate(String groupPanelName, String templateName){
/*this.cell("Administration").click();
this.waitFor(5000);
this.cell(groupPanelName).click();
this.image("edit.png[3]");*/
this.link(templateName).click();
this.cell("Edit").click();
this.cell("Dampening").click();
// this.div("selectItemText[2]").click();
this.cell("Save").click();
this.bold("Back to List").click();
}
public boolean deleteAlertDefinitionTemplate(String templateName){
if(!selectDivElement(templateName)){
return false;
}
this.cell("Delete").near(this.cell("Disable")).click();
this.cell("Yes").near(this.cell("No")).click();
return this.link(templateName.trim()).exists();
}
public void servicesSearchBy(String key, String value) {
this.link("Inventory").click();
this.waitFor(5000);
Assert.assertTrue(this.link("Inventory").exists());
this.cell("Services").click();
this.waitFor(5000);
checkSearchBox();
setSearchBox("version==2");
this.waitFor(5000);
}
public void createGroupWithAllResources(String groupPanelName, String groupName, String groupDesc) {
this.link("Inventory").click();
this.waitFor(5000);
this.cell(groupPanelName).click();
this.cell("New").click();
this.textbox("name").setValue(groupName);
this.textarea("description").setValue(groupDesc);
this.cell("Next").click();
this.image("right_all.png").click();
this.cell("Finish").click();
}
public void removeResourcesFromGroup(String groupPanelName, String groupName){
this.link("Inventory").click();
this.waitFor(5000);
this.cell(groupPanelName).click();
this.link(groupName).click();
this.image("Inventory_grey_16.png").click();
this.cell("Update Membership...").click();
this.image("left_all.png").click();
this.cell("Save").click();
}
public void createRoleWithPermissions(String roleName, String desc, String compGroupName, String searchTestuser, String [] permissions) {
this.link("Administration").click();
this.cell("Roles").click();
this.cell("New").click();
this.textbox("name").setValue(roleName);
this.textbox("description").setValue(desc);
if (permissions != null){
for (int i =0; i< permissions.length ;i++ ){
this.div(permissions[i]).click();
if(this.image("unchecked.png").near(this.div(permissions[i])).exists()){
this.image("unchecked.png").near(this.div(permissions[i])).click();
}
}
}
this.cell("Resource Groups").click();
this.div(compGroupName).click();
this.image("right.png").click();
this.cell("Users").click();
this.div(searchTestuser).click();
this.image("right.png").click();
this.cell("Save").click();
}
public void removePermissionsFromRole(String roleName, String desc, String compGroupName, String searchTestuser, String [] permissions){
this.link("Administration").click();
this.cell("Roles").click();
this.link(roleName).click();
this.textbox("name").setValue(roleName);
this.textbox("description").setValue(desc);
if (permissions != null){
for (int i =0; i< permissions.length ;i++ ){
this.div(permissions[i]).click();
}
}
this.image("checked.png").click();
this.cell("Save").click();
}
public boolean isUserAvailable(String userName){
selectPage("Administration-->Users", this.cell("User Name"), 1000*5, 2);
if(this.link(userName).in(this.div("gridBody")).exists()){
return true;
}
_logger.log(Level.FINE, "User["+userName+"] is not available");
return false;
}
public void preConfigPermissionTest(String userName, String password, String firstName, String lastName, String email, String groupPanelName, String groupName, String groupDesc, String roleName, String roleDesc, String[] permissions){
if(!this.getCurrentLogin().equals(ADMIN_USER)){
relogin(ADMIN_USER, ADMIN_PASSWORD);
}
if(!this.isUserAvailable(userName)){
createUser(userName, password, firstName, lastName, email);
}
createGroup(groupPanelName, groupName, groupDesc);
createRoleWithPermissions(roleName, roleDesc, groupName, userName, permissions);
//relogin(userName, password);
}
public void postConfigPermissionTest(String userName, String role, String groupPanelName, String groupName) throws SahiTasksException{
relogin(ADMIN_USER, ADMIN_PASSWORD);
deleteUser(userName);
deleteRole(role);
deleteGroup(groupPanelName, groupName);
}
public void checkManageSecurity(String searchTestuser, String password, String firstName, String secondName, String emailId, String roleName, String desc, String compTestGroup, String searchQueryName) throws SahiTasksException {
String [] permissions = new String [] {"Manage Security"};
preConfigPermissionTest(searchTestuser, password, firstName, secondName, emailId, "All Groups", compTestGroup, desc, roleName, desc, permissions);
// login with created user
relogin(searchTestuser, password);
// go to Administration-->Users
this.link("Administration").click();
this.cell("Users").click();
this.link("rhqadmin").click();
this.waitFor(5000);
Assert.assertTrue(this.cell("Cancel").exists());
Assert.assertTrue(this.password("password").exists());
// login with rhqadmin user
relogin("rhqadmin", "rhqadmin");
// remove manage security permission
removePermissionsFromRole(roleName, desc, compTestGroup,
searchTestuser, permissions);
// login with created user
relogin(searchTestuser, password);
this.link("Administration").click();
this.cell("Users").click();
this.link("rhqadmin").click();
this.waitFor(5000);
Assert.assertFalse(this.cell("Cancel").exists());
Assert.assertFalse(this.password("password").exists());
postConfigPermissionTest(searchTestuser, roleName, "All Groups", compTestGroup);
}
public void checkManageInventory(String searchTestuser, String password, String firstName, String secondName, String emailId, String roleName, String desc, String compTestGroup, String searchQueryName) throws SahiTasksException {
String [] permissions = new String [] {"Manage Inventory"};
preConfigPermissionTest(searchTestuser, password, firstName, secondName, emailId, "All Groups", compTestGroup, desc, roleName, desc, permissions);
// login with created user
relogin(searchTestuser, password);
// go to Administration-->Users
this.link("Inventory").click();
this.waitFor(2000);
this.cell("Discovery Queue").click();
Assert.assertTrue(this.span("Discovery Queue").exists());
this.cell("Servers").click();
this.cell("RHQ Agent").click();
this.cell("Disable").click();
this.cell("Yes").click();
this.cell("RHQ Agent").click();
this.cell("Enable").click();
this.cell("Yes").click();
// // login with rhqadmin user
relogin("rhqadmin", "rhqadmin");
// // remove manage security permission
removePermissionsFromRole(roleName, desc, compTestGroup,
searchTestuser, permissions);
// login with created user
relogin(searchTestuser, password);
this.link("Inventory").click();
this.waitFor(2000);
this.cell("Discovery Queue").click();
Assert.assertFalse(this.span("Discovery Queue").exists());
postConfigPermissionTest(searchTestuser, roleName, "All Groups", compTestGroup);
}
public void createTestRepo(String testRepoName){
this.link("Administration").click();
this.cell("Repositories").click();
this.submit("CREATE NEW").click();
this.textbox("createRepoDetailsForm:name").setValue(testRepoName);
// this.checkbox("createRepoDetailsForm:isPrivate").uncheck();
this.select("createRepoDetailsForm:j_id13").click();
this.option("--None--").click();
this.submit("SAVE").click();
}
public void deleteTestRepo(String testRepoName){
this.link("Administration").click();
this.cell("Repositories").click();
this.checkbox("selectedRepos").near(this.link("testRepo")).click();
this.submit("DELETE SELECTED").click();
}
public void checkManageRespository(String searchTestuser, String password, String firstName, String secondName, String emailId, String roleName, String desc, String compTestGroup, String searchQueryName) throws SahiTasksException {
String [] permissions = new String [] {"Manage Repositories"};
preConfigPermissionTest(searchTestuser, password, firstName, secondName, emailId, "All Groups", compTestGroup, desc, roleName, desc, permissions);
//create test repo
String testReponame="testRepo";
createTestRepo(testReponame);
// login with created user
relogin(searchTestuser, password);
// go to Administration-->Users
this.link("Administration").click();
this.waitFor(2000);
this.cell("Content Sources").click();
this.waitFor(2000);
Assert.assertTrue(this.submit("CREATE NEW").exists());
this.link("Administration").click();
this.waitFor(2000);
this.cell("Repositories").click();
this.waitFor(2000);
Assert.assertTrue(this.link(testReponame).exists());
// login with rhqadmin user
relogin("rhqadmin", "rhqadmin");
// remove manage security permission
removePermissionsFromRole(roleName, desc, compTestGroup,
searchTestuser, permissions);
// login with created user
relogin(searchTestuser, password);
this.link("Administration").click();
this.waitFor(2000);
this.cell("Content Sources").click();
this.waitFor(2000);
Assert.assertFalse(this.button("CREATE NEW").exists());
this.cell("Repositories").click();
this.waitFor(2000);
Assert.assertFalse(this.link(testReponame).exists());
postConfigPermissionTest(searchTestuser, roleName, "All Groups", compTestGroup);
}
public void checkViewUsers(String searchTestuser, String password, String firstName, String secondName, String emailId, String roleName, String desc, String compTestGroup, String searchQueryName) throws SahiTasksException {
String [] permissions = new String [] {"View Users"};
preConfigPermissionTest(searchTestuser, password, firstName, secondName, emailId, "All Groups", compTestGroup, desc, roleName, desc, permissions);
// login with created user
relogin(searchTestuser, password);
// go to Administration-->Users
selectPage("Administration-->Users", this.cell("User Name"), 1000*5, 2);
Assert.assertTrue(this.link(searchTestuser).exists());
Assert.assertTrue(this.link("rhqadmin").exists());
this.link(searchTestuser).click();
Assert.assertTrue(this.password("password").exists());
Assert.assertTrue(this.span("Edit User ["+searchTestuser+"]").exists());
selectPage("Administration-->Users", this.cell("User Name"), 1000*5, 2);
this.link("rhqadmin").click();
Assert.assertFalse(this.password("password").exists());
Assert.assertTrue(this.span("View User [rhqadmin]").exists());
// login with rhqadmin user
relogin("rhqadmin", "rhqadmin");
// remove manage security permission
removePermissionsFromRole(roleName, desc, compTestGroup,
searchTestuser, permissions);
// login with created user
relogin(searchTestuser, password);
selectPage("Administration-->Users", this.cell("User Name"), 1000*5, 2);
Assert.assertTrue(this.link(searchTestuser).exists());
Assert.assertFalse(this.link("rhqadmin").exists());
this.link(searchTestuser).click();
Assert.assertTrue(this.password("password").exists());
Assert.assertTrue(this.span("Edit User ["+searchTestuser+"]").exists());
postConfigPermissionTest(searchTestuser, roleName, "All Groups", compTestGroup);
}
public void checkManageSettings(String searchTestuser, String password, String firstName, String secondName, String emailId, String roleName, String desc, String compTestGroup, String searchQueryName) throws SahiTasksException {
String [] permissions = new String [] {"Manage Settings"};
preConfigPermissionTest(searchTestuser, password, firstName, secondName, emailId, "All Groups", compTestGroup, desc, roleName, desc, permissions);
// login with created user
relogin(searchTestuser, password);
// go to Administration-->Users
this.link("Administration").click();
Assert.assertTrue(this.cell("System Settings").exists());
this.cell("System Settings").click();
Assert.assertTrue(this.cell("Server Local Time :").exists());
// login with rhqadmin user
relogin("rhqadmin", "rhqadmin");
// remove manage security permission
removePermissionsFromRole(roleName, desc, compTestGroup,
searchTestuser, permissions);
// login with created user
relogin(searchTestuser, password);
this.link("Administration").click();
Assert.assertTrue(this.cell("System Settings").exists());
this.cell("System Settings").click();
Assert.assertFalse(this.cell("Server Local Time :").exists());
postConfigPermissionTest(searchTestuser, roleName, "All Groups", compTestGroup);
}
public void checkManageBundles(String searchTestuser, String password, String firstName, String secondName, String emailId, String roleName, String desc, String compTestGroup, String searchQueryName) throws SahiTasksException {
String [] permissions = new String [] {"Manage Bundles"};
preConfigPermissionTest(searchTestuser, password, firstName, secondName, emailId, "All Groups", compTestGroup, desc, roleName, desc, permissions);
// login with created user
relogin(searchTestuser, password);
// go to Bundles
this.link("Bundles").click();
this.cell("New").click();
Assert.assertTrue(this.cell("Next").exists());
this.cell("Cancel").click();
// login with rhqadmin user
relogin("rhqadmin", "rhqadmin");
// remove manage security permission
removePermissionsFromRole(roleName, desc, compTestGroup,
searchTestuser, permissions);
// login with created user
relogin(searchTestuser, password);
// go to Bundles
this.link("Bundles").click();
this.cell("New").click();
Assert.assertFalse(this.cell("Next").exists());
postConfigPermissionTest(searchTestuser, roleName, "All Groups", compTestGroup);
}
public void checkGroupsPermission(String searchTestuser, String password, String firstName, String secondName, String emailId, String roleName, String desc, String compTestGroup, String searchQueryName) throws SahiTasksException {
preConfigPermissionTest(searchTestuser, password, firstName, secondName, emailId, "All Groups", compTestGroup, desc, roleName, desc, null); //this is the default role creation which has View Users checked
// login with created user
relogin(searchTestuser, password);
// go to Administration-->Users
this.link("Inventory").click();
this.waitFor(2000);
this.cell("Servers").click();
this.waitFor(2000);
Assert.assertTrue(this.div("RHQ Agent").exists());
// login with rhqadmin user
relogin("rhqadmin", "rhqadmin");
// remove resources from group
removeResourcesFromGroup("All Groups", compTestGroup);
// login with created user
relogin(searchTestuser, password);
this.link("Inventory").click();
this.waitFor(2000);
this.cell("Servers").click();
this.waitFor(2000);
Assert.assertFalse(this.div("RHQ Agent").exists());
postConfigPermissionTest(searchTestuser, roleName, "All Groups", compTestGroup);
}
//*************************************************************************************
//* Drift Definition Template
//*************************************************************************************
public void createDriftDefinitionTemplate(String name) {
this.link("Administration").click();
Assert.assertTrue(this.cell("Drift Definition Templates").exists());
this.cell("Drift Definition Templates").click();
this.image("edit.png").near(this.div("Linux")).click();
this.cell("New").click();
this.cell("Next").click();
this.textbox("name").setValue(name);
this.cell("Finish").click();
}
public void editDriftDefinitionTemplate(String name) {
this.link("Administration").click();
Assert.assertTrue(this.cell("Drift Definition Templates").exists());
this.cell("Drift Definition Templates").click();
this.image("edit.png").near(this.div("Linux")).click();
this.link(name).click();
this.textbox("interval").setValue("123456");
this.cell("Save").click();
Assert.assertTrue(this.cell("Drift template updated and changes pushed to attached definitions.").exists());
}
public void deleteDriftDefinitionTemplate(String name) {
this.link("Administration").click();
Assert.assertTrue(this.cell("Drift Definition Templates").exists());
this.cell("Drift Definition Templates").click();
this.image("edit.png").near(this.div("Linux")).click();
this.image("availability_green_16.png").near(this.cell(name)).click();
this.cell("Delete").click();
this.cell("Yes").click();
Assert.assertFalse(this.cell(name).exists());
}
//Changed the search field name from the version : 4.5.0-SNAPSHOT, Build Number: 1704544. Still we have the field in JBOSS ON, Hence dealing with both search fields
public void setSearchBox(String boxValue){
if(this.textbox("SearchPatternField").exists()){
this.textbox("SearchPatternField").setValue(boxValue);
this.execute("_sahi._keyPress(_sahi._textbox('SearchPatternField'), 13);"); //13 - Enter key
}else{
this.textbox("search").click();
this.textbox("search").setValue(boxValue);
this.waitFor(2000);
this.execute("_sahi._keyPress(_sahi._textbox('search'), 13);"); //13 - Enter key
}
}
}
| true | false | null | null |
diff --git a/org.springextensions.db4o-it-osgi/src/test/java/org/springextensions/db4o/BlueprintIT.java b/org.springextensions.db4o-it-osgi/src/test/java/org/springextensions/db4o/BlueprintIT.java
index 7e8a6a1..c4643b7 100644
--- a/org.springextensions.db4o-it-osgi/src/test/java/org/springextensions/db4o/BlueprintIT.java
+++ b/org.springextensions.db4o-it-osgi/src/test/java/org/springextensions/db4o/BlueprintIT.java
@@ -1,82 +1,82 @@
/*
* Copyright 2010-2012 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.springextensions.db4o;
import javax.inject.Inject;
import com.db4o.events.EventRegistry;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.testng.listener.PaxExam;
import org.ops4j.pax.exam.util.Filter;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import static org.ops4j.pax.exam.CoreOptions.bundle;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.options;
/**
* @author olli
*/
@Listeners({PaxExam.class})
public class BlueprintIT {
@Inject
- @Filter(timeout = 1000)
+ @Filter(timeout = 5000)
private Db4oOperations db4oOperations;
@Inject
- @Filter(timeout = 1000)
+ @Filter(timeout = 5000)
private EventRegistry eventRegistry;
@Configuration
public Option[] configure() {
return options(
// test
mavenBundle("org.testng", "testng", "6.4"),
// Spring Framework
mavenBundle("org.springframework", "org.springframework.beans", "3.0.0.RELEASE"),
mavenBundle("org.springframework", "org.springframework.core", "3.0.0.RELEASE"),
mavenBundle("org.springframework", "org.springframework.transaction", "3.0.0.RELEASE"),
// db4o
mavenBundle("com.db4o", "db4o-full-java5", "8.1.209.15862"),
mavenBundle("org.apache.ant", "com.springsource.org.apache.tools.ant", "1.7.1"),
// Spring db4o
// mavenBundle("org.springextensions.db4o", "org.springextensions.db4o", "1.0.0.BUILD-SNAPSHOT"),
bundle("file:../org.springextensions.db4o/target/org.springextensions.db4o-1.0.0.BUILD-SNAPSHOT.jar"),
// Aries Blueprint
mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint", "1.0.0"),
mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy", "1.0.0"),
mavenBundle("org.apache.aries", "org.apache.aries.util", "1.0.0"),
mavenBundle("org.objectweb.asm", "com.springsource.org.objectweb.asm", "3.2.0"),
mavenBundle("org.objectweb.asm", "com.springsource.org.objectweb.asm.commons", "3.2.0"),
mavenBundle("org.objectweb.asm", "com.springsource.org.objectweb.asm.tree", "3.2.0")
);
}
@Test
public void testDb4oOperations() {
Assert.assertNotNull(db4oOperations, "Db4oOperations is null");
}
@Test
public void testEventRegistry() {
Assert.assertNotNull(eventRegistry, "EventRegistry is null");
}
}
| false | false | null | null |
diff --git a/consulo-google-protobuf-java/src/org/consulo/google/protobuf/java/GoogleProtobufJavaModuleExtensionProvider.java b/consulo-google-protobuf-java/src/org/consulo/google/protobuf/java/GoogleProtobufJavaModuleExtensionProvider.java
index a7bfec8..2dc2f66 100644
--- a/consulo-google-protobuf-java/src/org/consulo/google/protobuf/java/GoogleProtobufJavaModuleExtensionProvider.java
+++ b/consulo-google-protobuf-java/src/org/consulo/google/protobuf/java/GoogleProtobufJavaModuleExtensionProvider.java
@@ -1,29 +1,23 @@
package org.consulo.google.protobuf.java;
-import com.intellij.openapi.module.Module;
import org.consulo.google.protobuf.module.extension.GoogleProtobufModuleExtensionProvider;
import org.jetbrains.annotations.NotNull;
+import com.intellij.openapi.module.Module;
/**
* @author VISTALL
* @since 06.07.13.
*/
public class GoogleProtobufJavaModuleExtensionProvider extends GoogleProtobufModuleExtensionProvider<GoogleProtobufJavaModuleExtension, GoogleProtobufJavaMutableModuleExtension> {
@NotNull
@Override
- public Class<GoogleProtobufJavaModuleExtension> getImmutableClass() {
- return GoogleProtobufJavaModuleExtension.class;
- }
-
- @NotNull
- @Override
public GoogleProtobufJavaModuleExtension createImmutable(@NotNull String s, @NotNull Module module) {
return new GoogleProtobufJavaModuleExtension(s, module);
}
@NotNull
@Override
public GoogleProtobufJavaMutableModuleExtension createMutable(@NotNull String s, @NotNull Module module, @NotNull GoogleProtobufJavaModuleExtension googleProtobufJavaModuleExtension) {
return new GoogleProtobufJavaMutableModuleExtension(s, module, googleProtobufJavaModuleExtension);
}
}
| false | false | null | null |
diff --git a/src/web/org/openmrs/web/controller/RegimenPortletController.java b/src/web/org/openmrs/web/controller/RegimenPortletController.java
index 6d77b647..9483859a 100644
--- a/src/web/org/openmrs/web/controller/RegimenPortletController.java
+++ b/src/web/org/openmrs/web/controller/RegimenPortletController.java
@@ -1,99 +1,102 @@
/**
* 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.controller;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.openmrs.Concept;
import org.openmrs.DrugOrder;
import org.openmrs.api.context.Context;
public class RegimenPortletController extends PortletController {
@SuppressWarnings("unchecked")
protected void populateModel(HttpServletRequest request, Map<String, Object> model) {
String drugSetIds = (String) model.get("displayDrugSetIds");
String cachedDrugSetIds = (String) model.get("cachedDrugSetIds");
if (cachedDrugSetIds == null || !cachedDrugSetIds.equals(drugSetIds)) {
if (drugSetIds != null && drugSetIds.length() > 0) {
Map<String, List<DrugOrder>> patientDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> currentDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> completedDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, Collection<Concept>> drugConceptsBySetId = new LinkedHashMap<String, Collection<Concept>>();
boolean includeOther = false;
{
for (String setId : drugSetIds.split(",")) {
if ("*".equals(setId)) {
includeOther = true;
continue;
}
Concept drugSet = Context.getConceptService().getConcept(setId);
Collection<Concept> members = new ArrayList<Concept>();
if (drugSet != null)
members = Context.getConceptService().getConceptsByConceptSet(drugSet);
drugConceptsBySetId.put(setId, members);
}
}
- for (DrugOrder order : ((List<DrugOrder>) model.get("patientDrugOrders"))) {
- String setIdToUse = null;
- if (order.getDrug() != null) {
- Concept orderConcept = order.getDrug().getConcept();
- for (Map.Entry<String, Collection<Concept>> e : drugConceptsBySetId.entrySet()) {
- if (e.getValue().contains(orderConcept)) {
- setIdToUse = e.getKey();
- break;
+ List<DrugOrder> patientDrugOrders = (List<DrugOrder>) model.get("patientDrugOrders");
+ if (patientDrugOrders != null) {
+ for (DrugOrder order : patientDrugOrders) {
+ String setIdToUse = null;
+ if (order.getDrug() != null) {
+ Concept orderConcept = order.getDrug().getConcept();
+ for (Map.Entry<String, Collection<Concept>> e : drugConceptsBySetId.entrySet()) {
+ if (e.getValue().contains(orderConcept)) {
+ setIdToUse = e.getKey();
+ break;
+ }
}
}
- }
- if (setIdToUse == null && includeOther)
- setIdToUse = "*";
- if (setIdToUse != null) {
- helper(patientDrugOrderSets, setIdToUse, order);
- if (order.isCurrent() || order.isFuture())
- helper(currentDrugOrderSets, setIdToUse, order);
- else
- helper(completedDrugOrderSets, setIdToUse, order);
+ if (setIdToUse == null && includeOther)
+ setIdToUse = "*";
+ if (setIdToUse != null) {
+ helper(patientDrugOrderSets, setIdToUse, order);
+ if (order.isCurrent() || order.isFuture())
+ helper(currentDrugOrderSets, setIdToUse, order);
+ else
+ helper(completedDrugOrderSets, setIdToUse, order);
+ }
}
}
model.put("patientDrugOrderSets", patientDrugOrderSets);
model.put("currentDrugOrderSets", currentDrugOrderSets);
model.put("completedDrugOrderSets", completedDrugOrderSets);
model.put("cachedDrugSetIds", drugSetIds);
} // else do nothing - we already have orders in the model
}
}
/**
* Null-safe version of "drugOrderSets.get(setIdToUse).add(order)"
*/
private void helper(Map<String, List<DrugOrder>> drugOrderSets, String setIdToUse, DrugOrder order) {
List<DrugOrder> list = drugOrderSets.get(setIdToUse);
if (list == null) {
list = new ArrayList<DrugOrder>();
drugOrderSets.put(setIdToUse, list);
}
list.add(order);
}
}
| false | true | protected void populateModel(HttpServletRequest request, Map<String, Object> model) {
String drugSetIds = (String) model.get("displayDrugSetIds");
String cachedDrugSetIds = (String) model.get("cachedDrugSetIds");
if (cachedDrugSetIds == null || !cachedDrugSetIds.equals(drugSetIds)) {
if (drugSetIds != null && drugSetIds.length() > 0) {
Map<String, List<DrugOrder>> patientDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> currentDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> completedDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, Collection<Concept>> drugConceptsBySetId = new LinkedHashMap<String, Collection<Concept>>();
boolean includeOther = false;
{
for (String setId : drugSetIds.split(",")) {
if ("*".equals(setId)) {
includeOther = true;
continue;
}
Concept drugSet = Context.getConceptService().getConcept(setId);
Collection<Concept> members = new ArrayList<Concept>();
if (drugSet != null)
members = Context.getConceptService().getConceptsByConceptSet(drugSet);
drugConceptsBySetId.put(setId, members);
}
}
for (DrugOrder order : ((List<DrugOrder>) model.get("patientDrugOrders"))) {
String setIdToUse = null;
if (order.getDrug() != null) {
Concept orderConcept = order.getDrug().getConcept();
for (Map.Entry<String, Collection<Concept>> e : drugConceptsBySetId.entrySet()) {
if (e.getValue().contains(orderConcept)) {
setIdToUse = e.getKey();
break;
}
}
}
if (setIdToUse == null && includeOther)
setIdToUse = "*";
if (setIdToUse != null) {
helper(patientDrugOrderSets, setIdToUse, order);
if (order.isCurrent() || order.isFuture())
helper(currentDrugOrderSets, setIdToUse, order);
else
helper(completedDrugOrderSets, setIdToUse, order);
}
}
model.put("patientDrugOrderSets", patientDrugOrderSets);
model.put("currentDrugOrderSets", currentDrugOrderSets);
model.put("completedDrugOrderSets", completedDrugOrderSets);
model.put("cachedDrugSetIds", drugSetIds);
} // else do nothing - we already have orders in the model
}
}
| protected void populateModel(HttpServletRequest request, Map<String, Object> model) {
String drugSetIds = (String) model.get("displayDrugSetIds");
String cachedDrugSetIds = (String) model.get("cachedDrugSetIds");
if (cachedDrugSetIds == null || !cachedDrugSetIds.equals(drugSetIds)) {
if (drugSetIds != null && drugSetIds.length() > 0) {
Map<String, List<DrugOrder>> patientDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> currentDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, List<DrugOrder>> completedDrugOrderSets = new HashMap<String, List<DrugOrder>>();
Map<String, Collection<Concept>> drugConceptsBySetId = new LinkedHashMap<String, Collection<Concept>>();
boolean includeOther = false;
{
for (String setId : drugSetIds.split(",")) {
if ("*".equals(setId)) {
includeOther = true;
continue;
}
Concept drugSet = Context.getConceptService().getConcept(setId);
Collection<Concept> members = new ArrayList<Concept>();
if (drugSet != null)
members = Context.getConceptService().getConceptsByConceptSet(drugSet);
drugConceptsBySetId.put(setId, members);
}
}
List<DrugOrder> patientDrugOrders = (List<DrugOrder>) model.get("patientDrugOrders");
if (patientDrugOrders != null) {
for (DrugOrder order : patientDrugOrders) {
String setIdToUse = null;
if (order.getDrug() != null) {
Concept orderConcept = order.getDrug().getConcept();
for (Map.Entry<String, Collection<Concept>> e : drugConceptsBySetId.entrySet()) {
if (e.getValue().contains(orderConcept)) {
setIdToUse = e.getKey();
break;
}
}
}
if (setIdToUse == null && includeOther)
setIdToUse = "*";
if (setIdToUse != null) {
helper(patientDrugOrderSets, setIdToUse, order);
if (order.isCurrent() || order.isFuture())
helper(currentDrugOrderSets, setIdToUse, order);
else
helper(completedDrugOrderSets, setIdToUse, order);
}
}
}
model.put("patientDrugOrderSets", patientDrugOrderSets);
model.put("currentDrugOrderSets", currentDrugOrderSets);
model.put("completedDrugOrderSets", completedDrugOrderSets);
model.put("cachedDrugSetIds", drugSetIds);
} // else do nothing - we already have orders in the model
}
}
|
diff --git a/connectors/sipgate/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java b/connectors/sipgate/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java
index 1662aaa1..faebb4bb 100644
--- a/connectors/sipgate/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java
+++ b/connectors/sipgate/src/de/ub0r/android/websms/connector/sipgate/ConnectorSipgate.java
@@ -1,224 +1,226 @@
/*
* Copyright (C) 2010 Mirko Weber, Felix Bechstein
*
* This file is part of WebSMS.
*
* 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 de.ub0r.android.websms.connector.sipgate;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import org.xmlrpc.android.XMLRPCFault;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import de.ub0r.android.websms.connector.common.Connector;
import de.ub0r.android.websms.connector.common.ConnectorCommand;
import de.ub0r.android.websms.connector.common.ConnectorSpec;
import de.ub0r.android.websms.connector.common.Utils;
import de.ub0r.android.websms.connector.common.WebSMSException;
import de.ub0r.android.websms.connector.common.ConnectorSpec.SubConnectorSpec;
/**
* AsyncTask to manage XMLRPC-Calls to sipgate.de remote-API.
*
* @author Mirko Weber
*/
public class ConnectorSipgate extends Connector {
/** Tag for output. */
private static final String TAG = "WebSMS.Sipg";
/** Sipgate.de API URL. */
private static final String SIPGATE_URL = "https://"
+ "samurai.sipgate.net/RPC2";
/** Sipfate.de TEAM-API URL. */
private static final String SIPGATE_TEAM_URL = "https://"
+ "api.sipgate.net/RPC2";
/**
* {@inheritDoc}
*/
@Override
public final ConnectorSpec initSpec(final Context context) {
final String name = context.getString(R.string.connector_sipgate_name);
ConnectorSpec c = new ConnectorSpec(TAG, name);
c.setAuthor(// .
context.getString(R.string.connector_sipgate_author));
c.setBalance(null);
c.setPrefsTitle(context
.getString(R.string.connector_sipgate_preferences));
c.setCapabilities(ConnectorSpec.CAPABILITIES_UPDATE
| ConnectorSpec.CAPABILITIES_SEND
| ConnectorSpec.CAPABILITIES_PREFS);
c.addSubConnector(TAG, c.getName(),
SubConnectorSpec.FEATURE_MULTIRECIPIENTS);
return c;
}
/**
* {@inheritDoc}
*/
@Override
public final ConnectorSpec updateSpec(final Context context,
final ConnectorSpec connectorSpec) {
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(context);
if (p.getBoolean(Preferences.PREFS_ENABLE_SIPGATE, false)) {
if (p.getString(Preferences.PREFS_USER_SIPGATE, "").length() > 0
&& p.getString(Preferences.PREFS_PASSWORD_SIPGATE, "") // .
.length() > 0) {
connectorSpec.setReady();
} else {
connectorSpec.setStatus(ConnectorSpec.STATUS_ENABLED);
}
} else {
connectorSpec.setStatus(ConnectorSpec.STATUS_INACTIVE);
}
return connectorSpec;
}
/**
* {@inheritDoc}
*/
@Override
protected final void doSend(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doSend()");
Object back;
try {
XMLRPCClient client = this.init(context);
Vector<String> remoteUris = new Vector<String>();
ConnectorCommand command = new ConnectorCommand(intent);
final String defPrefx = command.getDefPrefix();
String u;
- for (String t : command.getRecipients()) {
+ String[] rr = command.getRecipients();
+ for (String t : rr) {
if (t != null && t.length() > 1) {
u = "sip:"
+ Utils.national2international(defPrefx,
Utils.getRecipientsNumber(t)).replaceAll(
"\\+", "") + "@sipgate.net";
remoteUris.add(u);
Log.d(TAG, "Mobile number: " + u);
}
}
u = null;
+ rr = null;
Hashtable<String, Serializable> params = // .
new Hashtable<String, Serializable>();
final String sender = Utils.getSender(context, command
.getDefSender());
if (sender.length() > 6) {
String localUri = "sip:" + sender.replaceAll("\\+", "")
+ "@sipgate.net";
params.put("LocalUri", localUri);
}
params.put("RemoteUri", remoteUris);
params.put("TOS", "text");
- params.put("Content", command.getText());
+ params.put("Content", command.getText().replace("\n", " "));
back = client.call("samurai.SessionInitiateMulti", params);
Log.d(TAG, back.toString());
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
protected final void doUpdate(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doUpdate()");
Map<String, Object> back = null;
try {
XMLRPCClient client = this.init(context);
back = (Map<String, Object>) client.call("samurai.BalanceGet");
Log.d(TAG, back.toString());
if (back.get("StatusCode").equals(
new Integer(Utils.HTTP_SERVICE_OK))) {
final String b = String.format("%.2f \u20AC",
((Double) ((Map<String, Object>) back
.get("CurrentBalance"))
.get("TotalIncludingVat")));
this.getSpec(context).setBalance(b);
}
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
/**
* Sets up and instance of {@link XMLRPCClient}.
*
* @param context
* {@link Context}
* @return the initialized {@link XMLRPCClient}
* @throws XMLRPCException
* XMLRPCException
*/
private XMLRPCClient init(final Context context) throws XMLRPCException {
Log.d(TAG, "init()");
final String version = context.getString(R.string.app_version);
final String vendor = context
.getString(R.string.connector_sipgate_author);
XMLRPCClient client = null;
final SharedPreferences p = PreferenceManager
.getDefaultSharedPreferences(context);
if (p.getBoolean(Preferences.PREFS_ENABLE_SIPGATE_TEAM, false)) {
client = new XMLRPCClient(SIPGATE_TEAM_URL);
} else {
client = new XMLRPCClient(SIPGATE_URL);
}
client.setBasicAuthentication(p.getString(
Preferences.PREFS_USER_SIPGATE, ""), p.getString(
Preferences.PREFS_PASSWORD_SIPGATE, ""));
Object back;
try {
Hashtable<String, String> ident = new Hashtable<String, String>();
ident.put("ClientName", TAG);
ident.put("ClientVersion", version);
ident.put("ClientVendor", vendor);
back = client.call("samurai.ClientIdentify", ident);
Log.d(TAG, back.toString());
return client;
} catch (XMLRPCException e) {
Log.e(TAG, "XMLRPCExceptin in init()", e);
throw e;
}
}
}
| false | true | protected final void doSend(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doSend()");
Object back;
try {
XMLRPCClient client = this.init(context);
Vector<String> remoteUris = new Vector<String>();
ConnectorCommand command = new ConnectorCommand(intent);
final String defPrefx = command.getDefPrefix();
String u;
for (String t : command.getRecipients()) {
if (t != null && t.length() > 1) {
u = "sip:"
+ Utils.national2international(defPrefx,
Utils.getRecipientsNumber(t)).replaceAll(
"\\+", "") + "@sipgate.net";
remoteUris.add(u);
Log.d(TAG, "Mobile number: " + u);
}
}
u = null;
Hashtable<String, Serializable> params = // .
new Hashtable<String, Serializable>();
final String sender = Utils.getSender(context, command
.getDefSender());
if (sender.length() > 6) {
String localUri = "sip:" + sender.replaceAll("\\+", "")
+ "@sipgate.net";
params.put("LocalUri", localUri);
}
params.put("RemoteUri", remoteUris);
params.put("TOS", "text");
params.put("Content", command.getText());
back = client.call("samurai.SessionInitiateMulti", params);
Log.d(TAG, back.toString());
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
| protected final void doSend(final Context context, final Intent intent)
throws WebSMSException {
Log.d(TAG, "doSend()");
Object back;
try {
XMLRPCClient client = this.init(context);
Vector<String> remoteUris = new Vector<String>();
ConnectorCommand command = new ConnectorCommand(intent);
final String defPrefx = command.getDefPrefix();
String u;
String[] rr = command.getRecipients();
for (String t : rr) {
if (t != null && t.length() > 1) {
u = "sip:"
+ Utils.national2international(defPrefx,
Utils.getRecipientsNumber(t)).replaceAll(
"\\+", "") + "@sipgate.net";
remoteUris.add(u);
Log.d(TAG, "Mobile number: " + u);
}
}
u = null;
rr = null;
Hashtable<String, Serializable> params = // .
new Hashtable<String, Serializable>();
final String sender = Utils.getSender(context, command
.getDefSender());
if (sender.length() > 6) {
String localUri = "sip:" + sender.replaceAll("\\+", "")
+ "@sipgate.net";
params.put("LocalUri", localUri);
}
params.put("RemoteUri", remoteUris);
params.put("TOS", "text");
params.put("Content", command.getText().replace("\n", " "));
back = client.call("samurai.SessionInitiateMulti", params);
Log.d(TAG, back.toString());
} catch (XMLRPCFault e) {
Log.e(TAG, null, e);
if (e.getFaultCode() == Utils.HTTP_SERVICE_UNAUTHORIZED) {
throw new WebSMSException(context, R.string.error_pw);
}
throw new WebSMSException(e);
} catch (XMLRPCException e) {
Log.e(TAG, null, e);
throw new WebSMSException(e);
}
}
|
diff --git a/iserve-discovery-disco/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/OntologyUpdateResource.java b/iserve-discovery-disco/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/OntologyUpdateResource.java
index 8ae13f59..69941031 100644
--- a/iserve-discovery-disco/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/OntologyUpdateResource.java
+++ b/iserve-discovery-disco/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/OntologyUpdateResource.java
@@ -1,247 +1,255 @@
/*
Copyright ${year} Knowledge Media Institute - The Open University
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 uk.ac.open.kmi.iserve.discovery.disco;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.ontoware.rdf2go.model.QueryResultTable;
import org.ontoware.rdf2go.model.QueryRow;
import org.ontoware.rdf2go.model.Statement;
import org.ontoware.rdf2go.model.node.URI;
import org.openrdf.rdf2go.RepositoryModel;
import org.openrdf.repository.RepositoryException;
import uk.ac.open.kmi.iserve.commons.io.RDFRepositoryConnector;
import uk.ac.open.kmi.iserve.commons.vocabulary.MSM;
-import uk.ac.open.kmi.iserve.sal.manager.ServiceManager;
+import uk.ac.open.kmi.iserve.commons.vocabulary.SAWSDL;
+import uk.ac.open.kmi.iserve.commons.vocabulary.WSMO_LITE;
import uk.ac.open.kmi.iserve.sal.manager.impl.ManagerSingleton;
-import uk.ac.open.kmi.iserve.sal.manager.impl.ServiceManagerRdf;
/**
* This class takes care of loading the ontologies that are referenced within
* service descriptions in order to support adequate discovery
*
* TODO: Should perhaps be pushed down to the SAL layer?
*
* @author ??
*/
@Path("/update-ontologies")
public class OntologyUpdateResource {
/**
*
*/
private static final String MODELREF_DEFN_CACHE_CTXT = "internal:iserve-modelref-defn-cache";
private static final List<URI> builtinExtras;
private static RdfCrawler rdfCrawler = new RdfCrawler();
// these are only informational fields so I don't care about any potential race conditions in reading and updating them
private static Date lastUpdate = null;
private static long lastTripleCount = 0;
private static Thread updaterThread;
private static final String[] NONE = new String[0];
private static final String[] EMPTY = new String[]{};
static {
List<URI> extras = new ArrayList<URI>(1);
extras.add(new org.ontoware.rdf2go.model.node.impl.URIImpl("http://www.w3.org/2009/08/skos-reference/skos.rdf"));
builtinExtras = Collections.unmodifiableList(extras);
}
private static RDFRepositoryConnector serviceConnector;
public OntologyUpdateResource() throws RepositoryException, IOException {
- ServiceManager svcManager = ManagerSingleton.getInstance().getServiceManager();
- if (svcManager instanceof ServiceManagerRdf) {
- serviceConnector = ((ServiceManagerRdf)svcManager).getRepoConnector();
+ String repoName = ManagerSingleton.getInstance().getConfiguration().getDataRepositoryName();
+ java.net.URI repoUri = ManagerSingleton.getInstance().getConfiguration().getDataRepositoryUri();
+
+ if (repoName != null && repoUri != null) {
+ try {
+ serviceConnector = new RDFRepositoryConnector(repoUri.toString(), repoName);
+ } catch (RepositoryException e) {
+ throw new WebApplicationException(
+ new IllegalStateException("The ontology updater could not connect to the RDF Repository."),
+ Response.Status.INTERNAL_SERVER_ERROR);
+ }
} else {
throw new WebApplicationException(
- new IllegalStateException("The Ontology Updater requires a Service Manager based backed by an RDF Repository."),
- Response.Status.INTERNAL_SERVER_ERROR);
+ new IllegalStateException("The ontology updater requires a Service Manager based backed by an RDF Repository."),
+ Response.Status.INTERNAL_SERVER_ERROR);
}
if (updaterThread == null) {
initUpdaterThread();
}
}
@GET
@Produces(MediaType.TEXT_HTML)
public Response getStatistics() {
RepositoryModel repoModel = serviceConnector.openRepositoryModel();
Set<URI> modelRefs = getExternalReferences(repoModel, NONE, NONE);
serviceConnector.closeRepositoryModel(repoModel);
String result = "<html><head><title>iServe Ontology Autoupdater</title></head><body><h1>iServe Ontology Autoupdater</h1>\n" +
"<p>Last update was on " + String.valueOf(lastUpdate) + ", resulting in " + lastTripleCount + " triples.</p>\n" +
"<form action='' method='post'>Extra: (optional) <input type='text' name='extra'/><br/><input type='submit' value='Update now!'></form>\n" +
"<p>Current references (count " + modelRefs.size() + "):</p>\n<pre>";
for (URI ref : modelRefs) {
result += ref.toString() + "\n";
}
result += "</pre></body></html>";
return Response.ok(result).build();
}
@POST
@Produces(MediaType.TEXT_HTML)
public Response update(@Context UriInfo ui) {
MultivaluedMap<String, String> params = ui.getQueryParameters();
List<String> extras = params.get("extra");
List<String> svcs = params.get("svc");
Set<Statement> crawledData = updateOntologies(listToArray(svcs), listToArray(extras));
lastUpdate = new Date();
lastTripleCount = crawledData.size();
String result = "<html><head><title>iServe Ontology Autoupdater - Updated</title></head><body><h1>iServe Ontology Autoupdater - Successfully updated</h1>\n" +
"<p>Updated on " + String.valueOf(lastUpdate) + ", got " + crawledData.size() + " statements.</p>\n" +
"<form action='' method='post'>Extra: (optional) <input type='text' name='extra'/><br/><input type='submit' value='Update again!'></form></body></html>";
return Response.ok(result).build();
}
private String[] listToArray(List<String> stringList) {
String[] result = new String[stringList.size()];
for ( int i = 0; i < stringList.size(); i++ ) {
result[i] = stringList.get(i);
}
return result;
}
private static synchronized void initUpdaterThread() {
if (updaterThread != null) {
return; // thread already initialized
}
updaterThread = new Thread(new Runnable(){
public void run() {
while (true) {
try {
Thread.sleep(1000*60*60*24); // wait a day
updateOntologies();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
updaterThread.start();
}
private static void updateOntologies() {
try {
updateOntologies(EMPTY, EMPTY);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Set<Statement> updateOntologies(String[] services, String[] extras) {
// the incoming representation is ignored and can be empty
RepositoryModel repoModel = serviceConnector.openRepositoryModel();
Set<URI> modelRefs = getExternalReferences(repoModel, services, extras);
serviceConnector.closeRepositoryModel(repoModel);
Set<Statement> crawledData = rdfCrawler.crawl(modelRefs);
if (crawledData.size() != 0) {
// put the statements in the repository
repoModel = serviceConnector.openRepositoryModel(MODELREF_DEFN_CACHE_CTXT);
// repoModel.removeAll(); // todo clear the cache context if we want to perform an update here, but owlim seems to interpret this as clearing the whole repository
repoModel.addAll(crawledData.iterator());
serviceConnector.closeRepositoryModel(repoModel);
}
return crawledData;
}
/**
* returns model references and usesOntology links from all the service descriptions; i.e., the references that we want to learn about
* @param repoModel the repository
* @param services if this array has any non-empty value, this function will return only the model references and usesOntology links from the given service(s)
* @param extras extra URIs that will be included in the returned set of URIs (those that are non-empty)
* @return a set of URIs that contains all the model references and usesOntology links
* @throws ResourceException
*/
private static Set<URI> getExternalReferences(RepositoryModel repoModel, String[] services, String[] extras) throws WebApplicationException {
if (services.length != 0) {
throw new WebApplicationException(Response.status(501).entity("limiting the ontology update by service is not implemented yet").build());
// TODO: implement ontology update limited by services
}
Set<URI> modelRefs = new HashSet<URI>();
- String query = "prefix sawsdl: <" + MSM.SAWSDL_NS_URI + ">\n" + "select distinct ?ref \n" +
+ String query = "prefix sawsdl: <" + SAWSDL.NS + ">\n" + "select distinct ?ref \n" +
"where { ?x sawsdl:modelReference ?ref . }";
QueryResultTable qresult = repoModel.querySelect(query, "sparql");
for (Iterator<QueryRow> it = qresult.iterator(); it.hasNext();) {
QueryRow row = it.next();
URI ref = row.getValue("ref").asURI();
modelRefs.add(ref);
}
- query = "prefix wl: <" + MSM.WL_NS_URI + ">\n" + "select distinct ?ref \n" +
+ query = "prefix wl: <" + WSMO_LITE.NS + ">\n" + "select distinct ?ref \n" +
"where { ?x wl:usesOntology ?ref . }";
qresult = repoModel.querySelect(query, "sparql");
for (Iterator<QueryRow> it = qresult.iterator(); it.hasNext();) {
QueryRow row = it.next();
URI ref = row.getValue("ref").asURI();
modelRefs.add(ref);
}
for (String extra : extras) {
if (extra != null && !"".equals(extra)) {
modelRefs.add(new org.ontoware.rdf2go.model.node.impl.URIImpl(extra));
System.err.println("added extra " + extra);
}
}
for (URI extra : builtinExtras) {
modelRefs.add(extra);
}
return modelRefs;
}
}
| false | false | null | null |
diff --git a/xmlunit/src/java/org/custommonkey/xmlunit/XpathNodeTracker.java b/xmlunit/src/java/org/custommonkey/xmlunit/XpathNodeTracker.java
index 9854f72..8bd88f6 100644
--- a/xmlunit/src/java/org/custommonkey/xmlunit/XpathNodeTracker.java
+++ b/xmlunit/src/java/org/custommonkey/xmlunit/XpathNodeTracker.java
@@ -1,278 +1,278 @@
/*
******************************************************************
Copyright (c) 2001, Jeff Martin, Tim Bacon
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 xmlunit.sourceforge.net nor the names
of its contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
******************************************************************
*/
package org.custommonkey.xmlunit;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Tracks Nodes visited by the DifferenceEngine and
* converts that information into an Xpath-String to supply
* to the NodeDetail of a Difference instance
* @see NodeDetail#getXpathLocation()
* @see Difference#getControlNodeDetail
* @see Difference#getTestNodeDetail
*/
public class XpathNodeTracker implements XMLConstants {
private final List indentationList = new ArrayList();
private TrackingEntry currentEntry;
private boolean trackRepeatedVisits = false;
/**
* Simple constructor
*/
public XpathNodeTracker() {
indent();
}
/**
* Clear state data.
* Call if required to reuse an existing instance.
*/
public void reset() {
indentationList.clear();
indent();
}
/**
* Call before examining child nodes one level of indentation into DOM
*/
public void indent() {
if (currentEntry != null) {
currentEntry.clearTrackedAttribute();
}
currentEntry = new TrackingEntry();
indentationList.add(currentEntry);
}
/**
* Call after examining child nodes, ie before returning back one level of indentation from DOM
*/
public void outdent() {
int last = indentationList.size() - 1;
indentationList.remove(last);
--last;
- if (last > 0) {
+ if (last >= 0) {
currentEntry = (TrackingEntry) indentationList.get(last);
}
}
/**
* Call when visiting a node whose xpath location needs tracking
* @param node the Node being visited
*/
public void visited(Node node) {
String nodeName;
switch(node.getNodeType()) {
case Node.ATTRIBUTE_NODE:
nodeName = ((Attr)node).getLocalName();
if (nodeName == null || nodeName.length() == 0) {
nodeName = node.getNodeName();
}
visitedAttribute(nodeName);
break;
case Node.ELEMENT_NODE:
nodeName = ((Element)node).getLocalName();
if (nodeName == null || nodeName.length() == 0) {
nodeName = node.getNodeName();
}
visitedNode(node, nodeName);
break;
case Node.COMMENT_NODE:
visitedNode(node, XPATH_COMMENT_IDENTIFIER);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
visitedNode(node, XPATH_PROCESSING_INSTRUCTION_IDENTIFIER);
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
visitedNode(node, XPATH_CHARACTER_NODE_IDENTIFIER);
break;
}
}
protected void visitedNode(Node visited, String value) {
currentEntry.trackNode(visited, value);
}
protected void visitedAttribute(String visited) {
currentEntry.trackAttribute(visited);
}
/**
* Preload the items in a NodeList by visiting each in turn
* Required for pieces of test XML whose node children can be visited
* out of sequence by a DifferenceEngine comparison
* @param nodeList the items to preload
*/
public void preloadNodeList(NodeList nodeList) {
currentEntry.trackNodesAsWellAsValues(true);
int length = nodeList.getLength();
for (int i=0; i < length; ++i) {
visited(nodeList.item(i));
}
currentEntry.trackNodesAsWellAsValues(false);
}
/**
* @return the last visited node as an xpath-location String
*/
public String toXpathString() {
StringBuffer buf = new StringBuffer();
TrackingEntry nextEntry;
for (Iterator iter = indentationList.iterator(); iter.hasNext(); ) {
nextEntry = (TrackingEntry) iter.next();
nextEntry.appendEntryTo(buf);
}
return buf.toString();
}
/**
* Wrapper class around a mutable <code>int</code> value
* Avoids creation of many immutable <code>Integer</code> objects
*/
private final class Int {
private int value;
public Int(int startAt) {
value = startAt;
}
public final void increment() {
++value;
}
public final int getValue() {
return value;
}
public final Integer toInteger() {
return new Integer(value);
}
}
/**
* Holds node tracking details - one instance is used for each level of indentation in a DOM
* Provides reference between a String-ified Node value and the xpath index of that value
*/
private final class TrackingEntry {
private final Map valueMap = new HashMap();
private String currentValue, currentAttribute;
private Map nodeReferenceMap;
private boolean trackNodeReferences = false;
private Integer nodeReferenceLookup = null;
private Int lookup(String value) {
return (Int) valueMap.get(value);
}
/**
* Keep a reference to the current visited (non-attribute) node
* @param visited the non-attribute node visited
* @param value the String-ified value of the non-attribute node visited
*/
public final void trackNode(Node visited, String value) {
if (nodeReferenceMap == null || trackNodeReferences) {
Int occurrence = lookup(value);
if (occurrence == null) {
occurrence = new Int(1);
valueMap.put(value, occurrence);
} else {
occurrence.increment();
}
if (trackNodeReferences) {
nodeReferenceMap.put(visited, occurrence.toInteger());
}
} else {
nodeReferenceLookup = (Integer) nodeReferenceMap.get(visited);
}
currentValue = value;
clearTrackedAttribute();
}
/**
* Keep a reference to the visited attribute at the current visited node
* @param value the attribute visited
*/
public final void trackAttribute(String visited) {
currentAttribute = visited;
}
/**
* Clear any reference to the current visited attribute
*/
public final void clearTrackedAttribute() {
currentAttribute = null;
}
/**
* Append the details of the current visited node to a StringBuffer
* @param buf the StringBuffer to append to
*/
public final void appendEntryTo(StringBuffer buf) {
if (currentValue == null) {
return;
}
buf.append(XPATH_SEPARATOR).append(currentValue);
int value = nodeReferenceLookup == null
? lookup(currentValue).getValue() : nodeReferenceLookup.intValue();
buf.append(XPATH_NODE_INDEX_START).append(value).append(XPATH_NODE_INDEX_END);
if (currentAttribute != null) {
buf.append(XPATH_SEPARATOR).append(XPATH_ATTRIBUTE_IDENTIFIER)
.append(currentAttribute);
}
}
public void trackNodesAsWellAsValues(boolean yesNo) {
this.trackNodeReferences = yesNo;
if (yesNo) {
nodeReferenceMap = new HashMap();
}
}
}
}
| true | false | null | null |
diff --git a/src/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl.java b/src/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl.java
index 3ca672514..1826262b6 100644
--- a/src/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl.java
+++ b/src/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl.java
@@ -1,3275 +1,3289 @@
/*
* Copyright 2001-2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xerces.impl.dv.xs;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.dv.DatatypeException;
import org.apache.xerces.impl.dv.InvalidDatatypeFacetException;
import org.apache.xerces.impl.dv.InvalidDatatypeValueException;
import org.apache.xerces.impl.dv.ValidatedInfo;
import org.apache.xerces.impl.dv.ValidationContext;
import org.apache.xerces.impl.dv.XSFacets;
import org.apache.xerces.impl.dv.XSSimpleType;
import org.apache.xerces.impl.xpath.regex.RegularExpression;
import org.apache.xerces.impl.xs.SchemaSymbols;
import org.apache.xerces.impl.xs.util.ShortListImpl;
import org.apache.xerces.impl.xs.util.StringListImpl;
import org.apache.xerces.impl.xs.util.XSObjectListImpl;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xs.ShortList;
import org.apache.xerces.xs.StringList;
import org.apache.xerces.xs.XSAnnotation;
import org.apache.xerces.xs.XSConstants;
import org.apache.xerces.xs.XSFacet;
import org.apache.xerces.xs.XSMultiValueFacet;
import org.apache.xerces.xs.XSNamespaceItem;
import org.apache.xerces.xs.XSObjectList;
import org.apache.xerces.xs.XSSimpleTypeDefinition;
import org.apache.xerces.xs.XSTypeDefinition;
import org.apache.xerces.xs.datatypes.ObjectList;
import org.w3c.dom.TypeInfo;
/**
* @xerces.internal
*
* @author Sandy Gao, IBM
* @author Neeraj Bajaj, Sun Microsystems, inc.
*
* @version $Id$
*/
public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
static final short DV_STRING = PRIMITIVE_STRING;
static final short DV_BOOLEAN = PRIMITIVE_BOOLEAN;
static final short DV_DECIMAL = PRIMITIVE_DECIMAL;
static final short DV_FLOAT = PRIMITIVE_FLOAT;
static final short DV_DOUBLE = PRIMITIVE_DOUBLE;
static final short DV_DURATION = PRIMITIVE_DURATION;
static final short DV_DATETIME = PRIMITIVE_DATETIME;
static final short DV_TIME = PRIMITIVE_TIME;
static final short DV_DATE = PRIMITIVE_DATE;
static final short DV_GYEARMONTH = PRIMITIVE_GYEARMONTH;
static final short DV_GYEAR = PRIMITIVE_GYEAR;
static final short DV_GMONTHDAY = PRIMITIVE_GMONTHDAY;
static final short DV_GDAY = PRIMITIVE_GDAY;
static final short DV_GMONTH = PRIMITIVE_GMONTH;
static final short DV_HEXBINARY = PRIMITIVE_HEXBINARY;
static final short DV_BASE64BINARY = PRIMITIVE_BASE64BINARY;
static final short DV_ANYURI = PRIMITIVE_ANYURI;
static final short DV_QNAME = PRIMITIVE_QNAME;
static final short DV_PRECISIONDECIMAL = PRIMITIVE_PRECISIONDECIMAL;
static final short DV_NOTATION = PRIMITIVE_NOTATION;
static final short DV_ANYSIMPLETYPE = 0;
static final short DV_ID = DV_NOTATION + 1;
static final short DV_IDREF = DV_NOTATION + 2;
static final short DV_ENTITY = DV_NOTATION + 3;
static final short DV_INTEGER = DV_NOTATION + 4;
static final short DV_LIST = DV_NOTATION + 5;
static final short DV_UNION = DV_NOTATION + 6;
static final short DV_YEARMONTHDURATION = DV_NOTATION + 7;
static final short DV_DAYTIMEDURATION = DV_NOTATION + 8;
static final short DV_ANYATOMICTYPE = DV_NOTATION + 9;
static final TypeValidator[] fDVs = {
new AnySimpleDV(),
new StringDV(),
new BooleanDV(),
new DecimalDV(),
new FloatDV(),
new DoubleDV(),
new DurationDV(),
new DateTimeDV(),
new TimeDV(),
new DateDV(),
new YearMonthDV(),
new YearDV(),
new MonthDayDV(),
new DayDV(),
new MonthDV(),
new HexBinaryDV(),
new Base64BinaryDV(),
new AnyURIDV(),
new QNameDV(),
new PrecisionDecimalDV(), // XML Schema 1.1 type
new QNameDV(), // notation use the same one as qname
new IDDV(),
new IDREFDV(),
new EntityDV(),
new IntegerDV(),
new ListDV(),
new UnionDV(),
new YearMonthDurationDV(), // XML Schema 1.1 type
new DayTimeDurationDV(), // XML Schema 1.1 type
new AnyAtomicDV() // XML Schema 1.1 type
};
static final short NORMALIZE_NONE = 0;
static final short NORMALIZE_TRIM = 1;
static final short NORMALIZE_FULL = 2;
static final short[] fDVNormalizeType = {
NORMALIZE_NONE, //AnySimpleDV(),
NORMALIZE_FULL, //StringDV(),
NORMALIZE_TRIM, //BooleanDV(),
NORMALIZE_TRIM, //DecimalDV(),
NORMALIZE_TRIM, //FloatDV(),
NORMALIZE_TRIM, //DoubleDV(),
NORMALIZE_TRIM, //DurationDV(),
NORMALIZE_TRIM, //DateTimeDV(),
NORMALIZE_TRIM, //TimeDV(),
NORMALIZE_TRIM, //DateDV(),
NORMALIZE_TRIM, //YearMonthDV(),
NORMALIZE_TRIM, //YearDV(),
NORMALIZE_TRIM, //MonthDayDV(),
NORMALIZE_TRIM, //DayDV(),
NORMALIZE_TRIM, //MonthDV(),
NORMALIZE_TRIM, //HexBinaryDV(),
NORMALIZE_NONE, //Base64BinaryDV(), // Base64 know how to deal with spaces
NORMALIZE_TRIM, //AnyURIDV(),
NORMALIZE_TRIM, //QNameDV(),
NORMALIZE_TRIM, //PrecisionDecimalDV() (Schema 1.1)
NORMALIZE_TRIM, //QNameDV(), // notation
NORMALIZE_TRIM, //IDDV(),
NORMALIZE_TRIM, //IDREFDV(),
NORMALIZE_TRIM, //EntityDV(),
NORMALIZE_TRIM, //IntegerDV(),
NORMALIZE_FULL, //ListDV(),
NORMALIZE_NONE, //UnionDV(),
NORMALIZE_TRIM, //YearMonthDurationDV() (Schema 1.1)
NORMALIZE_TRIM, //DayTimeDurationDV() (Schema 1.1)
NORMALIZE_NONE, //AnyAtomicDV() (Schema 1.1)
};
static final short SPECIAL_PATTERN_NONE = 0;
static final short SPECIAL_PATTERN_NMTOKEN = 1;
static final short SPECIAL_PATTERN_NAME = 2;
static final short SPECIAL_PATTERN_NCNAME = 3;
static final String[] SPECIAL_PATTERN_STRING = {
"NONE", "NMTOKEN", "Name", "NCName"
};
static final String[] WS_FACET_STRING = {
"preserve", "replace", "collapse"
};
static final String URI_SCHEMAFORSCHEMA = "http://www.w3.org/2001/XMLSchema";
static final String ANY_TYPE = "anyType";
// XML Schema 1.1 type constants
public static final short YEARMONTHDURATION_DT = 46;
public static final short DAYTIMEDURATION_DT = 47;
public static final short PRECISIONDECIMAL_DT = 48;
public static final short ANYATOMICTYPE_DT = 49;
// DOM Level 3 TypeInfo Derivation Method constants
static final int DERIVATION_ANY = 0;
static final int DERIVATION_RESTRICTION = 1;
static final int DERIVATION_EXTENSION = 2;
static final int DERIVATION_UNION = 4;
static final int DERIVATION_LIST = 8;
static final ValidationContext fEmptyContext = new ValidationContext() {
public boolean needFacetChecking() {
return true;
}
public boolean needExtraChecking() {
return false;
}
public boolean needToNormalize() {
return true;
}
public boolean useNamespaces () {
return true;
}
public boolean isEntityDeclared (String name) {
return false;
}
public boolean isEntityUnparsed (String name) {
return false;
}
public boolean isIdDeclared (String name) {
return false;
}
public void addId(String name) {
}
public void addIdRef(String name) {
}
public String getSymbol (String symbol) {
return symbol.intern();
}
public String getURI(String prefix) {
return null;
}
};
// this will be true if this is a static XSSimpleTypeDecl
// and hence must remain immutable (i.e., applyFacets
// may not be permitted to have any effect).
private boolean fIsImmutable = false;
private XSSimpleTypeDecl fItemType;
private XSSimpleTypeDecl[] fMemberTypes;
// The most specific built-in type kind.
private short fBuiltInKind;
private String fTypeName;
private String fTargetNamespace;
private short fFinalSet = 0;
private XSSimpleTypeDecl fBase;
private short fVariety = -1;
private short fValidationDV = -1;
private short fFacetsDefined = 0;
private short fFixedFacet = 0;
//for constraining facets
private short fWhiteSpace = 0;
private int fLength = -1;
private int fMinLength = -1;
private int fMaxLength = -1;
private int fTotalDigits = -1;
private int fFractionDigits = -1;
private Vector fPattern;
private Vector fPatternStr;
private Vector fEnumeration;
private short[] fEnumerationType;
private ShortList[] fEnumerationItemType; // used in case fenumerationType value is LIST or LISTOFUNION
private ShortList fEnumerationTypeList;
private ObjectList fEnumerationItemTypeList;
private StringList fLexicalPattern;
private StringList fLexicalEnumeration;
private ObjectList fActualEnumeration;
private Object fMaxInclusive;
private Object fMaxExclusive;
private Object fMinExclusive;
private Object fMinInclusive;
// annotations for constraining facets
public XSAnnotation lengthAnnotation;
public XSAnnotation minLengthAnnotation;
public XSAnnotation maxLengthAnnotation;
public XSAnnotation whiteSpaceAnnotation;
public XSAnnotation totalDigitsAnnotation;
public XSAnnotation fractionDigitsAnnotation;
public XSObjectListImpl patternAnnotations;
public XSObjectList enumerationAnnotations;
public XSAnnotation maxInclusiveAnnotation;
public XSAnnotation maxExclusiveAnnotation;
public XSAnnotation minInclusiveAnnotation;
public XSAnnotation minExclusiveAnnotation;
// facets as objects
private XSObjectListImpl fFacets;
// enumeration and pattern facets
private XSObjectListImpl fMultiValueFacets;
// simpleType annotations
private XSObjectList fAnnotations = null;
private short fPatternType = SPECIAL_PATTERN_NONE;
// for fundamental facets
private short fOrdered;
private boolean fFinite;
private boolean fBounded;
private boolean fNumeric;
// default constructor
public XSSimpleTypeDecl(){}
//Create a new built-in primitive types (and id/idref/entity/integer/yearMonthDuration)
protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, short validateDV,
short ordered, boolean bounded, boolean finite,
boolean numeric, boolean isImmutable, short builtInKind) {
fIsImmutable = isImmutable;
fBase = base;
fTypeName = name;
fTargetNamespace = URI_SCHEMAFORSCHEMA;
// To simplify the code for anySimpleType, we treat it as an atomic type
fVariety = VARIETY_ATOMIC;
fValidationDV = validateDV;
fFacetsDefined = FACET_WHITESPACE;
if (validateDV == DV_STRING) {
fWhiteSpace = WS_PRESERVE;
} else {
fWhiteSpace = WS_COLLAPSE;
fFixedFacet = FACET_WHITESPACE;
}
this.fOrdered = ordered;
this.fBounded = bounded;
this.fFinite = finite;
this.fNumeric = numeric;
fAnnotations = null;
// Specify the build in kind for this primitive type
fBuiltInKind = builtInKind;
}
//Create a new simple type for restriction for built-in types
protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, String uri, short finalSet, boolean isImmutable,
XSObjectList annotations, short builtInKind) {
this(base, name, uri, finalSet, isImmutable, annotations);
// Specify the build in kind for this built-in type
fBuiltInKind = builtInKind;
}
//Create a new simple type for restriction.
protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, String uri, short finalSet, boolean isImmutable,
XSObjectList annotations) {
fBase = base;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fAnnotations = annotations;
fVariety = fBase.fVariety;
fValidationDV = fBase.fValidationDV;
switch (fVariety) {
case VARIETY_ATOMIC:
break;
case VARIETY_LIST:
fItemType = fBase.fItemType;
break;
case VARIETY_UNION:
fMemberTypes = fBase.fMemberTypes;
break;
}
// always inherit facets from the base.
// in case a type is created, but applyFacets is not called
fLength = fBase.fLength;
fMinLength = fBase.fMinLength;
fMaxLength = fBase.fMaxLength;
fPattern = fBase.fPattern;
fPatternStr = fBase.fPatternStr;
fEnumeration = fBase.fEnumeration;
fEnumerationType = fBase.fEnumerationType;
fEnumerationItemType = fBase.fEnumerationItemType;
fWhiteSpace = fBase.fWhiteSpace;
fMaxExclusive = fBase.fMaxExclusive;
fMaxInclusive = fBase.fMaxInclusive;
fMinExclusive = fBase.fMinExclusive;
fMinInclusive = fBase.fMinInclusive;
fTotalDigits = fBase.fTotalDigits;
fFractionDigits = fBase.fFractionDigits;
fPatternType = fBase.fPatternType;
fFixedFacet = fBase.fFixedFacet;
fFacetsDefined = fBase.fFacetsDefined;
+
+ // always inherit facet annotations in case applyFacets is not called.
+ lengthAnnotation = fBase.lengthAnnotation;
+ minLengthAnnotation = fBase.minLengthAnnotation;
+ maxLengthAnnotation = fBase.maxLengthAnnotation;
+ patternAnnotations = fBase.patternAnnotations;
+ enumerationAnnotations = fBase.enumerationAnnotations;
+ whiteSpaceAnnotation = fBase.whiteSpaceAnnotation;
+ maxExclusiveAnnotation = fBase.maxExclusiveAnnotation;
+ maxInclusiveAnnotation = fBase.maxInclusiveAnnotation;
+ minExclusiveAnnotation = fBase.minExclusiveAnnotation;
+ minInclusiveAnnotation = fBase.minInclusiveAnnotation;
+ totalDigitsAnnotation = fBase.totalDigitsAnnotation;
+ fractionDigitsAnnotation = fBase.fractionDigitsAnnotation;
//we also set fundamental facets information in case applyFacets is not called.
calcFundamentalFacets();
fIsImmutable = isImmutable;
// Inherit from the base type
fBuiltInKind = base.fBuiltInKind;
}
//Create a new simple type for list.
protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl itemType, boolean isImmutable,
XSObjectList annotations) {
fBase = fAnySimpleType;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fAnnotations = annotations;
fVariety = VARIETY_LIST;
fItemType = (XSSimpleTypeDecl)itemType;
fValidationDV = DV_LIST;
fFacetsDefined = FACET_WHITESPACE;
fFixedFacet = FACET_WHITESPACE;
fWhiteSpace = WS_COLLAPSE;
//setting fundamental facets
calcFundamentalFacets();
fIsImmutable = isImmutable;
// Values of this type are lists
fBuiltInKind = XSConstants.LIST_DT;
}
//Create a new simple type for union.
protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes,
XSObjectList annotations) {
fBase = fAnySimpleType;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fAnnotations = annotations;
fVariety = VARIETY_UNION;
fMemberTypes = memberTypes;
fValidationDV = DV_UNION;
// even for union, we set whitespace to something
// this will never be used, but we can use fFacetsDefined to check
// whether applyFacets() is allwwed: it's not allowed
// if fFacetsDefined != 0
fFacetsDefined = FACET_WHITESPACE;
fWhiteSpace = WS_COLLAPSE;
//setting fundamental facets
calcFundamentalFacets();
// none of the schema-defined types are unions, so just set
// fIsImmutable to false.
fIsImmutable = false;
// No value can be of this type, so it's unavailable.
fBuiltInKind = XSConstants.UNAVAILABLE_DT;
}
//set values for restriction.
protected XSSimpleTypeDecl setRestrictionValues(XSSimpleTypeDecl base, String name, String uri, short finalSet,
XSObjectList annotations) {
//decline to do anything if the object is immutable.
if(fIsImmutable) return null;
fBase = base;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fAnnotations = annotations;
fVariety = fBase.fVariety;
fValidationDV = fBase.fValidationDV;
switch (fVariety) {
case VARIETY_ATOMIC:
break;
case VARIETY_LIST:
fItemType = fBase.fItemType;
break;
case VARIETY_UNION:
fMemberTypes = fBase.fMemberTypes;
break;
}
// always inherit facets from the base.
// in case a type is created, but applyFacets is not called
fLength = fBase.fLength;
fMinLength = fBase.fMinLength;
fMaxLength = fBase.fMaxLength;
fPattern = fBase.fPattern;
fPatternStr = fBase.fPatternStr;
fEnumeration = fBase.fEnumeration;
fEnumerationType = fBase.fEnumerationType;
fEnumerationItemType = fBase.fEnumerationItemType;
fWhiteSpace = fBase.fWhiteSpace;
fMaxExclusive = fBase.fMaxExclusive;
fMaxInclusive = fBase.fMaxInclusive;
fMinExclusive = fBase.fMinExclusive;
fMinInclusive = fBase.fMinInclusive;
fTotalDigits = fBase.fTotalDigits;
fFractionDigits = fBase.fFractionDigits;
fPatternType = fBase.fPatternType;
fFixedFacet = fBase.fFixedFacet;
fFacetsDefined = fBase.fFacetsDefined;
//we also set fundamental facets information in case applyFacets is not called.
calcFundamentalFacets();
// Inherit from the base type
fBuiltInKind = base.fBuiltInKind;
return this;
}
//set values for list.
protected XSSimpleTypeDecl setListValues(String name, String uri, short finalSet, XSSimpleTypeDecl itemType,
XSObjectList annotations) {
//decline to do anything if the object is immutable.
if(fIsImmutable) return null;
fBase = fAnySimpleType;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fAnnotations = annotations;
fVariety = VARIETY_LIST;
fItemType = (XSSimpleTypeDecl)itemType;
fValidationDV = DV_LIST;
fFacetsDefined = FACET_WHITESPACE;
fFixedFacet = FACET_WHITESPACE;
fWhiteSpace = WS_COLLAPSE;
//setting fundamental facets
calcFundamentalFacets();
// Values of this type are lists
fBuiltInKind = XSConstants.LIST_DT;
return this;
}
//set values for union.
protected XSSimpleTypeDecl setUnionValues(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes,
XSObjectList annotations) {
//decline to do anything if the object is immutable.
if(fIsImmutable) return null;
fBase = fAnySimpleType;
fTypeName = name;
fTargetNamespace = uri;
fFinalSet = finalSet;
fAnnotations = annotations;
fVariety = VARIETY_UNION;
fMemberTypes = memberTypes;
fValidationDV = DV_UNION;
// even for union, we set whitespace to something
// this will never be used, but we can use fFacetsDefined to check
// whether applyFacets() is allwwed: it's not allowed
// if fFacetsDefined != 0
fFacetsDefined = FACET_WHITESPACE;
fWhiteSpace = WS_COLLAPSE;
//setting fundamental facets
calcFundamentalFacets();
// No value can be of this type, so it's unavailable.
fBuiltInKind = XSConstants.UNAVAILABLE_DT;
return this;
}
public short getType () {
return XSConstants.TYPE_DEFINITION;
}
public short getTypeCategory () {
return SIMPLE_TYPE;
}
public String getName() {
return getAnonymous()?null:fTypeName;
}
public String getTypeName() {
return fTypeName;
}
public String getNamespace() {
return fTargetNamespace;
}
public short getFinal(){
return fFinalSet;
}
public boolean isFinal(short derivation) {
return (fFinalSet & derivation) != 0;
}
public XSTypeDefinition getBaseType(){
return fBase;
}
public boolean getAnonymous() {
return fAnonymous || (fTypeName == null);
}
public short getVariety(){
// for anySimpleType, return absent variaty
return fValidationDV == DV_ANYSIMPLETYPE ? VARIETY_ABSENT : fVariety;
}
public boolean isIDType(){
switch (fVariety) {
case VARIETY_ATOMIC:
return fValidationDV == DV_ID;
case VARIETY_LIST:
return fItemType.isIDType();
case VARIETY_UNION:
for (int i = 0; i < fMemberTypes.length; i++) {
if (fMemberTypes[i].isIDType())
return true;
}
}
return false;
}
public short getWhitespace() throws DatatypeException{
if (fVariety == VARIETY_UNION) {
throw new DatatypeException("dt-whitespace", new Object[]{fTypeName});
}
return fWhiteSpace;
}
public short getPrimitiveKind() {
if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE) {
if (fValidationDV == DV_ID || fValidationDV == DV_IDREF || fValidationDV == DV_ENTITY) {
return DV_STRING;
}
else if (fValidationDV == DV_INTEGER) {
return DV_DECIMAL;
}
else if (Constants.SCHEMA_1_1_SUPPORT && (fValidationDV == DV_YEARMONTHDURATION || fValidationDV == DV_DAYTIMEDURATION)) {
return DV_DURATION;
}
else {
return fValidationDV;
}
}
else {
// REVISIT: error situation. runtime exception?
return (short)0;
}
}
/**
* Returns the closest built-in type category this type represents or
* derived from. For example, if this simple type is a built-in derived
* type integer the <code>INTEGER_DV</code> is returned.
*/
public short getBuiltInKind() {
return this.fBuiltInKind;
}
/**
* If variety is <code>atomic</code> the primitive type definition (a
* built-in primitive datatype definition or the simple ur-type
* definition) is available, otherwise <code>null</code>.
*/
public XSSimpleTypeDefinition getPrimitiveType() {
if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE) {
XSSimpleTypeDecl pri = this;
// recursively get base, until we reach anySimpleType
while (pri.fBase != fAnySimpleType)
pri = pri.fBase;
return pri;
}
else {
// REVISIT: error situation. runtime exception?
return null;
}
}
/**
* If variety is <code>list</code> the item type definition (an atomic or
* union simple type definition) is available, otherwise
* <code>null</code>.
*/
public XSSimpleTypeDefinition getItemType() {
if (fVariety == VARIETY_LIST) {
return fItemType;
}
else {
// REVISIT: error situation. runtime exception?
return null;
}
}
/**
* If variety is <code>union</code> the list of member type definitions (a
* non-empty sequence of simple type definitions) is available,
* otherwise an empty <code>XSObjectList</code>.
*/
public XSObjectList getMemberTypes() {
if (fVariety == VARIETY_UNION) {
return new XSObjectListImpl(fMemberTypes, fMemberTypes.length);
}
else {
return XSObjectListImpl.EMPTY_LIST;
}
}
/**
* If <restriction> is chosen
*/
public void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, ValidationContext context)
throws InvalidDatatypeFacetException {
applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, context);
}
/**
* built-in derived types by restriction
*/
void applyFacets1(XSFacets facets, short presentFacet, short fixedFacet) {
try {
applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, fDummyContext);
} catch (InvalidDatatypeFacetException e) {
// should never gets here, internel error
throw new RuntimeException("internal error");
}
// we've now applied facets; so lock this object:
fIsImmutable = true;
}
/**
* built-in derived types by restriction
*/
void applyFacets1(XSFacets facets, short presentFacet, short fixedFacet, short patternType) {
try {
applyFacets(facets, presentFacet, fixedFacet, patternType, fDummyContext);
} catch (InvalidDatatypeFacetException e) {
// should never gets here, internel error
throw new RuntimeException("internal error");
}
// we've now applied facets; so lock this object:
fIsImmutable = true;
}
/**
* If <restriction> is chosen, or built-in derived types by restriction
*/
void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, short patternType, ValidationContext context)
throws InvalidDatatypeFacetException {
// if the object is immutable, should not apply facets...
if(fIsImmutable) return;
ValidatedInfo tempInfo = new ValidatedInfo();
// clear facets. because we always inherit facets in the constructor
// REVISIT: in fact, we don't need to clear them.
// we can convert 5 string values (4 bounds + 1 enum) to actual values,
// store them somewhere, then do facet checking at once, instead of
// going through the following steps. (lots of checking are redundant:
// for example, ((presentFacet & FACET_XXX) != 0))
fFacetsDefined = 0;
fFixedFacet = 0;
int result = 0 ;
// step 1: parse present facets
short allowedFacet = fDVs[fValidationDV].getAllowedFacets();
// length
if ((presentFacet & FACET_LENGTH) != 0) {
if ((allowedFacet & FACET_LENGTH) == 0) {
reportError("cos-applicable-facets", new Object[]{"length", fTypeName});
} else {
fLength = facets.length;
lengthAnnotation = facets.lengthAnnotation;
fFacetsDefined |= FACET_LENGTH;
if ((fixedFacet & FACET_LENGTH) != 0)
fFixedFacet |= FACET_LENGTH;
}
}
// minLength
if ((presentFacet & FACET_MINLENGTH) != 0) {
if ((allowedFacet & FACET_MINLENGTH) == 0) {
reportError("cos-applicable-facets", new Object[]{"minLength", fTypeName});
} else {
fMinLength = facets.minLength;
minLengthAnnotation = facets.minLengthAnnotation;
fFacetsDefined |= FACET_MINLENGTH;
if ((fixedFacet & FACET_MINLENGTH) != 0)
fFixedFacet |= FACET_MINLENGTH;
}
}
// maxLength
if ((presentFacet & FACET_MAXLENGTH) != 0) {
if ((allowedFacet & FACET_MAXLENGTH) == 0) {
reportError("cos-applicable-facets", new Object[]{"maxLength", fTypeName});
} else {
fMaxLength = facets.maxLength;
maxLengthAnnotation = facets.maxLengthAnnotation;
fFacetsDefined |= FACET_MAXLENGTH;
if ((fixedFacet & FACET_MAXLENGTH) != 0)
fFixedFacet |= FACET_MAXLENGTH;
}
}
// pattern
if ((presentFacet & FACET_PATTERN) != 0) {
if ((allowedFacet & FACET_PATTERN) == 0) {
reportError("cos-applicable-facets", new Object[]{"pattern", fTypeName});
} else {
patternAnnotations = facets.patternAnnotations;
RegularExpression regex = null;
try {
regex = new RegularExpression(facets.pattern, "X");
} catch (Exception e) {
reportError("InvalidRegex", new Object[]{facets.pattern, e.getLocalizedMessage()});
}
if (regex != null) {
fPattern = new Vector();
fPattern.addElement(regex);
fPatternStr = new Vector();
fPatternStr.addElement(facets.pattern);
fFacetsDefined |= FACET_PATTERN;
if ((fixedFacet & FACET_PATTERN) != 0)
fFixedFacet |= FACET_PATTERN;
}
}
}
// enumeration
if ((presentFacet & FACET_ENUMERATION) != 0) {
if ((allowedFacet & FACET_ENUMERATION) == 0) {
reportError("cos-applicable-facets", new Object[]{"enumeration", fTypeName});
} else {
fEnumeration = new Vector();
Vector enumVals = facets.enumeration;
fEnumerationType = new short[enumVals.size()];
fEnumerationItemType = new ShortList[enumVals.size()];
Vector enumNSDecls = facets.enumNSDecls;
ValidationContextImpl ctx = new ValidationContextImpl(context);
enumerationAnnotations = facets.enumAnnotations;
for (int i = 0; i < enumVals.size(); i++) {
if (enumNSDecls != null)
ctx.setNSContext((NamespaceContext)enumNSDecls.elementAt(i));
try {
ValidatedInfo info = this.fBase.validateWithInfo((String)enumVals.elementAt(i), ctx, tempInfo);
// check 4.3.5.c0 must: enumeration values from the value space of base
fEnumeration.addElement(info.actualValue);
fEnumerationType[i] = info.actualValueType;
fEnumerationItemType[i] = info.itemValueTypes;
} catch (InvalidDatatypeValueException ide) {
reportError("enumeration-valid-restriction", new Object[]{enumVals.elementAt(i), this.getBaseType().getName()});
}
}
fFacetsDefined |= FACET_ENUMERATION;
if ((fixedFacet & FACET_ENUMERATION) != 0)
fFixedFacet |= FACET_ENUMERATION;
}
}
// whiteSpace
if ((presentFacet & FACET_WHITESPACE) != 0) {
if ((allowedFacet & FACET_WHITESPACE) == 0) {
reportError("cos-applicable-facets", new Object[]{"whiteSpace", fTypeName});
} else {
fWhiteSpace = facets.whiteSpace;
whiteSpaceAnnotation = facets.whiteSpaceAnnotation;
fFacetsDefined |= FACET_WHITESPACE;
if ((fixedFacet & FACET_WHITESPACE) != 0)
fFixedFacet |= FACET_WHITESPACE;
}
}
// maxInclusive
if ((presentFacet & FACET_MAXINCLUSIVE) != 0) {
if ((allowedFacet & FACET_MAXINCLUSIVE) == 0) {
reportError("cos-applicable-facets", new Object[]{"maxInclusive", fTypeName});
} else {
maxInclusiveAnnotation = facets.maxInclusiveAnnotation;
try {
fMaxInclusive = fBase.getActualValue(facets.maxInclusive, context, tempInfo, true);
fFacetsDefined |= FACET_MAXINCLUSIVE;
if ((fixedFacet & FACET_MAXINCLUSIVE) != 0)
fFixedFacet |= FACET_MAXINCLUSIVE;
} catch (InvalidDatatypeValueException ide) {
reportError(ide.getKey(), ide.getArgs());
reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxInclusive,
"maxInclusive", fBase.getName()});
}
// check against fixed value in base
if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0) {
if (fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive) != 0)
reportError( "FixedFacetValue", new Object[]{"maxInclusive", fMaxInclusive, fBase.fMaxInclusive, fTypeName});
}
}
// maxInclusive from base
try {
fBase.validate(context, tempInfo);
} catch (InvalidDatatypeValueException ide) {
reportError(ide.getKey(), ide.getArgs());
reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxInclusive,
"maxInclusive", fBase.getName()});
}
}
}
// maxExclusive
boolean needCheckBase = true;
if ((presentFacet & FACET_MAXEXCLUSIVE) != 0) {
if ((allowedFacet & FACET_MAXEXCLUSIVE) == 0) {
reportError("cos-applicable-facets", new Object[]{"maxExclusive", fTypeName});
} else {
maxExclusiveAnnotation = facets.maxExclusiveAnnotation;
try {
fMaxExclusive = fBase.getActualValue(facets.maxExclusive, context, tempInfo, true);
fFacetsDefined |= FACET_MAXEXCLUSIVE;
if ((fixedFacet & FACET_MAXEXCLUSIVE) != 0)
fFixedFacet |= FACET_MAXEXCLUSIVE;
} catch (InvalidDatatypeValueException ide) {
reportError(ide.getKey(), ide.getArgs());
reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxExclusive,
"maxExclusive", fBase.getName()});
}
// check against fixed value in base
if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive);
if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"maxExclusive", facets.maxExclusive, fBase.fMaxExclusive, fTypeName});
}
if (result == 0) {
needCheckBase = false;
}
}
// maxExclusive from base
if (needCheckBase) {
try {
fBase.validate(context, tempInfo);
} catch (InvalidDatatypeValueException ide) {
reportError(ide.getKey(), ide.getArgs());
reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxExclusive,
"maxExclusive", fBase.getName()});
}
}
// If maxExclusive == base.maxExclusive, then we only need to check
// maxExclusive <= base.maxInclusive
else if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
if (fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxInclusive) > 0) {
reportError( "maxExclusive-valid-restriction.2", new Object[]{facets.maxExclusive, fBase.fMaxInclusive});
}
}
}
}
// minExclusive
needCheckBase = true;
if ((presentFacet & FACET_MINEXCLUSIVE) != 0) {
if ((allowedFacet & FACET_MINEXCLUSIVE) == 0) {
reportError("cos-applicable-facets", new Object[]{"minExclusive", fTypeName});
} else {
minExclusiveAnnotation = facets.minExclusiveAnnotation;
try {
fMinExclusive = fBase.getActualValue(facets.minExclusive, context, tempInfo, true);
fFacetsDefined |= FACET_MINEXCLUSIVE;
if ((fixedFacet & FACET_MINEXCLUSIVE) != 0)
fFixedFacet |= FACET_MINEXCLUSIVE;
} catch (InvalidDatatypeValueException ide) {
reportError(ide.getKey(), ide.getArgs());
reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minExclusive,
"minExclusive", fBase.getName()});
}
// check against fixed value in base
if (((fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive);
if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"minExclusive", facets.minExclusive, fBase.fMinExclusive, fTypeName});
}
if (result == 0) {
needCheckBase = false;
}
}
// minExclusive from base
if (needCheckBase) {
try {
fBase.validate(context, tempInfo);
} catch (InvalidDatatypeValueException ide) {
reportError(ide.getKey(), ide.getArgs());
reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minExclusive,
"minExclusive", fBase.getName()});
}
}
// If minExclusive == base.minExclusive, then we only need to check
// minExclusive >= base.minInclusive
else if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
if (fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinInclusive) < 0) {
reportError( "minExclusive-valid-restriction.3", new Object[]{facets.minExclusive, fBase.fMinInclusive});
}
}
}
}
// minInclusive
if ((presentFacet & FACET_MININCLUSIVE) != 0) {
if ((allowedFacet & FACET_MININCLUSIVE) == 0) {
reportError("cos-applicable-facets", new Object[]{"minInclusive", fTypeName});
} else {
minInclusiveAnnotation = facets.minInclusiveAnnotation;
try {
fMinInclusive = fBase.getActualValue(facets.minInclusive, context, tempInfo, true);
fFacetsDefined |= FACET_MININCLUSIVE;
if ((fixedFacet & FACET_MININCLUSIVE) != 0)
fFixedFacet |= FACET_MININCLUSIVE;
} catch (InvalidDatatypeValueException ide) {
reportError(ide.getKey(), ide.getArgs());
reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minInclusive,
"minInclusive", fBase.getName()});
}
// check against fixed value in base
if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0) {
if (fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive) != 0)
reportError( "FixedFacetValue", new Object[]{"minInclusive", facets.minInclusive, fBase.fMinInclusive, fTypeName});
}
}
// minInclusive from base
try {
fBase.validate(context, tempInfo);
} catch (InvalidDatatypeValueException ide) {
reportError(ide.getKey(), ide.getArgs());
reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minInclusive,
"minInclusive", fBase.getName()});
}
}
}
// totalDigits
if ((presentFacet & FACET_TOTALDIGITS) != 0) {
if ((allowedFacet & FACET_TOTALDIGITS) == 0) {
reportError("cos-applicable-facets", new Object[]{"totalDigits", fTypeName});
} else {
totalDigitsAnnotation = facets.totalDigitsAnnotation;
fTotalDigits = facets.totalDigits;
fFacetsDefined |= FACET_TOTALDIGITS;
if ((fixedFacet & FACET_TOTALDIGITS) != 0)
fFixedFacet |= FACET_TOTALDIGITS;
}
}
// fractionDigits
if ((presentFacet & FACET_FRACTIONDIGITS) != 0) {
if ((allowedFacet & FACET_FRACTIONDIGITS) == 0) {
reportError("cos-applicable-facets", new Object[]{"fractionDigits", fTypeName});
} else {
fFractionDigits = facets.fractionDigits;
fractionDigitsAnnotation = facets.fractionDigitsAnnotation;
fFacetsDefined |= FACET_FRACTIONDIGITS;
if ((fixedFacet & FACET_FRACTIONDIGITS) != 0)
fFixedFacet |= FACET_FRACTIONDIGITS;
}
}
// token type: internal use, so do less checking
if (patternType != SPECIAL_PATTERN_NONE) {
fPatternType = patternType;
}
// step 2: check facets against each other: length, bounds
if(fFacetsDefined != 0) {
// check 4.3.2.c1 must: minLength <= maxLength
if(((fFacetsDefined & FACET_MINLENGTH ) != 0 ) && ((fFacetsDefined & FACET_MAXLENGTH) != 0))
{
if(fMinLength > fMaxLength)
reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fMaxLength), fTypeName});
}
// check 4.3.8.c1 error: maxInclusive + maxExclusive
if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
reportError( "maxInclusive-maxExclusive", new Object[]{fMaxInclusive, fMaxExclusive, fTypeName});
}
// check 4.3.9.c1 error: minInclusive + minExclusive
if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
reportError("minInclusive-minExclusive", new Object[]{fMinInclusive, fMinExclusive, fTypeName});
}
// check 4.3.7.c1 must: minInclusive <= maxInclusive
if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinInclusive, fMaxInclusive);
if (result != -1 && result != 0)
reportError("minInclusive-less-than-equal-to-maxInclusive", new Object[]{fMinInclusive, fMaxInclusive, fTypeName});
}
// check 4.3.8.c2 must: minExclusive <= maxExclusive ??? minExclusive < maxExclusive
if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinExclusive, fMaxExclusive);
if (result != -1 && result != 0)
reportError( "minExclusive-less-than-equal-to-maxExclusive", new Object[]{fMinExclusive, fMaxExclusive, fTypeName});
}
// check 4.3.9.c2 must: minExclusive < maxInclusive
if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
if (fDVs[fValidationDV].compare(fMinExclusive, fMaxInclusive) != -1)
reportError( "minExclusive-less-than-maxInclusive", new Object[]{fMinExclusive, fMaxInclusive, fTypeName});
}
// check 4.3.10.c1 must: minInclusive < maxExclusive
if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
if (fDVs[fValidationDV].compare(fMinInclusive, fMaxExclusive) != -1)
reportError( "minInclusive-less-than-maxExclusive", new Object[]{fMinInclusive, fMaxExclusive, fTypeName});
}
// check 4.3.12.c1 must: fractionDigits <= totalDigits
if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) &&
((fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
if (fFractionDigits > fTotalDigits)
reportError( "fractionDigits-totalDigits", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fTotalDigits), fTypeName});
}
// step 3: check facets against base
// check 4.3.1.c1 error: length & (fBase.maxLength | fBase.minLength)
if((fFacetsDefined & FACET_LENGTH) != 0 ){
if ((fBase.fFacetsDefined & FACET_MINLENGTH) != 0 &&
fLength < fBase.fMinLength) {
// length, fBase.minLength and fBase.maxLength defined
reportError("length-minLength-maxLength.1.1", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fBase.fMinLength)});
}
if ((fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 &&
fLength > fBase.fMaxLength) {
// length and fBase.maxLength defined
reportError("length-minLength-maxLength.2.1", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fBase.fMaxLength)});
}
if ( (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) {
// check 4.3.1.c2 error: length != fBase.length
if ( fLength != fBase.fLength )
reportError( "length-valid-restriction", new Object[]{Integer.toString(fLength), Integer.toString(fBase.fLength), fTypeName});
}
}
// check 4.3.1.c1 error: fBase.length & (maxLength | minLength)
if((fBase.fFacetsDefined & FACET_LENGTH) != 0 || (fFacetsDefined & FACET_LENGTH) != 0){
if ((fFacetsDefined & FACET_MINLENGTH) != 0){
if (fBase.fLength < fMinLength) {
// fBase.length, minLength and maxLength defined
reportError("length-minLength-maxLength.1.1", new Object[]{fTypeName, Integer.toString(fBase.fLength), Integer.toString(fMinLength)});
}
if ((fBase.fFacetsDefined & FACET_MINLENGTH) == 0){
reportError("length-minLength-maxLength.1.2.a", new Object[]{fTypeName});
}
if (fMinLength != fBase.fMinLength){
reportError("length-minLength-maxLength.1.2.b", new Object[]{fTypeName, Integer.toString(fMinLength), Integer.toString(fBase.fMinLength)});
}
}
if ((fFacetsDefined & FACET_MAXLENGTH) != 0){
if (fBase.fLength > fMaxLength) {
// fBase.length, minLength and maxLength defined
reportError("length-minLength-maxLength.2.1", new Object[]{fTypeName, Integer.toString(fBase.fLength), Integer.toString(fMaxLength)});
}
if ((fBase.fFacetsDefined & FACET_MAXLENGTH) == 0){
reportError("length-minLength-maxLength.2.2.a", new Object[]{fTypeName});
}
if (fMaxLength != fBase.fMaxLength){
reportError("length-minLength-maxLength.2.2.b", new Object[]{fTypeName, Integer.toString(fMaxLength), Integer.toString(fBase.fBase.fMaxLength)});
}
}
}
// check 4.3.2.c1 must: minLength <= fBase.maxLength
if ( ((fFacetsDefined & FACET_MINLENGTH ) != 0 ) ) {
if ( (fBase.fFacetsDefined & FACET_MAXLENGTH ) != 0 ) {
if ( fMinLength > fBase.fMaxLength ) {
reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMaxLength), fTypeName});
}
}
else if ( (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) {
if ( (fBase.fFixedFacet & FACET_MINLENGTH) != 0 && fMinLength != fBase.fMinLength ) {
reportError( "FixedFacetValue", new Object[]{"minLength", Integer.toString(fMinLength), Integer.toString(fBase.fMinLength), fTypeName});
}
// check 4.3.2.c2 error: minLength < fBase.minLength
if ( fMinLength < fBase.fMinLength ) {
reportError( "minLength-valid-restriction", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMinLength), fTypeName});
}
}
}
// check 4.3.2.c1 must: maxLength < fBase.minLength
if ( ((fFacetsDefined & FACET_MAXLENGTH ) != 0 ) && ((fBase.fFacetsDefined & FACET_MINLENGTH ) != 0 )) {
if ( fMaxLength < fBase.fMinLength) {
reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fBase.fMinLength), Integer.toString(fMaxLength)});
}
}
// check 4.3.3.c1 error: maxLength > fBase.maxLength
if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
if ( (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ){
if(( (fBase.fFixedFacet & FACET_MAXLENGTH) != 0 )&& fMaxLength != fBase.fMaxLength ) {
reportError( "FixedFacetValue", new Object[]{"maxLength", Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength), fTypeName});
}
if ( fMaxLength > fBase.fMaxLength ) {
reportError( "maxLength-valid-restriction", new Object[]{Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength), fTypeName});
}
}
}
/* // check 4.3.7.c2 error:
// maxInclusive > fBase.maxInclusive
// maxInclusive >= fBase.maxExclusive
// maxInclusive < fBase.minInclusive
// maxInclusive <= fBase.minExclusive
if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive);
if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"maxInclusive", fMaxInclusive, fBase.fMaxInclusive, fTypeName});
}
if (result != -1 && result != 0) {
reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMaxInclusive, fTypeName});
}
}
if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxExclusive) != -1){
reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMaxExclusive, fTypeName});
}
if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinInclusive);
if (result != 1 && result != 0) {
reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMinInclusive, fTypeName});
}
}
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinExclusive ) != 1)
reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMinExclusive, fTypeName});
}
// check 4.3.8.c3 error:
// maxExclusive > fBase.maxExclusive
// maxExclusive > fBase.maxInclusive
// maxExclusive <= fBase.minInclusive
// maxExclusive <= fBase.minExclusive
if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) {
if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) {
result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive);
if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"maxExclusive", fMaxExclusive, fBase.fMaxExclusive, fTypeName});
}
if (result != -1 && result != 0) {
reportError( "maxExclusive-valid-restriction.1", new Object[]{fMaxExclusive, fBase.fMaxExclusive, fTypeName});
}
}
if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxInclusive);
if (result != -1 && result != 0) {
reportError( "maxExclusive-valid-restriction.2", new Object[]{fMaxExclusive, fBase.fMaxInclusive, fTypeName});
}
}
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinExclusive ) != 1)
reportError( "maxExclusive-valid-restriction.3", new Object[]{fMaxExclusive, fBase.fMinExclusive, fTypeName});
if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinInclusive) != 1)
reportError( "maxExclusive-valid-restriction.4", new Object[]{fMaxExclusive, fBase.fMinInclusive, fTypeName});
}
// check 4.3.9.c3 error:
// minExclusive < fBase.minExclusive
// minExclusive > fBase.maxInclusive
// minExclusive < fBase.minInclusive
// minExclusive >= fBase.maxExclusive
if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
result= fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive);
if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"minExclusive", fMinExclusive, fBase.fMinExclusive, fTypeName});
}
if (result != 1 && result != 0) {
reportError( "minExclusive-valid-restriction.1", new Object[]{fMinExclusive, fBase.fMinExclusive, fTypeName});
}
}
if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
result=fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxInclusive);
if (result != -1 && result != 0) {
reportError( "minExclusive-valid-restriction.2", new Object[]{fMinExclusive, fBase.fMaxInclusive, fTypeName});
}
}
if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinInclusive);
if (result != 1 && result != 0) {
reportError( "minExclusive-valid-restriction.3", new Object[]{fMinExclusive, fBase.fMinInclusive, fTypeName});
}
}
if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxExclusive) != -1)
reportError( "minExclusive-valid-restriction.4", new Object[]{fMinExclusive, fBase.fMaxExclusive, fTypeName});
}
// check 4.3.10.c2 error:
// minInclusive < fBase.minInclusive
// minInclusive > fBase.maxInclusive
// minInclusive <= fBase.minExclusive
// minInclusive >= fBase.maxExclusive
if (((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
result = fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive);
if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0 && result != 0) {
reportError( "FixedFacetValue", new Object[]{"minInclusive", fMinInclusive, fBase.fMinInclusive, fTypeName});
}
if (result != 1 && result != 0) {
reportError( "minInclusive-valid-restriction.1", new Object[]{fMinInclusive, fBase.fMinInclusive, fTypeName});
}
}
if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
result=fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxInclusive);
if (result != -1 && result != 0) {
reportError( "minInclusive-valid-restriction.2", new Object[]{fMinInclusive, fBase.fMaxInclusive, fTypeName});
}
}
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinExclusive ) != 1)
reportError( "minInclusive-valid-restriction.3", new Object[]{fMinInclusive, fBase.fMinExclusive, fTypeName});
if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxExclusive) != -1)
reportError( "minInclusive-valid-restriction.4", new Object[]{fMinInclusive, fBase.fMaxExclusive, fTypeName});
}
*/
// check 4.3.11.c1 error: totalDigits > fBase.totalDigits
if (((fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
if ((fBase.fFixedFacet & FACET_TOTALDIGITS) != 0 && fTotalDigits != fBase.fTotalDigits) {
reportError("FixedFacetValue", new Object[]{"totalDigits", Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits), fTypeName});
}
if (fTotalDigits > fBase.fTotalDigits) {
reportError( "totalDigits-valid-restriction", new Object[]{Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits), fTypeName});
}
}
}
// check 4.3.12.c1 must: fractionDigits <= base.totalDigits
if ((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) {
if ((fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0) {
if (fFractionDigits > fBase.fTotalDigits)
reportError( "fractionDigits-totalDigits", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fTotalDigits), fTypeName});
}
}
// check 4.3.12.c2 error: fractionDigits > fBase.fractionDigits
// check fixed value for fractionDigits
if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) {
if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) {
if ((fBase.fFixedFacet & FACET_FRACTIONDIGITS) != 0 && fFractionDigits != fBase.fFractionDigits) {
reportError("FixedFacetValue", new Object[]{"fractionDigits", Integer.toString(fFractionDigits), Integer.toString(fBase.fFractionDigits), fTypeName});
}
if (fFractionDigits > fBase.fFractionDigits) {
reportError( "fractionDigits-valid-restriction", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fBase.fFractionDigits), fTypeName});
}
}
}
// check 4.3.6.c1 error:
// (whiteSpace = preserve || whiteSpace = replace) && fBase.whiteSpace = collapese or
// whiteSpace = preserve && fBase.whiteSpace = replace
if ( (fFacetsDefined & FACET_WHITESPACE) != 0 && (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ){
if ( (fBase.fFixedFacet & FACET_WHITESPACE) != 0 && fWhiteSpace != fBase.fWhiteSpace ) {
reportError( "FixedFacetValue", new Object[]{"whiteSpace", whiteSpaceValue(fWhiteSpace), whiteSpaceValue(fBase.fWhiteSpace), fTypeName});
}
if ( fWhiteSpace == WS_PRESERVE && fBase.fWhiteSpace == WS_COLLAPSE ){
reportError( "whiteSpace-valid-restriction.1", new Object[]{fTypeName, "preserve"});
}
if ( fWhiteSpace == WS_REPLACE && fBase.fWhiteSpace == WS_COLLAPSE ){
reportError( "whiteSpace-valid-restriction.1", new Object[]{fTypeName, "replace"});
}
if ( fWhiteSpace == WS_PRESERVE && fBase.fWhiteSpace == WS_REPLACE ){
reportError( "whiteSpace-valid-restriction.2", new Object[]{fTypeName});
}
}
}//fFacetsDefined != null
// step 4: inherit other facets from base (including fTokeyType)
// inherit length
if ( (fFacetsDefined & FACET_LENGTH) == 0 && (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) {
fFacetsDefined |= FACET_LENGTH;
fLength = fBase.fLength;
lengthAnnotation = fBase.lengthAnnotation;
}
// inherit minLength
if ( (fFacetsDefined & FACET_MINLENGTH) == 0 && (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) {
fFacetsDefined |= FACET_MINLENGTH;
fMinLength = fBase.fMinLength;
minLengthAnnotation = fBase.minLengthAnnotation;
}
// inherit maxLength
if ((fFacetsDefined & FACET_MAXLENGTH) == 0 && (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
fFacetsDefined |= FACET_MAXLENGTH;
fMaxLength = fBase.fMaxLength;
maxLengthAnnotation = fBase.maxLengthAnnotation;
}
// inherit pattern
if ( (fBase.fFacetsDefined & FACET_PATTERN) != 0 ) {
if ((fFacetsDefined & FACET_PATTERN) == 0) {
fPattern = fBase.fPattern;
fPatternStr = fBase.fPatternStr;
fFacetsDefined |= FACET_PATTERN;
}
else {
for (int i = fBase.fPattern.size()-1; i >= 0; i--) {
fPattern.addElement(fBase.fPattern.elementAt(i));
fPatternStr.addElement(fBase.fPatternStr.elementAt(i));
}
if (fBase.patternAnnotations != null){
for (int i = fBase.patternAnnotations.getLength()-1;i>=0;i--){
patternAnnotations.add(fBase.patternAnnotations.item(i));
}
}
}
}
// inherit whiteSpace
if ( (fFacetsDefined & FACET_WHITESPACE) == 0 && (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ) {
fFacetsDefined |= FACET_WHITESPACE;
fWhiteSpace = fBase.fWhiteSpace;
whiteSpaceAnnotation = fBase.whiteSpaceAnnotation;
}
// inherit enumeration
if ((fFacetsDefined & FACET_ENUMERATION) == 0 && (fBase.fFacetsDefined & FACET_ENUMERATION) != 0) {
fFacetsDefined |= FACET_ENUMERATION;
fEnumeration = fBase.fEnumeration;
enumerationAnnotations = fBase.enumerationAnnotations;
}
// inherit maxExclusive
if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
!((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
fFacetsDefined |= FACET_MAXEXCLUSIVE;
fMaxExclusive = fBase.fMaxExclusive;
maxExclusiveAnnotation = fBase.maxExclusiveAnnotation;
}
// inherit maxInclusive
if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0) &&
!((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
fFacetsDefined |= FACET_MAXINCLUSIVE;
fMaxInclusive = fBase.fMaxInclusive;
maxInclusiveAnnotation = fBase.maxInclusiveAnnotation;
}
// inherit minExclusive
if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
!((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
fFacetsDefined |= FACET_MINEXCLUSIVE;
fMinExclusive = fBase.fMinExclusive;
minExclusiveAnnotation = fBase.minExclusiveAnnotation;
}
// inherit minExclusive
if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) &&
!((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
fFacetsDefined |= FACET_MININCLUSIVE;
fMinInclusive = fBase.fMinInclusive;
minInclusiveAnnotation = fBase.minInclusiveAnnotation;
}
// inherit totalDigits
if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0) &&
!((fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
fFacetsDefined |= FACET_TOTALDIGITS;
fTotalDigits = fBase.fTotalDigits;
totalDigitsAnnotation = fBase.totalDigitsAnnotation;
}
// inherit fractionDigits
if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0)
&& !((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) {
fFacetsDefined |= FACET_FRACTIONDIGITS;
fFractionDigits = fBase.fFractionDigits;
fractionDigitsAnnotation = fBase.fractionDigitsAnnotation;
}
//inherit tokeytype
if ((fPatternType == SPECIAL_PATTERN_NONE ) && (fBase.fPatternType != SPECIAL_PATTERN_NONE)) {
fPatternType = fBase.fPatternType ;
}
// step 5: mark fixed values
fFixedFacet |= fBase.fFixedFacet;
//step 6: setting fundamental facets
calcFundamentalFacets();
} //applyFacets()
/**
* validate a value, and return the compiled form
*/
public Object validate(String content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
if (context == null)
context = fEmptyContext;
if (validatedInfo == null)
validatedInfo = new ValidatedInfo();
else
validatedInfo.memberType = null;
// first normalize string value, and convert it to actual value
boolean needNormalize = context==null||context.needToNormalize();
Object ob = getActualValue(content, context, validatedInfo, needNormalize);
validate(context, validatedInfo);
return ob;
}
/**
* validate a value, and return the compiled form
*/
public ValidatedInfo validateWithInfo(String content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
if (context == null)
context = fEmptyContext;
if (validatedInfo == null)
validatedInfo = new ValidatedInfo();
else
validatedInfo.memberType = null;
// first normalize string value, and convert it to actual value
boolean needNormalize = context==null||context.needToNormalize();
getActualValue(content, context, validatedInfo, needNormalize);
validate(context, validatedInfo);
return validatedInfo;
}
/**
* validate a value, and return the compiled form
*/
public Object validate(Object content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
if (context == null)
context = fEmptyContext;
if (validatedInfo == null)
validatedInfo = new ValidatedInfo();
else
validatedInfo.memberType = null;
// first normalize string value, and convert it to actual value
boolean needNormalize = context==null||context.needToNormalize();
Object ob = getActualValue(content, context, validatedInfo, needNormalize);
validate(context, validatedInfo);
return ob;
}
/**
* validate an actual value against this DV
*
* @param context the validation context
* @param validatedInfo used to provide the actual value and member types
*/
public void validate(ValidationContext context, ValidatedInfo validatedInfo)
throws InvalidDatatypeValueException {
if (context == null)
context = fEmptyContext;
// then validate the actual value against the facets
if (context.needFacetChecking() &&
(fFacetsDefined != 0 && fFacetsDefined != FACET_WHITESPACE)) {
checkFacets(validatedInfo);
}
// now check extra rules: for ID/IDREF/ENTITY
if (context.needExtraChecking()) {
checkExtraRules(context, validatedInfo);
}
}
private void checkFacets(ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
Object ob = validatedInfo.actualValue;
String content = validatedInfo.normalizedValue;
short type = validatedInfo.actualValueType;
ShortList itemType = validatedInfo.itemValueTypes;
// For QName and NOTATION types, we don't check length facets
if (fValidationDV != DV_QNAME && fValidationDV != DV_NOTATION) {
int length = fDVs[fValidationDV].getDataLength(ob);
// maxLength
if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
if ( length > fMaxLength ) {
throw new InvalidDatatypeValueException("cvc-maxLength-valid",
new Object[]{content, Integer.toString(length), Integer.toString(fMaxLength), fTypeName});
}
}
//minLength
if ( (fFacetsDefined & FACET_MINLENGTH) != 0 ) {
if ( length < fMinLength ) {
throw new InvalidDatatypeValueException("cvc-minLength-valid",
new Object[]{content, Integer.toString(length), Integer.toString(fMinLength), fTypeName});
}
}
//length
if ( (fFacetsDefined & FACET_LENGTH) != 0 ) {
if ( length != fLength ) {
throw new InvalidDatatypeValueException("cvc-length-valid",
new Object[]{content, Integer.toString(length), Integer.toString(fLength), fTypeName});
}
}
}
//enumeration
if ( ((fFacetsDefined & FACET_ENUMERATION) != 0 ) ) {
boolean present = false;
final int enumSize = fEnumeration.size();
final short primitiveType1 = convertToPrimitiveKind(type);
for (int i = 0; i < enumSize; i++) {
final short primitiveType2 = convertToPrimitiveKind(fEnumerationType[i]);
if ((primitiveType1 == primitiveType2 ||
primitiveType1 == XSConstants.ANYSIMPLETYPE_DT && primitiveType2 == XSConstants.STRING_DT ||
primitiveType1 == XSConstants.STRING_DT && primitiveType2 == XSConstants.ANYSIMPLETYPE_DT)
&& fEnumeration.elementAt(i).equals(ob)) {
if (primitiveType1 == XSConstants.LIST_DT || primitiveType1 == XSConstants.LISTOFUNION_DT) {
ShortList enumItemType = fEnumerationItemType[i];
final int typeList1Length = itemType != null ? itemType.getLength() : 0;
final int typeList2Length = enumItemType != null ? enumItemType.getLength() : 0;
if (typeList1Length == typeList2Length) {
int j;
for (j = 0; j < typeList1Length; ++j) {
final short primitiveItem1 = convertToPrimitiveKind(itemType.item(j));
final short primitiveItem2 = convertToPrimitiveKind(enumItemType.item(j));
if (primitiveItem1 != primitiveItem2) {
if (primitiveItem1 == XSConstants.ANYSIMPLETYPE_DT && primitiveItem2 == XSConstants.STRING_DT ||
primitiveItem1 == XSConstants.STRING_DT && primitiveItem2 == XSConstants.ANYSIMPLETYPE_DT) {
continue;
}
break;
}
}
if (j == typeList1Length) {
present = true;
break;
}
}
}
else {
present = true;
break;
}
}
}
if(!present){
throw new InvalidDatatypeValueException("cvc-enumeration-valid",
new Object [] {content, fEnumeration.toString()});
}
}
//fractionDigits
if ((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) {
int scale = fDVs[fValidationDV].getFractionDigits(ob);
if (scale > fFractionDigits) {
throw new InvalidDatatypeValueException("cvc-fractionDigits-valid",
new Object[] {content, Integer.toString(scale), Integer.toString(fFractionDigits)});
}
}
//totalDigits
if ((fFacetsDefined & FACET_TOTALDIGITS)!=0) {
int totalDigits = fDVs[fValidationDV].getTotalDigits(ob);
if (totalDigits > fTotalDigits) {
throw new InvalidDatatypeValueException("cvc-totalDigits-valid",
new Object[] {content, Integer.toString(totalDigits), Integer.toString(fTotalDigits)});
}
}
int compare;
//maxinclusive
if ( (fFacetsDefined & FACET_MAXINCLUSIVE) != 0 ) {
compare = fDVs[fValidationDV].compare(ob, fMaxInclusive);
if (compare != -1 && compare != 0) {
throw new InvalidDatatypeValueException("cvc-maxInclusive-valid",
new Object[] {content, fMaxInclusive, fTypeName});
}
}
//maxExclusive
if ( (fFacetsDefined & FACET_MAXEXCLUSIVE) != 0 ) {
compare = fDVs[fValidationDV].compare(ob, fMaxExclusive );
if (compare != -1) {
throw new InvalidDatatypeValueException("cvc-maxExclusive-valid",
new Object[] {content, fMaxExclusive, fTypeName});
}
}
//minInclusive
if ( (fFacetsDefined & FACET_MININCLUSIVE) != 0 ) {
compare = fDVs[fValidationDV].compare(ob, fMinInclusive);
if (compare != 1 && compare != 0) {
throw new InvalidDatatypeValueException("cvc-minInclusive-valid",
new Object[] {content, fMinInclusive, fTypeName});
}
}
//minExclusive
if ( (fFacetsDefined & FACET_MINEXCLUSIVE) != 0 ) {
compare = fDVs[fValidationDV].compare(ob, fMinExclusive);
if (compare != 1) {
throw new InvalidDatatypeValueException("cvc-minExclusive-valid",
new Object[] {content, fMinExclusive, fTypeName});
}
}
}
private void checkExtraRules(ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
Object ob = validatedInfo.actualValue;
if (fVariety == VARIETY_ATOMIC) {
fDVs[fValidationDV].checkExtraRules(ob, context);
} else if (fVariety == VARIETY_LIST) {
ListDV.ListData values = (ListDV.ListData)ob;
int len = values.getLength();
if (fItemType.fVariety == VARIETY_UNION) {
XSSimpleTypeDecl[] memberTypes = (XSSimpleTypeDecl[])validatedInfo.memberTypes;
XSSimpleType memberType = validatedInfo.memberType;
for (int i = len-1; i >= 0; i--) {
validatedInfo.actualValue = values.item(i);
validatedInfo.memberType = memberTypes[i];
fItemType.checkExtraRules(context, validatedInfo);
}
validatedInfo.memberType = memberType;
} else { // (fVariety == VARIETY_ATOMIC)
for (int i = len-1; i >= 0; i--) {
validatedInfo.actualValue = values.item(i);
fItemType.checkExtraRules(context, validatedInfo);
}
}
validatedInfo.actualValue = values;
} else { // (fVariety == VARIETY_UNION)
((XSSimpleTypeDecl)validatedInfo.memberType).checkExtraRules(context, validatedInfo);
}
}// checkExtraRules()
//we can still return object for internal use.
private Object getActualValue(Object content, ValidationContext context,
ValidatedInfo validatedInfo, boolean needNormalize)
throws InvalidDatatypeValueException{
String nvalue;
if (needNormalize) {
nvalue = normalize(content, fWhiteSpace);
} else {
nvalue = content.toString();
}
if ( (fFacetsDefined & FACET_PATTERN ) != 0 ) {
RegularExpression regex;
for (int idx = fPattern.size()-1; idx >= 0; idx--) {
regex = (RegularExpression)fPattern.elementAt(idx);
if (!regex.matches(nvalue)){
throw new InvalidDatatypeValueException("cvc-pattern-valid",
new Object[]{content,
fPatternStr.elementAt(idx),
fTypeName});
}
}
}
if (fVariety == VARIETY_ATOMIC) {
// validate special kinds of token, in place of old pattern matching
if (fPatternType != SPECIAL_PATTERN_NONE) {
boolean seenErr = false;
if (fPatternType == SPECIAL_PATTERN_NMTOKEN) {
// PATTERN "\\c+"
seenErr = !XMLChar.isValidNmtoken(nvalue);
}
else if (fPatternType == SPECIAL_PATTERN_NAME) {
// PATTERN "\\i\\c*"
seenErr = !XMLChar.isValidName(nvalue);
}
else if (fPatternType == SPECIAL_PATTERN_NCNAME) {
// PATTERN "[\\i-[:]][\\c-[:]]*"
seenErr = !XMLChar.isValidNCName(nvalue);
}
if (seenErr) {
throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1",
new Object[]{nvalue, SPECIAL_PATTERN_STRING[fPatternType]});
}
}
validatedInfo.normalizedValue = nvalue;
Object avalue = fDVs[fValidationDV].getActualValue(nvalue, context);
validatedInfo.actualValue = avalue;
validatedInfo.actualValueType = fBuiltInKind;
return avalue;
} else if (fVariety == VARIETY_LIST) {
StringTokenizer parsedList = new StringTokenizer(nvalue, " ");
int countOfTokens = parsedList.countTokens() ;
Object[] avalue = new Object[countOfTokens];
boolean isUnion = fItemType.getVariety() == VARIETY_UNION;
short[] itemTypes = new short[isUnion ? countOfTokens : 1];
if (!isUnion)
itemTypes[0] = fItemType.fBuiltInKind;
XSSimpleTypeDecl[] memberTypes = new XSSimpleTypeDecl[countOfTokens];
for(int i = 0 ; i < countOfTokens ; i ++){
// we can't call fItemType.validate(), otherwise checkExtraRules()
// will be called twice: once in fItemType.validate, once in
// validate method of this type.
// so we take two steps to get the actual value:
// 1. fItemType.getActualValue()
// 2. fItemType.chekcFacets()
avalue[i] = fItemType.getActualValue(parsedList.nextToken(), context, validatedInfo, false);
if (context.needFacetChecking() &&
(fItemType.fFacetsDefined != 0 && fItemType.fFacetsDefined != FACET_WHITESPACE)) {
fItemType.checkFacets(validatedInfo);
}
memberTypes[i] = (XSSimpleTypeDecl)validatedInfo.memberType;
if (isUnion)
itemTypes[i] = memberTypes[i].fBuiltInKind;
}
ListDV.ListData v = new ListDV.ListData(avalue);
validatedInfo.actualValue = v;
validatedInfo.actualValueType = isUnion ? XSConstants.LISTOFUNION_DT : XSConstants.LIST_DT;
validatedInfo.memberType = null;
validatedInfo.memberTypes = memberTypes;
validatedInfo.itemValueTypes = new ShortListImpl(itemTypes, itemTypes.length);
validatedInfo.normalizedValue = nvalue;
return v;
} else { // (fVariety == VARIETY_UNION)
for(int i = 0 ; i < fMemberTypes.length; i++) {
try {
// we can't call fMemberType[i].validate(), otherwise checkExtraRules()
// will be called twice: once in fMemberType[i].validate, once in
// validate method of this type.
// so we take two steps to get the actual value:
// 1. fMemberType[i].getActualValue()
// 2. fMemberType[i].chekcFacets()
Object aValue = fMemberTypes[i].getActualValue(content, context, validatedInfo, true);
if (context.needFacetChecking() &&
(fMemberTypes[i].fFacetsDefined != 0 && fMemberTypes[i].fFacetsDefined != FACET_WHITESPACE)) {
fMemberTypes[i].checkFacets(validatedInfo);
}
validatedInfo.memberType = fMemberTypes[i];
return aValue;
} catch(InvalidDatatypeValueException invalidValue) {
}
}
StringBuffer typesBuffer = new StringBuffer();
XSSimpleTypeDecl decl;
for(int i = 0;i < fMemberTypes.length; i++) {
if(i != 0)
typesBuffer.append(" | ");
decl = fMemberTypes[i];
if(decl.fTargetNamespace != null) {
typesBuffer.append('{');
typesBuffer.append(decl.fTargetNamespace);
typesBuffer.append('}');
}
typesBuffer.append(decl.fTypeName);
if(decl.fEnumeration != null) {
Vector v = decl.fEnumeration;
typesBuffer.append(" : [");
for(int j = 0;j < v.size(); j++) {
if(j != 0)
typesBuffer.append(',');
typesBuffer.append(v.elementAt(j));
}
typesBuffer.append(']');
}
}
throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.3",
new Object[]{content, fTypeName, typesBuffer.toString()});
}
}//getActualValue()
public boolean isEqual(Object value1, Object value2) {
if (value1 == null) {
return false;
}
return value1.equals(value2);
}//isEqual()
// determine whether the two values are identical
public boolean isIdentical (Object value1, Object value2) {
if (value1 == null) {
return false;
}
return fDVs[fValidationDV].isIdentical(value1, value2);
}//isIdentical()
// normalize the string according to the whiteSpace facet
public static String normalize(String content, short ws) {
int len = content == null ? 0 : content.length();
if (len == 0 || ws == WS_PRESERVE)
return content;
StringBuffer sb = new StringBuffer();
if (ws == WS_REPLACE) {
char ch;
// when it's replace, just replace #x9, #xa, #xd by #x20
for (int i = 0; i < len; i++) {
ch = content.charAt(i);
if (ch != 0x9 && ch != 0xa && ch != 0xd)
sb.append(ch);
else
sb.append((char)0x20);
}
} else {
char ch;
int i;
boolean isLeading = true;
// when it's collapse
for (i = 0; i < len; i++) {
ch = content.charAt(i);
// append real characters, so we passed leading ws
if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) {
sb.append(ch);
isLeading = false;
}
else {
// for whitespaces, we skip all following ws
for (; i < len-1; i++) {
ch = content.charAt(i+1);
if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20)
break;
}
// if it's not a leading or tailing ws, then append a space
if (i < len - 1 && !isLeading)
sb.append((char)0x20);
}
}
}
return sb.toString();
}
// normalize the string according to the whiteSpace facet
protected String normalize(Object content, short ws) {
if (content == null)
return null;
// If pattern is not defined, we can skip some of the normalization.
// Otherwise we have to normalize the data for correct result of
// pattern validation.
if ( (fFacetsDefined & FACET_PATTERN ) == 0 ) {
short norm_type = fDVNormalizeType[fValidationDV];
if (norm_type == NORMALIZE_NONE) {
return content.toString();
}
else if (norm_type == NORMALIZE_TRIM) {
return content.toString().trim();
}
}
if (!(content instanceof StringBuffer)) {
String strContent = content.toString();
return normalize(strContent, ws);
}
StringBuffer sb = (StringBuffer)content;
int len = sb.length();
if (len == 0)
return "";
if (ws == WS_PRESERVE)
return sb.toString();
if (ws == WS_REPLACE) {
char ch;
// when it's replace, just replace #x9, #xa, #xd by #x20
for (int i = 0; i < len; i++) {
ch = sb.charAt(i);
if (ch == 0x9 || ch == 0xa || ch == 0xd)
sb.setCharAt(i, (char)0x20);
}
} else {
char ch;
int i, j = 0;
boolean isLeading = true;
// when it's collapse
for (i = 0; i < len; i++) {
ch = sb.charAt(i);
// append real characters, so we passed leading ws
if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) {
sb.setCharAt(j++, ch);
isLeading = false;
}
else {
// for whitespaces, we skip all following ws
for (; i < len-1; i++) {
ch = sb.charAt(i+1);
if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20)
break;
}
// if it's not a leading or tailing ws, then append a space
if (i < len - 1 && !isLeading)
sb.setCharAt(j++, (char)0x20);
}
}
sb.setLength(j);
}
return sb.toString();
}
void reportError(String key, Object[] args) throws InvalidDatatypeFacetException {
throw new InvalidDatatypeFacetException(key, args);
}
private String whiteSpaceValue(short ws){
return WS_FACET_STRING[ws];
}
/**
* Fundamental Facet: ordered.
*/
public short getOrdered() {
return fOrdered;
}
/**
* Fundamental Facet: bounded.
*/
public boolean getBounded(){
return fBounded;
}
/**
* Fundamental Facet: cardinality.
*/
public boolean getFinite(){
return fFinite;
}
/**
* Fundamental Facet: numeric.
*/
public boolean getNumeric(){
return fNumeric;
}
/**
* Convenience method. [Facets]: check whether a facet is defined on this
* type.
* @param facetName The name of the facet.
* @return True if the facet is defined, false otherwise.
*/
public boolean isDefinedFacet(short facetName) {
if ((fFacetsDefined & facetName) != 0)
return true;
if (fPatternType != SPECIAL_PATTERN_NONE)
return facetName == FACET_PATTERN;
if (fValidationDV == DV_INTEGER)
return facetName == FACET_PATTERN || facetName == FACET_FRACTIONDIGITS;
return false;
}
/**
* [facets]: all facets defined on this type. The value is a bit
* combination of FACET_XXX constants of all defined facets.
*/
public short getDefinedFacets() {
if (fPatternType != SPECIAL_PATTERN_NONE)
return (short)(fFacetsDefined | FACET_PATTERN);
if (fValidationDV == DV_INTEGER)
return (short)(fFacetsDefined | FACET_PATTERN | FACET_FRACTIONDIGITS);
return fFacetsDefined;
}
/**
* Convenience method. [Facets]: check whether a facet is defined and
* fixed on this type.
* @param facetName The name of the facet.
* @return True if the facet is fixed, false otherwise.
*/
public boolean isFixedFacet(short facetName) {
if ((fFixedFacet & facetName) != 0)
return true;
if (fValidationDV == DV_INTEGER)
return facetName == FACET_FRACTIONDIGITS;
return false;
}
/**
* [facets]: all defined facets for this type which are fixed.
*/
public short getFixedFacets() {
if (fValidationDV == DV_INTEGER)
return (short)(fFixedFacet | FACET_FRACTIONDIGITS);
return fFixedFacet;
}
/**
* Convenience method. Returns a value of a single constraining facet for
* this simple type definition. This method must not be used to retrieve
* values for <code>enumeration</code> and <code>pattern</code> facets.
* @param facetName The name of the facet, i.e.
* <code>FACET_LENGTH, FACET_TOTALDIGITS </code> (see
* <code>XSConstants</code>). To retrieve the value for a pattern or
* an enumeration, see <code>enumeration</code> and
* <code>pattern</code>.
* @return A value of the facet specified in <code>facetName</code> for
* this simple type definition or <code>null</code>.
*/
public String getLexicalFacetValue(short facetName) {
switch (facetName) {
case FACET_LENGTH:
return (fLength == -1)?null:Integer.toString(fLength);
case FACET_MINLENGTH:
return (fMinLength == -1)?null:Integer.toString(fMinLength);
case FACET_MAXLENGTH:
return (fMaxLength == -1)?null:Integer.toString(fMaxLength);
case FACET_WHITESPACE:
return WS_FACET_STRING[fWhiteSpace];
case FACET_MAXINCLUSIVE:
return (fMaxInclusive == null)?null:fMaxInclusive.toString();
case FACET_MAXEXCLUSIVE:
return (fMaxExclusive == null)?null:fMaxExclusive.toString();
case FACET_MINEXCLUSIVE:
return (fMinExclusive == null)?null:fMinExclusive.toString();
case FACET_MININCLUSIVE:
return (fMinInclusive == null)?null:fMinInclusive.toString();
case FACET_TOTALDIGITS:
if (fValidationDV == DV_INTEGER)
return "0";
return (fTotalDigits == -1)?null:Integer.toString(fTotalDigits);
case FACET_FRACTIONDIGITS:
return (fFractionDigits == -1)?null:Integer.toString(fFractionDigits);
}
return null;
}
/**
* A list of enumeration values if it exists, otherwise an empty
* <code>StringList</code>.
*/
public StringList getLexicalEnumeration() {
if (fLexicalEnumeration == null){
if (fEnumeration == null)
return StringListImpl.EMPTY_LIST;
int size = fEnumeration.size();
String[] strs = new String[size];
for (int i = 0; i < size; i++)
strs[i] = fEnumeration.elementAt(i).toString();
fLexicalEnumeration = new StringListImpl(strs, size);
}
return fLexicalEnumeration;
}
/**
* A list of actual enumeration values if it exists, otherwise an empty
* <code>ObjectList</code>.
*/
public ObjectList getActualEnumeration() {
if (fActualEnumeration == null) {
fActualEnumeration = new ObjectList () {
public int getLength() {
return (fEnumeration != null) ? fEnumeration.size() : 0;
}
public boolean contains(Object item) {
return (fEnumeration != null && fEnumeration.contains(item));
}
public Object item(int index) {
if (index < 0 || index >= getLength()) {
return null;
}
return fEnumeration.elementAt(index);
}
};
}
return fActualEnumeration;
}
/**
* A list of enumeration type values (as a list of ShortList objects) if it exists, otherwise returns
* null
*/
public ObjectList getEnumerationItemTypeList() {
if (fEnumerationItemTypeList == null) {
if(fEnumerationItemType == null)
return null;
fEnumerationItemTypeList = new ObjectList () {
public int getLength() {
return (fEnumerationItemType != null) ? fEnumerationItemType.length : 0;
}
public boolean contains(Object item) {
if(fEnumerationItemType == null || !(item instanceof ShortList))
return false;
for(int i = 0;i < fEnumerationItemType.length; i++)
if(fEnumerationItemType[i] == item)
return true;
return false;
}
public Object item(int index) {
if (index < 0 || index >= getLength()) {
return null;
}
return fEnumerationItemType[index];
}
};
}
return fEnumerationItemTypeList;
}
public ShortList getEnumerationTypeList() {
if (fEnumerationTypeList == null) {
if (fEnumerationType == null)
return null;
fEnumerationTypeList = new ShortListImpl (fEnumerationType, fEnumerationType.length);
}
return fEnumerationTypeList;
}
/**
* A list of pattern values if it exists, otherwise an empty
* <code>StringList</code>.
*/
public StringList getLexicalPattern() {
if (fPatternType == SPECIAL_PATTERN_NONE && fValidationDV != DV_INTEGER && fPatternStr == null)
return StringListImpl.EMPTY_LIST;
if (fLexicalPattern == null){
int size = fPatternStr == null ? 0 : fPatternStr.size();
String[] strs;
if (fPatternType == SPECIAL_PATTERN_NMTOKEN) {
strs = new String[size+1];
strs[size] = "\\c+";
}
else if (fPatternType == SPECIAL_PATTERN_NAME) {
strs = new String[size+1];
strs[size] = "\\i\\c*";
}
else if (fPatternType == SPECIAL_PATTERN_NCNAME) {
strs = new String[size+2];
strs[size] = "\\i\\c*";
strs[size+1] = "[\\i-[:]][\\c-[:]]*";
}
else if (fValidationDV == DV_INTEGER) {
strs = new String[size+1];
strs[size] = "[\\-+]?[0-9]+";
}
else {
strs = new String[size];
}
for (int i = 0; i < size; i++)
strs[i] = (String)fPatternStr.elementAt(i);
fLexicalPattern = new StringListImpl(strs, strs.length);
}
return fLexicalPattern;
}
/**
* [annotations]: a set of annotations for this simple type component if
* it exists, otherwise an empty <code>XSObjectList</code>.
*/
public XSObjectList getAnnotations() {
return (fAnnotations != null) ? fAnnotations : XSObjectListImpl.EMPTY_LIST;
}
private void calcFundamentalFacets() {
setOrdered();
setNumeric();
setBounded();
setCardinality();
}
private void setOrdered(){
// When {variety} is atomic, {value} is inherited from {value} of {base type definition}. For all "primitive" types {value} is as specified in the table in Fundamental Facets (C.1).
if(fVariety == VARIETY_ATOMIC){
this.fOrdered = fBase.fOrdered;
}
// When {variety} is list, {value} is false.
else if(fVariety == VARIETY_LIST){
this.fOrdered = ORDERED_FALSE;
}
// When {variety} is union, the {value} is partial unless one of the following:
// 1. If every member of {member type definitions} is derived from a common ancestor other than the simple ur-type, then {value} is the same as that ancestor's ordered facet.
// 2. If every member of {member type definitions} has a {value} of false for the ordered facet, then {value} is false.
else if(fVariety == VARIETY_UNION){
int length = fMemberTypes.length;
// REVISIT: is the length possible to be 0?
if (length == 0) {
this.fOrdered = ORDERED_PARTIAL;
return;
}
// we need to process the first member type before entering the loop
short ancestorId = getPrimitiveDV(fMemberTypes[0].fValidationDV);
boolean commonAnc = ancestorId != DV_ANYSIMPLETYPE;
boolean allFalse = fMemberTypes[0].fOrdered == ORDERED_FALSE;
// for the other member types, check whether the value is false
// and whether they have the same ancestor as the first one
for (int i = 1; i < fMemberTypes.length && (commonAnc || allFalse); i++) {
if (commonAnc)
commonAnc = ancestorId == getPrimitiveDV(fMemberTypes[i].fValidationDV);
if (allFalse)
allFalse = fMemberTypes[i].fOrdered == ORDERED_FALSE;
}
if (commonAnc) {
// REVISIT: all member types should have the same ordered value
// just use the first one. Can we assume this?
this.fOrdered = fMemberTypes[0].fOrdered;
} else if (allFalse) {
this.fOrdered = ORDERED_FALSE;
} else {
this.fOrdered = ORDERED_PARTIAL;
}
}
}//setOrdered
private void setNumeric(){
if(fVariety == VARIETY_ATOMIC){
this.fNumeric = fBase.fNumeric;
}
else if(fVariety == VARIETY_LIST){
this.fNumeric = false;
}
else if(fVariety == VARIETY_UNION){
XSSimpleType[] memberTypes = fMemberTypes;
for(int i = 0 ; i < memberTypes.length ; i++){
if(!memberTypes[i].getNumeric() ){
this.fNumeric = false;
return;
}
}
this.fNumeric = true;
}
}//setNumeric
private void setBounded(){
if(fVariety == VARIETY_ATOMIC){
if( (((this.fFacetsDefined & FACET_MININCLUSIVE) != 0) || ((this.fFacetsDefined & FACET_MINEXCLUSIVE) != 0))
&& (((this.fFacetsDefined & FACET_MAXINCLUSIVE) != 0) || ((this.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) ){
this.fBounded = true;
}
else{
this.fBounded = false;
}
}
else if(fVariety == VARIETY_LIST){
if( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ( ((this.fFacetsDefined & FACET_MINLENGTH) != 0 )
&& ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )) ){
this.fBounded = true;
}
else{
this.fBounded = false;
}
}
else if(fVariety == VARIETY_UNION){
XSSimpleTypeDecl [] memberTypes = this.fMemberTypes;
short ancestorId = 0 ;
if(memberTypes.length > 0){
ancestorId = getPrimitiveDV(memberTypes[0].fValidationDV);
}
for(int i = 0 ; i < memberTypes.length ; i++){
if(!memberTypes[i].getBounded() || (ancestorId != getPrimitiveDV(memberTypes[i].fValidationDV)) ){
this.fBounded = false;
return;
}
}
this.fBounded = true;
}
}//setBounded
private boolean specialCardinalityCheck(){
if( (fBase.fValidationDV == XSSimpleTypeDecl.DV_DATE) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GYEARMONTH)
|| (fBase.fValidationDV == XSSimpleTypeDecl.DV_GYEAR) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GMONTHDAY)
|| (fBase.fValidationDV == XSSimpleTypeDecl.DV_GDAY) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GMONTH) ){
return true;
}
return false;
} //specialCardinalityCheck()
private void setCardinality(){
if(fVariety == VARIETY_ATOMIC){
if(fBase.fFinite){
this.fFinite = true;
}
else {// (!fBase.fFinite)
if ( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )
|| ((this.fFacetsDefined & FACET_TOTALDIGITS) != 0 ) ){
this.fFinite = true;
}
else if( (((this.fFacetsDefined & FACET_MININCLUSIVE) != 0 ) || ((this.fFacetsDefined & FACET_MINEXCLUSIVE) != 0 ))
&& (((this.fFacetsDefined & FACET_MAXINCLUSIVE) != 0 ) || ((this.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0 )) ){
if( ((this.fFacetsDefined & FACET_FRACTIONDIGITS) != 0 ) || specialCardinalityCheck()){
this.fFinite = true;
}
else{
this.fFinite = false;
}
}
else{
this.fFinite = false;
}
}
}
else if(fVariety == VARIETY_LIST){
if( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ( ((this.fFacetsDefined & FACET_MINLENGTH) != 0 )
&& ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )) ){
this.fFinite = true;
}
else{
this.fFinite = false;
}
}
else if(fVariety == VARIETY_UNION){
XSSimpleType [] memberTypes = fMemberTypes;
for(int i = 0 ; i < memberTypes.length ; i++){
if(!(memberTypes[i].getFinite()) ){
this.fFinite = false;
return;
}
}
this.fFinite = true;
}
}//setCardinality
private short getPrimitiveDV(short validationDV){
if (validationDV == DV_ID || validationDV == DV_IDREF || validationDV == DV_ENTITY){
return DV_STRING;
}
else if (validationDV == DV_INTEGER) {
return DV_DECIMAL;
}
else if (Constants.SCHEMA_1_1_SUPPORT && (validationDV == DV_YEARMONTHDURATION || validationDV == DV_DAYTIMEDURATION)) {
return DV_DURATION;
}
else {
return validationDV;
}
}//getPrimitiveDV()
public boolean derivedFromType(XSTypeDefinition ancestor, short derivation) {
// REVISIT: implement according to derivation
// ancestor is null, retur false
if (ancestor == null)
return false;
// ancestor is anyType, return true
// anyType is the only type whose base type is itself
if (ancestor.getBaseType() == ancestor)
return true;
// recursively get base, and compare it with ancestor
XSTypeDefinition type = this;
while (type != ancestor && // compare with ancestor
type != fAnySimpleType) { // reached anySimpleType
type = type.getBaseType();
}
return type == ancestor;
}
public boolean derivedFrom(String ancestorNS, String ancestorName, short derivation) {
// REVISIT: implement according to derivation
// ancestor is null, retur false
if (ancestorName == null)
return false;
// ancestor is anyType, return true
if (URI_SCHEMAFORSCHEMA.equals(ancestorNS) &&
ANY_TYPE.equals(ancestorName)) {
return true;
}
// recursively get base, and compare it with ancestor
XSTypeDefinition type = this;
while (!(ancestorName.equals(type.getName()) &&
((ancestorNS == null && type.getNamespace() == null) ||
(ancestorNS != null && ancestorNS.equals(type.getNamespace())))) && // compare with ancestor
type != fAnySimpleType) { // reached anySimpleType
type = (XSTypeDefinition)type.getBaseType();
}
return type != fAnySimpleType;
}
/**
* Checks if a type is derived from another by restriction, given the name
* and namespace. See:
* http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom
*
* @param ancestorNS
* The namspace of the ancestor type declaration
* @param ancestorName
* The name of the ancestor type declaration
* @param derivationMethod
* The derivation method
*
* @return boolean True if the ancestor type is derived from the reference type by the specifiied derivation method.
*/
public boolean isDOMDerivedFrom(String ancestorNS, String ancestorName, int derivationMethod) {
// ancestor is null, return false
if (ancestorName == null)
return false;
// ancestor is anyType, return true
if (SchemaSymbols.URI_SCHEMAFORSCHEMA.equals(ancestorNS)
&& SchemaSymbols.ATTVAL_ANYTYPE.equals(ancestorName)
&& (((derivationMethod & DERIVATION_RESTRICTION) != 0)
|| (derivationMethod == DERIVATION_ANY))) {
return true;
}
// restriction
if ((derivationMethod & DERIVATION_RESTRICTION) != 0) {
if (isDerivedByRestriction(ancestorNS, ancestorName, this)) {
return true;
}
}
// list
if ((derivationMethod & DERIVATION_LIST) != 0) {
if (isDerivedByList(ancestorNS, ancestorName, this)) {
return true;
}
}
// union
if ((derivationMethod & DERIVATION_UNION) != 0) {
if (isDerivedByUnion(ancestorNS, ancestorName, this)) {
return true;
}
}
// extension
if (((derivationMethod & DERIVATION_EXTENSION) != 0)
&& (((derivationMethod & DERIVATION_RESTRICTION) == 0)
&& ((derivationMethod & DERIVATION_LIST) == 0)
&& ((derivationMethod & DERIVATION_UNION) == 0))) {
return false;
}
// If the value of the parameter is 0 i.e. no bit (corresponding to
// restriction, list, extension or union) is set to 1 for the
// derivationMethod parameter.
if (((derivationMethod & DERIVATION_EXTENSION) == 0)
&& (((derivationMethod & DERIVATION_RESTRICTION) == 0)
&& ((derivationMethod & DERIVATION_LIST) == 0)
&& ((derivationMethod & DERIVATION_UNION) == 0))) {
return isDerivedByAny(ancestorNS, ancestorName, this);
}
return false;
}
/**
* Checks if a type is derived from another by any combination of restriction, list ir union. See:
* http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom
*
* @param ancestorNS
* The namspace of the ancestor type declaration
* @param ancestorName
* The name of the ancestor type declaration
* @param type
* The reference type definition
*
* @return boolean True if the type is derived by restriciton for the reference type
*/
private boolean isDerivedByAny(String ancestorNS, String ancestorName,
XSTypeDefinition type) {
boolean derivedFrom = false;
XSTypeDefinition oldType = null;
// for each base, item or member type
while (type != null && type != oldType) {
// If the ancestor type is reached or is the same as this type.
if ((ancestorName.equals(type.getName()))
&& ((ancestorNS == null && type.getNamespace() == null)
|| (ancestorNS != null && ancestorNS.equals(type.getNamespace())))) {
derivedFrom = true;
break;
}
// check if derived by restriction or list or union
if (isDerivedByRestriction(ancestorNS, ancestorName, type)) {
return true;
} else if (isDerivedByList(ancestorNS, ancestorName, type)) {
return true;
} else if (isDerivedByUnion(ancestorNS, ancestorName, type)) {
return true;
}
oldType = type;
// get the base, item or member type depending on the variety
if (((XSSimpleTypeDecl) type).getVariety() == VARIETY_ABSENT
|| ((XSSimpleTypeDecl) type).getVariety() == VARIETY_ATOMIC) {
type = type.getBaseType();
} else if (((XSSimpleTypeDecl) type).getVariety() == VARIETY_UNION) {
for (int i = 0; i < ((XSSimpleTypeDecl) type).getMemberTypes().getLength(); i++) {
return isDerivedByAny(ancestorNS, ancestorName,
(XSTypeDefinition) ((XSSimpleTypeDecl) type)
.getMemberTypes().item(i));
}
} else if (((XSSimpleTypeDecl) type).getVariety() == VARIETY_LIST) {
type = ((XSSimpleTypeDecl) type).getItemType();
}
}
return derivedFrom;
}
/**
* DOM Level 3
* Checks if a type is derived from another by restriction. See:
* http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom
*
* @param ancestorNS
* The namspace of the ancestor type declaration
* @param ancestorName
* The name of the ancestor type declaration
* @param type
* The reference type definition
*
* @return boolean True if the type is derived by restriciton for the
* reference type
*/
private boolean isDerivedByRestriction (String ancestorNS, String ancestorName, XSTypeDefinition type) {
XSTypeDefinition oldType = null;
while (type != null && type != oldType) {
if ((ancestorName.equals(type.getName()))
&& ((ancestorNS != null && ancestorNS.equals(type.getNamespace()))
|| (type.getNamespace() == null && ancestorNS == null))) {
return true;
}
oldType = type;
type = type.getBaseType();
}
return false;
}
/**
* Checks if a type is derived from another by list. See:
* http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom
*
* @param ancestorNS
* The namspace of the ancestor type declaration
* @param ancestorName
* The name of the ancestor type declaration
* @param type
* The reference type definition
*
* @return boolean True if the type is derived by list for the reference type
*/
private boolean isDerivedByList (String ancestorNS, String ancestorName, XSTypeDefinition type) {
// If the variety is union
if (type !=null && ((XSSimpleTypeDefinition)type).getVariety() == VARIETY_LIST) {
// get the {item type}
XSTypeDefinition itemType = ((XSSimpleTypeDefinition)type).getItemType();
// T2 is the {item type definition}
if (itemType != null) {
// T2 is derived from the other type definition by DERIVATION_RESTRICTION
if (isDerivedByRestriction(ancestorNS, ancestorName, itemType)) {
return true;
}
}
}
return false;
}
/**
* Checks if a type is derived from another by union. See:
* http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom
*
* @param ancestorNS
* The namspace of the ancestor type declaration
* @param ancestorName
* The name of the ancestor type declaration
* @param type
* The reference type definition
*
* @return boolean True if the type is derived by union for the reference type
*/
private boolean isDerivedByUnion (String ancestorNS, String ancestorName, XSTypeDefinition type) {
// If the variety is union
if (type !=null && ((XSSimpleTypeDefinition)type).getVariety() == VARIETY_UNION) {
// get member types
XSObjectList memberTypes = ((XSSimpleTypeDefinition)type).getMemberTypes();
for (int i = 0; i < memberTypes.getLength(); i++) {
// One of the {member type definitions} is T2.
if (memberTypes.item(i) != null) {
// T2 is derived from the other type definition by DERIVATION_RESTRICTION
if (isDerivedByRestriction(ancestorNS, ancestorName,(XSSimpleTypeDefinition)memberTypes.item(i))) {
return true;
}
}
}
}
return false;
}
static final XSSimpleTypeDecl fAnySimpleType = new XSSimpleTypeDecl(null, "anySimpleType", DV_ANYSIMPLETYPE, ORDERED_FALSE, false, true, false, true, XSConstants.ANYSIMPLETYPE_DT);
static final XSSimpleTypeDecl fAnyAtomicType = new XSSimpleTypeDecl(fAnySimpleType, "anyAtomicType", DV_ANYATOMICTYPE, ORDERED_FALSE, false, true, false, true, XSSimpleTypeDecl.ANYATOMICTYPE_DT);
/**
* Validation context used to validate facet values.
*/
static final ValidationContext fDummyContext = new ValidationContext() {
public boolean needFacetChecking() {
return true;
}
public boolean needExtraChecking() {
return false;
}
public boolean needToNormalize() {
return false;
}
public boolean useNamespaces() {
return true;
}
public boolean isEntityDeclared(String name) {
return false;
}
public boolean isEntityUnparsed(String name) {
return false;
}
public boolean isIdDeclared(String name) {
return false;
}
public void addId(String name) {
}
public void addIdRef(String name) {
}
public String getSymbol (String symbol) {
return symbol.intern();
}
public String getURI(String prefix) {
return null;
}
};
private boolean fAnonymous = false;
/**
* A wrapper of ValidationContext, to provide a way of switching to a
* different Namespace declaration context.
*/
class ValidationContextImpl implements ValidationContext {
ValidationContext fExternal;
ValidationContextImpl(ValidationContext external) {
fExternal = external;
}
NamespaceContext fNSContext;
void setNSContext(NamespaceContext nsContext) {
fNSContext = nsContext;
}
public boolean needFacetChecking() {
return fExternal.needFacetChecking();
}
public boolean needExtraChecking() {
return fExternal.needExtraChecking();
}
public boolean needToNormalize() {
return fExternal.needToNormalize();
}
// schema validation is predicated upon namespaces
public boolean useNamespaces() {
return true;
}
public boolean isEntityDeclared (String name) {
return fExternal.isEntityDeclared(name);
}
public boolean isEntityUnparsed (String name) {
return fExternal.isEntityUnparsed(name);
}
public boolean isIdDeclared (String name) {
return fExternal.isIdDeclared(name);
}
public void addId(String name) {
fExternal.addId(name);
}
public void addIdRef(String name) {
fExternal.addIdRef(name);
}
public String getSymbol (String symbol) {
return fExternal.getSymbol(symbol);
}
public String getURI(String prefix) {
if (fNSContext == null)
return fExternal.getURI(prefix);
else
return fNSContext.getURI(prefix);
}
}
public void reset(){
// if it's immutable, can't be reset:
if (fIsImmutable) return;
fItemType = null;
fMemberTypes = null;
fTypeName = null;
fTargetNamespace = null;
fFinalSet = 0;
fBase = null;
fVariety = -1;
fValidationDV = -1;
fFacetsDefined = 0;
fFixedFacet = 0;
//for constraining facets
fWhiteSpace = 0;
fLength = -1;
fMinLength = -1;
fMaxLength = -1;
fTotalDigits = -1;
fFractionDigits = -1;
fPattern = null;
fPatternStr = null;
fEnumeration = null;
fEnumerationType = null;
fEnumerationItemType = null;
fLexicalPattern = null;
fLexicalEnumeration = null;
fMaxInclusive = null;
fMaxExclusive = null;
fMinExclusive = null;
fMinInclusive = null;
lengthAnnotation = null;
minLengthAnnotation = null;
maxLengthAnnotation = null;
whiteSpaceAnnotation = null;
totalDigitsAnnotation = null;
fractionDigitsAnnotation = null;
patternAnnotations = null;
enumerationAnnotations = null;
maxInclusiveAnnotation = null;
maxExclusiveAnnotation = null;
minInclusiveAnnotation = null;
minExclusiveAnnotation = null;
fPatternType = SPECIAL_PATTERN_NONE;
fAnnotations = null;
fFacets = null;
// REVISIT: reset for fundamental facets
}
/**
* @see org.apache.xerces.xs.XSObject#getNamespaceItem()
*/
public XSNamespaceItem getNamespaceItem() {
// REVISIT: implement
return null;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return this.fTargetNamespace+"," +this.fTypeName;
}
/**
* A list of constraining facets if it exists, otherwise an empty
* <code>XSObjectList</code>. Note: This method must not be used to
* retrieve values for <code>enumeration</code> and <code>pattern</code>
* facets.
*/
public XSObjectList getFacets() {
if (fFacets == null &&
(fFacetsDefined != 0 || fValidationDV == DV_INTEGER)) {
XSFacetImpl[] facets = new XSFacetImpl[10];
int count = 0;
if ((fFacetsDefined & FACET_WHITESPACE) != 0) {
facets[count] =
new XSFacetImpl(
FACET_WHITESPACE,
WS_FACET_STRING[fWhiteSpace],
(fFixedFacet & FACET_WHITESPACE) != 0,
whiteSpaceAnnotation);
count++;
}
if (fLength != -1) {
facets[count] =
new XSFacetImpl(
FACET_LENGTH,
Integer.toString(fLength),
(fFixedFacet & FACET_LENGTH) != 0,
lengthAnnotation);
count++;
}
if (fMinLength != -1) {
facets[count] =
new XSFacetImpl(
FACET_MINLENGTH,
Integer.toString(fMinLength),
(fFixedFacet & FACET_MINLENGTH) != 0,
minLengthAnnotation);
count++;
}
if (fMaxLength != -1) {
facets[count] =
new XSFacetImpl(
FACET_MAXLENGTH,
Integer.toString(fMaxLength),
(fFixedFacet & FACET_MAXLENGTH) != 0,
maxLengthAnnotation);
count++;
}
if (fTotalDigits != -1) {
facets[count] =
new XSFacetImpl(
FACET_TOTALDIGITS,
Integer.toString(fTotalDigits),
(fFixedFacet & FACET_TOTALDIGITS) != 0,
totalDigitsAnnotation);
count++;
}
if (fValidationDV == DV_INTEGER) {
facets[count] =
new XSFacetImpl(
FACET_FRACTIONDIGITS,
"0",
true,
null);
count++;
}
if (fFractionDigits != -1) {
facets[count] =
new XSFacetImpl(
FACET_FRACTIONDIGITS,
Integer.toString(fFractionDigits),
(fFixedFacet & FACET_FRACTIONDIGITS) != 0,
fractionDigitsAnnotation);
count++;
}
if (fMaxInclusive != null) {
facets[count] =
new XSFacetImpl(
FACET_MAXINCLUSIVE,
fMaxInclusive.toString(),
(fFixedFacet & FACET_MAXINCLUSIVE) != 0,
maxInclusiveAnnotation);
count++;
}
if (fMaxExclusive != null) {
facets[count] =
new XSFacetImpl(
FACET_MAXEXCLUSIVE,
fMaxExclusive.toString(),
(fFixedFacet & FACET_MAXEXCLUSIVE) != 0,
maxExclusiveAnnotation);
count++;
}
if (fMinExclusive != null) {
facets[count] =
new XSFacetImpl(
FACET_MINEXCLUSIVE,
fMinExclusive.toString(),
(fFixedFacet & FACET_MINEXCLUSIVE) != 0,
minExclusiveAnnotation);
count++;
}
if (fMinInclusive != null) {
facets[count] =
new XSFacetImpl(
FACET_MININCLUSIVE,
fMinInclusive.toString(),
(fFixedFacet & FACET_MININCLUSIVE) != 0,
minInclusiveAnnotation);
count++;
}
fFacets = new XSObjectListImpl(facets, count);
}
return (fFacets != null) ? fFacets : XSObjectListImpl.EMPTY_LIST;
}
/**
* A list of enumeration and pattern constraining facets if it exists,
* otherwise an empty <code>XSObjectList</code>.
*/
public XSObjectList getMultiValueFacets() {
if (fMultiValueFacets == null &&
((fFacetsDefined & FACET_ENUMERATION) != 0 ||
(fFacetsDefined & FACET_PATTERN) != 0 ||
fPatternType != SPECIAL_PATTERN_NONE ||
fValidationDV == DV_INTEGER)) {
XSMVFacetImpl[] facets = new XSMVFacetImpl[2];
int count = 0;
if ((fFacetsDefined & FACET_PATTERN) != 0 ||
fPatternType != SPECIAL_PATTERN_NONE ||
fValidationDV == DV_INTEGER) {
facets[count] =
new XSMVFacetImpl(
FACET_PATTERN,
this.getLexicalPattern(),
patternAnnotations);
count++;
}
if (fEnumeration != null) {
facets[count] =
new XSMVFacetImpl(
FACET_ENUMERATION,
this.getLexicalEnumeration(),
enumerationAnnotations);
count++;
}
fMultiValueFacets = new XSObjectListImpl(facets, count);
}
return (fMultiValueFacets != null) ?
fMultiValueFacets : XSObjectListImpl.EMPTY_LIST;
}
public Object getMinInclusiveValue() {
return fMinInclusive;
}
public Object getMinExclusiveValue() {
return fMinExclusive;
}
public Object getMaxInclusiveValue() {
return fMaxInclusive;
}
public Object getMaxExclusiveValue() {
return fMaxExclusive;
}
public void setAnonymous(boolean anon) {
fAnonymous = anon;
}
private static final class XSFacetImpl implements XSFacet {
final short kind;
final String value;
final boolean fixed;
final XSObjectList annotations;
public XSFacetImpl(short kind, String value, boolean fixed, XSAnnotation annotation) {
this.kind = kind;
this.value = value;
this.fixed = fixed;
if (annotation != null) {
this.annotations = new XSObjectListImpl();
((XSObjectListImpl)this.annotations).add(annotation);
}
else {
this.annotations = XSObjectListImpl.EMPTY_LIST;
}
}
/*
* (non-Javadoc)
*
* @see org.apache.xerces.xs.XSFacet#getAnnotation()
*/
/**
* Optional. Annotation.
*/
public XSAnnotation getAnnotation() {
return (XSAnnotation) annotations.item(0);
}
/*
* (non-Javadoc)
*
* @see org.apache.xerces.xs.XSFacet#getAnnotations()
*/
/**
* Optional. Annotations.
*/
public XSObjectList getAnnotations() {
return annotations;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSFacet#getFacetKind()
*/
public short getFacetKind() {
return kind;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSFacet#getLexicalFacetValue()
*/
public String getLexicalFacetValue() {
return value;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSFacet#isFixed()
*/
public boolean getFixed() {
return fixed;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSObject#getName()
*/
public String getName() {
return null;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSObject#getNamespace()
*/
public String getNamespace() {
return null;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSObject#getNamespaceItem()
*/
public XSNamespaceItem getNamespaceItem() {
// REVISIT: implement
return null;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSObject#getType()
*/
public short getType() {
return XSConstants.FACET;
}
}
private static final class XSMVFacetImpl implements XSMultiValueFacet {
final short kind;
final XSObjectList annotations;
final StringList values;
public XSMVFacetImpl(short kind, StringList values, XSObjectList annotations) {
this.kind = kind;
this.values = values;
this.annotations = (annotations != null) ? annotations : XSObjectListImpl.EMPTY_LIST;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSFacet#getFacetKind()
*/
public short getFacetKind() {
return kind;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSMultiValueFacet#getAnnotations()
*/
public XSObjectList getAnnotations() {
return annotations;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSMultiValueFacet#getLexicalFacetValues()
*/
public StringList getLexicalFacetValues() {
return values;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSObject#getName()
*/
public String getName() {
return null;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSObject#getNamespace()
*/
public String getNamespace() {
return null;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSObject#getNamespaceItem()
*/
public XSNamespaceItem getNamespaceItem() {
// REVISIT: implement
return null;
}
/* (non-Javadoc)
* @see org.apache.xerces.xs.XSObject#getType()
*/
public short getType() {
return XSConstants.MULTIVALUE_FACET;
}
}
public String getTypeNamespace() {
return getNamespace();
}
public boolean isDerivedFrom(String typeNamespaceArg, String typeNameArg, int derivationMethod) {
return isDOMDerivedFrom(typeNamespaceArg, typeNameArg, derivationMethod);
}
private short convertToPrimitiveKind(short valueType) {
/** Primitive datatypes. */
if (valueType <= XSConstants.NOTATION_DT) {
return valueType;
}
/** Types derived from string. */
if (valueType <= XSConstants.ENTITY_DT) {
return XSConstants.STRING_DT;
}
/** Types derived from decimal. */
if (valueType <= XSConstants.POSITIVEINTEGER_DT) {
return XSConstants.DECIMAL_DT;
}
/** Other types. */
return valueType;
}
} // class XSSimpleTypeDecl
| true | false | null | null |
diff --git a/atlas-dao/src/main/java/uk/ac/ebi/gxa/dao/AtlasDAO.java b/atlas-dao/src/main/java/uk/ac/ebi/gxa/dao/AtlasDAO.java
index a3789182d..f9c26de4e 100644
--- a/atlas-dao/src/main/java/uk/ac/ebi/gxa/dao/AtlasDAO.java
+++ b/atlas-dao/src/main/java/uk/ac/ebi/gxa/dao/AtlasDAO.java
@@ -1,2304 +1,2311 @@
package uk.ac.ebi.gxa.dao;
import oracle.jdbc.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.*;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.core.support.AbstractSqlTypeValue;
import uk.ac.ebi.microarray.atlas.model.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.text.DecimalFormat;
import java.util.*;
/**
* A data access object designed for retrieving common sorts of data from the atlas database. This DAO should be
* configured with a spring {@link JdbcTemplate} object which will be used to query the database.
*
* @author Tony Burdett
* @date 21-Sep-2009
*/
public class AtlasDAO {
// load monitor
private static final String LOAD_MONITOR_SELECT =
"SELECT accession, status, netcdf, similarity, ranking, searchindex, load_type " +
"FROM load_monitor " +
"WHERE load_type='experiment'";
private static final String LOAD_MONITOR_BY_ACC_SELECT =
LOAD_MONITOR_SELECT + " " +
"AND accession=?";
private static final String LOAD_MONITOR_SORTED_EXPERIMENT_ACCESSIONS =
"SELECT accession, status, netcdf, similarity, ranking, searchindex, load_type FROM ( " +
"SELECT ROWNUM r, accession, status, netcdf, similarity, ranking, searchindex, load_type FROM ( " +
"SELECT accession, status, netcdf, similarity, ranking, searchindex, load_type " +
"FROM load_monitor " +
"WHERE load_type='experiment' " +
"ORDER BY accession)) " +
"WHERE r BETWEEN ? AND ?";
// experiment queries
private static final String EXPERIMENTS_COUNT =
"SELECT COUNT(*) FROM a2_experiment";
private static final String EXPERIMENTS_SELECT =
"SELECT accession, description, performer, lab, experimentid " +
"FROM a2_experiment";
private static final String EXPERIMENTS_PENDING_INDEX_SELECT =
"SELECT e.accession, e.description, e.performer, e.lab, e.experimentid " +
"FROM a2_experiment e, load_monitor lm " +
"WHERE e.accession=lm.accession " +
"AND (lm.searchindex='pending' OR lm.searchindex='failed') " +
"AND lm.load_type='experiment'";
private static final String EXPERIMENTS_PENDING_NETCDF_SELECT =
"SELECT e.accession, e.description, e.performer, e.lab, e.experimentid " +
"FROM a2_experiment e, load_monitor lm " +
"WHERE e.accession=lm.accession " +
"AND (lm.netcdf='pending' OR lm.netcdf='failed') " +
"AND lm.load_type='experiment'";
private static final String EXPERIMENTS_PENDING_ANALYTICS_SELECT =
"SELECT e.accession, e.description, e.performer, e.lab, e.experimentid " +
"FROM a2_experiment e, load_monitor lm " +
"WHERE e.accession=lm.accession " +
"AND (lm.ranking='pending' OR lm.ranking='failed') " + // fixme: similarity?
"AND lm.load_type='experiment'";
private static final String EXPERIMENT_BY_ACC_SELECT =
EXPERIMENTS_SELECT + " " +
"WHERE accession=?";
// gene queries
private static final String GENES_COUNT =
"SELECT COUNT(*) FROM a2_gene";
private static final String GENES_SELECT =
"SELECT DISTINCT g.geneid, g.identifier, g.name, s.name AS species " +
"FROM a2_gene g, a2_spec s " +
"WHERE g.specid=s.specid";
private static final String GENE_BY_IDENTIFIER =
"SELECT DISTINCT g.geneid, g.identifier, g.name, s.name AS species " +
"FROM a2_gene g, a2_spec s " +
"WHERE g.identifier=?";
private static final String DESIGN_ELEMENTS_AND_GENES_SELECT =
"SELECT de.geneid, de.designelementid " +
"FROM a2_designelement de";
private static final String GENES_PENDING_SELECT =
"SELECT DISTINCT g.geneid, g.identifier, g.name, s.name AS species " +
"FROM a2_gene g, a2_spec s, load_monitor lm " +
"WHERE g.specid=s.specid " +
"AND g.identifier=lm.accession " +
"AND (lm.searchindex='pending' OR lm.searchindex='failed') " +
"AND lm.load_type='gene'";
private static final String DESIGN_ELEMENTS_AND_GENES_PENDING_SELECT =
"SELECT de.geneid, de.designelementid " +
"FROM a2_designelement de, a2_gene g, load_monitor lm " +
"WHERE de.geneid=g.geneid " +
"AND g.identifier=lm.accession " +
"AND (lm.searchindex='pending' OR lm.searchindex='failed') " +
"AND lm.load_type='gene'";
private static final String GENES_BY_EXPERIMENT_ACCESSION =
"SELECT DISTINCT g.geneid, g.identifier, g.name, s.name AS species " +
"FROM a2_gene g, a2_spec s, a2_designelement d, a2_assay a, " +
"a2_experiment e " +
"WHERE g.geneid=d.geneid " +
"AND g.specid = s.specid " +
"AND d.arraydesignid=a.arraydesignid " +
"AND a.experimentid=e.experimentid " +
"AND e.accession=?";
private static final String DESIGN_ELEMENTS_AND_GENES_BY_EXPERIMENT_ACCESSION =
"SELECT de.geneid, de.designelementid " +
"FROM a2_designelement de, a2_assay a, a2_experiment e " +
"WHERE de.arraydesignid=a.arraydesignid " +
"AND a.experimentid=e.experimentid " +
"AND e.accession=?";
private static final String PROPERTIES_BY_RELATED_GENES =
"SELECT gpv.geneid, gp.name AS property, gpv.value AS propertyvalue " +
"FROM a2_geneproperty gp, a2_genepropertyvalue gpv " +
"WHERE gpv.genepropertyid=gp.genepropertyid " +
"AND gpv.geneid IN (:geneids)";
private static final String GENE_COUNT_SELECT =
"SELECT COUNT(DISTINCT identifier) FROM a2_gene";
// assay queries
private static final String ASSAYS_COUNT =
"SELECT COUNT(*) FROM a2_assay";
private static final String ASSAYS_SELECT =
"SELECT a.accession, e.accession, ad.accession, a.assayid " +
"FROM a2_assay a, a2_experiment e, a2_arraydesign ad " +
"WHERE e.experimentid=a.experimentid " +
"AND a.arraydesignid=ad.arraydesignid";
private static final String ASSAYS_BY_EXPERIMENT_ACCESSION =
ASSAYS_SELECT + " " +
"AND e.accession=?";
private static final String ASSAYS_BY_EXPERIMENT_AND_ARRAY_ACCESSION =
ASSAYS_BY_EXPERIMENT_ACCESSION + " " +
"AND ad.accession=?";
private static final String ASSAYS_BY_RELATED_SAMPLES =
"SELECT s.sampleid, a.accession " +
"FROM a2_assay a, a2_assaysample s " +
"WHERE a.assayid=s.assayid " +
"AND s.sampleid IN (:sampleids)";
private static final String PROPERTIES_BY_RELATED_ASSAYS =
"SELECT apv.assayid, p.name AS property, pv.name AS propertyvalue, apv.isfactorvalue " +
"FROM a2_property p, a2_propertyvalue pv, a2_assaypropertyvalue apv " +
"WHERE apv.propertyvalueid=pv.propertyvalueid " +
"AND pv.propertyid=p.propertyid " +
"AND apv.assayid IN (:assayids)";
// expression value queries
private static final String EXPRESSION_VALUES_BY_RELATED_ASSAYS =
"SELECT ev.assayid, ev.designelementid, ev.value " +
"FROM a2_expressionvalue ev, a2_designelement de " +
"WHERE ev.designelementid=de.designelementid " +
"AND ev.assayid IN (:assayids)";
private static final String EXPRESSION_VALUES_BY_EXPERIMENT_AND_ARRAY =
"SELECT ev.assayid, ev.designelementid, ev.value " +
"FROM a2_expressionvalue ev " +
"JOIN a2_designelement de ON de.designelementid=ev.designelementid " +
"JOIN a2_assay a ON a.assayid = ev.assayid " +
"WHERE a.experimentid=? AND de.arraydesignid=?";
// sample queries
private static final String SAMPLES_BY_ASSAY_ACCESSION =
"SELECT s.accession, s.species, s.channel, s.sampleid " +
"FROM a2_sample s, a2_assay a, a2_assaysample ass " +
"WHERE s.sampleid=ass.sampleid " +
"AND a.assayid=ass.assayid " +
"AND a.accession=?";
private static final String SAMPLES_BY_EXPERIMENT_ACCESSION =
"SELECT s.accession, s.species, s.channel, s.sampleid " +
"FROM a2_sample s, a2_assay a, a2_assaysample ass, a2_experiment e " +
"WHERE s.sampleid=ass.sampleid " +
"AND a.assayid=ass.assayid " +
"AND a.experimentid=e.experimentid " +
"AND e.accession=?";
private static final String PROPERTIES_BY_RELATED_SAMPLES =
"SELECT spv.sampleid, p.name AS property, pv.name AS propertyvalue, spv.isfactorvalue " +
"FROM a2_property p, a2_propertyvalue pv, a2_samplepropertyvalue spv " +
"WHERE spv.propertyvalueid=pv.propertyvalueid " +
"AND pv.propertyid=p.propertyid " +
"AND spv.sampleid IN (:sampleids)";
// query for counts, for statistics
private static final String PROPERTY_VALUE_COUNT_SELECT =
"SELECT COUNT(DISTINCT name) FROM a2_propertyvalue";
// array and design element queries
private static final String ARRAY_DESIGN_SELECT =
"SELECT accession, type, name, provider, arraydesignid " +
"FROM a2_arraydesign";
private static final String ARRAY_DESIGN_BY_ACC_SELECT =
ARRAY_DESIGN_SELECT + " " +
"WHERE accession=?";
private static final String ARRAY_DESIGN_BY_EXPERIMENT_ACCESSION =
"SELECT " +
"DISTINCT d.accession, d.type, d.name, d.provider, d.arraydesignid " +
"FROM a2_arraydesign d, a2_assay a, a2_experiment e " +
"WHERE e.experimentid=a.experimentid " +
"AND a.arraydesignid=d.arraydesignid " +
"AND e.accession=?";
private static final String DESIGN_ELEMENTS_BY_ARRAY_ACCESSION =
"SELECT de.designelementid, de.accession " +
"FROM A2_ARRAYDESIGN ad, A2_DESIGNELEMENT de " +
"WHERE de.arraydesignid=ad.arraydesignid " +
"AND ad.accession=?";
private static final String DESIGN_ELEMENT_NAMES_BY_ARRAY_ACCESSION =
"SELECT de.designelementid, de.name " +
"FROM A2_ARRAYDESIGN ad, A2_DESIGNELEMENT de " +
"WHERE de.arraydesignid=ad.arraydesignid " +
"AND ad.accession=?";
private static final String DESIGN_ELEMENTS_BY_ARRAY_ID =
"SELECT de.designelementid, de.accession " +
"FROM a2_designelement de " +
"WHERE de.arraydesignid=?";
private static final String DESIGN_ELEMENTS_AND_GENES_BY_RELATED_ARRAY =
"SELECT de.arraydesignid, de.designelementid, de.accession, de.geneid " +
"FROM a2_designelement de " +
"WHERE de.arraydesignid IN (:arraydesignids)";
private static final String DESIGN_ELEMENTS_BY_GENEID =
"SELECT de.designelementid, de.accession " +
"FROM a2_designelement de " +
"WHERE de.geneid=?";
// other useful queries
private static final String EXPRESSIONANALYTICS_BY_EXPERIMENTID =
"SELECT ef.name AS ef, efv.name AS efv, a.experimentid, " +
"a.designelementid, a.tstat, a.pvaladj, " +
"ef.propertyid as efid, efv.propertyvalueid as efvid " +
"FROM a2_expressionanalytics a " +
"JOIN a2_propertyvalue efv ON efv.propertyvalueid=a.propertyvalueid " +
"JOIN a2_property ef ON ef.propertyid=efv.propertyid " +
"JOIN a2_designelement de ON de.designelementid=a.designelementID " +
"WHERE a.experimentid=?";
private static final String EXPRESSIONANALYTICS_BY_GENEID =
"SELECT ef, efv, experimentid, null, tstat, min(pvaladj), efid, efvid FROM " +
"(SELECT ef.name AS ef, efv.name AS efv, a.experimentid AS experimentid, " +
"first_value(a.tstat) over (partition BY ef.name, efv.name, a.experimentid ORDER BY a.pvaladj ASC) AS tstat, " +
"(a.pvaladj ) AS pvaladj," +
"ef.propertyid AS efid, efv.propertyvalueid as efvid " +
"FROM a2_expressionanalytics a " +
"JOIN a2_propertyvalue efv ON efv.propertyvalueid=a.propertyvalueid " +
"JOIN a2_property ef ON ef.propertyid=efv.propertyid " +
"JOIN a2_designelement de ON de.designelementid=a.designelementid " +
"WHERE de.geneid=? AND a.pvaladj < 0.05) GROUP BY ef, efv, experimentid, tstat, efid, efvid";
private static final String EXPRESSIONANALYTICS_BY_DESIGNELEMENTID =
"SELECT ef.name AS ef, efv.name AS efv, a.experimentid, a.designelementid, " +
"a.tstat, a.pvaladj, " +
"ef.propertyid as efid, efv.propertyvalueid as efvid " +
"FROM a2_expressionanalytics a " +
"JOIN a2_propertyvalue efv ON efv.propertyvalueid=a.propertyvalueid " +
"JOIN a2_property ef ON ef.propertyid=efv.propertyid " +
"WHERE a.designelementid=?";
private static final String ONTOLOGY_MAPPINGS_SELECT =
"SELECT DISTINCT accession, property, propertyvalue, ontologyterm, " +
"issampleproperty, isassayproperty, isfactorvalue, experimentid " +
"FROM a2_ontologymapping";
private static final String ONTOLOGY_MAPPINGS_BY_ONTOLOGY_NAME =
ONTOLOGY_MAPPINGS_SELECT + " " +
"WHERE ontologyname=?";
private static final String ONTOLOGY_MAPPINGS_BY_EXPERIMENT_ACCESSION =
ONTOLOGY_MAPPINGS_SELECT + " " +
"WHERE accession=?";
// queries for atlas interface
private static final String ATLAS_RESULTS_SELECT =
"SELECT " +
"ea.experimentid, " +
"g.geneid, " +
"p.name AS property, " +
"pv.name AS propertyvalue, " +
"CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END AS updn, " +
"min(ea.pvaladj), " +
"FROM a2_expressionanalytics ea " +
"JOIN a2_propertyvalue pv ON pv.propertyvalueid=ea.propertyvalueid " +
"JOIN a2_property p ON p.propertyid=pv.propertyid " +
"JOIN a2_designelement de ON de.designelementid=ea.designelementid " +
"JOIN a2_gene g ON g.geneid=de.geneid";
// same as results, but counts geneids instead of returning them
private static final String ATLAS_COUNTS_SELECT =
"SELECT " +
"ea.experimentid, " +
"p.name AS property, " +
"pv.name AS propertyvalue, " +
"CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END AS updn, " +
"min(ea.pvaladj), " +
"COUNT(DISTINCT(g.geneid)) AS genes, " +
"min(p.propertyid) AS propertyid, " +
"min(pv.propertyvalueid) AS propertyvalueid " +
"FROM a2_expressionanalytics ea " +
"JOIN a2_propertyvalue pv ON pv.propertyvalueid=ea.propertyvalueid " +
"JOIN a2_property p ON p.propertyid=pv.propertyid " +
"JOIN a2_designelement de ON de.designelementid=ea.designelementid " +
"JOIN a2_gene g ON g.geneid=de.geneid";
private static final String ATLAS_COUNTS_BY_EXPERIMENTID =
ATLAS_COUNTS_SELECT + " " +
"WHERE ea.experimentid=? " +
"GROUP BY ea.experimentid, p.name, pv.name, " +
"CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END";
private static final String ATLAS_RESULTS_UP_BY_EXPERIMENTID_GENEID_AND_EFV =
ATLAS_RESULTS_SELECT + " " +
"WHERE ea.experimentid IN (:exptids) " +
"AND g.geneid IN (:geneids) " +
"AND pv.name IN (:efvs) " +
"AND updn='1' " +
"AND TOPN<=20 " +
"ORDER BY ea.pvaladj " +
"GROUP BY ea.experimentid, g.geneid, p.name, pv.name, " +
"CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END";
private static final String ATLAS_RESULTS_DOWN_BY_EXPERIMENTID_GENEID_AND_EFV =
ATLAS_RESULTS_SELECT + " " +
"WHERE ea.experimentid IN (:exptids) " +
"AND g.geneid IN (:geneids) " +
"AND pv.name IN (:efvs) " +
"AND updn='-1' " +
"AND TOPN<=20 " +
"ORDER BY ea.pvaladj " +
"GROUP BY ea.experimentid, g.geneid, p.name, pv.name, ea.pvaladj, " +
"CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END";
private static final String ATLAS_RESULTS_UPORDOWN_BY_EXPERIMENTID_GENEID_AND_EFV =
ATLAS_RESULTS_SELECT + " " +
"WHERE ea.experimentid IN (:exptids) " +
"AND g.geneid IN (:geneids) " +
"AND pv.name IN (:efvs) " +
"AND updn<>0 " +
"AND TOPN<=20 " +
"ORDER BY ea.pvaladj " +
"GROUP BY ea.experimentid, g.geneid, p.name, pv.name, ea.pvaladj, " +
"CASE WHEN ea.tstat < 0 THEN -1 ELSE 1 END"; // fixme: exclude experiment ids?
// old atlas queries contained "NOT IN (211794549,215315583,384555530,411493378,411512559)"
private static final String SPECIES_ALL =
"SELECT specid, name FROM A2_SPEC";
private static final String PROPERTIES_ALL =
"SELECT min(p.propertyid), p.name, min(pv.propertyvalueid), pv.name, 1 as isfactorvalue " +
"FROM a2_property p, a2_propertyvalue pv " +
"WHERE pv.propertyid=p.propertyid GROUP BY p.name, pv.name";
private static final String GENEPROPERTY_ALL_NAMES =
"SELECT name FROM A2_GENEPROPERTY";
private static final String BEST_DESIGNELEMENTID_FOR_GENE =
"SELECT topde FROM (SELECT de.designelementid as topde," +
" MIN(a.pvaladj) KEEP(DENSE_RANK FIRST ORDER BY a.pvaladj ASC)" +
" OVER (PARTITION BY a.propertyvalueid) as minp" +
" FROM a2_expressionanalytics a, a2_propertyvalue pv, a2_property p, a2_designelement de" +
" WHERE pv.propertyid = p.propertyid" +
" AND pv.propertyvalueid = a.propertyvalueid" +
" AND a.designelementid = de.designelementid" +
" AND p.name = ?" +
" AND a.experimentid = ?" +
" AND de.geneid = ?" +
" and rownum=1)";
private JdbcTemplate template;
private int maxQueryParams = 500;
private Logger log = LoggerFactory.getLogger(getClass());
public JdbcTemplate getJdbcTemplate() {
return template;
}
public void setJdbcTemplate(JdbcTemplate template) {
this.template = template;
}
/**
* Get the maximum allowed number of parameters that can be supplied to a parameterised query. This is effectively
* the maximum bound for an "IN" list - i.e. SELECT * FROM foo WHERE foo.bar IN (?,?,?,...,?). If unset, this
* defaults to 500. Typically, the limit for oracle databases is 1000. If, for any query that takes a list, the
* size of the list is greater than this value, the query will be split into several smaller subqueries and the
* results aggregated. As a user, you should not notice any difference.
*
* @return the maximum bound on the query list size
*/
public int getMaxQueryParams() {
return maxQueryParams;
}
/**
* Set the maximum allowed number of parameters that can be supplied to a parameterised query. This is effectively
* the maximum bound for an "IN" list - i.e. SELECT * FROM foo WHERE foo.bar IN (?,?,?,...,?). If unset, this
* defaults to 500. Typically, the limit for oracle databases is 1000. If, for any query that takes a list, the
* size of the list is greater than this value, the query will be split into several smaller subqueries and the
* results aggregated.
*
* @param maxQueryParams the maximum bound on the query list size - this should never be greater than that allowed
* by the database, but can be smaller
*/
public void setMaxQueryParams(int maxQueryParams) {
this.maxQueryParams = maxQueryParams;
}
/*
DAO read methods
*/
public List<LoadDetails> getLoadDetailsForExperiments() {
List results = template.query(LOAD_MONITOR_SELECT,
new LoadDetailsMapper());
return (List<LoadDetails>) results;
}
public LoadDetails getLoadDetailsForExperimentsByAccession(String accession) {
List results = template.query(LOAD_MONITOR_BY_ACC_SELECT,
new Object[]{accession},
new LoadDetailsMapper());
return results.size() > 0 ? (LoadDetails) results.get(0) : null;
}
public List<LoadDetails> getLoadDetailsForExperimentsByPage(int pageNumber, int experimentsPerPage) {
int offset = (pageNumber - 1) * experimentsPerPage;
int rowcount = pageNumber * experimentsPerPage;
log.debug("Query is {}, from " + offset + " to " + rowcount, LOAD_MONITOR_SORTED_EXPERIMENT_ACCESSIONS);
List results = template.query(LOAD_MONITOR_SORTED_EXPERIMENT_ACCESSIONS,
new Object[]{offset, rowcount},
new LoadDetailsMapper());
return (List<LoadDetails>) results;
}
public List<Experiment> getAllExperiments() {
List results = template.query(EXPERIMENTS_SELECT,
new ExperimentMapper());
return (List<Experiment>) results;
}
public List<Experiment> getAllExperimentsPendingIndexing() {
List results = template.query(EXPERIMENTS_PENDING_INDEX_SELECT,
new ExperimentMapper());
return (List<Experiment>) results;
}
public List<Experiment> getAllExperimentsPendingNetCDFs() {
List results = template.query(EXPERIMENTS_PENDING_NETCDF_SELECT,
new ExperimentMapper());
return (List<Experiment>) results;
}
public List<Experiment> getAllExperimentsPendingAnalytics() {
List results = template.query(EXPERIMENTS_PENDING_ANALYTICS_SELECT,
new ExperimentMapper());
return (List<Experiment>) results;
}
/**
* Gets a single experiment from the Atlas Database, queried by the accession of the experiment.
*
* @param accession the experiment's accession number (usually in the format E-ABCD-1234)
* @return an object modelling this experiment
*/
public Experiment getExperimentByAccession(String accession) {
List results = template.query(EXPERIMENT_BY_ACC_SELECT,
new Object[]{accession},
new ExperimentMapper());
return results.size() > 0 ? (Experiment) results.get(0) : null;
}
/**
* Fetches all genes in the database. Note that genes are not automatically prepopulated with property information,
* to keep query time down. If you require this data, you can fetch it for the list of genes you want to obtain
* properties for by calling {@link #getPropertiesForGenes(java.util.List)}. Genes <b>are</b> prepopulated with
* design element information, however.
*
* @return the list of all genes in the database
*/
public List<Gene> getAllGenes() {
// do the first query to fetch genes without design elements
List results = template.query(GENES_SELECT,
new GeneMapper());
// do the second query to obtain design elements
List<Gene> genes = (List<Gene>) results;
// map genes to gene id
Map<Integer, Gene> genesByID = new HashMap<Integer, Gene>();
for (Gene gene : genes) {
// index this assay
genesByID.put(gene.getGeneID(), gene);
// also, initialize properties if null - once this method is called, you should never get an NPE
if (gene.getDesignElementIDs() == null) {
gene.setDesignElementIDs(new HashSet<Integer>());
}
}
// map of genes and their design elements
GeneDesignElementMapper geneDesignElementMapper = new GeneDesignElementMapper(genesByID);
// now query for design elements, and genes, by the experiment accession, and map them together
template.query(DESIGN_ELEMENTS_AND_GENES_SELECT,
geneDesignElementMapper);
// and return
return genes;
}
/**
* Same as getAllGenes(), but doesn't do design elements. Sometime we just don't need them.
*
* @return list of all genes
*/
public List<Gene> getAllGenesFast() {
// do the query to fetch genes without design elements
return (List<Gene>) template.query(GENES_SELECT,
new GeneMapper());
}
public Gene getGeneByIdentifier(String identifier) {
// do the query to fetch gene without design elements
List results = template.query(GENE_BY_IDENTIFIER,
new Object[]{identifier},
new GeneMapper());
if (results.size() > 0) {
Gene gene = (Gene) results.get(0);
gene.setDesignElementIDs(getDesignElementsByGeneID(gene.getGeneID()).keySet());
return gene;
}
return null;
}
/**
* Fetches all genes in the database that are pending indexing. Note that genes are not automatically prepopulated
* with property information, to keep query time down. If you require this data, you can fetch it for the list of
* genes you want to obtain properties for by calling {@link #getPropertiesForGenes(java.util.List)}. Genes
* <b>are</b> prepopulated with design element information, however.
*
* @return the list of all genes in the database that are pending indexing
*/
public List<Gene> getAllPendingGenes() {
// do the first query to fetch genes without design elements
List results = template.query(GENES_PENDING_SELECT,
new GeneMapper());
// do the second query to obtain design elements
List<Gene> genes = (List<Gene>) results;
// map genes to gene id
Map<Integer, Gene> genesByID = new HashMap<Integer, Gene>();
for (Gene gene : genes) {
// index this assay
genesByID.put(gene.getGeneID(), gene);
// also, initialize properties if null - once this method is called, you should never get an NPE
if (gene.getDesignElementIDs() == null) {
gene.setDesignElementIDs(new HashSet<Integer>());
}
}
// map of genes and their design elements
GeneDesignElementMapper geneDesignElementMapper = new GeneDesignElementMapper(genesByID);
// now query for design elements, and genes, by the experiment accession, and map them together
template.query(DESIGN_ELEMENTS_AND_GENES_PENDING_SELECT,
geneDesignElementMapper);
// and return
return genes;
}
/**
* Fetches all genes in the database that are pending indexing. No properties or design elements, when you dont'
* need that.
*
* @return the list of all genes in the database that are pending indexing
*/
public List<Gene> getAllPendingGenesFast() {
// do the query to fetch genes without design elements
return (List<Gene>) template.query(GENES_PENDING_SELECT,
new GeneMapper());
}
/**
* Fetches all genes for the given experiment accession. Note that genes are not automatically prepopulated with
* property information, to keep query time down. If you require this data, you can fetch it for the list of genes
* you want to obtain properties for by calling {@link #getPropertiesForGenes(java.util.List)}. Genes <b>are</b>
* prepopulated with design element information, however.
*
* @param exptAccession the accession number of the experiment to query for
* @return the list of all genes in the database for this experiment accession
*/
public List<Gene> getGenesByExperimentAccession(String exptAccession) {
// do the first query to fetch genes without design elements
log.debug("Querying for genes by experiment " + exptAccession);
List results = template.query(GENES_BY_EXPERIMENT_ACCESSION,
new Object[]{exptAccession},
new GeneMapper());
log.debug("Genes for " + exptAccession + " acquired");
// do the second query to obtain design elements
List<Gene> genes = (List<Gene>) results;
// map genes to gene id
Map<Integer, Gene> genesByID = new HashMap<Integer, Gene>();
for (Gene gene : genes) {
// index this assay
genesByID.put(gene.getGeneID(), gene);
// also, initialize properties if null - once this method is called, you should never get an NPE
if (gene.getDesignElementIDs() == null) {
gene.setDesignElementIDs(new HashSet<Integer>());
}
}
// map of genes and their design elements
GeneDesignElementMapper geneDesignElementMapper = new GeneDesignElementMapper(genesByID);
// now query for design elements, and genes, by the experiment accession, and map them together
log.debug("Querying for design elements mapped to genes of " + exptAccession);
template.query(DESIGN_ELEMENTS_AND_GENES_BY_EXPERIMENT_ACCESSION,
new Object[]{exptAccession},
geneDesignElementMapper);
log.debug("Design elements for genes of " + exptAccession + " acquired");
// and return
return genes;
}
public void getPropertiesForGenes(List<Gene> genes) {
// populate the other info for these genes
if (genes.size() > 0) {
fillOutGeneProperties(genes);
}
}
public int getGeneCount() {
Object result = template.query(GENE_COUNT_SELECT, new ResultSetExtractor() {
public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
if (resultSet.next()) {
return resultSet.getInt(1);
}
else {
return 0;
}
}
});
return (Integer) result;
}
/**
* Gets all assays in the database. Note that, unlike other queries for assays, this query does not prepopulate all
* property information. This is done to keep the query time don to a minimum. If you need this information, you
* should populate it by calling {@link #getPropertiesForAssays(java.util.List)} on the list (or sublist) of assays
* you wish to fetch properties for. Bear in mind that doing this for a very large list of assays will result in a
* slow query.
*
* @return the list of all assays in the database
*/
public List<Assay> getAllAssays() {
List results = template.query(ASSAYS_SELECT,
new AssayMapper());
// and return
return (List<Assay>) results;
}
public List<Assay> getAssaysByExperimentAccession(
String experimentAccession) {
List results = template.query(ASSAYS_BY_EXPERIMENT_ACCESSION,
new Object[]{experimentAccession},
new AssayMapper());
List<Assay> assays = (List<Assay>) results;
// populate the other info for these assays
if (assays.size() > 0) {
fillOutAssays(assays);
}
// and return
return assays;
}
public List<Assay> getAssaysByExperimentAndArray(String experimentAccession,
String arrayAccession) {
List results = template.query(ASSAYS_BY_EXPERIMENT_AND_ARRAY_ACCESSION,
new Object[]{experimentAccession,
arrayAccession},
new AssayMapper());
List<Assay> assays = (List<Assay>) results;
// populate the other info for these assays
if (assays.size() > 0) {
fillOutAssays(assays);
}
// and return
return assays;
}
public void getPropertiesForAssays(List<Assay> assays) {
// populate the other info for these assays
if (assays.size() > 0) {
fillOutAssays(assays);
}
}
public void getExpressionValuesForAssays(List<Assay> assays) {
// map assays to assay id
Map<Integer, Assay> assaysByID = new HashMap<Integer, Assay>();
for (Assay assay : assays) {
// index this assay
assaysByID.put(assay.getAssayID(), assay);
// also, initialize properties if null - once this method is called, you should never get an NPE
if (assay.getExpressionValues() == null) {
assay.setExpressionValues(new HashMap<Integer, Float>());
}
}
// maps properties to assays
AssayExpressionValueMapper assayExpressionValueMapper = new AssayExpressionValueMapper(assaysByID);
// query template for assays
NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
// if we have more than 'maxQueryParams' assays, split into smaller queries
List<Integer> assayIDs = new ArrayList<Integer>(assaysByID.keySet());
boolean done = false;
int startpos = 0;
int endpos = maxQueryParams;
while (!done) {
List<Integer> assayIDsChunk;
if (endpos > assayIDs.size()) {
// we've reached the last segment, so query all of these
assayIDsChunk = assayIDs.subList(startpos, assayIDs.size());
done = true;
}
else {
// still more left - take next sublist and increment counts
assayIDsChunk = assayIDs.subList(startpos, endpos);
startpos = endpos;
endpos += maxQueryParams;
}
// now query for properties that map to one of the samples in the sublist
MapSqlParameterSource propertyParams = new MapSqlParameterSource();
propertyParams.addValue("assayids", assayIDsChunk);
namedTemplate.query(EXPRESSION_VALUES_BY_RELATED_ASSAYS, propertyParams, assayExpressionValueMapper);
}
}
public Map<Integer, Map<Integer, Float>> getExpressionValuesByExperimentAndArray(
int experimentID, int arrayDesignID) {
Object results = template.query(EXPRESSION_VALUES_BY_EXPERIMENT_AND_ARRAY,
new Object[]{experimentID, arrayDesignID},
new ExpressionValueMapper());
return (Map<Integer, Map<Integer, Float>>) results;
}
public List<Sample> getSamplesByAssayAccession(String assayAccession) {
List results = template.query(SAMPLES_BY_ASSAY_ACCESSION,
new Object[]{assayAccession},
new SampleMapper());
List<Sample> samples = (List<Sample>) results;
// populate the other info for these samples
if (samples.size() > 0) {
fillOutSamples(samples);
}
// and return
return samples;
}
public List<Sample> getSamplesByExperimentAccession(String exptAccession) {
List results = template.query(SAMPLES_BY_EXPERIMENT_ACCESSION,
new Object[]{exptAccession},
new SampleMapper());
List<Sample> samples = (List<Sample>) results;
// populate the other info for these samples
if (samples.size() > 0) {
fillOutSamples(samples);
}
// and return
return samples;
}
public int getPropertyValueCount() {
Object result = template.query(PROPERTY_VALUE_COUNT_SELECT, new ResultSetExtractor() {
public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
if (resultSet.next()) {
return resultSet.getInt(1);
}
else {
return 0;
}
}
});
return (Integer) result;
}
/**
* Returns all array designs in the underlying datasource. Note that, to reduce query times, this method does NOT
* prepopulate ArrayDesigns with their associated design elements (unlike other methods to retrieve array designs
* more specifically). For this reason, you should always ensure that after calling this method you use the {@link
* #getDesignElementsForArrayDesigns(java.util.List)} method on the resulting list.
*
* @return the list of array designs, not prepopulated with design elements.
*/
public List<ArrayDesign> getAllArrayDesigns() {
List results = template.query(ARRAY_DESIGN_SELECT,
new ArrayDesignMapper());
return (List<ArrayDesign>) results;
}
public ArrayDesign getArrayDesignByAccession(String accession) {
List results = template.query(ARRAY_DESIGN_BY_ACC_SELECT,
new Object[]{accession},
new ArrayDesignMapper());
// get first result only
ArrayDesign arrayDesign =
results.size() > 0 ? (ArrayDesign) results.get(0) : null;
if (arrayDesign != null) {
fillOutArrayDesigns(Collections.singletonList(arrayDesign));
}
return arrayDesign;
}
public List<ArrayDesign> getArrayDesignByExperimentAccession(
String exptAccession) {
List results = template.query(ARRAY_DESIGN_BY_EXPERIMENT_ACCESSION,
new Object[]{exptAccession},
new ArrayDesignMapper());
// cast to correct type
List<ArrayDesign> arrayDesigns = (List<ArrayDesign>) results;
// and populate design elements for each
if (arrayDesigns.size() > 0) {
fillOutArrayDesigns(arrayDesigns);
}
return arrayDesigns;
}
public void getDesignElementsForArrayDesigns(List<ArrayDesign> arrayDesigns) {
// populate the other info for these assays
if (arrayDesigns.size() > 0) {
fillOutArrayDesigns(arrayDesigns);
}
}
/**
* A convenience method that fetches the set of design elements by array design accession. Design elements are
* recorded as a map, indexed by design element id and with a value of the design element accession. The set of
* design element ids contains no duplicates, and the results that are returned are the internal database ids for
* design elements. This takes the accession of the array design as a parameter.
*
* @param arrayDesignAccession the accession number of the array design to query for
* @return the map of design element accessions indexed by unique design element id integers
*/
public Map<Integer, String> getDesignElementsByArrayAccession(
String arrayDesignAccession) {
Object results = template.query(DESIGN_ELEMENTS_BY_ARRAY_ACCESSION,
new Object[]{arrayDesignAccession},
new DesignElementMapper());
return (Map<Integer, String>) results;
}
/**
* A convenience method that fetches the set of design elements by array design accession. In this case, design
* elements are recorded as a map, indexed by design element id and with a value of the design element name. The
* design element name corresponds to the arraydesign reporter name or composite reporter name, and is usually the
* probeset ID. The set of design element ids contains no duplicates, and the results that are returned are the
* names for design elements. This takes the accession of the array design as a parameter.
*
* @param arrayDesignAccession the accession number of the array design to query for
* @return the map of design element names indexed by unique design element id integers
*/
public Map<Integer, String> getDesignElementNamesByArrayAccession(
String arrayDesignAccession) {
Object results = template.query(DESIGN_ELEMENT_NAMES_BY_ARRAY_ACCESSION,
new Object[]{arrayDesignAccession},
new DesignElementMapper());
return (Map<Integer, String>) results;
}
public Map<Integer, String> getDesignElementsByArrayID(
int arrayDesignID) {
Object results = template.query(DESIGN_ELEMENTS_BY_ARRAY_ID,
new Object[]{arrayDesignID},
new DesignElementMapper());
return (Map<Integer, String>) results;
}
public Map<Integer, String> getDesignElementsByGeneID(int geneID) {
Object results = template.query(DESIGN_ELEMENTS_BY_GENEID,
new Object[]{geneID},
new DesignElementMapper());
return (Map<Integer, String>) results;
}
public List<ExpressionAnalysis> getExpressionAnalyticsByGeneID(
int geneID) {
List results = template.query(EXPRESSIONANALYTICS_BY_GENEID,
new Object[]{geneID},
new ExpressionAnalyticsMapper());
return (List<ExpressionAnalysis>) results;
}
public List<ExpressionAnalysis> getExpressionAnalyticsByDesignElementID(
int designElementID) {
List results = template.query(EXPRESSIONANALYTICS_BY_DESIGNELEMENTID,
new Object[]{designElementID},
new ExpressionAnalyticsMapper());
return (List<ExpressionAnalysis>) results;
}
public List<ExpressionAnalysis> getExpressionAnalyticsByExperimentID(
int experimentID) {
List results = template.query(EXPRESSIONANALYTICS_BY_EXPERIMENTID,
new Object[]{experimentID},
new ExpressionAnalyticsMapper());
return (List<ExpressionAnalysis>) results;
}
public List<OntologyMapping> getOntologyMappings() {
List results = template.query(ONTOLOGY_MAPPINGS_SELECT,
new OntologyMappingMapper());
return (List<OntologyMapping>) results;
}
public List<OntologyMapping> getOntologyMappingsByOntology(
String ontologyName) {
List results = template.query(ONTOLOGY_MAPPINGS_BY_ONTOLOGY_NAME,
new Object[]{ontologyName},
new OntologyMappingMapper());
return (List<OntologyMapping>) results;
}
public List<OntologyMapping> getOntologyMappingsByExperimentAccession(
String experimentAccession) {
List results = template.query(ONTOLOGY_MAPPINGS_BY_EXPERIMENT_ACCESSION,
new Object[]{experimentAccession},
new OntologyMappingMapper());
return (List<OntologyMapping>) results;
}
public List<AtlasCount> getAtlasCountsByExperimentID(int experimentID) {
List results = template.query(ATLAS_COUNTS_BY_EXPERIMENTID,
new Object[]{experimentID},
new AtlasCountMapper());
return (List<AtlasCount>) results;
}
public List<Species> getAllSpecies() {
List results = template.query(SPECIES_ALL, new SpeciesMapper());
return (List<Species>) results;
}
public List<Property> getAllProperties() {
List results = template.query(PROPERTIES_ALL, new PropertyMapper());
return (List<Property>) results;
}
public Set<String> getAllGenePropertyNames() {
List results = template.query(GENEPROPERTY_ALL_NAMES, new RowMapper() {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
return resultSet.getString(1);
}
});
return new HashSet<String>(results);
}
public List<AtlasTableResult> getAtlasResults(int[] geneIds, int[] exptIds, int upOrDown, String[] efvs) {
NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("geneids", geneIds);
parameters.addValue("exptids", exptIds);
parameters.addValue("efvs", efvs);
List results;
if (upOrDown == 1) {
results = namedTemplate.query(ATLAS_RESULTS_UP_BY_EXPERIMENTID_GENEID_AND_EFV,
parameters,
new AtlasResultMapper());
}
else if (upOrDown == -1) {
results = namedTemplate.query(ATLAS_RESULTS_DOWN_BY_EXPERIMENTID_GENEID_AND_EFV,
parameters,
new AtlasResultMapper());
}
else {
results = namedTemplate.query(ATLAS_RESULTS_UPORDOWN_BY_EXPERIMENTID_GENEID_AND_EFV,
parameters,
new AtlasResultMapper());
}
return (List<AtlasTableResult>) results;
}
public AtlasStatistics getAtlasStatisticsByDataRelease(String dataRelease) {
// manually count all experiments/genes/assays
AtlasStatistics stats = new AtlasStatistics();
stats.setDataRelease(dataRelease);
stats.setExperimentCount(template.queryForInt(EXPERIMENTS_COUNT));
stats.setAssayCount(template.queryForInt(ASSAYS_COUNT));
stats.setGeneCount(template.queryForInt(GENES_COUNT));
stats.setNewExperimentCount(0);
stats.setPropertyValueCount(getPropertyValueCount());
return stats;
}
public Integer getBestDesignElementForExpressionProfile(int geneId, int experimentId, String ef) {
try {
return template.queryForInt(BEST_DESIGNELEMENTID_FOR_GENE, new Object[]{ef, experimentId, geneId});
}
catch (EmptyResultDataAccessException e) {
// no statistically best element found
return null;
}
}
/*
DAO write methods
*/
public void writeLoadDetails(final String accession,
final LoadStage loadStage,
final LoadStatus loadStatus) {
writeLoadDetails(accession, loadStage, loadStatus, LoadType.EXPERIMENT);
}
public void writeLoadDetails(final String accession,
final LoadStage loadStage,
final LoadStatus loadStatus,
final LoadType loadType) {
// execute this procedure...
/*
create or replace procedure load_progress(
experiment_accession varchar
,stage varchar --load, netcdf, similarity, ranking, searchindex
,status varchar --done, pending
)
*/
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.LOAD_PROGRESS")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("EXPERIMENT_ACCESSION")
.useInParameterNames("STAGE")
.useInParameterNames("STATUS")
.useInParameterNames("LOAD_TYPE")
.declareParameters(new SqlParameter("EXPERIMENT_ACCESSION", Types.VARCHAR))
.declareParameters(new SqlParameter("STAGE", Types.VARCHAR))
.declareParameters(new SqlParameter("STATUS", Types.VARCHAR))
.declareParameters(new SqlParameter("LOAD_TYPE", Types.VARCHAR));
// map parameters...
MapSqlParameterSource params = new MapSqlParameterSource()
.addValue("EXPERIMENT_ACCESSION", accession)
.addValue("STAGE", loadStage.toString().toLowerCase())
.addValue("STATUS", loadStatus.toString().toLowerCase())
.addValue("LOAD_TYPE", loadType.toString().toLowerCase());
log.debug("Invoking load_progress stored procedure with parameters (" + accession + ", " + loadStage + ", " +
loadStatus + ", " + loadType + ")");
procedure.execute(params);
log.debug("load_progress stored procedure completed");
}
/**
* Writes the given experiment to the database, using the default transaction strategy configured for the
* datasource.
*
* @param experiment the experiment to write
*/
public void writeExperiment(final Experiment experiment) {
// execute this procedure...
/*
PROCEDURE "A2_EXPERIMENTSET" (
TheAccession varchar2
,TheDescription varchar2
,ThePerformer varchar2
,TheLab varchar2
)
*/
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.A2_EXPERIMENTSET")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("THEACCESSION")
.useInParameterNames("THEDESCRIPTION")
.useInParameterNames("THEPERFORMER")
.useInParameterNames("THELAB")
.declareParameters(new SqlParameter("THEACCESSION", Types.VARCHAR))
.declareParameters(new SqlParameter("THEDESCRIPTION", Types.VARCHAR))
.declareParameters(new SqlParameter("THEPERFORMER", Types.VARCHAR))
.declareParameters(new SqlParameter("THELAB", Types.VARCHAR));
// map parameters...
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("THEACCESSION", experiment.getAccession())
.addValue("THEDESCRIPTION", experiment.getDescription())
.addValue("THEPERFORMER", experiment.getPerformer())
.addValue("THELAB", experiment.getLab());
procedure.execute(params);
}
/**
* Writes the given assay to the database, using the default transaction strategy configured for the datasource.
*
* @param assay the assay to write
*/
public void writeAssay(final Assay assay) {
// execute this procedure...
/*
PROCEDURE "A2_ASSAYSET" (
TheAccession varchar2
,TheExperimentAccession varchar2
,TheArrayDesignAccession varchar2
,TheProperties PropertyTable
,TheExpressionValues ExpressionValueTable
)
*/
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.A2_ASSAYSET")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("THEACCESSION")
.useInParameterNames("THEEXPERIMENTACCESSION")
.useInParameterNames("THEARRAYDESIGNACCESSION")
.useInParameterNames("THEPROPERTIES")
.useInParameterNames("THEEXPRESSIONVALUES")
.declareParameters(
new SqlParameter("THEACCESSION", Types.VARCHAR))
.declareParameters(
new SqlParameter("THEEXPERIMENTACCESSION", Types.VARCHAR))
.declareParameters(
new SqlParameter("THEARRAYDESIGNACCESSION", Types.VARCHAR))
.declareParameters(
new SqlParameter("THEPROPERTIES", OracleTypes.ARRAY, "PROPERTYTABLE"))
.declareParameters(
new SqlParameter("THEEXPRESSIONVALUES", OracleTypes.ARRAY, "EXPRESSIONVALUETABLE"));
// map parameters...
List<Property> props = assay.getProperties() == null
? new ArrayList<Property>()
: assay.getProperties();
Map<String, Float> evs = assay.getExpressionValuesByDesignElementReference() == null
? new HashMap<String, Float>()
: assay.getExpressionValuesByDesignElementReference();
MapSqlParameterSource params = new MapSqlParameterSource();
+ StringBuffer sb = new StringBuffer();
+ sb.append("Properties listing for ").append(assay.getAccession()).append(":\n");
+ for (Property p : props) {
+ sb.append("\t").append(p.getName()).append("\t\t->\t\t").append(p.getValue()).append("\n");
+ }
+ log.debug(sb.toString());
+
SqlTypeValue propertiesParam =
props.isEmpty() ? null :
convertPropertiesToOracleARRAY(props);
SqlTypeValue expressionValuesParam =
evs.isEmpty() ? null :
convertExpressionValuesToOracleARRAY(evs);
params.addValue("THEACCESSION", assay.getAccession())
.addValue("THEEXPERIMENTACCESSION", assay.getExperimentAccession())
.addValue("THEARRAYDESIGNACCESSION", assay.getArrayDesignAccession())
.addValue("THEPROPERTIES", propertiesParam, OracleTypes.ARRAY, "PROPERTYTABLE")
.addValue("THEEXPRESSIONVALUES", expressionValuesParam, OracleTypes.ARRAY, "EXPRESSIONVALUETABLE");
log.debug("Invoking A2_ASSAYSET with the following parameters..." +
"\n\tassay accession: {}" +
"\n\texperiment: {}" +
"\n\tarray design: {}" +
"\n\tproperties count: {}" +
"\n\texpression value count: {}",
new Object[]{assay.getAccession(), assay.getExperimentAccession(), assay.getArrayDesignAccession(),
props.size(), evs.size()});
// and execute
procedure.execute(params);
}
/**
* Writes the given sample to the database, using the default transaction strategy configured for the datasource.
*
* @param sample the sample to write
*/
public void writeSample(final Sample sample) {
// execute this procedure...
/*
PROCEDURE "A2_SAMPLESET" (
p_Accession varchar2
, p_Assays AccessionTable
, p_Properties PropertyTable
, p_Species varchar2
, p_Channel varchar2
)
*/
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.A2_SAMPLESET")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("P_ACCESSION")
.useInParameterNames("P_ASSAYS")
.useInParameterNames("P_PROPERTIES")
.useInParameterNames("P_SPECIES")
.useInParameterNames("P_CHANNEL")
.declareParameters(
new SqlParameter("P_ACCESSION", Types.VARCHAR))
.declareParameters(
new SqlParameter("P_ASSAYS", OracleTypes.ARRAY, "ACCESSIONTABLE"))
.declareParameters(
new SqlParameter("P_PROPERTIES", OracleTypes.ARRAY, "PROPERTYTABLE"))
.declareParameters(
new SqlParameter("P_SPECIES", Types.VARCHAR))
.declareParameters(
new SqlParameter("P_CHANNEL", Types.VARCHAR));
// map parameters...
MapSqlParameterSource params = new MapSqlParameterSource();
SqlTypeValue accessionsParam =
sample.getAssayAccessions() == null || sample.getAssayAccessions().isEmpty() ? null :
convertAssayAccessionsToOracleARRAY(sample.getAssayAccessions());
SqlTypeValue propertiesParam =
sample.getProperties() == null || sample.getProperties().isEmpty()
? null
: convertPropertiesToOracleARRAY(sample.getProperties());
params.addValue("P_ACCESSION", sample.getAccession())
.addValue("P_ASSAYS", accessionsParam, OracleTypes.ARRAY, "ACCESSIONTABLE")
.addValue("P_PROPERTIES", propertiesParam, OracleTypes.ARRAY, "PROPERTYTABLE")
.addValue("P_SPECIES", sample.getSpecies())
.addValue("P_CHANNEL", sample.getChannel());
int assayCount = sample.getAssayAccessions() == null ? 0 : sample.getAssayAccessions().size();
int propertiesCount = sample.getProperties() == null ? 0 : sample.getProperties().size();
log.debug("Invoking A2_SAMPLESET with the following parameters..." +
"\n\tsample accession: {}" +
"\n\tassays count: {}" +
"\n\tproperties count: {}" +
"\n\tspecies: {}" +
"\n\tchannel: {}",
new Object[]{sample.getAccession(), assayCount, propertiesCount, sample.getSpecies(),
sample.getChannel()});
// and execute
procedure.execute(params);
}
/**
* Writes expression analytics data back to the database, after post-processing by an external analytics process.
* Expression analytics consist of p-values and t-statistics for each design element, annotated with a property and
* property value. As such, for each annotated design element there should be unique analytics data for each
* annotation.
*
* @param experimentAccession the accession of the experiment these analytics values belong to
* @param property the name of the property for this set of analytics
* @param propertyValue the property value for this set of analytics
* @param designElements an array of ints, representing the design element ids for this analytics 'bundle'
* @param pValues an array of doubles, indexed in the same order as design elements, capturing the
* pValues in the context of this property/property value pair
* @param tStatistics an array of doubles, indexed in the same order as design elements, capturing the
* tStatistic (a double) in the context of this property/property value pair
*/
public void writeExpressionAnalytics(String experimentAccession,
String property,
String propertyValue,
int[] designElements,
double[] pValues,
double[] tStatistics) {
// execute this procedure...
/*
PROCEDURE A2_AnalyticsSet(
ExperimentAccession IN varchar2
,Property IN varchar2
,PropertyValue IN varchar2
,ExpressionAnalytics ExpressionAnalyticsTable
)
*/
log.debug("Starting writing analytics for [experiment: " + experimentAccession + "; " +
"Property: " + property + "; Property Value: " + propertyValue + "]");
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.A2_ANALYTICSSET")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("EXPERIMENTACCESSION")
.useInParameterNames("PROPERTY")
.useInParameterNames("PROPERTYVALUE")
.useInParameterNames("EXPRESSIONANALYTICS")
.declareParameters(
new SqlParameter("EXPERIMENTACCESSION", Types.VARCHAR))
.declareParameters(
new SqlParameter("PROPERTY", Types.VARCHAR))
.declareParameters(
new SqlParameter("PROPERTYVALUE", Types.VARCHAR))
.declareParameters(
new SqlParameter("EXPRESSIONANALYTICS", OracleTypes.ARRAY, "EXPRESSIONANALYTICSTABLE"));
// tracking variables for timings
long start, end;
String total;
// map parameters...
log.trace("Mapping parameters to oracle structures for [experiment: " + experimentAccession + "; " +
"Property: " + property + "; Property Value: " + propertyValue + "]");
start = System.currentTimeMillis();
MapSqlParameterSource params = new MapSqlParameterSource();
SqlTypeValue analyticsParam =
designElements == null || designElements.length == 0
? null
: convertExpressionAnalyticsToOracleARRAY(designElements, pValues, tStatistics);
params.addValue("EXPERIMENTACCESSION", experimentAccession)
.addValue("PROPERTY", property)
.addValue("PROPERTYVALUE", propertyValue)
.addValue("EXPRESSIONANALYTICS", analyticsParam);
end = System.currentTimeMillis();
total = new DecimalFormat("#.##").format((end - start) / 1000);
log.trace("Parameter mapping for [experiment: " + experimentAccession + "; " +
"Property: " + property + "; Property Value: " + propertyValue + "] complete in " + total + "s.");
log.trace("Executing procedure for [experiment: " + experimentAccession + "; " +
"Property: " + property + "; Property Value: " + propertyValue + "]");
start = System.currentTimeMillis();
procedure.execute(params);
end = System.currentTimeMillis();
total = new DecimalFormat("#.##").format((end - start) / 1000);
log.trace("Procedure execution for [experiment: " + experimentAccession + "; " +
"Property: " + property + "; Property Value: " + propertyValue + "] complete in " + total + "s.");
log.debug("Writing analytics for [experiment: " + experimentAccession + "; " +
"Property: " + property + "; Property Value: " + propertyValue + "] completed!");
}
/**
* Writes array designs and associated data back to the database.
*/
public void writeArrayDesign(final ArrayDesign arrayDesign) {
// execute this procedure...
/*
PROCEDURE A2_ARRAYDESIGNSET(
Accession varchar2
,Type varchar2
,Name varchar2
,Provider varchar2
,DesignElements DesignElementTable
);
*/
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.A2_ARRAYDESIGNSET")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("ACCESSION")
.useInParameterNames("TYPE")
.useInParameterNames("NAME")
.useInParameterNames("PROVIDER")
.useInParameterNames("DESIGNELEMENTS")
.declareParameters(
new SqlParameter("ACCESSION", Types.VARCHAR))
.declareParameters(
new SqlParameter("TYPE", Types.VARCHAR))
.declareParameters(
new SqlParameter("NAME", Types.VARCHAR))
.declareParameters(
new SqlParameter("PROVIDER", Types.VARCHAR))
.declareParameters(
new SqlParameter("DESIGNELEMENTS", OracleTypes.ARRAY, "DESIGNELEMENTTABLE"));
SqlTypeValue designElementsParam =
arrayDesign.getDesignElements().isEmpty() ? null :
convertDesignElementsToOracleARRAY(arrayDesign.getDesignElements());
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("ACCESSION", arrayDesign.getAccession())
.addValue("TYPE", arrayDesign.getType())
.addValue("NAME", arrayDesign.getName())
.addValue("PROVIDER", arrayDesign.getProvider())
.addValue("DESIGNELEMENTS", designElementsParam, OracleTypes.ARRAY, "DESIGNELEMENTTABLE");
procedure.execute(params);
}
/*
DAO delete methods
*/
/**
* Deletes the experiment with the given accession from the database. If this experiment is not present, this does
* nothing.
*
* @param experimentAccession the accession of the experiment to remove
*/
public void deleteExperiment(final String experimentAccession) {
// execute this procedure...
/*
PROCEDURE A2_EXPERIMENTDELETE(
Accession varchar2
)
*/
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.A2_EXPERIMENTDELETE")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("ACCESSION")
.declareParameters(new SqlParameter("THEACCESSION", Types.VARCHAR));
// map parameters...
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("THEACCESSION", experimentAccession);
procedure.execute(params);
}
public void deleteExpressionAnalytics(String experimentAccession) {
// execute this procedure...
/*
PROCEDURE A2_ANALYTICSDELETE(
ExperimentAccession varchar2
)
*/
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.A2_ANALYTICSDELETE")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("EXPERIMENTACCESSION")
.declareParameters(new SqlParameter("EXPERIMENTACCESSION", Types.VARCHAR));
// map parameters...
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("EXPERIMENTACCESSION", experimentAccession);
// tracking variables for timings
long start, end;
String total;
log.trace("Executing procedure to delete analytics for experiment: " + experimentAccession);
start = System.currentTimeMillis();
procedure.execute(params);
end = System.currentTimeMillis();
total = new DecimalFormat("#.##").format((end - start) / 1000);
log.trace("Procedure execution to delete analytics for experiment: " + experimentAccession +
" complete in " + total + "s.");
}
/*
utils methods for doing standard stuff
*/
public void startExpressionAnalytics(String experimentAccession) {
// execute the startup analytics procedure...
/*
PROCEDURE A2_AnalyticsSetBegin(
ExperimentAccession IN varchar2
)
*/
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.A2_ANALYTICSSETBEGIN")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("EXPERIMENTACCESSION")
.declareParameters(new SqlParameter("EXPERIMENTACCESSION", Types.VARCHAR));
// map single param
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("EXPERIMENTACCESSION", experimentAccession);
// and execute
procedure.execute(params);
}
public void finaliseExpressionAnalytics(String experimentAccession) {
// execute the ending analytics procedure...
/*
PROCEDURE A2_AnalyticsSetEnd(
ExperimentAccession IN varchar2
)
*/
SimpleJdbcCall procedure =
new SimpleJdbcCall(template)
.withProcedureName("ATLASLDR.A2_ANALYTICSSETEND")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("EXPERIMENTACCESSION")
.declareParameters(new SqlParameter("EXPERIMENTACCESSION", Types.VARCHAR));
// map single param
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("EXPERIMENTACCESSION", experimentAccession);
// and execute
procedure.execute(params);
}
private void fillOutArrayDesigns(List<ArrayDesign> arrayDesigns) {
// map array designs to array design id
Map<Integer, ArrayDesign> arrayDesignsByID = new HashMap<Integer, ArrayDesign>();
for (ArrayDesign array : arrayDesigns) {
// index this array
arrayDesignsByID.put(array.getArrayDesignID(), array);
// also initialize design elements is null - once this method is called, you should never get an NPE
if (array.getDesignElements() == null) {
array.setDesignElements(new HashMap<Integer, String>());
}
if (array.getGenes() == null) {
array.setGenes(new HashMap<Integer, List<Integer>>());
}
}
NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
// now query for design elements that map to one of these array designs
ArrayDesignElementMapper arrayDesignElementMapper = new ArrayDesignElementMapper(arrayDesignsByID);
MapSqlParameterSource arrayParams = new MapSqlParameterSource();
arrayParams.addValue("arraydesignids", arrayDesignsByID.keySet());
namedTemplate.query(DESIGN_ELEMENTS_AND_GENES_BY_RELATED_ARRAY, arrayParams, arrayDesignElementMapper);
}
private void fillOutGeneProperties(List<Gene> genes) {
// map genes to gene id
Map<Integer, Gene> genesByID = new HashMap<Integer, Gene>();
for (Gene gene : genes) {
// index this assay
genesByID.put(gene.getGeneID(), gene);
// also, initialize properties if null - once this method is called, you should never get an NPE
if (gene.getProperties() == null) {
gene.setProperties(new ArrayList<Property>());
}
}
// map of genes and their properties
GenePropertyMapper genePropertyMapper = new GenePropertyMapper(genesByID);
// query template for genes
NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
// if we have more than 'maxQueryParams' genes, split into smaller queries
List<Integer> geneIDs = new ArrayList<Integer>(genesByID.keySet());
boolean done = false;
int startpos = 0;
int endpos = maxQueryParams;
while (!done) {
List<Integer> geneIDsChunk;
if (endpos > geneIDs.size()) {
// we've reached the last segment, so query all of these
geneIDsChunk = geneIDs.subList(startpos, geneIDs.size());
done = true;
}
else {
// still more left - take next sublist and increment counts
geneIDsChunk = geneIDs.subList(startpos, endpos);
startpos = endpos;
endpos += maxQueryParams;
}
// now query for properties that map to one of these genes
MapSqlParameterSource propertyParams = new MapSqlParameterSource();
propertyParams.addValue("geneids", geneIDsChunk);
namedTemplate.query(PROPERTIES_BY_RELATED_GENES, propertyParams, genePropertyMapper);
}
}
private void fillOutAssays(List<Assay> assays) {
// map assays to assay id
Map<Integer, Assay> assaysByID = new HashMap<Integer, Assay>();
for (Assay assay : assays) {
// index this assay
assaysByID.put(assay.getAssayID(), assay);
// also, initialize properties if null - once this method is called, you should never get an NPE
if (assay.getProperties() == null) {
assay.setProperties(new ArrayList<Property>());
}
}
// maps properties to assays
AssayPropertyMapper assayPropertyMapper = new AssayPropertyMapper(assaysByID);
// query template for assays
NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
// if we have more than 'maxQueryParams' assays, split into smaller queries
List<Integer> assayIDs = new ArrayList<Integer>(assaysByID.keySet());
boolean done = false;
int startpos = 0;
int endpos = maxQueryParams;
while (!done) {
List<Integer> assayIDsChunk;
if (endpos > assayIDs.size()) {
// we've reached the last segment, so query all of these
assayIDsChunk = assayIDs.subList(startpos, assayIDs.size());
done = true;
}
else {
// still more left - take next sublist and increment counts
assayIDsChunk = assayIDs.subList(startpos, endpos);
startpos = endpos;
endpos += maxQueryParams;
}
// now query for properties that map to one of the samples in the sublist
MapSqlParameterSource propertyParams = new MapSqlParameterSource();
propertyParams.addValue("assayids", assayIDsChunk);
namedTemplate.query(PROPERTIES_BY_RELATED_ASSAYS, propertyParams, assayPropertyMapper);
}
}
private void fillOutSamples(List<Sample> samples) {
// map samples to sample id
Map<Integer, Sample> samplesByID = new HashMap<Integer, Sample>();
for (Sample sample : samples) {
samplesByID.put(sample.getSampleID(), sample);
// also, initialize properties/assays if null - once this method is called, you should never get an NPE
if (sample.getProperties() == null) {
sample.setProperties(new ArrayList<Property>());
}
if (sample.getAssayAccessions() == null) {
sample.setAssayAccessions(new ArrayList<String>());
}
}
// maps properties and assays to relevant sample
AssaySampleMapper assaySampleMapper = new AssaySampleMapper(samplesByID);
SamplePropertyMapper samplePropertyMapper = new SamplePropertyMapper(samplesByID);
// query template for samples
NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(template);
// if we have more than 'maxQueryParams' samples, split into smaller queries
List<Integer> sampleIDs = new ArrayList<Integer>(samplesByID.keySet());
boolean done = false;
int startpos = 0;
int endpos = maxQueryParams;
while (!done) {
List<Integer> sampleIDsChunk;
if (endpos > sampleIDs.size()) {
sampleIDsChunk = sampleIDs.subList(startpos, sampleIDs.size());
done = true;
}
else {
sampleIDsChunk = sampleIDs.subList(startpos, endpos);
startpos = endpos;
endpos += maxQueryParams;
}
// now query for assays that map to one of these samples
MapSqlParameterSource assayParams = new MapSqlParameterSource();
assayParams.addValue("sampleids", sampleIDsChunk);
namedTemplate.query(ASSAYS_BY_RELATED_SAMPLES, assayParams, assaySampleMapper);
// now query for properties that map to one of these samples
MapSqlParameterSource propertyParams = new MapSqlParameterSource();
propertyParams.addValue("sampleids", sampleIDsChunk);
namedTemplate.query(PROPERTIES_BY_RELATED_SAMPLES, propertyParams, samplePropertyMapper);
}
}
private SqlTypeValue convertPropertiesToOracleARRAY(final List<Property> properties) {
return new AbstractSqlTypeValue() {
protected Object createTypeValue(Connection connection, int sqlType, String typeName) throws SQLException {
// this should be creating an oracle ARRAY of properties
// the array of STRUCTS representing each property
Object[] propArrayValues;
if (properties != null && !properties.isEmpty()) {
propArrayValues = new Object[properties.size()];
// convert each property to an oracle STRUCT
int i = 0;
Object[] propStructValues = new Object[4];
for (Property property : properties) {
// array representing the values to go in the STRUCT
propStructValues[0] = property.getAccession();
propStructValues[1] = property.getName();
propStructValues[2] = property.getValue();
propStructValues[3] = property.isFactorValue();
// descriptor for PROPERTY type
StructDescriptor structDescriptor = StructDescriptor.createDescriptor("PROPERTY", connection);
// each array value is a new STRUCT
propArrayValues[i++] = new STRUCT(structDescriptor, connection, propStructValues);
}
// created the array of STRUCTs, group into ARRAY
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(typeName, connection);
return new ARRAY(arrayDescriptor, connection, propArrayValues);
}
else {
// throw an SQLException, as we cannot create a ARRAY with an empty array
throw new SQLException("Unable to create an ARRAY from an empty list of properties");
}
}
};
}
private SqlTypeValue convertExpressionValuesToOracleARRAY(final Map<String, Float> expressionValues) {
return new AbstractSqlTypeValue() {
protected Object createTypeValue(Connection connection, int sqlType, String typeName) throws SQLException {
// this should be creating an oracle ARRAY of expression values
// the array of STRUCTS representing each expression value
Object[] evArrayValues;
if (expressionValues != null && !expressionValues.isEmpty()) {
evArrayValues = new Object[expressionValues.size()];
// convert each property to an oracle STRUCT
// descriptor for EXPRESSIONVALUE type
StructDescriptor structDescriptor =
StructDescriptor.createDescriptor("EXPRESSIONVALUE", connection);
int i = 0;
Object[] evStructValues = new Object[2];
for (Map.Entry<String, Float> expressionValue : expressionValues.entrySet()) {
// array representing the values to go in the STRUCT
evStructValues[0] = expressionValue.getKey();
evStructValues[1] = expressionValue.getValue();
evArrayValues[i++] = new STRUCT(structDescriptor, connection, evStructValues);
}
// created the array of STRUCTs, group into ARRAY
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(typeName, connection);
return new ARRAY(arrayDescriptor, connection, evArrayValues);
}
else {
// throw an SQLException, as we cannot create a ARRAY with an empty array
throw new SQLException("Unable to create an ARRAY from an empty list of expression values");
}
}
};
}
private SqlTypeValue convertAssayAccessionsToOracleARRAY(final List<String> assayAccessions) {
return new AbstractSqlTypeValue() {
protected Object createTypeValue(Connection connection, int sqlType, String typeName) throws SQLException {
Object[] accessions;
if (assayAccessions != null && !assayAccessions.isEmpty()) {
accessions = new Object[assayAccessions.size()];
int i = 0;
for (String assayAccession : assayAccessions) {
accessions[i++] = assayAccession;
}
// created the array of STRUCTs, group into ARRAY
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(typeName, connection);
return new ARRAY(arrayDescriptor, connection, accessions);
}
else {
// throw an SQLException, as we cannot create a ARRAY with an empty array
throw new SQLException("Unable to create an ARRAY from an empty list of accessions");
}
}
};
}
private SqlTypeValue convertExpressionAnalyticsToOracleARRAY(final int[] designElements,
final double[] pValues,
final double[] tStatistics) {
if (designElements == null || pValues == null || tStatistics == null ||
designElements.length != pValues.length || pValues.length != tStatistics.length) {
throw new RuntimeException(
"Cannot store analytics - inconsistent design element counts for pValues and tStatistics");
}
else {
final int deCount = designElements.length;
return new AbstractSqlTypeValue() {
protected Object createTypeValue(Connection connection, int sqlType, String typeName)
throws SQLException {
// this should be creating an oracle ARRAY of 'expressionAnalytics'
// the array of STRUCTS representing each property
Object[] expressionAnalytics;
if (deCount != 0) {
expressionAnalytics = new Object[deCount];
// convert each expression analytic pair into an oracle STRUCT
// descriptor for EXPRESSIONANALYTICS type
StructDescriptor structDescriptor =
StructDescriptor.createDescriptor("EXPRESSIONANALYTICS", connection);
Object[] expressionAnalyticsValues = new Object[3];
for (int i = 0; i < designElements.length; i++) {
// array representing the values to go in the STRUCT
// Note the floatValue - EXPRESSIONANALYTICS structure assumes floats
expressionAnalyticsValues[0] = designElements[i];
expressionAnalyticsValues[1] = pValues[i];
expressionAnalyticsValues[2] = tStatistics[i];
expressionAnalytics[i] =
new STRUCT(structDescriptor, connection, expressionAnalyticsValues);
}
// created the array of STRUCTs, group into ARRAY
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(typeName, connection);
return new ARRAY(arrayDescriptor, connection, expressionAnalytics);
}
else {
// throw an SQLException, as we cannot create a ARRAY with an empty array
throw new SQLException("Unable to create an ARRAY from empty lists of expression analytics");
}
}
};
}
}
private SqlTypeValue convertDesignElementsToOracleARRAY(final Map<Integer, String> designElements) {
return new AbstractSqlTypeValue() {
protected Object createTypeValue(Connection connection, int sqlType, String typeName) throws SQLException {
// this should be creating an oracle ARRAY of expression values
// the array of STRUCTS representing each expression value
Object[] deArrayValues;
if (designElements != null && !designElements.isEmpty()) {
deArrayValues = new Object[designElements.size()];
// convert each property to an oracle STRUCT
// descriptor for DESIGNELEMENT type
StructDescriptor structDescriptor =
StructDescriptor.createDescriptor("DESIGNELEMENT", connection);
int i = 0;
Object[] deStructValues = new Object[2];
for (Map.Entry<Integer, String> designElement : designElements.entrySet()) {
// array representing the values to go in the STRUCT
deStructValues[0] = designElement.getKey();
deStructValues[1] = designElement.getValue();
deArrayValues[i++] = new STRUCT(structDescriptor, connection, deStructValues);
}
// created the array of STRUCTs, group into ARRAY
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor(typeName, connection);
return new ARRAY(arrayDescriptor, connection, deArrayValues);
}
else {
// throw an SQLException, as we cannot create a ARRAY with an empty array
throw new SQLException("Unable to create an ARRAY from an empty list of design elements");
}
}
};
}
private class LoadDetailsMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
LoadDetails details = new LoadDetails();
// accession, netcdf, similarity, ranking, searchindex
details.setAccession(resultSet.getString(1));
details.setStatus(resultSet.getString(2));
details.setNetCDF(resultSet.getString(3));
details.setSimilarity(resultSet.getString(4));
details.setRanking(resultSet.getString(5));
details.setSearchIndex(resultSet.getString(6));
details.setLoadType(resultSet.getString(7));
return details;
}
}
private class ExperimentMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Experiment experiment = new Experiment();
experiment.setAccession(resultSet.getString(1));
experiment.setDescription(resultSet.getString(2));
experiment.setPerformer(resultSet.getString(3));
experiment.setLab(resultSet.getString(4));
experiment.setExperimentID(resultSet.getInt(5));
return experiment;
}
}
private class GeneMapper implements RowMapper {
public Gene mapRow(ResultSet resultSet, int i) throws SQLException {
Gene gene = new Gene();
gene.setGeneID(resultSet.getInt(1));
gene.setIdentifier(resultSet.getString(2));
gene.setName(resultSet.getString(3));
gene.setSpecies(resultSet.getString(4));
return gene;
}
}
private class AssayMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Assay assay = new Assay();
assay.setAccession(resultSet.getString(1));
assay.setExperimentAccession(resultSet.getString(2));
assay.setArrayDesignAccession(resultSet.getString(3));
assay.setAssayID(resultSet.getInt(4));
return assay;
}
}
private class ExpressionValueMapper implements ResultSetExtractor {
public Object extractData(ResultSet resultSet)
throws SQLException, DataAccessException {
// maps assay ID (int) to a map of expression values - which is...
// a map of design element IDs (int) to expression value (float)
Map<Integer, Map<Integer, Float>> assayToEVs =
new HashMap<Integer, Map<Integer, Float>>();
while (resultSet.next()) {
// get assay ID key
int assayID = resultSet.getInt(1);
// get design element id key
int designElementID = resultSet.getInt(2);
// get expression value
float value = resultSet.getFloat(3);
// check assay key - can we add new expression value to existing map?
if (!assayToEVs.containsKey(assayID)) {
// if not, create a new expression values maps
assayToEVs.put(assayID, new HashMap<Integer, Float>());
}
// insert the expression value map into the assay-linked map
assayToEVs.get(assayID).put(designElementID, value);
}
return assayToEVs;
}
}
private class AssayExpressionValueMapper implements RowMapper {
private Map<Integer, Assay> assaysByID;
public AssayExpressionValueMapper(Map<Integer, Assay> assaysByID) {
this.assaysByID = assaysByID;
}
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
// get assay ID key
int assayID = resultSet.getInt(1);
// get design element id key
int designElementID = resultSet.getInt(2);
// get expression value
float value = resultSet.getFloat(3);
assaysByID.get(assayID).getExpressionValues().put(designElementID, value);
return null;
}
}
private class SampleMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Sample sample = new Sample();
sample.setAccession(resultSet.getString(1));
sample.setSpecies(resultSet.getString(2));
sample.setChannel(resultSet.getString(3));
sample.setSampleID(resultSet.getInt(4));
return sample;
}
}
private class AssaySampleMapper implements RowMapper {
Map<Integer, Sample> samplesMap;
public AssaySampleMapper(Map<Integer, Sample> samplesMap) {
this.samplesMap = samplesMap;
}
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
int sampleID = resultSet.getInt(1);
samplesMap.get(sampleID).addAssayAccession(resultSet.getString(2));
return null;
}
}
private class ArrayDesignMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i)
throws SQLException {
ArrayDesign array = new ArrayDesign();
array.setAccession(resultSet.getString(1));
array.setType(resultSet.getString(2));
array.setName(resultSet.getString(3));
array.setProvider(resultSet.getString(4));
array.setArrayDesignID(resultSet.getInt(5));
return array;
}
}
private class DesignElementMapper implements ResultSetExtractor {
public Object extractData(ResultSet resultSet)
throws SQLException, DataAccessException {
Map<Integer, String> designElements = new HashMap<Integer, String>();
while (resultSet.next()) {
designElements.put(resultSet.getInt(1), resultSet.getString(2));
}
return designElements;
}
}
private class ExpressionAnalyticsMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
ExpressionAnalysis ea = new ExpressionAnalysis();
ea.setEfName(resultSet.getString(1));
ea.setEfvName(resultSet.getString(2));
ea.setExperimentID(resultSet.getInt(3));
ea.setDesignElementID(resultSet.getInt(4));
ea.setTStatistic(resultSet.getDouble(5));
ea.setPValAdjusted(resultSet.getDouble(6));
ea.setEfId(resultSet.getInt(7));
ea.setEfvId(resultSet.getInt(8));
return ea;
}
}
private class OntologyMappingMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
OntologyMapping mapping = new OntologyMapping();
mapping.setExperimentAccession(resultSet.getString(1));
mapping.setProperty(resultSet.getString(2));
mapping.setPropertyValue(resultSet.getString(3));
mapping.setOntologyTerm(resultSet.getString(4));
mapping.setSampleProperty(resultSet.getBoolean(5));
mapping.setAssayProperty(resultSet.getBoolean(6));
mapping.setFactorValue(resultSet.getBoolean(7));
mapping.setExperimentId(resultSet.getLong(8));
return mapping;
}
}
private class ArrayDesignElementMapper implements RowMapper {
private Map<Integer, ArrayDesign> arrayByID;
public ArrayDesignElementMapper(Map<Integer, ArrayDesign> arraysByID) {
this.arrayByID = arraysByID;
}
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
int assayID = resultSet.getInt(1);
Integer id = resultSet.getInt(2);
String acc = resultSet.getString(3);
Integer geneId = resultSet.getInt(4);
ArrayDesign ad = arrayByID.get(assayID);
ad.getDesignElements().put(id, acc);
ad.getGenes().put(id, Collections.singletonList(geneId)); // TODO: as of today, we have one gene per de
return null;
}
}
private class AssayPropertyMapper implements RowMapper {
private Map<Integer, Assay> assaysByID;
public AssayPropertyMapper(Map<Integer, Assay> assaysByID) {
this.assaysByID = assaysByID;
}
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Property property = new Property();
int assayID = resultSet.getInt(1);
property.setName(resultSet.getString(2));
property.setValue(resultSet.getString(3));
property.setFactorValue(resultSet.getBoolean(4));
assaysByID.get(assayID).addProperty(property);
return property;
}
}
private class SamplePropertyMapper implements RowMapper {
private Map<Integer, Sample> samplesByID;
public SamplePropertyMapper(Map<Integer, Sample> samplesByID) {
this.samplesByID = samplesByID;
}
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Property property = new Property();
int sampleID = resultSet.getInt(1);
property.setName(resultSet.getString(2));
property.setValue(resultSet.getString(3));
property.setFactorValue(resultSet.getBoolean(4));
samplesByID.get(sampleID).addProperty(property);
return property;
}
}
private class GenePropertyMapper implements RowMapper {
private Map<Integer, Gene> genesByID;
public GenePropertyMapper(Map<Integer, Gene> genesByID) {
this.genesByID = genesByID;
}
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Property property = new Property();
int geneID = resultSet.getInt(1);
property.setName(resultSet.getString(2));
property.setValue(resultSet.getString(3));
property.setFactorValue(false);
genesByID.get(geneID).addProperty(property);
return property;
}
}
private class GeneDesignElementMapper implements RowMapper {
private Map<Integer, Gene> genesByID;
public GeneDesignElementMapper(Map<Integer, Gene> genesByID) {
this.genesByID = genesByID;
}
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
int geneID = resultSet.getInt(1);
int designElementID = resultSet.getInt(2);
genesByID.get(geneID).getDesignElementIDs().add(designElementID);
return designElementID;
}
}
// todo - AtlasCount and AtlasResult can probably be consolidated to link a collection of genes to atlas results
private class AtlasCountMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
AtlasCount atlasCount = new AtlasCount();
atlasCount.setProperty(resultSet.getString(2));
atlasCount.setPropertyValue(resultSet.getString(3));
atlasCount.setUpOrDown(resultSet.getString(4));
atlasCount.setGeneCount(resultSet.getInt(6));
atlasCount.setPropertyId(resultSet.getInt(7));
atlasCount.setPropertyValueId(resultSet.getInt(8));
return atlasCount;
}
}
private class AtlasResultMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
AtlasTableResult atlasTableResult = new AtlasTableResult();
atlasTableResult.setExperimentID(resultSet.getInt(1));
atlasTableResult.setGeneID(resultSet.getInt(2));
atlasTableResult.setProperty(resultSet.getString(3));
atlasTableResult.setPropertyValue(resultSet.getString(4));
atlasTableResult.setUpOrDown(resultSet.getString(5));
atlasTableResult.setPValAdj(resultSet.getDouble(6));
return atlasTableResult;
}
}
private static class SpeciesMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
return new Species(resultSet.getInt(1), resultSet.getString(2));
}
}
private static class PropertyMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Property property = new Property();
property.setPropertyId(resultSet.getInt(1));
property.setAccession(resultSet.getString(2));
property.setName(resultSet.getString(2));
property.setPropertyValueId(resultSet.getInt(3));
property.setValue(resultSet.getString(4));
property.setFactorValue(resultSet.getInt(5) > 0);
return property;
}
}
//AZ:to be moved to model
public static class ExpressionValueMatrix {
public static class ExpressionValue {
//can I just leave it here without get/set methods?
public int assayID;
public int designElementID;
public double value;
public ExpressionValue(int assayID, int designElementID, float value) {
this.assayID = assayID;
this.designElementID = designElementID;
this.value = value;
}
}
public static class DesignElement {
public int designElementID;
public int geneID;
public DesignElement(int designElementID, int geneID) {
this.designElementID = designElementID;
this.geneID = geneID;
}
}
public List<ExpressionValue> expressionValues;
public List<DesignElement> designElements;
public List<Integer> assays;
public ExpressionValueMatrix() {
expressionValues = new ArrayList<ExpressionValue>();
designElements = new ArrayList<DesignElement>();
assays = new ArrayList<Integer>();
}
}
public class AssayRowMapper implements ParameterizedRowMapper<Integer> {
public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getInt("AssayID");
}
}
public class DesignElementRowMapper implements ParameterizedRowMapper<ExpressionValueMatrix.DesignElement> {
public ExpressionValueMatrix.DesignElement mapRow(ResultSet rs, int rowNum) throws SQLException {
return new ExpressionValueMatrix.DesignElement(rs.getInt("DesignElementID")
, rs.getInt("GeneID"));
}
}
public class ExpressionValueRowMapper implements ParameterizedRowMapper<ExpressionValueMatrix.ExpressionValue> {
public ExpressionValueMatrix.ExpressionValue mapRow(ResultSet rs, int rowNum) throws SQLException {
return new ExpressionValueMatrix.ExpressionValue(rs.getInt("AssayID")
, rs.getInt("DesignElementID")
, rs.getFloat("Value"));
}
}
public ExpressionValueMatrix getExpressionValueMatrix(int ExperimentID, int ArrayDesignID) {
ExpressionValueMatrix result = new ExpressionValueMatrix();
SimpleJdbcCall procedure1 =
new SimpleJdbcCall(template)
.withProcedureName("ATLASAPI.A2_EXPRESSIONVALUEGET")
.withoutProcedureColumnMetaDataAccess()
.useInParameterNames("EXPERIMENTID")
.useInParameterNames("ARRAYDESIGNID")
.declareParameters(new SqlParameter("EXPERIMENTID", Types.INTEGER))
.declareParameters(new SqlParameter("ARRAYDESIGNID", Types.INTEGER))
.returningResultSet("ASSAYS", new AssayRowMapper())
.returningResultSet("DESIGNELEMENTS", new DesignElementRowMapper())
.returningResultSet("EXPRESSIONVALUES", new ExpressionValueRowMapper());
// map parameters...
MapSqlParameterSource params1 = new MapSqlParameterSource()
.addValue("EXPERIMENTID", ExperimentID)
.addValue("ARRAYDESIGNID", ArrayDesignID);
Map<String, Object> proc_result = procedure1.execute(params1);
result.assays = (List<Integer>) proc_result.get("ASSAYS");
result.designElements = (List<ExpressionValueMatrix.DesignElement>) proc_result.get("DESIGNELEMENTS");
result.expressionValues = (List<ExpressionValueMatrix.ExpressionValue>) proc_result.get("EXPRESSIONVALUES");
return result;
}
}
diff --git a/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/utils/SDRFWritingUtils.java b/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/utils/SDRFWritingUtils.java
index 0b137aed3..8077aa30d 100644
--- a/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/utils/SDRFWritingUtils.java
+++ b/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/utils/SDRFWritingUtils.java
@@ -1,247 +1,247 @@
package uk.ac.ebi.gxa.loader.utils;
import org.mged.magetab.error.ErrorItem;
import org.mged.magetab.error.ErrorItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.MAGETABInvestigation;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.SDRF;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.AssayNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.HybridizationNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.SDRFNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.SourceNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.CharacteristicsAttribute;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.FactorValueAttribute;
import uk.ac.ebi.arrayexpress2.magetab.exception.ObjectConversionException;
import uk.ac.ebi.microarray.atlas.model.Assay;
import uk.ac.ebi.microarray.atlas.model.Property;
import uk.ac.ebi.microarray.atlas.model.Sample;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* A class filled with handy convenience methods for performing writing tasks common to lots of SDRF graph nodes. This
* class contains methods that hepl with writing {@link Property} objects out given some nodes in the SDRF graph.
*
* @author Tony Burdett
* @date 28-Aug-2009
*/
public class SDRFWritingUtils {
private static Logger log = LoggerFactory.getLogger(SDRFWritingUtils.class);
/**
* Write out the properties associated with a {@link Sample} in the SDRF graph. These properties are obtained by
* looking at the "characteristic" column in the SDRF graph, extracting the type and linking this type (the
* property) to the name of the {@link SourceNode} provided (the property value).
*
* @param investigation the investigation being loaded
* @param sample the sample you want to attach properties to
* @param sourceNode the sourceNode being read
* @throws ObjectConversionException if there is a problem creating the property object
*/
public static void writeSampleProperties(
MAGETABInvestigation investigation,
Sample sample,
SourceNode sourceNode)
throws ObjectConversionException {
// fetch characteristics of this sourceNode
for (CharacteristicsAttribute characteristicsAttribute : sourceNode.characteristics) {
// create Property for this attribute
if (characteristicsAttribute.type.contains("||") || characteristicsAttribute.getNodeName().contains("||")) {
// generate error item and throw exception
String message = "Characteristics and their values must NOT contain '||' - " +
"this is a special reserved character used as a delimiter in the database";
ErrorItem error = ErrorItemFactory.getErrorItemFactory(SDRFWritingUtils.class.getClassLoader())
.generateErrorItem(message, 999, SDRFWritingUtils.class);
throw new ObjectConversionException(error, true);
}
// does this sample already contain this property/property value pair?
boolean existing = false;
if (sample.getProperties() != null) {
for (Property sp : sample.getProperties()) {
if (sp.getName().equals(characteristicsAttribute.type)) {
if (sp.getValue().equals(characteristicsAttribute.getNodeName())) {
existing = true;
break;
}
else {
// generate error item and throw exception
String message = "Inconsistent characteristic values for sample " + sample.getAccession() +
": property " + sp.getName() + " has values " + sp.getValue() + " and " +
characteristicsAttribute.getNodeName() + " in different rows. Second value (" +
characteristicsAttribute + ") will be ignored";
ErrorItem error =
ErrorItemFactory.getErrorItemFactory(SDRFWritingUtils.class.getClassLoader())
.generateErrorItem(message, 40, SDRFWritingUtils.class);
throw new ObjectConversionException(error, false);
}
}
}
}
if (!existing) {
Property p = new Property();
p.setAccession(AtlasLoaderUtils.getNodeAccession(
investigation, characteristicsAttribute));
p.setName(characteristicsAttribute.type);
p.setValue(characteristicsAttribute.getNodeName());
p.setFactorValue(false);
sample.addProperty(p);
// todo - characteristics can have ontology entries, and units (which can also have ontology entries) - set these values
}
}
}
/**
* Write out the properties associated with an {@link Assay} in the SDRF graph. These properties are obtained by
* looking at the "factorvalue" column in the SDRF graph, extracting the type and linking this type (the property)
* to the name of the {@link uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.AssayNode} provided (the property
* value).
*
* @param investigation the investigation being loaded
* @param assay the assay you want to attach properties to
* @param assayNode the assayNode being read
* @throws ObjectConversionException if there is a problem creating the property object
*/
public static void writeAssayProperties(
MAGETABInvestigation investigation,
Assay assay,
AssayNode assayNode)
throws ObjectConversionException {
// fetch factor values of this assayNode
for (FactorValueAttribute factorValueAttribute : assayNode.factorValues) {
// create Property for this attribute
if (factorValueAttribute.type.contains("||") || factorValueAttribute.getNodeName().contains("||")) {
// generate error item and throw exception
String message = "Factors and their values must NOT contain '||' - " +
"this is a special reserved character used as a delimiter in the database";
ErrorItem error = ErrorItemFactory.getErrorItemFactory(SDRFWritingUtils.class.getClassLoader())
.generateErrorItem(message, 999, SDRFWritingUtils.class);
throw new ObjectConversionException(error, true);
}
// does this assay already contain this property/property value pair?
boolean existing = false;
if (assay.getProperties() != null) {
for (Property ap : assay.getProperties()) {
if (ap.getName().equals(factorValueAttribute.type)) {
if (ap.getValue().equals(factorValueAttribute.getNodeName())) {
existing = true;
break;
}
else {
// generate error item and throw exception
String message = "Inconsistent characteristic values for assay " + assay.getAccession() +
": property " + ap.getName() + " has values " + ap.getValue() + " and " +
factorValueAttribute.getNodeName() + " in different rows. Second value (" +
factorValueAttribute + ") will be ignored";
ErrorItem error =
ErrorItemFactory.getErrorItemFactory(SDRFWritingUtils.class.getClassLoader())
.generateErrorItem(message, 40, SDRFWritingUtils.class);
throw new ObjectConversionException(error, false);
}
}
}
}
if (!existing) {
Property p = new Property();
p.setAccession(AtlasLoaderUtils.getNodeAccession(
investigation, factorValueAttribute));
p.setName(factorValueAttribute.type);
p.setValue(factorValueAttribute.getNodeName());
- p.setFactorValue(false);
+ p.setFactorValue(true);
assay.addProperty(p);
// todo - factor values can have ontology entries, set these values
}
}
}
/**
* Write out the properties associated with an {@link Assay} in the SDRF graph. These properties are obtained by
* looking at the "factorvalue" column in the SDRF graph, extracting the type and linking this type (the property)
* to the name of the {@link uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.HybridizationNode} provided (the
* property value).
*
* @param investigation the investigation being loaded
* @param assay the assay you want to attach properties to
* @param hybridizationNode the hybridizationNode being read
* @throws ObjectConversionException if there is a problem creating the property object
*/
public static void writeHybridizationProperties(MAGETABInvestigation investigation,
Assay assay,
HybridizationNode hybridizationNode)
throws ObjectConversionException {
// fetch factor values of this assayNode
for (FactorValueAttribute factorValueAttribute : hybridizationNode.factorValues) {
// create Property for this attribute
if (factorValueAttribute.type.contains("||") || factorValueAttribute.getNodeName().contains("||")) {
// generate error item and throw exception
String message = "Factors and their values must NOT contain '||' - " +
"this is a special reserved character used as a delimiter in the database";
ErrorItem error = ErrorItemFactory.getErrorItemFactory(SDRFWritingUtils.class.getClassLoader())
.generateErrorItem(message, 999, SDRFWritingUtils.class);
throw new ObjectConversionException(error, true);
}
// does this assay already contain this property/property value pair?
boolean existing = false;
if (assay.getProperties() != null) {
for (Property ap : assay.getProperties()) {
if (ap.getName().equals(factorValueAttribute.type)) {
if (ap.getValue().equals(factorValueAttribute.getNodeName())) {
existing = true;
break;
}
else {
// generate error item and throw exception
String message = "Inconsistent characteristic values for assay " + assay.getAccession() +
": property " + ap.getName() + " has values " + ap.getValue() + " and " +
factorValueAttribute.getNodeName() + " in different rows. Second value (" +
factorValueAttribute + ") will be ignored";
ErrorItem error =
ErrorItemFactory.getErrorItemFactory(SDRFWritingUtils.class.getClassLoader())
.generateErrorItem(message, 40, SDRFWritingUtils.class);
throw new ObjectConversionException(error, false);
}
}
}
}
if (!existing) {
Property p = new Property();
p.setAccession(AtlasLoaderUtils.getNodeAccession(
investigation, factorValueAttribute));
p.setName(factorValueAttribute.type);
p.setValue(factorValueAttribute.getNodeName());
- p.setFactorValue(false);
+ p.setFactorValue(true);
assay.addProperty(p);
// todo - factor values can have ontology entries, set these values
}
}
}
}
diff --git a/atlas-test/src/main/java/uk/ac/ebi/gxa/loader/LoaderDriver.java b/atlas-test/src/main/java/uk/ac/ebi/gxa/loader/LoaderDriver.java
index d7d197926..fad33f811 100644
--- a/atlas-test/src/main/java/uk/ac/ebi/gxa/loader/LoaderDriver.java
+++ b/atlas-test/src/main/java/uk/ac/ebi/gxa/loader/LoaderDriver.java
@@ -1,290 +1,290 @@
package uk.ac.ebi.gxa.loader;
import org.apache.solr.core.CoreContainer;
import org.slf4j.bridge.SLF4JBridgeHandler;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import uk.ac.ebi.gxa.analytics.generator.AnalyticsGenerator;
import uk.ac.ebi.gxa.analytics.generator.AnalyticsGeneratorException;
import uk.ac.ebi.gxa.index.builder.IndexBuilder;
import uk.ac.ebi.gxa.index.builder.IndexBuilderException;
import uk.ac.ebi.gxa.loader.listener.AtlasLoaderEvent;
import uk.ac.ebi.gxa.loader.listener.AtlasLoaderListener;
import uk.ac.ebi.gxa.netcdf.generator.NetCDFGenerator;
import uk.ac.ebi.gxa.netcdf.generator.NetCDFGeneratorException;
import uk.ac.ebi.gxa.netcdf.generator.listener.NetCDFGenerationEvent;
import uk.ac.ebi.gxa.netcdf.generator.listener.NetCDFGeneratorListener;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.logging.LogManager;
/**
* Javadocs go here!
*
* @author Tony Burdett
* @date 09-Sep-2009
*/
public class LoaderDriver {
public static void main(String[] args) {
// configure logging
try {
LogManager.getLogManager()
.readConfiguration(LoaderDriver.class.getClassLoader().getResourceAsStream("logging.properties"));
}
catch (Exception e) {
e.printStackTrace();
}
SLF4JBridgeHandler.install();
// load spring config
BeanFactory factory =
new ClassPathXmlApplicationContext("loaderContext.xml");
// loader
final AtlasLoader loader = (AtlasLoader) factory.getBean("atlasLoader");
// index
final IndexBuilder builder = (IndexBuilder) factory.getBean("indexBuilder");
// netcdfs
final NetCDFGenerator generator = (NetCDFGenerator) factory.getBean("netcdfGenerator");
// analytics
final AnalyticsGenerator analytics = (AnalyticsGenerator) factory.getBean("analyticsGenerator");
// solrIndex
final CoreContainer solrContainer = (CoreContainer) factory.getBean("solrContainer");
// run the loader
try {
- final URL url = URI.create("file:////Work/PFIZER/E-PFIZ-2.idf.txt").toURL();
+ final URL url = URI.create("file:///home/tburdett/Documents/MAGE-TAB/E-PFIZ-2/E-PFIZ-2.idf.txt").toURL();
final long indexStart = System.currentTimeMillis();
loader.loadExperiment(url, new AtlasLoaderListener() {
public void loadSuccess(AtlasLoaderEvent event) {
final long indexEnd = System.currentTimeMillis();
String total = new DecimalFormat("#.##").format(
(indexEnd - indexStart) / 60000);
System.out.println(
"Load completed successfully in " + total + " mins.");
try {
loader.shutdown();
}
catch (AtlasLoaderException e) {
e.printStackTrace();
}
}
public void loadError(AtlasLoaderEvent event) {
System.out.println("Load failed");
for (Throwable t : event.getErrors()) {
t.printStackTrace();
}
try {
loader.shutdown();
}
catch (AtlasLoaderException e) {
e.printStackTrace();
}
}
});
}
catch (MalformedURLException e) {
e.printStackTrace();
System.out.println("Load failed - inaccessible URL");
}
// in case we don't run loader
// try {
// loader.shutdown();
// }
// catch (AtlasLoaderException e) {
// e.printStackTrace();
// }
// run the index builder
// final long indexStart = System.currentTimeMillis();
// builder.buildIndex(new IndexBuilderListener() {
//
// public void buildSuccess(IndexBuilderEvent event) {
// final long indexEnd = System.currentTimeMillis();
//
// String total = new DecimalFormat("#.##").format(
// (indexEnd - indexStart) / 60000);
// System.out.println(
// "Index built successfully in " + total + " mins.");
//
// try {
// builder.shutdown();
// solrContainer.shutdown();
// }
// catch (IndexBuilderException e) {
// e.printStackTrace();
// }
// }
//
// public void buildError(IndexBuilderEvent event) {
// System.out.println("Index failed to build");
// for (Throwable t : event.getErrors()) {
// t.printStackTrace();
// }
//
//
// try {
// builder.shutdown();
// solrContainer.shutdown();
// }
// catch (IndexBuilderException e) {
// e.printStackTrace();
// }
// }
// });
// in case we don't run index
try {
builder.shutdown();
solrContainer.shutdown();
}
catch (IndexBuilderException e) {
e.printStackTrace();
}
// run the NetCDFGenerator
// final long netStart = System.currentTimeMillis();
// generator.generateNetCDFs(
// new NetCDFGeneratorListener() {
// public void buildSuccess(NetCDFGenerationEvent event) {
// final long netEnd = System.currentTimeMillis();
//
// String total = new DecimalFormat("#.##").format(
// (netEnd - netStart) / 60000);
// System.out.println(
// "NetCDFs generated successfully in " + total + " mins.");
//
// try {
// generator.shutdown();
// }
// catch (NetCDFGeneratorException e) {
// e.printStackTrace();
// }
// }
//
// public void buildError(NetCDFGenerationEvent event) {
// System.out.println("NetCDF Generation failed!");
// for (Throwable t : event.getErrors()) {
// t.printStackTrace();
// }
//
// try {
// generator.shutdown();
// }
// catch (NetCDFGeneratorException e) {
// e.printStackTrace();
// }
// }
// });
// iteratively invoke netcdf generator
// iterativelyInvokeNetCDFs(generator, 0, 5);
// in case we don't run netCDF generator
try {
generator.shutdown();
}
catch (NetCDFGeneratorException e) {
e.printStackTrace();
}
// run the analytics
// final long netStart = System.currentTimeMillis();
// analytics.generateAnalytics(
// new AnalyticsGeneratorListener() {
// public void buildSuccess(AnalyticsGenerationEvent event) {
// final long netEnd = System.currentTimeMillis();
//
// String total = new DecimalFormat("#.##").format(
// (netEnd - netStart) / 60000);
// System.out.println(
// "Analytics generated successfully in " + total + " mins.");
//
// try {
// analytics.shutdown();
// }
// catch (AnalyticsGeneratorException e) {
// e.printStackTrace();
// }
// }
//
// public void buildError(AnalyticsGenerationEvent event) {
// System.out.println("Analytics Generation failed!");
// for (Throwable t : event.getErrors()) {
// t.printStackTrace();
// }
//
// try {
// analytics.shutdown();
// }
// catch (AnalyticsGeneratorException e) {
// e.printStackTrace();
// }
// }
// });
// in case we don't run analytics
try {
analytics.shutdown();
}
catch (AnalyticsGeneratorException e) {
e.printStackTrace();
}
}
private static void iterativelyInvokeNetCDFs(final NetCDFGenerator generator,
final int iteration,
final int maxTimes) {
System.out.println("Invoking generator, iteration " + iteration);
// run the NetCDFGenerator
final long netStart = System.currentTimeMillis();
generator.generateNetCDFsForExperiment(
"E-TABM-199",
new NetCDFGeneratorListener() {
public void buildSuccess(NetCDFGenerationEvent event) {
int it = iteration + 1;
final long netEnd = System.currentTimeMillis();
String total = new DecimalFormat("#.##").format(
(netEnd - netStart) / 60000);
System.out.println(
"NetCDFs generated successfully in " + total + " mins.");
if (it <= maxTimes) {
iterativelyInvokeNetCDFs(generator, it, maxTimes);
}
else {
try {
generator.shutdown();
}
catch (NetCDFGeneratorException e) {
e.printStackTrace();
}
}
}
public void buildError(NetCDFGenerationEvent event) {
System.out.println("NetCDF Generation failed!");
for (Throwable t : event.getErrors()) {
t.printStackTrace();
try {
generator.shutdown();
}
catch (NetCDFGeneratorException e) {
e.printStackTrace();
}
}
}
});
}
}
| false | false | null | null |
diff --git a/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/FieldImpl.java b/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/FieldImpl.java
index 502cf0d9..5fefa045 100644
--- a/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/FieldImpl.java
+++ b/plugins/org.eclipse.m2m.atl.emftvm/src/org/eclipse/m2m/atl/emftvm/impl/FieldImpl.java
@@ -1,594 +1,586 @@
/*******************************************************************************
* Copyright (c) 2011-2012 Dennis Wagelaar, Vrije Universiteit Brussel.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Dennis Wagelaar, Vrije Universiteit Brussel - initial API and
* implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.m2m.atl.emftvm.impl;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.m2m.atl.emftvm.CodeBlock;
import org.eclipse.m2m.atl.emftvm.EmftvmPackage;
import org.eclipse.m2m.atl.emftvm.Field;
import org.eclipse.m2m.atl.emftvm.Rule;
import org.eclipse.m2m.atl.emftvm.util.LazyCollection;
import org.eclipse.m2m.atl.emftvm.util.StackFrame;
import org.eclipse.m2m.atl.emftvm.util.VMException;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Field</b></em>'.
* @author <a href="mailto:[email protected]">Dennis Wagelaar</a>
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.m2m.atl.emftvm.impl.FieldImpl#getStaticValue <em>Static Value</em>}</li>
* <li>{@link org.eclipse.m2m.atl.emftvm.impl.FieldImpl#getInitialiser <em>Initialiser</em>}</li>
* <li>{@link org.eclipse.m2m.atl.emftvm.impl.FieldImpl#getRule <em>Rule</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class FieldImpl extends FeatureImpl implements Field {
/**
* The default value of the '{@link #getStaticValue() <em>Static Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStaticValue()
* @generated
* @ordered
*/
protected static final Object STATIC_VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getStaticValue() <em>Static Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStaticValue()
* @generated
* @ordered
*/
protected Object staticValue = STATIC_VALUE_EDEFAULT;
/**
* The cached value of the '{@link #getInitialiser() <em>Initialiser</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getInitialiser()
* @generated
* @ordered
*/
protected CodeBlock initialiser;
/**
* Map of instance values.
*/
protected final Map<Object, Object> values = new HashMap<Object, Object>();
/**
* Flag that signifies whether this field's static value is initialised.
*/
protected boolean staticValueInitialised;
/**
* <!-- begin-user-doc -->
* Creates a new {@link FieldImpl}.
* <!-- end-user-doc -->
* @generated
*/
protected FieldImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* Returns the {@link EClass} that correspond to this metaclass.
* @return the {@link EClass} that correspond to this metaclass.
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return EmftvmPackage.Literals.FIELD;
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
public Object getStaticValue() {
return staticValue;
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
public void setStaticValue(Object newStaticValue) {
Object oldStaticValue = staticValue;
staticValue = newStaticValue;
staticValueInitialised = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.FIELD__STATIC_VALUE, oldStaticValue, staticValue));
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
public CodeBlock getInitialiser() {
return initialiser;
}
/**
* <!-- begin-user-doc. -->
* @see #setInitialiser(CodeBlock)
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetInitialiser(CodeBlock newInitialiser, NotificationChain msgs) {
CodeBlock oldInitialiser = initialiser;
initialiser = newInitialiser;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, EmftvmPackage.FIELD__INITIALISER, oldInitialiser, newInitialiser);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
public void setInitialiser(CodeBlock newInitialiser) {
if (newInitialiser != initialiser) {
NotificationChain msgs = null;
if (initialiser != null)
msgs = ((InternalEObject)initialiser).eInverseRemove(this, EmftvmPackage.CODE_BLOCK__INITIALISER_FOR, CodeBlock.class, msgs);
if (newInitialiser != null)
msgs = ((InternalEObject)newInitialiser).eInverseAdd(this, EmftvmPackage.CODE_BLOCK__INITIALISER_FOR, CodeBlock.class, msgs);
msgs = basicSetInitialiser(newInitialiser, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.FIELD__INITIALISER, newInitialiser, newInitialiser));
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
public Rule getRule() {
if (eContainerFeatureID() != EmftvmPackage.FIELD__RULE) return null;
return (Rule)eInternalContainer();
}
/**
* <!-- begin-user-doc. -->
* @see #setRule(Rule)
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetRule(Rule newRule, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newRule, EmftvmPackage.FIELD__RULE, msgs);
return msgs;
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
public void setRule(Rule newRule) {
if (newRule != eInternalContainer() || (eContainerFeatureID() != EmftvmPackage.FIELD__RULE && newRule != null)) {
if (EcoreUtil.isAncestor(this, newRule))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newRule != null)
msgs = ((InternalEObject)newRule).eInverseAdd(this, EmftvmPackage.RULE__FIELDS, Rule.class, msgs);
msgs = basicSetRule(newRule, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, EmftvmPackage.FIELD__RULE, newRule, newRule));
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
*/
public Object getValue(final Object context) {
return values.get(context==null ? Void.TYPE : context);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
*/
public void setValue(final Object context, final Object value) {
values.put(context==null ? Void.TYPE : context, value);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
*/
public Object getValue(final Object context, final StackFrame frame) {
if (!values.containsKey(context==null ? Void.TYPE : context)) {
checkFrame(context, frame);
final CodeBlock cb = getInitialiser();
setValue(context, cb.execute(frame.getSubFrame(cb, context)));
}
return getValue(context);
}
/**
* Checks <pre>frame</pre> for execution loop in initialiser code block.
* @param context the 'self' object of the stack frame
* @param frame the stack frame to check
*/
private void checkFrame(final Object context, final StackFrame frame) {
final CodeBlock initCb = getInitialiser();
StackFrame newFrame = frame;
while (newFrame != null) {
if (newFrame.getCodeBlock() == initCb) {
if (newFrame.getLocal(0, 0) == context) {
throw new VMException(newFrame, String.format(
"Infinite loop detected in field initialiser for %s.%s",
context, this));
}
}
newFrame = newFrame.getParent();
}
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
*/
public Object getStaticValue(final StackFrame frame) {
if (!staticValueInitialised) {
checkStaticFrame(frame);
final CodeBlock cb = getInitialiser();
setStaticValue(cb.execute(new StackFrame(frame, cb)));
staticValueInitialised = true;
}
return getStaticValue();
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
*/
public void clear() {
staticValueInitialised = false;
staticValue = null;
values.clear();
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
@SuppressWarnings("unchecked")
public void addValue(final Object context, final Object value, final int index, final StackFrame frame) {
final Object currentVal = getValue(context, frame);
if (currentVal instanceof Collection<?>) {
if (currentVal instanceof List<?>) {
if (currentVal instanceof LazyCollection<?>) {
if (value instanceof Collection<?>) {
addValue(context, (Collection<Object>) value, index, (LazyCollection<Object>) currentVal);
} else {
addValue(context, value, index, (LazyCollection<Object>) currentVal);
}
} else {
if (value instanceof Collection<?>) {
if (index > -1) {
((List<Object>) currentVal).addAll(index, (Collection<?>) value);
} else {
((List<Object>) currentVal).addAll((Collection<?>) value);
}
} else {
if (index > -1) {
((List<Object>) currentVal).add(index, value);
} else {
((List<Object>) currentVal).add(value);
}
}
}
} else {
if (index > -1) {
throw new IllegalArgumentException(String.format(
"Cannot specify index for adding values to unordered collection field %s.%s", context, this));
}
if (currentVal instanceof LazyCollection<?>) {
if (value instanceof Collection<?>) {
addValue(context, (Collection<Object>) value, (LazyCollection<Object>) currentVal);
} else {
addValue(context, value, (LazyCollection<Object>) currentVal);
}
} else {
if (value instanceof Collection<?>) {
((Collection<Object>) currentVal).addAll((Collection<?>) value);
} else {
((Collection<Object>) currentVal).add(value);
}
}
}
} else {
if (currentVal != null) {
throw new IllegalArgumentException(String.format("Cannot add more than one value to %s.%s", context, this));
}
if (index > 0) {
throw new IndexOutOfBoundsException(String.valueOf(index));
}
setValue(context, value);
}
}
private <T> void addValue(final Object context, final Collection<T> value, final int index, final LazyCollection<T> currentVal) {
setValue(context, currentVal.includingAll(value, index + 1));
}
private <T> void addValue(final Object context, final T value, final int index, final LazyCollection<T> currentVal) {
setValue(context, currentVal.including(value, index + 1));
}
private <T> void addValue(final Object context, final Collection<T> value, final LazyCollection<T> currentVal) {
setValue(context, currentVal.includingAll(value));
}
private <T> void addValue(final Object context, final T value, final LazyCollection<T> currentVal) {
setValue(context, currentVal.including(value));
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
@SuppressWarnings("unchecked")
public void removeValue(final Object context, final Object value, final StackFrame frame) {
final Object currentVal = getValue(context, frame);
if (currentVal instanceof Collection<?>) {
if (currentVal instanceof LazyCollection<?>) {
if (value instanceof Collection<?>) {
removeValue(context, (Collection<Object>) value, (LazyCollection<Object>) currentVal);
} else {
removeValue(context, value, (LazyCollection<Object>) currentVal);
}
} else {
if (value instanceof Collection<?>) {
((Collection<Object>) currentVal).removeAll((Collection<?>) value);
} else {
((Collection<Object>) currentVal).remove(value);
}
}
} else {
if (currentVal != null && currentVal.equals(value)) {
// Do not actually remove the value, as this triggers the initialiser again on GET
setValue(context, null);
}
}
}
private <T> void removeValue(final Object context, final Collection<T> value, final LazyCollection<T> currentVal) {
setValue(context, currentVal.excludingAll(value));
}
private <T> void removeValue(final Object context, final T value, final LazyCollection<T> currentVal) {
setValue(context, currentVal.excluding(value));
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case EmftvmPackage.FIELD__INITIALISER:
if (initialiser != null)
msgs = ((InternalEObject)initialiser).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - EmftvmPackage.FIELD__INITIALISER, null, msgs);
return basicSetInitialiser((CodeBlock)otherEnd, msgs);
case EmftvmPackage.FIELD__RULE:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetRule((Rule)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case EmftvmPackage.FIELD__INITIALISER:
return basicSetInitialiser(null, msgs);
case EmftvmPackage.FIELD__RULE:
return basicSetRule(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case EmftvmPackage.FIELD__RULE:
return eInternalContainer().eInverseRemove(this, EmftvmPackage.RULE__FIELDS, Rule.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case EmftvmPackage.FIELD__STATIC_VALUE:
return getStaticValue();
case EmftvmPackage.FIELD__INITIALISER:
return getInitialiser();
case EmftvmPackage.FIELD__RULE:
return getRule();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case EmftvmPackage.FIELD__STATIC_VALUE:
setStaticValue(newValue);
return;
case EmftvmPackage.FIELD__INITIALISER:
setInitialiser((CodeBlock)newValue);
return;
case EmftvmPackage.FIELD__RULE:
setRule((Rule)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case EmftvmPackage.FIELD__STATIC_VALUE:
setStaticValue(STATIC_VALUE_EDEFAULT);
return;
case EmftvmPackage.FIELD__INITIALISER:
setInitialiser((CodeBlock)null);
return;
case EmftvmPackage.FIELD__RULE:
setRule((Rule)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case EmftvmPackage.FIELD__STATIC_VALUE:
return STATIC_VALUE_EDEFAULT == null ? staticValue != null : !STATIC_VALUE_EDEFAULT.equals(staticValue);
case EmftvmPackage.FIELD__INITIALISER:
return initialiser != null;
case EmftvmPackage.FIELD__RULE:
return getRule() != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc. -->
* {@inheritDoc}
* <!-- end-user-doc -->
* @generated NOT
*/
@Override
public String toString() {
- if (eIsProxy()) return super.toString();
-
- StringBuffer result = new StringBuffer(super.toString());
- if (isStatic()) {
- result.append(" (staticValue: ");
- result.append(staticValue);
- result.append(')');
- }
- return result.toString();
+ return super.toString();
}
/**
* Checks frame for execution loop in a static initialiser code block.
* @param frame the stack frame to check
*/
private void checkStaticFrame(final StackFrame frame) {
final CodeBlock initCb = getInitialiser();
StackFrame newFrame = frame;
while (newFrame != null) {
if (newFrame.getCodeBlock() == initCb) {
throw new VMException(newFrame, String.format(
"Infinite loop detected in field initialiser for %s",
this));
}
newFrame = newFrame.getParent();
}
}
} //FieldImpl
| true | false | null | null |
diff --git a/core/plugins/org.eclipse.dltk.debug.ui/src/org/eclipse/dltk/internal/debug/ui/handlers/DebuggingEngineNotConfiguredStatusHandler.java b/core/plugins/org.eclipse.dltk.debug.ui/src/org/eclipse/dltk/internal/debug/ui/handlers/DebuggingEngineNotConfiguredStatusHandler.java
index 6aef4902e..2e63e4d92 100644
--- a/core/plugins/org.eclipse.dltk.debug.ui/src/org/eclipse/dltk/internal/debug/ui/handlers/DebuggingEngineNotConfiguredStatusHandler.java
+++ b/core/plugins/org.eclipse.dltk.debug.ui/src/org/eclipse/dltk/internal/debug/ui/handlers/DebuggingEngineNotConfiguredStatusHandler.java
@@ -1,43 +1,45 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.internal.debug.ui.handlers;
import org.eclipse.dltk.launching.DebuggingEngineRunner;
import org.eclipse.dltk.launching.debug.IDebuggingEngine;
/**
* Debugging engine configuration problem that prevents debugging engine from
* starting
*
* @author kds
*
*/
public class DebuggingEngineNotConfiguredStatusHandler extends
AbstractOpenPreferencePageStatusHandler {
protected String getPreferencePageId(Object source) {
if (source instanceof DebuggingEngineRunner) {
final DebuggingEngineRunner runner = (DebuggingEngineRunner) source;
final IDebuggingEngine engine = runner.getDebuggingEngine();
- return engine.getPreferencePageId();
+ if (engine != null) {
+ return engine.getPreferencePageId();
+ }
}
return null;
}
public String getTitle() {
return HandlerMessages.DebuggingEngineNotConfiguredTitle;
}
protected String getQuestion() {
return HandlerMessages.DebuggingEngineNotConfiguredQuestion;
}
}
| true | true | protected String getPreferencePageId(Object source) {
if (source instanceof DebuggingEngineRunner) {
final DebuggingEngineRunner runner = (DebuggingEngineRunner) source;
final IDebuggingEngine engine = runner.getDebuggingEngine();
return engine.getPreferencePageId();
}
return null;
}
| protected String getPreferencePageId(Object source) {
if (source instanceof DebuggingEngineRunner) {
final DebuggingEngineRunner runner = (DebuggingEngineRunner) source;
final IDebuggingEngine engine = runner.getDebuggingEngine();
if (engine != null) {
return engine.getPreferencePageId();
}
}
return null;
}
|
diff --git a/org.eclipse.gmf.runtime.common.ui.services.properties/src/org/eclipse/gmf/runtime/common/ui/services/properties/extended/MultiButtonCellEditor.java b/org.eclipse.gmf.runtime.common.ui.services.properties/src/org/eclipse/gmf/runtime/common/ui/services/properties/extended/MultiButtonCellEditor.java
index 37754d2b..730a7ba8 100644
--- a/org.eclipse.gmf.runtime.common.ui.services.properties/src/org/eclipse/gmf/runtime/common/ui/services/properties/extended/MultiButtonCellEditor.java
+++ b/org.eclipse.gmf.runtime.common.ui.services.properties/src/org/eclipse/gmf/runtime/common/ui/services/properties/extended/MultiButtonCellEditor.java
@@ -1,340 +1,356 @@
/******************************************************************************
- * Copyright (c) 2004 IBM Corporation and others.
+ * Copyright (c) 2014 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
****************************************************************************/
package org.eclipse.gmf.runtime.common.ui.services.properties.extended;
import java.text.MessageFormat;
import java.util.ArrayList;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Text;
/**
* Cell editor that provides for a read-only label representation of the value
* and multiple buttons at the end. The last button receives the focus. The
* subclasses have to override the initButtons() method. The implementation of
* that method should only make calls to the method addButton() to initialize
* the desired buttons.
*
* @author dmisic
*/
public abstract class MultiButtonCellEditor
extends CellEditor {
/**
* The cell editor control itself
*/
private Composite editor;
/**
* Font used by all controls
*/
private Font font;
/**
* The label part of the editor
*/
private Control label;
/**
* Array of the editor's buttons
*/
private ArrayList buttonList;
/**
* The value of the cell editor; initially null
*/
private Object value = null;
/**
* Internal layout manager for multi button cell editors
*/
private class MultiButtonCellLayout
extends Layout {
/**
* @see org.eclipse.swt.widgets.Layout#computeSize(org.eclipse.swt.widgets.Composite,
* int, int, boolean)
*/
protected Point computeSize(Composite composite, int wHint, int hHint,
boolean flushCache) {
// check the hints
if (wHint != SWT.DEFAULT && hHint != SWT.DEFAULT) {
return new Point(wHint, hHint);
}
// calculate size of the buttons area
int height = 0;
int sumWidth = 0;
int count = buttonList.size();
for (int i = 0; i < count; i++) {
Point size = ((Button) buttonList.get(i)).computeSize(
SWT.DEFAULT, SWT.DEFAULT, flushCache);
sumWidth += size.x;
height = Math.max(height, size.y);
}
// label size
Point labelSize = label.computeSize(SWT.DEFAULT, SWT.DEFAULT,
flushCache);
return new Point(sumWidth, Math.max(labelSize.y, height));
}
/**
* @see org.eclipse.swt.widgets.Layout#layout(org.eclipse.swt.widgets.Composite,
* boolean)
*/
protected void layout(Composite composite, boolean flushCache) {
Rectangle bounds = editor.getClientArea();
int count = buttonList.size();
int sumWidth = 0;
int[] widthArray = new int[count];
int start = 0;
// calculate the aggregate width of the buttons
for (int i = 0; i < count; i++) {
Point size = ((Button) buttonList.get(i)).computeSize(
SWT.DEFAULT, SWT.DEFAULT, flushCache);
sumWidth += size.x;
widthArray[i] = size.x;
}
// set the size for the label
if (label != null) {
label.setBounds(0, 0, bounds.width - sumWidth, bounds.height);
start = bounds.width - sumWidth;
}
// set the size for the buttons
for (int i = 0; i < count; i++) {
Button button = (Button) buttonList.get(i);
button.setBounds(start, 0, widthArray[i], bounds.height);
start += widthArray[i];
}
}
}
/**
* @param parent
* The parent control
*/
public MultiButtonCellEditor(Composite parent) {
this(parent, SWT.NONE);
}
/**
* @param parent
* The parent control
* @param style
* The style bits
*/
public MultiButtonCellEditor(Composite parent, int style) {
super(parent, style);
}
/**
* @see org.eclipse.jface.viewers.CellEditor#createControl(org.eclipse.swt.widgets.Composite)
*/
protected Control createControl(Composite parent) {
buttonList = new ArrayList();
font = parent.getFont();
Color bg = parent.getBackground();
// create the cell editor
editor = new Composite(parent, getStyle());
editor.setFont(font);
editor.setBackground(bg);
editor.setLayout(new MultiButtonCellLayout());
// create the label
if (isModifiable()) {
label = (new Text(editor, SWT.LEFT));
} else {
label = (new Label(editor, SWT.LEFT));
}
label.setFont(font);
label.setBackground(bg);
updateLabel(value);
// init the buttons (there must be at least one)
initButtons();
assert buttonList.size() > 0 : "button list size must > 0"; //$NON-NLS-1$
setValueValid(true);
return editor;
}
/**
* Determine if the label in the cell editor is modifiable. The default is a
* read-only label representation of the value.
*
* @return <code>true</code> if the label is modifiable
*/
protected boolean isModifiable() {
return false;
}
/**
* @see org.eclipse.jface.viewers.CellEditor#doGetValue()
*/
protected Object doGetValue() {
return value;
}
/**
* This implementations sets focus on the last button
*
* @see org.eclipse.jface.viewers.CellEditor#doSetFocus()
*/
protected void doSetFocus() {
((Button) buttonList.get(buttonList.size() - 1)).setFocus();
}
/**
* @see org.eclipse.jface.viewers.CellEditor#doSetValue(java.lang.Object)
*/
protected void doSetValue(Object val) {
this.value = val;
updateLabel(val);
}
/**
* Creates and adds the button to the cell editor
*
* @param buttonLabel
* Button label
* @param buttonAction
* The action to be executed when the button is invoked
*/
protected void addButton(String buttonLabel,
final IPropertyAction buttonAction) {
+ addButton(buttonLabel, null, buttonAction);
+ }
+
+ /**
+ * Creates and adds the button to the cell editor
+ *
+ * @param buttonLabel
+ * Button label
+ * @param buttonToolTip
+ * Button buttonToolTip
+ * @param buttonAction
+ * The action to be executed when the button is invoked
+ */
+ protected void addButton(String buttonLabel,String buttonToolTip,
+ final IPropertyAction buttonAction) {
// create button
Button button = new Button(editor, SWT.DOWN);
button.setText(buttonLabel);
+ button.setToolTipText(buttonToolTip);
button.setFont(font);
// selection listener
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
Object newValue = buttonAction.execute(editor);
if (newValue != null) {
boolean newValidState = isCorrect(newValue);
if (newValidState) {
markDirty();
doSetValue(newValue);
} else {
setErrorMessage(MessageFormat.format(getErrorMessage(),
new Object[] {newValue.toString()}));
}
fireApplyEditorValue();
}
}
});
// key listener
button.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.character == '\u001b') { // Escape char
fireCancelEditor();
}
}
});
button.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
e.doit = false;
getControl().traverse(SWT.TRAVERSE_TAB_PREVIOUS);
}
if (e.detail == SWT.TRAVERSE_TAB_NEXT) {
e.doit = false;
getControl().traverse(SWT.TRAVERSE_TAB_NEXT);
}
}
});
buttonList.add(button);
}
/**
* Updates the label showing the value. The default implementation converts
* the passed object to a string using <code>toString</code> and sets this
* as the text of the label widget.
*
* @param val
* The new value
*/
protected void updateLabel(Object val) {
if (label == null)
return;
String text = ""; //$NON-NLS-1$
if (val != null) {
text = val.toString();
}
if (label instanceof Label) {
((Label)label).setText(text);
} else if (label instanceof Text) {
((Text)label).setText(text);
}
}
/**
* The subclasses have to override this method. The implementation should
* only make calls to the method addButton() to initialize the desired
* buttons. Note: the implementation of the IPropertyAction's execute method
* should return the new value for the editor or null if the value has not
* changed.
*/
protected abstract void initButtons();
/**
* Get the label widget.
* @return the label widget.
*/
protected Label getLabel() {
return (label != null && label instanceof Label) ? (Label) label
: null;
}
/**
* Get the text widget in the case where the label is modifiable.
* @return the label widget.
*/
protected Text getText() {
return (label != null && label instanceof Text) ? (Text) label
: null;
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/plugins/org.teiid.designer.dqp.ui/src/org/teiid/designer/runtime/ui/views/content/TeiidResourceNode.java b/plugins/org.teiid.designer.dqp.ui/src/org/teiid/designer/runtime/ui/views/content/TeiidResourceNode.java
index 378939275..e920b6f3b 100644
--- a/plugins/org.teiid.designer.dqp.ui/src/org/teiid/designer/runtime/ui/views/content/TeiidResourceNode.java
+++ b/plugins/org.teiid.designer.dqp.ui/src/org/teiid/designer/runtime/ui/views/content/TeiidResourceNode.java
@@ -1,188 +1,188 @@
/*
* JBoss, Home of Professional Open Source.
*
* See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing.
*
* See the AUTHORS.txt file distributed with this work for a full listing of individual contributors.
*/
package org.teiid.designer.runtime.ui.views.content;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import org.eclipse.wst.server.core.IServer;
import org.teiid.designer.runtime.TeiidServer;
import org.teiid.designer.runtime.ui.DqpUiConstants;
import org.teiid.designer.runtime.ui.views.TeiidServerContentProvider;
/**
* Root node of the {@link TeiidServer} tree view.
*
* The node is cached against its {@link TeiidServerContentProvider} so that the same
* node can be returned, allowing calls to method like setExpandedState(node, true) to
* still work.
*
* @since 8.0
*/
public class TeiidResourceNode extends TeiidContentNode implements ITeiidResourceNode {
private static Map<String, ITeiidResourceNode> nodeCache = new WeakHashMap<String, ITeiidResourceNode>();
private ArrayList<ITeiidContentNode<? extends ITeiidContainerNode<?>>> children;
private TeiidServerContentProvider provider;
private TeiidServer teiidServer;
private TeiidErrorNode error;
private boolean dirty = true;
/**
* @param server
* @param provider
*
* @return new or cached {@link ITeiidResourceNode}
*/
public static ITeiidResourceNode getInstance(IServer server, TeiidServerContentProvider provider) {
String key = server.toString() + provider.toString();
ITeiidResourceNode node = nodeCache.get(key);
if (node == null) {
node = new TeiidResourceNode(server, provider);
nodeCache.put(key, node);
}
return node;
}
/**
* Create a new instance
*
* @param server
* @param provider
*/
private TeiidResourceNode(IServer server, TeiidServerContentProvider provider) {
super(server, DqpUiConstants.UTIL.getString(TeiidResourceNode.class.getSimpleName() + ".label")); //$NON-NLS-1$
this.provider = provider;
}
@Override
public void setDirty() {
dirty = true;
}
@Override
public final List<? extends ITeiidContentNode<?>> getChildren() {
if (dirty) {
/*
* node flagged as dirty so the children are out-of-date. Avoid
* returning them thereby making the content provider reload
* them.
*/
return null;
}
if (error != null) {
return Collections.singletonList(error);
}
return children;
}
@Override
public final void load() {
clearChildren();
if (getServer().getServerState() != IServer.STATE_STARTED) {
setError(new TeiidErrorNode(this, null, DqpUiConstants.UTIL.getString(getClass().getSimpleName() + ".labelNotConnected"))); //$NON-NLS-1$
dirty = false;
return;
}
synchronized(provider) {
try {
teiidServer = (TeiidServer)getServer().loadAdapter(TeiidServer.class, null);
if (teiidServer != null && teiidServer.isConnected()) {
if (children == null)
children = new ArrayList<ITeiidContentNode<? extends ITeiidContainerNode<?>>>();
children.add(new TeiidServerContainerNode(this, provider));
} else {
setError(new TeiidErrorNode(this, teiidServer, DqpUiConstants.UTIL.getString(getClass().getSimpleName()
+ ".labelNotConnected"))); //$NON-NLS-1$
return;
}
clearError();
} catch (Exception e) {
DqpUiConstants.UTIL.log(e);
setError(new TeiidErrorNode(this, teiidServer, DqpUiConstants.UTIL.getString(getClass().getSimpleName()
+ ".labelRetrievalError"))); //$NON-NLS-1$
} finally {
dirty = false;
}
}
}
private void clearChildren() {
synchronized (provider) {
clearError();
if (children != null) {
for (ITeiidContentNode<? extends ITeiidContainerNode<?>> child : children) {
child.dispose();
}
children.clear();
children = null;
}
teiidServer = null;
}
}
private void clearError() {
if (error != null) {
error.dispose();
error = null;
}
}
protected void setError(TeiidErrorNode error) {
clearError();
this.error = error;
}
@Override
public void dispose() {
clearChildren();
super.dispose();
}
/**
* @return the teiidServer
*/
@Override
public TeiidServer getTeiidServer() {
return this.teiidServer;
}
@Override
public boolean hasChildren() {
- return dirty || (children != null && ! children.isEmpty());
+ return !dirty || (children != null && ! children.isEmpty());
}
@Override
public String toString() {
if (teiidServer == null)
return DqpUiConstants.UTIL.getString(TeiidResourceNode.class.getSimpleName() + ".labelNotConnected"); //$NON-NLS-1$
String ttip = teiidServer.toString();
if( teiidServer.getConnectionError() != null ) {
ttip = ttip + "\n\n" + teiidServer.getConnectionError(); //$NON-NLS-1$
}
return ttip;
}
}
diff --git a/plugins/org.teiid.designer.dqp.ui/src/org/teiid/designer/runtime/ui/views/content/adapter/TeiidResourceNodeAdapterFactory.java b/plugins/org.teiid.designer.dqp.ui/src/org/teiid/designer/runtime/ui/views/content/adapter/TeiidResourceNodeAdapterFactory.java
index 949daa572..a23535454 100644
--- a/plugins/org.teiid.designer.dqp.ui/src/org/teiid/designer/runtime/ui/views/content/adapter/TeiidResourceNodeAdapterFactory.java
+++ b/plugins/org.teiid.designer.dqp.ui/src/org/teiid/designer/runtime/ui/views/content/adapter/TeiidResourceNodeAdapterFactory.java
@@ -1,71 +1,73 @@
/*
* JBoss, Home of Professional Open Source.
*
* See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing.
*
* See the AUTHORS.txt file distributed with this work for a full listing of individual contributors.
*/
package org.teiid.designer.runtime.ui.views.content.adapter;
import java.util.List;
import org.eclipse.core.runtime.IAdapterFactory;
import org.teiid.designer.runtime.TeiidServer;
import org.teiid.designer.runtime.ui.views.content.ITeiidContentNode;
import org.teiid.designer.runtime.ui.views.content.ITeiidResourceNode;
import org.teiid.designer.runtime.ui.views.content.TeiidServerContainerNode;
/**
* Adapt a {@link ITeiidResourceNode}
*/
public class TeiidResourceNodeAdapterFactory implements IAdapterFactory {
@Override
public Object getAdapter(Object adaptableObject, Class adapterType) {
if (! (adaptableObject instanceof ITeiidResourceNode))
return null;
ITeiidResourceNode teiidResourceNode = (ITeiidResourceNode) adaptableObject;
if (ITeiidResourceNode.class == adapterType)
return teiidResourceNode;
if (TeiidServer.class == adapterType)
return adaptToTeiidServer(teiidResourceNode);
if (TeiidServerContainerNode.class == adapterType)
return adaptToTeiidServerContainerNode(teiidResourceNode);
return null;
}
/**
* Adapt to a {@link TeiidServer}
*
* @param adaptableObject
*/
private TeiidServer adaptToTeiidServer(ITeiidResourceNode teiidResourceNode) {
return teiidResourceNode.getTeiidServer();
}
/**
* Adapt to a {@link TeiidServerContainerNode}
*
* @param adaptableObject
* @return
*/
private TeiidServerContainerNode adaptToTeiidServerContainerNode(ITeiidResourceNode teiidResourceNode) {
if (teiidResourceNode.hasChildren()) {
List<? extends ITeiidContentNode<?>> children = teiidResourceNode.getChildren();
- return (TeiidServerContainerNode) children.get(0);
+ ITeiidContentNode<?> child = children.get(0);
+ if (child instanceof TeiidServerContainerNode)
+ return (TeiidServerContainerNode) child;
}
return null;
}
@Override
public Class[] getAdapterList() {
return new Class[] { TeiidServer.class, ITeiidResourceNode.class, TeiidServerContainerNode.class };
}
}
| false | false | null | null |
diff --git a/avatica/src/main/java/net/hydromatic/avatica/UnregisteredDriver.java b/avatica/src/main/java/net/hydromatic/avatica/UnregisteredDriver.java
index a724d415..14693091 100644
--- a/avatica/src/main/java/net/hydromatic/avatica/UnregisteredDriver.java
+++ b/avatica/src/main/java/net/hydromatic/avatica/UnregisteredDriver.java
@@ -1,232 +1,232 @@
/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde 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 net.hydromatic.avatica;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Implementation of JDBC driver that does not register itself.
*
* <p>You can easily create a "vanity driver" that recognizes its own
* URL prefix as a sub-class of this class. Per the JDBC specification it
* must register itself when the class is loaded.</p>
*
* <p>Derived classes must implement {@link #createDriverVersion()} and
* {@link #getConnectStringPrefix()}, and may override
* {@link #createFactory()}.</p>
*
* <p>The provider must implement:</p>
* <ul>
* <li>{@link net.hydromatic.avatica.Meta#prepare(AvaticaStatement, String)}</li>
* <li>{@link net.hydromatic.avatica.Meta#createCursor(AvaticaResultSet)}</li>
* </ul>
*/
public abstract class UnregisteredDriver implements java.sql.Driver {
final DriverVersion version;
final AvaticaFactory factory;
public final Handler handler;
protected UnregisteredDriver() {
this.factory = createFactory();
this.version = createDriverVersion();
this.handler = createHandler();
}
/**
* Creates a factory for JDBC objects (connection, statement).
* Called from the driver constructor.
*
* <p>The default implementation calls {@link JdbcVersion#current},
* then {@link #getFactoryClassName} with that version,
* then passes that class name to {@link #instantiateFactory(String)}.
* This approach is recommended it does not include in the code references
* to classes that may not be instantiable in all JDK versions.
* But drivers are free to do it their own way.</p>
*
* @return JDBC object factory
*/
protected AvaticaFactory createFactory() {
return instantiateFactory(getFactoryClassName(JdbcVersion.current()));
}
/** Creates a Handler. */
protected Handler createHandler() {
return new HandlerImpl();
}
/**
* Returns the name of a class to be factory for JDBC objects
* (connection, statement) appropriate for the current JDBC version.
*/
protected String getFactoryClassName(JdbcVersion jdbcVersion) {
switch (jdbcVersion) {
case JDBC_30:
return "net.hydromatic.avatica.AvaticaFactoryJdbc3Impl";
case JDBC_40:
- return "net.hydromatic.avatica.AvaticaFactoryJdbc4Impl";
+ return "net.hydromatic.avatica.AvaticaJdbc40Factory";
case JDBC_41:
default:
- return "net.hydromatic.avatica.AvaticaFactoryJdbc41";
+ return "net.hydromatic.avatica.AvaticaJdbc41Factory";
}
}
/**
* Creates an object describing the name and version of this driver.
* Called from the driver constructor.
*/
protected abstract DriverVersion createDriverVersion();
/** Helper method for creating factories. */
protected static AvaticaFactory instantiateFactory(String factoryClassName) {
try {
final Class<?> clazz = Class.forName(factoryClassName);
return (AvaticaFactory) clazz.newInstance();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
}
public Connection connect(String url, Properties info) throws SQLException {
if (!acceptsURL(url)) {
return null;
}
final String prefix = getConnectStringPrefix();
assert url.startsWith(prefix);
final String urlSuffix = url.substring(prefix.length());
final Properties info2 = ConnectStringParser.parse(urlSuffix, info);
final AvaticaConnection connection =
factory.newConnection(this, factory, url, info2);
handler.onConnectionInit(connection);
return connection;
}
public boolean acceptsURL(String url) throws SQLException {
return url.startsWith(getConnectStringPrefix());
}
/** Returns the prefix of the connect string that this driver will recognize
* as its own. For example, "jdbc:optiq:". */
protected abstract String getConnectStringPrefix();
public DriverPropertyInfo[] getPropertyInfo(
String url, Properties info) throws SQLException {
List<DriverPropertyInfo> list = new ArrayList<DriverPropertyInfo>();
// First, add the contents of info
for (Map.Entry<Object, Object> entry : info.entrySet()) {
list.add(
new DriverPropertyInfo(
(String) entry.getKey(),
(String) entry.getValue()));
}
// Next, add property definitions not mentioned in info
for (ConnectionProperty p : ConnectionProperty.values()) {
if (info.containsKey(p.name())) {
continue;
}
list.add(
new DriverPropertyInfo(
p.name(),
null));
}
return list.toArray(new DriverPropertyInfo[list.size()]);
}
// JDBC 4.1 support (JDK 1.7 and higher)
public Logger getParentLogger() {
return Logger.getLogger("");
}
/**
* Returns the driver version object. Not in the JDBC API.
*
* @return Driver version
*/
public DriverVersion getDriverVersion() {
return version;
}
public final int getMajorVersion() {
return version.majorVersion;
}
public final int getMinorVersion() {
return version.minorVersion;
}
public boolean jdbcCompliant() {
return version.jdbcCompliant;
}
/**
* Registers this driver with the driver manager.
*/
protected void register() {
try {
DriverManager.registerDriver(this);
} catch (SQLException e) {
System.out.println(
"Error occurred while registering JDBC driver "
+ this + ": " + e.toString());
}
}
/** JDBC version. */
protected enum JdbcVersion {
/** Unknown JDBC version. */
JDBC_UNKNOWN,
/** JDBC version 3.0. Generally associated with JDK 1.5. */
JDBC_30,
/** JDBC version 4.0. Generally associated with JDK 1.6. */
JDBC_40,
/** JDBC version 4.1. Generally associated with JDK 1.7. */
JDBC_41;
/** Deduces the current JDBC version. */
public static JdbcVersion current() {
try {
// If java.sql.PseudoColumnUsage is present, we are running JDBC
// 4.1 or later.
Class.forName("java.sql.PseudoColumnUsage");
return JDBC_41;
} catch (ClassNotFoundException e) {
// java.sql.PseudoColumnUsage is not present. This means we are
// running JDBC 4.0 or earlier.
try {
Class.forName("java.sql.Wrapper");
return JDBC_40;
} catch (ClassNotFoundException e2) {
// java.sql.Wrapper is not present. This means we are
// running JDBC 3.0 or earlier (probably JDK 1.5).
return JDBC_30;
}
}
}
}
}
// End UnregisteredDriver.java
| false | false | null | null |
diff --git a/de.htwg.kalaha/test/de/htwg/kalaha/model/BoardTest.java b/de.htwg.kalaha/test/de/htwg/kalaha/model/BoardTest.java
index 319c562..2b85aed 100644
--- a/de.htwg.kalaha/test/de/htwg/kalaha/model/BoardTest.java
+++ b/de.htwg.kalaha/test/de/htwg/kalaha/model/BoardTest.java
@@ -1,55 +1,61 @@
package de.htwg.kalaha.model;
import junit.framework.TestCase;
public class BoardTest extends TestCase {
Board board;
Player player1, player2;
public void setUp() {
player1 = new Player("Player 1");
player2 = new Player("Player 2");
board = new Board(player1,player2);
}
public void testGetHollow() {
assertEquals(board.getHollow(player1, 2), board.getNextHollow(board.getHollow(player1, 1)));
assertEquals(board.getHollow(player2, 6), board.getNextHollow(board.getHollow(player2, 5)));
assertNull(board.getHollow(new Player("Someone else"), 1));
}
public void testGetOppositeHollow() {
assertEquals(board.getHollow(player1, 6), board.getOppositeHollow(board.getHollow(player2, 1)));
assertEquals(board.getHollow(player2, 1), board.getOppositeHollow(board.getHollow(player1, 6)));
assertNull(board.getOppositeHollow(null));
}
public void testGetNextHollow() {
Hollow newHollow = new Hollow(player1);
assertNull(board.getNextHollow(newHollow));
assertEquals(board.getNextHollow(board.getHollow(player1, 1)), board.getHollow(player1, 2));
assertEquals(board.getNextHollow(board.getHollow(player2, 1)), board.getHollow(player2, 2));
assertEquals(board.getNextHollow(board.getHollow(player2, 6)), board.getHollow(player1, 1));
assertFalse(board.getNextHollow(board.getHollow(player1, 6)).equals(board.getHollow(player2, 1)));
assertEquals(board.getNextHollow(board.getNextHollow(board.getHollow(player1, 6))), board.getHollow(player2, 1));
board.switchActivePlayer();
assertEquals(board.getNextHollow(board.getHollow(player1, 6)), board.getHollow(player2, 1));
assertFalse(board.getNextHollow(board.getHollow(player2, 6)).equals(board.getHollow(player1, 1)));
assertEquals(board.getNextHollow(board.getNextHollow(board.getHollow(player2, 6))), board.getHollow(player1, 1));
}
public void testSwitchActivePlayer() {
assertEquals(player1,board.getActivePlayer());
board.switchActivePlayer();
assertEquals(player2,board.getActivePlayer());
board.switchActivePlayer();
assertEquals(player1,board.getActivePlayer());
}
public void testToString(){
assertNotNull(board.toString());
+
+ board.getNextHollow(board.getHollow(player1, 6)).setMarbles(15);
+ board.switchActivePlayer();
+ board.getNextHollow(board.getHollow(player2, 6)).setMarbles(15);
+
+ assertNotNull(board.toString());
}
}
| true | false | null | null |
diff --git a/src/com/id/ui/app/AppLayout.java b/src/com/id/ui/app/AppLayout.java
index e0575c6..5f30cc6 100644
--- a/src/com/id/ui/app/AppLayout.java
+++ b/src/com/id/ui/app/AppLayout.java
@@ -1,63 +1,63 @@
package com.id.ui.app;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
public class AppLayout implements LayoutManager {
private Component filelist = null;
private Component spotlight = null;
private Component stack = null;
private Component fuzzyFinder;
@Override
public void addLayoutComponent(String name, Component component) {
if (name.equals("filelist")) {
filelist = component;
} else if (name.equals("spotlight")) {
spotlight = component;
} else if (name.equals("stack")) {
stack = component;
} else if (name.equals("fuzzyfinder")) {
fuzzyFinder = component;
}
}
@Override
public void layoutContainer(Container parent) {
int height = parent.getHeight();
- int fileListWidth = filelist.getPreferredSize().width;
+ int fileListWidth = 250;
int remainingWidth = parent.getWidth() - fileListWidth;
int editorWidth = remainingWidth / 2;
filelist.setBounds(0, 0, fileListWidth, height);
spotlight.setBounds(fileListWidth, 0, editorWidth, height);
stack.setBounds(fileListWidth + editorWidth, 0, editorWidth, height);
if (fuzzyFinder != null) {
- fuzzyFinder.setBounds(200, 0, 200, height);
+ fuzzyFinder.setBounds(250, 0, 200, height);
}
}
@Override
public Dimension minimumLayoutSize(Container parent) {
return new Dimension(800, 600);
}
@Override
public Dimension preferredLayoutSize(Container parent) {
return parent.getSize();
}
@Override
public void removeLayoutComponent(Component comp) {
if (filelist == comp) {
filelist = null;
} else if (spotlight == comp) {
spotlight = null;
} else if (stack == comp) {
stack = null;
} else if (fuzzyFinder == comp) {
fuzzyFinder = null;
}
}
}
| false | true | public void layoutContainer(Container parent) {
int height = parent.getHeight();
int fileListWidth = filelist.getPreferredSize().width;
int remainingWidth = parent.getWidth() - fileListWidth;
int editorWidth = remainingWidth / 2;
filelist.setBounds(0, 0, fileListWidth, height);
spotlight.setBounds(fileListWidth, 0, editorWidth, height);
stack.setBounds(fileListWidth + editorWidth, 0, editorWidth, height);
if (fuzzyFinder != null) {
fuzzyFinder.setBounds(200, 0, 200, height);
}
}
| public void layoutContainer(Container parent) {
int height = parent.getHeight();
int fileListWidth = 250;
int remainingWidth = parent.getWidth() - fileListWidth;
int editorWidth = remainingWidth / 2;
filelist.setBounds(0, 0, fileListWidth, height);
spotlight.setBounds(fileListWidth, 0, editorWidth, height);
stack.setBounds(fileListWidth + editorWidth, 0, editorWidth, height);
if (fuzzyFinder != null) {
fuzzyFinder.setBounds(250, 0, 200, height);
}
}
|
diff --git a/src/main/java/org/jeroen/ddd/specification/GreaterThanSpecification.java b/src/main/java/org/jeroen/ddd/specification/GreaterThanSpecification.java
index 52f6978..1053838 100644
--- a/src/main/java/org/jeroen/ddd/specification/GreaterThanSpecification.java
+++ b/src/main/java/org/jeroen/ddd/specification/GreaterThanSpecification.java
@@ -1,23 +1,23 @@
package org.jeroen.ddd.specification;
/**
* Determine if a property value is greater than the specified value.
*
* @author Jeroen van Schagen
* @since 5-1-2011
*
* @param <T> type of entity being checked
*/
public class GreaterThanSpecification<T> extends CompareSpecification<T> {
private static final int GREATER_THAN_COMPARISON = 1;
/**
* Construct a new {@link GreaterThanSpecification}.
- * @param property determines what property should be checked
- * @param value candiates are only matched when they property value is above this value
+ * @param property determines what property should be verified
+ * @param value candidates are only matched when their property value is above this value
*/
public GreaterThanSpecification(String property, Object value) {
super(property, value, GREATER_THAN_COMPARISON);
}
}
diff --git a/src/main/java/org/jeroen/ddd/specification/LessThanSpecification.java b/src/main/java/org/jeroen/ddd/specification/LessThanSpecification.java
index d7cc49f..532affc 100644
--- a/src/main/java/org/jeroen/ddd/specification/LessThanSpecification.java
+++ b/src/main/java/org/jeroen/ddd/specification/LessThanSpecification.java
@@ -1,23 +1,23 @@
package org.jeroen.ddd.specification;
/**
* Determine if a property value is less than the specified value.
*
* @author Jeroen van Schagen
* @since 5-1-2011
*
* @param <T> type of entity being checked
*/
public class LessThanSpecification<T> extends CompareSpecification<T> {
private static final int LESS_THAN_COMPARISON = -1;
/**
* Construct a new {@link LessThanSpecification}.
- * @param property determines what property should be checked
- * @param value candiates are only matched when they property value is beneat this value
+ * @param property determines what property should be verified
+ * @param value candidates are only matched when their property value is beneat this value
*/
public LessThanSpecification(String property, Object value) {
super(property, value, LESS_THAN_COMPARISON);
}
}
| false | false | null | null |