diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/ctomlabviewer/src/gov/nih/nci/caxchange/ctom/viewer/actions/LoadTocaAERSAction.java b/ctomlabviewer/src/gov/nih/nci/caxchange/ctom/viewer/actions/LoadTocaAERSAction.java
index cf1a961a..f75cb768 100644
--- a/ctomlabviewer/src/gov/nih/nci/caxchange/ctom/viewer/actions/LoadTocaAERSAction.java
+++ b/ctomlabviewer/src/gov/nih/nci/caxchange/ctom/viewer/actions/LoadTocaAERSAction.java
@@ -1,493 +1,493 @@
/**
* Copyright Notice. Copyright 2008 Scenpro, Inc (�caBIG� Participant�). caXchange
* was created with NCI funding and is part of the caBIG� initiative.
* The software subject to this notice and license includes both human readable source code form and
* machine readable, binary, object code form (the �caBIG� Software�).
* This caBIG� Software License (the �License�) is between caBIG� Participant and You.
* �You (or �Your�) shall mean a person or an entity, and all other entities that control,
* are controlled by, or are under common control with the entity. �Control� for purposes of this
* definition means (i) the direct or indirect power to cause the direction or management of such entity,
* whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares,
* or (iii) beneficial ownership of such entity.
* License. Provided that You agree to the conditions described below, caBIG� Participant grants
* You a non-exclusive, worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and
* royalty-free right and license in its rights in the caBIG� Software, including any copyright or patent rights therein, to
* (i) use, install, disclose, access, operate, execute, reproduce, copy, modify, translate, market, publicly display,
* publicly perform, and prepare derivative works of the caBIG� Software in any manner and for any purpose, and to have
* or permit others to do so; (ii) make, have made, use, practice, sell, and offer for sale, import, and/or otherwise
* dispose of caBIG� Software (or portions thereof); (iii) distribute and have distributed to and by third parties the
* caBIG� Software and any modifications and derivative works thereof; and (iv) sublicense the foregoing rights
* set out in (i), (ii) and (iii) to third parties, including the right to license such rights to further third parties.
* For sake of clarity, and not by way of limitation, caBIG� Participant shall have no right of accounting or right of payment
* from You or Your sublicensees for the rights granted under this License. This License is granted at no charge to You.
* Your downloading, copying, modifying, displaying, distributing or use of caBIG� Software constitutes acceptance of all
* of the terms and conditions of this Agreement. If you do not agree to such terms and conditions, you have no right to
* download, copy, modify, display, distribute or use the caBIG� Software.
* 1. Your redistributions of the source code for the caBIG� Software must retain the above copyright notice,
* this list of conditions and the disclaimer and limitation of liability of Article 6 below.
* Your redistributions in object code form must reproduce the above copyright notice, this list of conditions and
* the disclaimer of Article 6 in the documentation and/or other materials provided with the distribution, if any.
* 2. Your end-user documentation included with the redistribution, if any, must include the following acknowledgment:
* �This product includes software developed by Scenpro, Inc.�
* If You do not include such end-user documentation, You shall include this acknowledgment in the caBIG� Software itself,
* wherever such third-party acknowledgments normally appear.
* 3. You may not use the names �Scenpro, Inc�,
* �The National Cancer Institute�, �NCI�, �Cancer Bioinformatics Grid� or �caBIG�� to endorse or promote products
* derived from this caBIG� Software. This License does not authorize You to use any trademarks, service marks, trade names,
* logos or product names of either caBIG� Participant, NCI or caBIG�, except as required to comply with the terms of this
* License.
* 4. For sake of clarity, and not by way of limitation, You may incorporate this caBIG� Software into Your proprietary
* programs and into any third party proprietary programs. However, if You incorporate the caBIG� Software into third party
* proprietary programs, You agree that You are solely responsible for obtaining any permission from such third parties
* required to incorporate the caBIG� Software into such third party proprietary programs and for informing Your sublicensees,
* including without limitation Your end-users, of their obligation to secure any required permissions from such third parties
* before incorporating the caBIG� Software into such third party proprietary software programs. In the event that You fail to
* obtain such permissions, You agree to indemnify caBIG� Participant for any claims against caBIG� Participant by such third
* parties, except to the extent prohibited by law, resulting from Your failure to obtain such permissions.
* 5. For sake of clarity, and not by way of limitation, You may add Your own copyright statement to Your modifications and
* to the derivative works, and You may provide additional or different license terms and conditions in Your sublicenses of
* modifications of the caBIG� Software, or any derivative works of the caBIG� Software as a whole, provided Your use, reproduction,
* and distribution of the Work otherwise complies with the conditions stated in this License.
* 6. THIS caBIG� SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
* IN NO EVENT SHALL THE Scenpro, Inc OR ITS AFFILIATES
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS caBIG� SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
package gov.nih.nci.caxchange.ctom.viewer.actions;
import gov.nih.nci.cabig.ccts.domain.Documentation;
import gov.nih.nci.cabig.ccts.domain.LabResult;
import gov.nih.nci.cabig.ccts.domain.Participant;
import gov.nih.nci.cabig.ccts.domain.PerformedActivity;
import gov.nih.nci.cabig.ccts.domain.PerformedStudy;
import gov.nih.nci.cabig.ccts.domain.StudySubject;
import gov.nih.nci.cabig.ccts.domain.LoadLabsRequest;
import gov.nih.nci.cagrid.caxchange.client.CaXchangeRequestProcessorClient;
import gov.nih.nci.cagrid.caxchange.context.client.CaXchangeResponseServiceClient;
import gov.nih.nci.cagrid.caxchange.context.stubs.types.CaXchangeResponseServiceReference;
//import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.caxchange.Credentials;
import gov.nih.nci.caxchange.Message;
import gov.nih.nci.caxchange.MessagePayload;
import gov.nih.nci.caxchange.MessageTypes;
import gov.nih.nci.caxchange.Metadata;
import gov.nih.nci.caxchange.Request;
import gov.nih.nci.caxchange.Response;
import gov.nih.nci.caxchange.ResponseMessage;
import gov.nih.nci.caxchange.Statuses;
import gov.nih.nci.caxchange.TargetResponseMessage;
import gov.nih.nci.caxchange.ctom.viewer.beans.LabViewerStatus;
import gov.nih.nci.caxchange.ctom.viewer.beans.util.HibernateUtil;
import gov.nih.nci.caxchange.ctom.viewer.constants.DisplayConstants;
import gov.nih.nci.caxchange.ctom.viewer.constants.ForwardConstants;
import gov.nih.nci.caxchange.ctom.viewer.forms.LabActivitiesSearchResultForm;
import gov.nih.nci.caxchange.ctom.viewer.forms.LoginForm;
import gov.nih.nci.caxchange.ctom.viewer.viewobjects.LabActivityResult;
import gov.nih.nci.caxchange.ctom.viewer.viewobjects.SearchResult;
import gov.nih.nci.labhub.domain.II;
import gov.nih.nci.logging.api.user.UserInfoHelper;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
//import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.namespace.QName;
import org.apache.axis.message.MessageElement;
import org.apache.axis.types.URI;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
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.apache.struts.action.ActionMessages;
import org.hibernate.Session;
/**
* This class performs the Load to caAERS action. It loads the selected form data to caAERS.
* It checks if valid login information is in session; if not it redirects the user to login page.
*
* @author asharma
*
*/
public class LoadTocaAERSAction extends Action
{
private static final Logger logDB = Logger.getLogger(LoadTocaAERSAction.class);
private static final String CONFIG_FILE = "/loadLabURLS.properties";
/* (non-Javadoc)
* @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
ActionErrors errors = new ActionErrors();
ActionMessages messages = new ActionMessages();
HttpSession session = request.getSession();
LabActivitiesSearchResultForm lForm = (LabActivitiesSearchResultForm) form;
//if the session is new or the login object is null; redirects the user to login page
if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null))
{
logDB.error("No Session or User Object Forwarding to the Login Page");
return mapping.findForward(ForwardConstants.LOGIN_PAGE);
}
String username = ((LoginForm)session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId();
UserInfoHelper.setUserInfo(username, session.getId());
int numOfLabs =0;
try
{ //calls the loadTocaAERS method
numOfLabs = loadTocaAERS(request, lForm, username);
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(DisplayConstants.MESSAGE_ID, numOfLabs+" Message(s) Submitted to caAERS Successfully"));
updateLabResult(request);
updateLabResultForUI(request);
saveMessages( request, messages );
}
catch (Exception cse)
{
String msg = cse.getMessage();
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(DisplayConstants.ERROR_ID, "Error in Submitting Messages to caAERS: " + msg));
saveErrors( request,errors );
logDB.error("Error sending labs to caAERS", cse);
}
session.setAttribute(DisplayConstants.CURRENT_FORM, lForm);
//if the login is valid and the selected form data is successfully loaded to caAERS;
//it returns to the search results page and displays the load successful message
return (mapping.findForward(ForwardConstants.LOAD_TO_caAERS_EVENT_SUCCESS));
}
/**
* Collects the selected form data and calls the EvenManager sendLabActivitiesmethod to
* load the data to CTMS
* @param request
* @param form
* @param username
* @return numOfLabs number of labs laoded
* @throws Exception
*/
private int loadTocaAERS(HttpServletRequest request,ActionForm form, String username) throws Exception
{
HttpSession session = request.getSession();
LabActivitiesSearchResultForm lForm = (LabActivitiesSearchResultForm)form;
HashMap map = (HashMap) request.getSession().getAttribute("RESULT_SET");
HashMap<String,LabActivityResult> labResultsMap = new HashMap<String,LabActivityResult>();
HashMap<String,String> labResultIds = new HashMap<String,String>();
String[] test = lForm.getRecordIds();
int count =0;
int numOfLabs=0;
// Create the list of results to send
if(test!=null)
{
count = test.length;
for(int i=0;i<count;i++)
{
if(map.get(test[i]) != null){
LabActivityResult lar = (LabActivityResult)map.get(test[i]);
labResultsMap.put(test[i],lar);
labResultIds.put(test[i],lar.getLabResultId());
}
}
}
Properties props = new Properties();
//Get the file input stream
try
{
InputStream stream = getClass().getResourceAsStream(CONFIG_FILE);
props.load(stream);
}
catch (FileNotFoundException e1)
{
logDB.error("The config file not found: " + CONFIG_FILE);
}
catch (IOException e1)
{
logDB.error("Error reading the config file: " + CONFIG_FILE);
}
// Then create the request
String url = (String)props.getProperty("url");
CaXchangeRequestProcessorClient client = new CaXchangeRequestProcessorClient(url);
LoadLabsRequest labRequest = new LoadLabsRequest();
// Then for each lab selected set the lab information
LabResult labResults[]= new LabResult[labResultsMap.size()];
int i = 0;
for(String key: labResultsMap.keySet()){
LabActivityResult lab = labResultsMap.get(key);
// Populate the study information
Documentation documentation = new Documentation();
PerformedStudy performedStudy = new PerformedStudy();
String studyId = lab.getStudyId();
if (studyId != null)
{
// Set the study identifier on the document
gov.nih.nci.cabig.ccts.domain.II ii = new gov.nih.nci.cabig.ccts.domain.II();
ii.setExtension(studyId);
ii.setAssigningAuthorityName("CTODS");
ii.setRoot("caAERS");
gov.nih.nci.cabig.ccts.domain.II[] iis = new gov.nih.nci.cabig.ccts.domain.II[1];
iis[0] = ii;
documentation.setII(iis);
}
Documentation[] docs = new Documentation[1];
docs[0] = documentation;
performedStudy.setDocumentation(docs);
// Then set the participant and study subject assignment identifiers
Participant participant= new Participant();
StudySubject studySubject= new StudySubject();
Collection<II> studySubjectIds = lab.getSubjectAssignment().getStudySubjectIdentifier();
if (studySubjectIds != null && studySubjectIds.size() > 0)
{
Iterator<II> idIterator = studySubjectIds.iterator();
II ssII = idIterator.next();
gov.nih.nci.cabig.ccts.domain.II ii = new gov.nih.nci.cabig.ccts.domain.II();
ii.setAssigningAuthorityName("CTODS");
ii.setRoot("caAERS");
ii.setExtension(ssII.getExtension());
gov.nih.nci.cabig.ccts.domain.II[] iis = new gov.nih.nci.cabig.ccts.domain.II[1];
iis[0] = ii;
participant.setII(iis);
gov.nih.nci.cabig.ccts.domain.II ii2 = new gov.nih.nci.cabig.ccts.domain.II();
ii2.setAssigningAuthorityName("CTODS");
ii2.setRoot("caAERS");
ii2.setExtension(ssII.getExtension());
gov.nih.nci.cabig.ccts.domain.II[] iis2 = new gov.nih.nci.cabig.ccts.domain.II[1];
iis2[0] = ii2;
studySubject.setII(iis2);
}
studySubject.setParticipant(participant);
studySubject.setPerformedStudy(performedStudy);
// Set the activity name
PerformedActivity performedActivity= new PerformedActivity();
String testName = lab.getLabTestId();
performedActivity.setName(testName);
PerformedActivity[] performedActivitys = new PerformedActivity[1];
performedActivitys[0] = performedActivity;
studySubject.setPerformedActivity(performedActivitys);
// Then set the lab result
LabResult labResult = new LabResult();
labResult.setStudySubject(studySubject);
// Set the reported date
java.util.Date labDate = lab.getActualDate();
if (labDate != null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(labDate);
labResult.setReportedDateTime(cal);
}
// Set the lab result details
String numResult = lab.getNumericResult();
if ((numResult != null) && (!numResult.equals("")))
labResult.setNumericResult(Float.parseFloat(numResult));
String txtResult = lab.getTextResult();
if ((txtResult != null) && (!txtResult.equals("")))
labResult.setTextResult(txtResult);
String labUom = lab.getUnitOfMeasure();
if (labUom != null)
labResult.setNumericUnit(labUom);
String lowRange = lab.getLowRange();
if (lowRange != null)
labResult.setReferenceRangeLow(Float.parseFloat(lowRange));
String highRange = lab.getHighRange();
if (highRange != null)
labResult.setReferenceRangeHigh(Float.parseFloat(highRange));
labResults[i] = labResult;
i++;
}
labRequest.setLabResult(labResults);
numOfLabs = labResults.length;
//PrintWriter writer = new PrintWriter("caAERSmessage.xml");
QName lab = new QName("http://integration/caaers.nci.nih.gov/services","LoadLabsRequest");
//Utils.serializeObject(labRequest, lab, writer);
// Create the caxchange message
Message requestMessage = new Message();
Metadata metadata = new Metadata();
metadata.setExternalIdentifier("CTODS");
Credentials creds = new Credentials();
creds.setUserName(username);
String credentialEpr = (String)request.getSession().getAttribute("CAGRID_SSO_DELEGATION_SERVICE_EPR");
logDB.info("The credential EPR: "+ credentialEpr);
if (credentialEpr != null)
creds.setDelegatedCredentialReference(credentialEpr);
metadata.setCredentials(creds);
metadata.setMessageType(MessageTypes.LAB_BASED_AE);
requestMessage.setMetadata(metadata);
Request caxchangeRequest = new Request();
requestMessage.setRequest(caxchangeRequest);
MessagePayload messagePayload = new MessagePayload();
URI uri = new URI();
uri.setPath("gme://ccts.cabig/1.0/gov.nih.nci.cabig.ccts.domain");
messagePayload.setXmlSchemaDefinition(uri);
MessageElement messageElement = new MessageElement(lab, labRequest);
messagePayload.set_any(new MessageElement[]{messageElement});
requestMessage.getRequest().setBusinessMessagePayload(messagePayload);
CaXchangeResponseServiceReference crsr = client.processRequestAsynchronously(requestMessage);
CaXchangeResponseServiceClient responseService = new CaXchangeResponseServiceClient(crsr.getEndpointReference());
boolean gotResponse=false;
int responseCount = 0;
ResponseMessage responseMessage = null;
while(!gotResponse)
{
try
{
responseMessage = responseService.getResponse();
gotResponse = true;
}
catch (Exception e)
{
logDB.info("No response from caxchange", e);
responseCount++;
if (responseCount > 60)
{
logDB.error("Never got a response from caxchange hub");
throw new Exception("No response from hub");
}
Thread.sleep(1000);
}
}
if (responseMessage != null)
{
Response resp = responseMessage.getResponse();
logDB.info("caXchange response was " + resp.getResponseStatus().toString());
if (resp.getResponseStatus().equals(Statuses.SUCCESS))
{
if(resp.getCaXchangeError()!=null){
String message = resp.getCaXchangeError().getErrorDescription();
logDB.info("Received a success from caxchange hub: " + message);
}
if(resp.getTargetResponse()!=null)
{
for(TargetResponseMessage msg: resp.getTargetResponse()){
MessageElement[] messagePay = msg.getTargetBusinessMessage().get_any();
for(MessageElement mEle: messagePay)
{
- String mEleValue =mEle.getAttributeValue("Acknowlegdement");
+ String mEleValue = mEle.getAttributeValue("Acknowledgement");
if(mEleValue.equalsIgnoreCase("Processed"))
{
logDB.info("Response from Target Service was " + mEleValue);
}
else
{
logDB.error("Received response from Target Service: " + mEleValue);
throw new Exception(mEleValue);
}
}
}
}
}
else if (resp.getResponseStatus().equals(Statuses.FAILURE))
{ String message="";
if(resp.getCaXchangeError()!=null){
message = resp.getCaXchangeError().getErrorDescription();
logDB.error("Received a failure from caxchange hub: " + message);
}else{
if(resp.getTargetResponse()!=null)
{
for(TargetResponseMessage msg: resp.getTargetResponse()){
message = msg.getTargetMessageStatus().getValue() +":" +msg.getTargetError().getErrorDescription();
}
}
}
throw new Exception(message);
}
}
lForm.setRecordId("");
lForm.setRecordId(null);
session.setAttribute("LabResultIDs", labResultIds);
return numOfLabs;
}
/**
* updateLabResult updates the database with information about the
* labs results that were sent to caAERS.
* @param request
*/
private void updateLabResult(HttpServletRequest request)
{
Session session=null;
Date date = new Date();
try{
session = HibernateUtil.getSessionFactory().getCurrentSession();
if(session!=null)
{
HashMap<String,String> labResultIds = (HashMap<String,String>)request.getSession().getAttribute("LabResultIDs");
if(labResultIds!= null)
{
for(String key: labResultIds.keySet())
{
int labResutId = Integer.parseInt(labResultIds.get(key));
LabViewerStatus lvs = new LabViewerStatus();
lvs.setAdverseEventIndicator(true);
lvs.setAdverseEventSentDate(date);
lvs.setClinicalResultId(labResutId);
session.beginTransaction();
session.save(lvs);
}
session.getTransaction().commit();
}
}
}catch (Exception se){
logDB.error("Error updating Lab Result: ",se);
if (session.getTransaction() != null) {
session.getTransaction().rollback();
}
}
}
/**
* Update the LabResults for UI display
* @param request
*/
private void updateLabResultForUI(HttpServletRequest request){
SearchResult searchResult= (SearchResult)request.getSession().getAttribute("SEARCH_RESULT");
List search = searchResult.getSearchResultObjects();
HashMap<String,String> labResultIds = (HashMap<String,String>)request.getSession().getAttribute("LabResultIDs");
if(labResultIds!= null)
{
for(String key: labResultIds.keySet()){
int index = (Integer.parseInt(key))-1;
LabActivityResult lar = (LabActivityResult)search.get(index);
lar.setAdverseEventReported(true);
lar.setAdverseEventReportedDate(new java.util.Date().toString());
}
request.getSession().setAttribute("SEARCH_RESULT", searchResult);
}
}
}
| true | true | private int loadTocaAERS(HttpServletRequest request,ActionForm form, String username) throws Exception
{
HttpSession session = request.getSession();
LabActivitiesSearchResultForm lForm = (LabActivitiesSearchResultForm)form;
HashMap map = (HashMap) request.getSession().getAttribute("RESULT_SET");
HashMap<String,LabActivityResult> labResultsMap = new HashMap<String,LabActivityResult>();
HashMap<String,String> labResultIds = new HashMap<String,String>();
String[] test = lForm.getRecordIds();
int count =0;
int numOfLabs=0;
// Create the list of results to send
if(test!=null)
{
count = test.length;
for(int i=0;i<count;i++)
{
if(map.get(test[i]) != null){
LabActivityResult lar = (LabActivityResult)map.get(test[i]);
labResultsMap.put(test[i],lar);
labResultIds.put(test[i],lar.getLabResultId());
}
}
}
Properties props = new Properties();
//Get the file input stream
try
{
InputStream stream = getClass().getResourceAsStream(CONFIG_FILE);
props.load(stream);
}
catch (FileNotFoundException e1)
{
logDB.error("The config file not found: " + CONFIG_FILE);
}
catch (IOException e1)
{
logDB.error("Error reading the config file: " + CONFIG_FILE);
}
// Then create the request
String url = (String)props.getProperty("url");
CaXchangeRequestProcessorClient client = new CaXchangeRequestProcessorClient(url);
LoadLabsRequest labRequest = new LoadLabsRequest();
// Then for each lab selected set the lab information
LabResult labResults[]= new LabResult[labResultsMap.size()];
int i = 0;
for(String key: labResultsMap.keySet()){
LabActivityResult lab = labResultsMap.get(key);
// Populate the study information
Documentation documentation = new Documentation();
PerformedStudy performedStudy = new PerformedStudy();
String studyId = lab.getStudyId();
if (studyId != null)
{
// Set the study identifier on the document
gov.nih.nci.cabig.ccts.domain.II ii = new gov.nih.nci.cabig.ccts.domain.II();
ii.setExtension(studyId);
ii.setAssigningAuthorityName("CTODS");
ii.setRoot("caAERS");
gov.nih.nci.cabig.ccts.domain.II[] iis = new gov.nih.nci.cabig.ccts.domain.II[1];
iis[0] = ii;
documentation.setII(iis);
}
Documentation[] docs = new Documentation[1];
docs[0] = documentation;
performedStudy.setDocumentation(docs);
// Then set the participant and study subject assignment identifiers
Participant participant= new Participant();
StudySubject studySubject= new StudySubject();
Collection<II> studySubjectIds = lab.getSubjectAssignment().getStudySubjectIdentifier();
if (studySubjectIds != null && studySubjectIds.size() > 0)
{
Iterator<II> idIterator = studySubjectIds.iterator();
II ssII = idIterator.next();
gov.nih.nci.cabig.ccts.domain.II ii = new gov.nih.nci.cabig.ccts.domain.II();
ii.setAssigningAuthorityName("CTODS");
ii.setRoot("caAERS");
ii.setExtension(ssII.getExtension());
gov.nih.nci.cabig.ccts.domain.II[] iis = new gov.nih.nci.cabig.ccts.domain.II[1];
iis[0] = ii;
participant.setII(iis);
gov.nih.nci.cabig.ccts.domain.II ii2 = new gov.nih.nci.cabig.ccts.domain.II();
ii2.setAssigningAuthorityName("CTODS");
ii2.setRoot("caAERS");
ii2.setExtension(ssII.getExtension());
gov.nih.nci.cabig.ccts.domain.II[] iis2 = new gov.nih.nci.cabig.ccts.domain.II[1];
iis2[0] = ii2;
studySubject.setII(iis2);
}
studySubject.setParticipant(participant);
studySubject.setPerformedStudy(performedStudy);
// Set the activity name
PerformedActivity performedActivity= new PerformedActivity();
String testName = lab.getLabTestId();
performedActivity.setName(testName);
PerformedActivity[] performedActivitys = new PerformedActivity[1];
performedActivitys[0] = performedActivity;
studySubject.setPerformedActivity(performedActivitys);
// Then set the lab result
LabResult labResult = new LabResult();
labResult.setStudySubject(studySubject);
// Set the reported date
java.util.Date labDate = lab.getActualDate();
if (labDate != null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(labDate);
labResult.setReportedDateTime(cal);
}
// Set the lab result details
String numResult = lab.getNumericResult();
if ((numResult != null) && (!numResult.equals("")))
labResult.setNumericResult(Float.parseFloat(numResult));
String txtResult = lab.getTextResult();
if ((txtResult != null) && (!txtResult.equals("")))
labResult.setTextResult(txtResult);
String labUom = lab.getUnitOfMeasure();
if (labUom != null)
labResult.setNumericUnit(labUom);
String lowRange = lab.getLowRange();
if (lowRange != null)
labResult.setReferenceRangeLow(Float.parseFloat(lowRange));
String highRange = lab.getHighRange();
if (highRange != null)
labResult.setReferenceRangeHigh(Float.parseFloat(highRange));
labResults[i] = labResult;
i++;
}
labRequest.setLabResult(labResults);
numOfLabs = labResults.length;
//PrintWriter writer = new PrintWriter("caAERSmessage.xml");
QName lab = new QName("http://integration/caaers.nci.nih.gov/services","LoadLabsRequest");
//Utils.serializeObject(labRequest, lab, writer);
// Create the caxchange message
Message requestMessage = new Message();
Metadata metadata = new Metadata();
metadata.setExternalIdentifier("CTODS");
Credentials creds = new Credentials();
creds.setUserName(username);
String credentialEpr = (String)request.getSession().getAttribute("CAGRID_SSO_DELEGATION_SERVICE_EPR");
logDB.info("The credential EPR: "+ credentialEpr);
if (credentialEpr != null)
creds.setDelegatedCredentialReference(credentialEpr);
metadata.setCredentials(creds);
metadata.setMessageType(MessageTypes.LAB_BASED_AE);
requestMessage.setMetadata(metadata);
Request caxchangeRequest = new Request();
requestMessage.setRequest(caxchangeRequest);
MessagePayload messagePayload = new MessagePayload();
URI uri = new URI();
uri.setPath("gme://ccts.cabig/1.0/gov.nih.nci.cabig.ccts.domain");
messagePayload.setXmlSchemaDefinition(uri);
MessageElement messageElement = new MessageElement(lab, labRequest);
messagePayload.set_any(new MessageElement[]{messageElement});
requestMessage.getRequest().setBusinessMessagePayload(messagePayload);
CaXchangeResponseServiceReference crsr = client.processRequestAsynchronously(requestMessage);
CaXchangeResponseServiceClient responseService = new CaXchangeResponseServiceClient(crsr.getEndpointReference());
boolean gotResponse=false;
int responseCount = 0;
ResponseMessage responseMessage = null;
while(!gotResponse)
{
try
{
responseMessage = responseService.getResponse();
gotResponse = true;
}
catch (Exception e)
{
logDB.info("No response from caxchange", e);
responseCount++;
if (responseCount > 60)
{
logDB.error("Never got a response from caxchange hub");
throw new Exception("No response from hub");
}
Thread.sleep(1000);
}
}
if (responseMessage != null)
{
Response resp = responseMessage.getResponse();
logDB.info("caXchange response was " + resp.getResponseStatus().toString());
if (resp.getResponseStatus().equals(Statuses.SUCCESS))
{
if(resp.getCaXchangeError()!=null){
String message = resp.getCaXchangeError().getErrorDescription();
logDB.info("Received a success from caxchange hub: " + message);
}
if(resp.getTargetResponse()!=null)
{
for(TargetResponseMessage msg: resp.getTargetResponse()){
MessageElement[] messagePay = msg.getTargetBusinessMessage().get_any();
for(MessageElement mEle: messagePay)
{
String mEleValue =mEle.getAttributeValue("Acknowlegdement");
if(mEleValue.equalsIgnoreCase("Processed"))
{
logDB.info("Response from Target Service was " + mEleValue);
}
else
{
logDB.error("Received response from Target Service: " + mEleValue);
throw new Exception(mEleValue);
}
}
}
}
}
else if (resp.getResponseStatus().equals(Statuses.FAILURE))
{ String message="";
if(resp.getCaXchangeError()!=null){
message = resp.getCaXchangeError().getErrorDescription();
logDB.error("Received a failure from caxchange hub: " + message);
}else{
if(resp.getTargetResponse()!=null)
{
for(TargetResponseMessage msg: resp.getTargetResponse()){
message = msg.getTargetMessageStatus().getValue() +":" +msg.getTargetError().getErrorDescription();
}
}
}
throw new Exception(message);
}
}
lForm.setRecordId("");
lForm.setRecordId(null);
session.setAttribute("LabResultIDs", labResultIds);
return numOfLabs;
}
| private int loadTocaAERS(HttpServletRequest request,ActionForm form, String username) throws Exception
{
HttpSession session = request.getSession();
LabActivitiesSearchResultForm lForm = (LabActivitiesSearchResultForm)form;
HashMap map = (HashMap) request.getSession().getAttribute("RESULT_SET");
HashMap<String,LabActivityResult> labResultsMap = new HashMap<String,LabActivityResult>();
HashMap<String,String> labResultIds = new HashMap<String,String>();
String[] test = lForm.getRecordIds();
int count =0;
int numOfLabs=0;
// Create the list of results to send
if(test!=null)
{
count = test.length;
for(int i=0;i<count;i++)
{
if(map.get(test[i]) != null){
LabActivityResult lar = (LabActivityResult)map.get(test[i]);
labResultsMap.put(test[i],lar);
labResultIds.put(test[i],lar.getLabResultId());
}
}
}
Properties props = new Properties();
//Get the file input stream
try
{
InputStream stream = getClass().getResourceAsStream(CONFIG_FILE);
props.load(stream);
}
catch (FileNotFoundException e1)
{
logDB.error("The config file not found: " + CONFIG_FILE);
}
catch (IOException e1)
{
logDB.error("Error reading the config file: " + CONFIG_FILE);
}
// Then create the request
String url = (String)props.getProperty("url");
CaXchangeRequestProcessorClient client = new CaXchangeRequestProcessorClient(url);
LoadLabsRequest labRequest = new LoadLabsRequest();
// Then for each lab selected set the lab information
LabResult labResults[]= new LabResult[labResultsMap.size()];
int i = 0;
for(String key: labResultsMap.keySet()){
LabActivityResult lab = labResultsMap.get(key);
// Populate the study information
Documentation documentation = new Documentation();
PerformedStudy performedStudy = new PerformedStudy();
String studyId = lab.getStudyId();
if (studyId != null)
{
// Set the study identifier on the document
gov.nih.nci.cabig.ccts.domain.II ii = new gov.nih.nci.cabig.ccts.domain.II();
ii.setExtension(studyId);
ii.setAssigningAuthorityName("CTODS");
ii.setRoot("caAERS");
gov.nih.nci.cabig.ccts.domain.II[] iis = new gov.nih.nci.cabig.ccts.domain.II[1];
iis[0] = ii;
documentation.setII(iis);
}
Documentation[] docs = new Documentation[1];
docs[0] = documentation;
performedStudy.setDocumentation(docs);
// Then set the participant and study subject assignment identifiers
Participant participant= new Participant();
StudySubject studySubject= new StudySubject();
Collection<II> studySubjectIds = lab.getSubjectAssignment().getStudySubjectIdentifier();
if (studySubjectIds != null && studySubjectIds.size() > 0)
{
Iterator<II> idIterator = studySubjectIds.iterator();
II ssII = idIterator.next();
gov.nih.nci.cabig.ccts.domain.II ii = new gov.nih.nci.cabig.ccts.domain.II();
ii.setAssigningAuthorityName("CTODS");
ii.setRoot("caAERS");
ii.setExtension(ssII.getExtension());
gov.nih.nci.cabig.ccts.domain.II[] iis = new gov.nih.nci.cabig.ccts.domain.II[1];
iis[0] = ii;
participant.setII(iis);
gov.nih.nci.cabig.ccts.domain.II ii2 = new gov.nih.nci.cabig.ccts.domain.II();
ii2.setAssigningAuthorityName("CTODS");
ii2.setRoot("caAERS");
ii2.setExtension(ssII.getExtension());
gov.nih.nci.cabig.ccts.domain.II[] iis2 = new gov.nih.nci.cabig.ccts.domain.II[1];
iis2[0] = ii2;
studySubject.setII(iis2);
}
studySubject.setParticipant(participant);
studySubject.setPerformedStudy(performedStudy);
// Set the activity name
PerformedActivity performedActivity= new PerformedActivity();
String testName = lab.getLabTestId();
performedActivity.setName(testName);
PerformedActivity[] performedActivitys = new PerformedActivity[1];
performedActivitys[0] = performedActivity;
studySubject.setPerformedActivity(performedActivitys);
// Then set the lab result
LabResult labResult = new LabResult();
labResult.setStudySubject(studySubject);
// Set the reported date
java.util.Date labDate = lab.getActualDate();
if (labDate != null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(labDate);
labResult.setReportedDateTime(cal);
}
// Set the lab result details
String numResult = lab.getNumericResult();
if ((numResult != null) && (!numResult.equals("")))
labResult.setNumericResult(Float.parseFloat(numResult));
String txtResult = lab.getTextResult();
if ((txtResult != null) && (!txtResult.equals("")))
labResult.setTextResult(txtResult);
String labUom = lab.getUnitOfMeasure();
if (labUom != null)
labResult.setNumericUnit(labUom);
String lowRange = lab.getLowRange();
if (lowRange != null)
labResult.setReferenceRangeLow(Float.parseFloat(lowRange));
String highRange = lab.getHighRange();
if (highRange != null)
labResult.setReferenceRangeHigh(Float.parseFloat(highRange));
labResults[i] = labResult;
i++;
}
labRequest.setLabResult(labResults);
numOfLabs = labResults.length;
//PrintWriter writer = new PrintWriter("caAERSmessage.xml");
QName lab = new QName("http://integration/caaers.nci.nih.gov/services","LoadLabsRequest");
//Utils.serializeObject(labRequest, lab, writer);
// Create the caxchange message
Message requestMessage = new Message();
Metadata metadata = new Metadata();
metadata.setExternalIdentifier("CTODS");
Credentials creds = new Credentials();
creds.setUserName(username);
String credentialEpr = (String)request.getSession().getAttribute("CAGRID_SSO_DELEGATION_SERVICE_EPR");
logDB.info("The credential EPR: "+ credentialEpr);
if (credentialEpr != null)
creds.setDelegatedCredentialReference(credentialEpr);
metadata.setCredentials(creds);
metadata.setMessageType(MessageTypes.LAB_BASED_AE);
requestMessage.setMetadata(metadata);
Request caxchangeRequest = new Request();
requestMessage.setRequest(caxchangeRequest);
MessagePayload messagePayload = new MessagePayload();
URI uri = new URI();
uri.setPath("gme://ccts.cabig/1.0/gov.nih.nci.cabig.ccts.domain");
messagePayload.setXmlSchemaDefinition(uri);
MessageElement messageElement = new MessageElement(lab, labRequest);
messagePayload.set_any(new MessageElement[]{messageElement});
requestMessage.getRequest().setBusinessMessagePayload(messagePayload);
CaXchangeResponseServiceReference crsr = client.processRequestAsynchronously(requestMessage);
CaXchangeResponseServiceClient responseService = new CaXchangeResponseServiceClient(crsr.getEndpointReference());
boolean gotResponse=false;
int responseCount = 0;
ResponseMessage responseMessage = null;
while(!gotResponse)
{
try
{
responseMessage = responseService.getResponse();
gotResponse = true;
}
catch (Exception e)
{
logDB.info("No response from caxchange", e);
responseCount++;
if (responseCount > 60)
{
logDB.error("Never got a response from caxchange hub");
throw new Exception("No response from hub");
}
Thread.sleep(1000);
}
}
if (responseMessage != null)
{
Response resp = responseMessage.getResponse();
logDB.info("caXchange response was " + resp.getResponseStatus().toString());
if (resp.getResponseStatus().equals(Statuses.SUCCESS))
{
if(resp.getCaXchangeError()!=null){
String message = resp.getCaXchangeError().getErrorDescription();
logDB.info("Received a success from caxchange hub: " + message);
}
if(resp.getTargetResponse()!=null)
{
for(TargetResponseMessage msg: resp.getTargetResponse()){
MessageElement[] messagePay = msg.getTargetBusinessMessage().get_any();
for(MessageElement mEle: messagePay)
{
String mEleValue = mEle.getAttributeValue("Acknowledgement");
if(mEleValue.equalsIgnoreCase("Processed"))
{
logDB.info("Response from Target Service was " + mEleValue);
}
else
{
logDB.error("Received response from Target Service: " + mEleValue);
throw new Exception(mEleValue);
}
}
}
}
}
else if (resp.getResponseStatus().equals(Statuses.FAILURE))
{ String message="";
if(resp.getCaXchangeError()!=null){
message = resp.getCaXchangeError().getErrorDescription();
logDB.error("Received a failure from caxchange hub: " + message);
}else{
if(resp.getTargetResponse()!=null)
{
for(TargetResponseMessage msg: resp.getTargetResponse()){
message = msg.getTargetMessageStatus().getValue() +":" +msg.getTargetError().getErrorDescription();
}
}
}
throw new Exception(message);
}
}
lForm.setRecordId("");
lForm.setRecordId(null);
session.setAttribute("LabResultIDs", labResultIds);
return numOfLabs;
}
|
diff --git a/src/irc/IRCore.java b/src/irc/IRCore.java
index 27f462a..d8ed1c3 100644
--- a/src/irc/IRCore.java
+++ b/src/irc/IRCore.java
@@ -1,293 +1,293 @@
/**
* Copyright (C) 2009-2012 Kenneth Prugh
*
* 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.
*/
package irc;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.ArrayList;
import config.Config;
public class IRCore {
/* Instance Vars */
private final String network;
private final int port;
private final String ident;
private final String password;
private Socket s;
private BufferedReader in;
private BufferedWriter out;
/**
* Create IRC object and connects to network
*
* @param network
* - irc network to connect to
* @param port
* - irc port
* @param ident
* - irc username/identity
*/
public IRCore(Config config) {
this.network = config.getNetwork();
this.port = Integer.parseInt(config.getPort());
this.ident = config.getIdent();
this.password = config.getIdentpassword();
s = connect();
}
/**
* Create socket and connect to objects network/port
*/
private Socket connect() {
try {
s = new Socket(network, port);
s.setKeepAlive(true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
setIn(new BufferedReader(new InputStreamReader(s.getInputStream())));
out = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
sendMsgQueitly("NICK " + ident);
sendMsgQueitly("USER " + ident + " " + network + " bla :" + ident);
sendMsgQueitly("PRIVMSG NickServ :identify " + password);
return s;
}
/**
* Closes this network socket and input/output steams
*
* @throws IOException
*/
public void disconnect() throws IOException {
sendMsgUnfiltered("QUIT :System Hault");
s.close();
System.exit(0);
}
/**
* Recursive word wrap
*
* line - The remaining raw msg to be wrapped
* limit - Max length of a line to be wrapped
* wrapped - List of wrapped strings already processed
*/
private List<String> rwrap(String line, int limit, List<String> wrapped)
{
line = line.trim();
if (line.length() <= limit)
{
wrapped.add(line);
return wrapped;
}
else
{
if (line.charAt(limit-1) == ' ')
{
// We are in luck, we are splitting where a space is!
wrapped.add(line.substring(0, limit-1));
line = line.substring(limit);
return rwrap(line, limit, wrapped);
}
else
{
int iter = limit-1;
// scan backwards until we find a space in the line
- while (line.charAt(iter) != ' ' && iter >= 0)
+ while (iter >= 0 && line.charAt(iter) != ' ')
{
--iter;
}
// the line is one giant word, slice it at max len
if (iter == 0)
{
wrapped.add( line.substring(0, limit));
line = line.substring(limit);
return rwrap(line, limit, wrapped);
}
wrapped.add( line.substring(0, iter+1));
line = line.substring(iter+1);
return rwrap(line, limit, wrapped);
}
}
}
/**
* Wraps the given string at the given length, and returns the resultant
* list
*/
private List<String> wrap(String line, int limit)
{
List<String> wrapped = new ArrayList<String>();
return rwrap(line, limit, wrapped);
}
/**
* Private method to send irc messages to the socket
*
* Adds '\r\n' to the end of messages.
*/
private void sendMsg(String target, String msg) {
// Limit max msg length to 400 arbitarily until proper max length is
// calculated for IRC
int magic_limit = 400;
if (msg.length() > magic_limit)
{
//wrap
for (String line : wrap(msg, magic_limit))
{
line = target + line + "\r\n";
System.out.println("Message: " + line);
try {
out.write(line);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else
{
msg = target + msg + "\r\n";
System.out.println("Message: " + msg);
try {
out.write(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Send msg to socket without checkign for multiline or filtering it at all
*/
private void sendMsgUnfiltered(String msg)
{
msg = msg + "\r\n";
System.out.println("Message: " + msg);
try {
out.write(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Private method to send irc messages to the socket
*
* Adds '\r\n' to the end of messages.
*
* Not printed to console
*
* @param msg
* - The msg to be sent
*/
private void sendMsgQueitly(String msg) {
msg = msg + "\r\n";
try {
out.write(msg);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Send a notice to the specified user
*/
public void sendNotice(String user, String msg) {
String tmpMsg = "NOTICE " + user + " :" + msg;
sendMsgUnfiltered(tmpMsg);
}
/**
* Send a message to the specified channel and user.
*
* Can handle multiline string
*/
public void sendMsgTo(String channel, String user, String msg) {
String tmpMsg = "PRIVMSG " + channel + " :" + user + ": ";
sendMsg(tmpMsg, msg);
}
/**
* Send a query/private message to user
*/
public void sendPrivMsgTo(String user, String msg) {
String tmpMsg = "PRIVMSG " + user + " :";
sendMsg(tmpMsg, msg);
}
/**
* Send message to channel
*
* Currently unfiltered because only admin commands can msg a channel
*/
public void sendMsgToChan(String channel, String msg) {
sendMsgUnfiltered("PRIVMSG " + channel + " :" + msg);
}
/**
* Join specified channel on this network
*
* @param chan
* - Channel to join (#example)
*/
public void joinChannel(String chan) {
String tmp = "JOIN " + chan;
sendMsgUnfiltered(tmp);
}
/**
* Part specified channel on this network
*
* @param chan
* - Channel to part (#example)
*/
public void partChannel(String chan) {
String tmp = "PART " + chan;
sendMsgUnfiltered(tmp);
}
public void setIn(BufferedReader in) {
this.in = in;
}
public BufferedReader getIn() {
return in;
}
/**
* PONG the specified server
*/
public void doPong(String server) {
sendMsgUnfiltered("PONG " + server);
}
}
| true | true | private List<String> rwrap(String line, int limit, List<String> wrapped)
{
line = line.trim();
if (line.length() <= limit)
{
wrapped.add(line);
return wrapped;
}
else
{
if (line.charAt(limit-1) == ' ')
{
// We are in luck, we are splitting where a space is!
wrapped.add(line.substring(0, limit-1));
line = line.substring(limit);
return rwrap(line, limit, wrapped);
}
else
{
int iter = limit-1;
// scan backwards until we find a space in the line
while (line.charAt(iter) != ' ' && iter >= 0)
{
--iter;
}
// the line is one giant word, slice it at max len
if (iter == 0)
{
wrapped.add( line.substring(0, limit));
line = line.substring(limit);
return rwrap(line, limit, wrapped);
}
wrapped.add( line.substring(0, iter+1));
line = line.substring(iter+1);
return rwrap(line, limit, wrapped);
}
}
}
| private List<String> rwrap(String line, int limit, List<String> wrapped)
{
line = line.trim();
if (line.length() <= limit)
{
wrapped.add(line);
return wrapped;
}
else
{
if (line.charAt(limit-1) == ' ')
{
// We are in luck, we are splitting where a space is!
wrapped.add(line.substring(0, limit-1));
line = line.substring(limit);
return rwrap(line, limit, wrapped);
}
else
{
int iter = limit-1;
// scan backwards until we find a space in the line
while (iter >= 0 && line.charAt(iter) != ' ')
{
--iter;
}
// the line is one giant word, slice it at max len
if (iter == 0)
{
wrapped.add( line.substring(0, limit));
line = line.substring(limit);
return rwrap(line, limit, wrapped);
}
wrapped.add( line.substring(0, iter+1));
line = line.substring(iter+1);
return rwrap(line, limit, wrapped);
}
}
}
|
diff --git a/src/org/flowvisor/slicer/FVSlicer.java b/src/org/flowvisor/slicer/FVSlicer.java
index 04bc712..b179fe1 100644
--- a/src/org/flowvisor/slicer/FVSlicer.java
+++ b/src/org/flowvisor/slicer/FVSlicer.java
@@ -1,812 +1,812 @@
/**
*
*/
package org.flowvisor.slicer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.flowvisor.api.TopologyCallback;
import org.flowvisor.classifier.FVClassifier;
import org.flowvisor.classifier.FVSendMsg;
import org.flowvisor.config.ConfigError;
import org.flowvisor.config.ConfigurationEvent;
import org.flowvisor.config.FVConfig;
import org.flowvisor.config.FlowvisorChangedListener;
import org.flowvisor.config.FlowvisorImpl;
import org.flowvisor.config.SliceChangedListener;
import org.flowvisor.config.SliceImpl;
import org.flowvisor.events.FVEvent;
import org.flowvisor.events.FVEventHandler;
import org.flowvisor.events.FVEventLoop;
import org.flowvisor.events.FVIOEvent;
import org.flowvisor.events.OFKeepAlive;
import org.flowvisor.events.TearDownEvent;
import org.flowvisor.exceptions.BufferFull;
import org.flowvisor.exceptions.MalformedOFMessage;
import org.flowvisor.exceptions.UnhandledEvent;
import org.flowvisor.flows.FlowMap;
import org.flowvisor.flows.FlowRewriteDB;
import org.flowvisor.flows.FlowSpaceUtil;
import org.flowvisor.flows.LinearFlowRewriteDB;
import org.flowvisor.flows.NoopFlowRewriteDB;
import org.flowvisor.io.FVMessageAsyncStream;
import org.flowvisor.log.FVLog;
import org.flowvisor.log.LogLevel;
import org.flowvisor.log.SendRecvDropStats;
import org.flowvisor.log.SendRecvDropStats.FVStatsType;
import org.flowvisor.message.FVMessageFactory;
import org.flowvisor.message.FVPacketOut;
import org.flowvisor.message.FVPortStatus;
import org.flowvisor.message.SanityCheckable;
import org.flowvisor.message.Slicable;
import org.flowvisor.ofswitch.TopologyController;
import org.openflow.protocol.OFHello;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPhysicalPort;
import org.openflow.protocol.OFPort;
import org.openflow.protocol.OFPortStatus.OFPortReason;
import org.openflow.util.LRULinkedHashMap;
/**
* @author capveg
*
*/
public class FVSlicer implements FVEventHandler, FVSendMsg, FlowvisorChangedListener, SliceChangedListener {
public static final int MessagesPerRead = 50; // for performance tuning
String sliceName;
FVClassifier fvClassifier;
FVEventLoop loop;
SocketChannel sock;
String hostname;
int reconnectSeconds;
final int maxReconnectSeconds = 15;
int port; // the tcp port of our controller
boolean isConnected;
FVMessageAsyncStream msgStream;
short missSendLength;
boolean allowAllPorts;
FlowMap localFlowSpace;
boolean isShutdown;
boolean lldpOptIn = true;
OFKeepAlive keepAlive;
SendRecvDropStats stats;
FlowRewriteDB flowRewriteDB;
boolean floodPerms;
Map<Short, Boolean> allowedPorts; // ports in this slice and whether they
boolean reconnectEventScheduled = false;
LinkedHashMap<Integer, Integer> allowedBufferIDs; // LRU cached list of
// buffer-IDs
// that this slice can address
final private int MAX_ALLOWED_BUFFER_IDS = 256; // max cache size
private Integer fmlimit = -1;
protected FVSlicer() {}
// get OFPP_FLOOD'd
public FVSlicer(FVEventLoop loop, FVClassifier fvClassifier,
String sliceName) {
this.loop = loop;
this.fvClassifier = fvClassifier;
this.sliceName = sliceName;
this.isConnected = false;
this.msgStream = null;
this.missSendLength = 128; // openflow default (?) findout... TODO
this.allowAllPorts = false;
this.reconnectSeconds = 0;
this.isShutdown = false;
this.floodPerms = false;
this.allowedPorts = new HashMap<Short, Boolean>();
this.allowedBufferIDs = new LRULinkedHashMap<Integer, Integer>(10,
MAX_ALLOWED_BUFFER_IDS);
this.stats = SendRecvDropStats.createSharedStats(sliceName);
FlowvisorImpl.addListener(this);//FVConfig.watch(this, FVConfig.FLOW_TRACKING);
try {
setFlowTracking(FlowvisorImpl.getProxy().gettrack_flows());
} catch (ConfigError e) {
setFlowTracking(false);
}
//updateFlowTrackingConfig();
}
/*private void updateFlowTrackingConfig() {
try {
if (FVConfig.getBoolean(FVConfig.FLOW_TRACKING)) {
this.flowRewriteDB = new LinearFlowRewriteDB(this,
this.sliceName, fvClassifier.getDPID());
} else {
this.flowRewriteDB = new NoopFlowRewriteDB(this,
this.sliceName, fvClassifier.getDPID());
}
} catch (ConfigError e) {
// default to flow_tracking == off
this.flowRewriteDB = new NoopFlowRewriteDB(this, this.sliceName,
fvClassifier.getDPID());
}
}*/
public void init() {
FVLog.log(LogLevel.DEBUG, this, "initializing new FVSlicer");
// snag controller info from config
try {
hostname = FVConfig.getSliceHost(sliceName);
port = FVConfig.getSlicePort(sliceName);
lldpOptIn = FVConfig.getLLDPSpam(sliceName);
SliceImpl.addListener(sliceName, this);
} catch (ConfigError e) {
FVLog.log(LogLevel.CRIT, this, "ignoring slice ", sliceName,
" malformed slice definition: ", e);
this.tearDown();
return;
}
this.updatePortList();
this.reconnect();
this.keepAlive = new OFKeepAlive(this, this, loop);
this.keepAlive.scheduleNextCheck();
fvClassifier.loadLimit(sliceName);
try {
this.fmlimit = SliceImpl.getProxy().getMaxFlowMods(sliceName);
} catch (ConfigError e) {
FVLog.log(LogLevel.WARN, this, "Global slice flow mod limit unreadle; disabling.");
this.fmlimit = -1;
}
}
private FlowMap getLocalFlowSpace() {
FlowMap fm = this.fvClassifier.getSwitchFlowMap();
switch (fm.getType()) {
case LINEAR:
return fm.clone();
case FEDERATED:
return fm;
}
FVLog.log(LogLevel.FATAL, null,
"Something is fatally wrong with the flowmap. Cannot determine its type.");
return null;
}
private void updatePortList() {
ArrayList<Short> addedPorts = new ArrayList<Short>();
ArrayList<Short> removedPorts = new ArrayList<Short>();
synchronized (FVConfig.class) {
// update our local copy
this.localFlowSpace = getLocalFlowSpace();
}
Set<Short> ports = FlowSpaceUtil.getPortsBySlice(this.fvClassifier
.getSwitchInfo().getDatapathId(), this.sliceName,
this.localFlowSpace);
if (ports.contains(OFPort.OFPP_ALL.getValue())) {
// this switch has access to ALL PORTS; feed them in from the
// features request
ports.clear(); // remove the OFPP_ALL virtual port
this.allowAllPorts = true;
for (OFPhysicalPort phyPort : this.fvClassifier.getSwitchInfo()
.getPorts())
ports.add(phyPort.getPortNumber());
}
for (Short port : ports) {
if (!allowedPorts.keySet().contains(port)) {
FVLog.log(LogLevel.DEBUG, this, "adding access to port ", port);
allowedPorts.put(port, Boolean.TRUE);
addedPorts.add(port);
}
}
for (Iterator<Short> it = allowedPorts.keySet().iterator(); it
.hasNext();) {
Short port = it.next();
if (!ports.contains(port)) {
FVLog.log(LogLevel.DEBUG, this, "removing access to port ",
port);
it.remove();
removedPorts.add(port);
}
}
updatePortStatus(addedPorts, removedPorts);
}
private void updatePortStatus(ArrayList<Short> addedPorts,
ArrayList<Short> removedPorts) {
for (Short port : addedPorts) {
OFPhysicalPort phyPort = findPhyPort(port);
if (phyPort != null)
sendPortStatusUpdate(phyPort, true);
}
for (Short port : removedPorts) {
OFPhysicalPort phyPort = findPhyPort(port);
if (phyPort != null)
sendPortStatusUpdate(phyPort, false);
}
}
private void sendPortStatusUpdate(OFPhysicalPort phyPort, boolean added) {
FVPortStatus portStatus = new FVPortStatus();
portStatus.setDesc(phyPort);
portStatus.setReason(added ? (byte) OFPortReason.OFPPR_ADD.ordinal() :
(byte) OFPortReason.OFPPR_DELETE.ordinal());
FVLog.log(LogLevel.INFO, this, (added ? "added " : "removed ") + "port " + phyPort.getPortNumber());
sendMsg(portStatus, this);
}
private OFPhysicalPort findPhyPort(Short port) {
for (OFPhysicalPort phyPort : this.fvClassifier.getSwitchInfo()
.getPorts()) {
if (phyPort.getPortNumber() == port)
return phyPort;
}
return null;
}
/**
* Return the list of ports in this slice on this switch
*
* @return
*/
public Set<Short> getPorts() {
return this.allowedPorts.keySet();
}
/**
* Return the list of ports that have flooding enabled for OFPP_FLOOD
*
* @return
*/
public Set<Short> getFloodPorts() {
Set<Short> floodPorts = new LinkedHashSet<Short>();
for (Short port : this.allowedPorts.keySet())
if (this.allowedPorts.get(port))
floodPorts.add(port);
return floodPorts;
}
public boolean isAllowAllPorts() {
return allowAllPorts;
}
/**
* @return the missSendLength
*/
public short getMissSendLength() {
return missSendLength;
}
/**
* @param missSendLength
* the missSendLength to set
*/
public void setMissSendLength(short missSendLength) {
this.missSendLength = missSendLength;
}
/**
* Set the OFPP_FLOOD flag for this port silently fail if this port is not
* in the slice
*
* @param port
* @param status
*/
public void setFloodPortStatus(Short port, Boolean status) {
if (this.allowedPorts.containsKey(port))
this.allowedPorts.put(port, status);
}
/**
* Is this port in this slice on this switch?
*
* @param port
* @return true is yes, false is no.. durh
*/
public boolean portInSlice(Short port) {
return (this.allowAllPorts || this.allowedPorts.containsKey(port));
}
@Override
public void sendMsg(OFMessage msg, FVSendMsg from) {
if (this.msgStream != null) {
FVLog.log(LogLevel.DEBUG, this, "send to controller: ", msg);
try {
this.msgStream.testAndWrite(msg);
} catch (BufferFull e) {
FVLog.log(LogLevel.CRIT, this,
"buffer full: tearing down: got ", e,
": resetting connection");
this.reconnectLater();
} catch (MalformedOFMessage e) {
this.stats.increment(FVStatsType.DROP, from, msg);
FVLog.log(LogLevel.CRIT, this, "BUG: ", e);
} catch (IOException e) {
FVLog.log(LogLevel.WARN, this, "reconnection; got IO error: ",
e);
this.reconnectLater();
}
} else {
this.stats.increment(FVStatsType.DROP, from, msg);
FVLog.log(LogLevel.WARN, this,
"dropping msg: controller not connected: ", msg);
}
}
@Override
public void dropMsg(OFMessage msg, FVSendMsg from) {
this.stats.increment(FVStatsType.DROP, from, msg);
}
@Override
public boolean needsConnect() {
return !this.isConnected; // want connect events if we're not connected
}
@Override
public boolean needsRead() {
return this.isConnected; // want read events if we are connected
}
@Override
public boolean needsWrite() {
if (this.msgStream == null) // want write events if msgStream wants them
return false;
return this.msgStream.needsFlush();
}
@Override
public boolean needsAccept() {
return false;
}
/*
* (non-Javadoc)
*
* @see org.flowvisor.events.FVEventHandler#getName()
*/
@Override
public String getName() {
return new StringBuilder("slicer_").append(this.sliceName).append("_")
.append(fvClassifier.getSwitchName()).toString();
}
/*
* (non-Javadoc)
*
* @see org.flowvisor.events.FVEventHandler#getThreadContext()
*/
@Override
public long getThreadContext() {
return loop.getThreadContext();
}
/*
* (non-Javadoc)
*
* @see org.flowvisor.events.FVEventHandler#tearDown()
*/
@Override
public void tearDown() {
closeDown(true);
}
public void closeDown(boolean unregisterClassifier) {
FVLog.log(LogLevel.DEBUG, this, "tearing down");
this.isShutdown = true;
this.loop.unregister(this.sock, this);
if (this.sock != null) {
try {
this.sock.close(); // FIXME will this also cancel() the key in
// the event loop?
} catch (IOException e) {
// ignore if error... we're shutting down already
}
}
// tell the classifier to forget about us
if (unregisterClassifier)
fvClassifier.tearDownSlice(this.sliceName);
this.msgStream = null; // force this to GC, in case we have a memleak on
// "this"
HashMap<String, Object> info = this.getStatusInfo();
TopologyController tc = TopologyController.getRunningInstance();
if (tc != null)
tc.sliceConnectionJustChanged(info, TopologyCallback.EventType.SLICE_DISCONNECTED);
SliceImpl.removeListener(sliceName, this);
FlowvisorImpl.removeListener(this);
}
private HashMap<String, Object> getStatusInfo() {
HashMap<String, Object> info = new HashMap<String, Object>();
info.put("connection-status", this.isConnected());
info.put("slice-name", this.sliceName);
info.put("controller-host", this.hostname);
info.put("controller-port", this.port);
info.put("shutdown-status", this.isShutdown);
info.put("floodperms", this.floodPerms);
return info;
}
/*
* (non-Javadoc)
*
* @see
* org.flowvisor.events.FVEventHandler#handleEvent(org.flowvisor.events.
* FVEvent)
*/
@Override
public void handleEvent(FVEvent e) throws UnhandledEvent {
if (isShutdown) {
FVLog.log(LogLevel.WARN, this, "is shutdown; ignoring: " + e);
return; // don't process any events after shutdown
}
if (e instanceof FVIOEvent)
handleIOEvent((FVIOEvent) e);
else if (e instanceof OFKeepAlive)
handleKeepAlive(e);
else if (e instanceof ReconnectEvent) {
this.reconnectEventScheduled = false;
this.reconnect();
} else if (e instanceof TearDownEvent)
this.tearDown();
else
throw new UnhandledEvent(e);
}
private void handleKeepAlive(FVEvent e) {
if (!this.keepAlive.isAlive()) {
FVLog.log(LogLevel.WARN, this,
"keepAlive timeout; trying to reconnnect later");
try {
if (this.sock != null)
this.sock.close();
} catch (IOException e1) {
FVLog.log(LogLevel.WARN, this,
"ignoring error while closing socket: ", e1);
}
this.reconnectLater();
return;
}
this.keepAlive.sendPing();
this.keepAlive.scheduleNextCheck();
}
public void registerPong() {
this.keepAlive.registerPong();
}
private void reconnect() {
FVLog.log(LogLevel.INFO, this, "trying to reconnect to ",
this.hostname, ":", this.port);
// reset our state to unconnected (might be a NOOP)
this.isConnected = false;
this.msgStream = null;
// try to connect socket to controller
try {
if (this.sock != null)
// note that this automatically unregisters from selector
this.sock.close();
this.sock = SocketChannel.open();
sock.configureBlocking(false); // set to non-blocking
InetSocketAddress addr = new InetSocketAddress(hostname, port);
if (addr.isUnresolved()) {
FVLog.log(LogLevel.INFO, this,
"retrying: failed to resolve hostname: ", hostname);
this.reconnectLater();
return;
}
this.isConnected = this.sock.connect(addr); // try to connect
// register into event loop
this.loop.register(this.sock, SelectionKey.OP_CONNECT, this);
} catch (IOException e) {
FVLog.log(LogLevel.CRIT, this,
"Trying to reconnect; trying later; got : ", e);
this.reconnectLater();
}
}
private void handleIOEvent(FVIOEvent e) {
if (!this.isConnected) {
try {
if (!this.sock.finishConnect())
return; // not done yet
} catch (IOException e1) {
FVLog.log(LogLevel.DEBUG, this, "retrying connection in ",
this.reconnectSeconds, " seconds; got: ", e1);
this.reconnectLater();
return;
}
FVLog.log(LogLevel.DEBUG, this, "connected");
this.isConnected = true;
HashMap<String, Object> info = this.getStatusInfo();
TopologyController tc = TopologyController.getRunningInstance();
if (tc != null)
tc.sliceConnectionJustChanged(info, TopologyCallback.EventType.SLICE_CONNECTED);
this.reconnectSeconds = 0;
try {
msgStream = new FVMessageAsyncStream(this.sock,
new FVMessageFactory(), this, this.stats);
} catch (IOException e1) {
FVLog.log(
LogLevel.WARN,
this,
"Trying again later; while creating OFMessageAsyncStream, got: ",
e1);
this.reconnectLater();
return;
}
sendMsg(new OFHello(), this); // send initial handshake
}
try {
if (msgStream.needsFlush()) // flush any pending messages
msgStream.flush();
List<OFMessage> msgs = this.msgStream.read();
// .read(FVSlicer.MessagesPerRead); // read any new
// messages
if (msgs == null)
throw new IOException("got null from read()");
for (OFMessage msg : msgs) {
FVLog.log(LogLevel.DEBUG, this, "recv from controller: ", msg);
this.stats.increment(FVStatsType.SEND, this, msg);
if ((msg instanceof SanityCheckable)
&& (!((SanityCheckable) msg).isSane())) {
FVLog.log(LogLevel.CRIT, this,
"msg failed sanity check; dropping: " + msg);
continue;
}
if (msg instanceof Slicable) {
((Slicable) msg).sliceFromController(fvClassifier, this);
// mark this channel as still alive
this.keepAlive.registerPong();
} else
FVLog.log(LogLevel.CRIT, this,
"dropping msg that doesn't implement classify: ",
msg);
}
} catch (IOException e1) {
FVLog.log(LogLevel.WARN, this,
"got i/o error; tearing down and reconnecting: ", e1);
reconnect();
} catch (Exception e2) {
e2.printStackTrace();
FVLog.log(LogLevel.ALERT, this,
- "got unknown error; tearing down and reconnecting: " , e2);
+ "got unknown error; tearing down and reconnecting: " , e2.printStackTrace());
reconnect();
}
// no need to setup for next select; done in eventloop
}
private void reconnectLater() {
if (this.sock != null)
try {
this.sock.close();
this.sock = null;
this.isConnected = false;
HashMap<String, Object> info = this.getStatusInfo();
TopologyController tc = TopologyController.getRunningInstance();
if (tc != null)
tc.sliceConnectionJustChanged(info, TopologyCallback.EventType.SLICE_DISCONNECTED);
/*
* Place slice connection callback here
*/
} catch (IOException e) {
FVLog.log(LogLevel.WARN, this,
"ignoring error closing socket: ", e);
}
if (this.reconnectEventScheduled) {
// Don't schedule another reconnect, one's already in there
return;
}
// exponential back off
this.reconnectSeconds = Math.min(2 * this.reconnectSeconds + 1,
this.maxReconnectSeconds);
this.loop.addTimer(new ReconnectEvent(this.reconnectSeconds, this));
this.reconnectEventScheduled = true;
}
public String getSliceName() {
return this.sliceName;
}
public boolean getFloodPortStatus(short port) {
return this.allowedPorts.get(port);
}
public FlowMap getFlowSpace() {
return this.localFlowSpace;
}
@Override
public String getConnectionName() {
if (isConnected)
return FlowSpaceUtil.connectionToString(sock);
else
return "NONE (retry in " + this.reconnectSeconds
+ " seconds: max + " + this.maxReconnectSeconds + ")";
}
public boolean isConnected() {
return this.isConnected;
}
@Override
public SendRecvDropStats getStats() {
return stats;
}
/**
* @return the flowRewriteDB
*/
public FlowRewriteDB getFlowRewriteDB() {
return flowRewriteDB;
}
/**
* @param flowRewriteDB
* the flowRewriteDB to set
*/
public void setFlowRewriteDB(FlowRewriteDB flowRewriteDB) {
this.flowRewriteDB = flowRewriteDB;
}
/**
* @return the floodPerms
*/
public boolean hasFloodPerms() {
return floodPerms;
}
/**
* @return whether the slice is opted in for lldp messages that aren't
* from it's slice
*/
public boolean isOptedIn() {
return lldpOptIn;
}
/**
* @param floodPerms
* the floodPerms to set
*/
public void setFloodPerms(boolean floodPerms) {
this.floodPerms = floodPerms;
}
/**
* Check to see if this buffer_id is in the list of IDs that this slice is
* allowed to address
*
* if bufferID==NONE, then always allow
*
* if yes, for fun, increment a counter to see how often the buffer is
* referenced
*
* @param bufferID
* from, e.g., FVPacketOut->bufferID
* @return
*/
public boolean isBufferIDAllowed(int bufferID) {
if (bufferID == FVPacketOut.BUFFER_ID_NONE)
return true; // always allowed
Integer count = this.allowedBufferIDs.get(bufferID);
if (count == null)
return false; // not allowed
this.allowedBufferIDs.put(bufferID, count + 1);
return true;
}
/**
* Mark this bufferID as allowed and init its access count to zero
*
* @param bufferID
* from, e.g., FVPacketIn->bufferID
*/
public void setBufferIDAllowed(int bufferID) {
FVLog.log(LogLevel.DEBUG, this, "allowing bufferID: ", bufferID);
this.allowedBufferIDs.put(bufferID, 0);
}
/*
* Aweful temporary fix to support linear flowmap copying....
* this sux, can't stress it enough.
*
* Hopefully one day we will remove the need to copy
* the linear flow space all over the place!
*
* Called by FVClassifier when he updates his flowspace.
*/
public void updateFlowSpace() {
updatePortList();
/*
* FIXME: need to flush old flow entries
*/
}
@Override
public void processChange(ConfigurationEvent event) {
event.invoke();
}
@Override
public void setFlowTracking(Boolean in) {
if (in) {
this.flowRewriteDB = new LinearFlowRewriteDB(this,
this.sliceName, fvClassifier.getDPID());
} else {
this.flowRewriteDB = new NoopFlowRewriteDB(this,
this.sliceName, fvClassifier.getDPID());
}
}
@Override
public void setControllerHost(String in) {
this.hostname = in;
}
@Override
public void setControllerPort(Integer in) {
this.port = in;
}
@Override
public void setStatsDescHack(Boolean in) {}
@Override
public void setFloodPerm(String in) {}
@Override
public void setLLDP(Boolean in) {
lldpOptIn = in;
}
@Override
public void setDropPolicy(String in) {}
@Override
public void setFlowModLimit(Integer in) {
this.fmlimit = in;
}
public void incrementFlowRules(){
fvClassifier.incrementFlowMod(sliceName);
fvClassifier.getSlicerLimits().incrementSliceFMCounter(sliceName);
}
public void decrementFlowRules(){
fvClassifier.decrementFlowMod(sliceName);
fvClassifier.getSlicerLimits().decrementSliceFMCounter(sliceName);
}
public boolean permitFlowMod() {
if (fmlimit == -1)
return true && fvClassifier.permitFlowMod(sliceName);
int currlimit = fvClassifier.getSlicerLimits().getSliceFMLimit(sliceName);
return ((currlimit < fmlimit) && (fvClassifier.permitFlowMod(sliceName)));
}
}
| true | true | private void handleIOEvent(FVIOEvent e) {
if (!this.isConnected) {
try {
if (!this.sock.finishConnect())
return; // not done yet
} catch (IOException e1) {
FVLog.log(LogLevel.DEBUG, this, "retrying connection in ",
this.reconnectSeconds, " seconds; got: ", e1);
this.reconnectLater();
return;
}
FVLog.log(LogLevel.DEBUG, this, "connected");
this.isConnected = true;
HashMap<String, Object> info = this.getStatusInfo();
TopologyController tc = TopologyController.getRunningInstance();
if (tc != null)
tc.sliceConnectionJustChanged(info, TopologyCallback.EventType.SLICE_CONNECTED);
this.reconnectSeconds = 0;
try {
msgStream = new FVMessageAsyncStream(this.sock,
new FVMessageFactory(), this, this.stats);
} catch (IOException e1) {
FVLog.log(
LogLevel.WARN,
this,
"Trying again later; while creating OFMessageAsyncStream, got: ",
e1);
this.reconnectLater();
return;
}
sendMsg(new OFHello(), this); // send initial handshake
}
try {
if (msgStream.needsFlush()) // flush any pending messages
msgStream.flush();
List<OFMessage> msgs = this.msgStream.read();
// .read(FVSlicer.MessagesPerRead); // read any new
// messages
if (msgs == null)
throw new IOException("got null from read()");
for (OFMessage msg : msgs) {
FVLog.log(LogLevel.DEBUG, this, "recv from controller: ", msg);
this.stats.increment(FVStatsType.SEND, this, msg);
if ((msg instanceof SanityCheckable)
&& (!((SanityCheckable) msg).isSane())) {
FVLog.log(LogLevel.CRIT, this,
"msg failed sanity check; dropping: " + msg);
continue;
}
if (msg instanceof Slicable) {
((Slicable) msg).sliceFromController(fvClassifier, this);
// mark this channel as still alive
this.keepAlive.registerPong();
} else
FVLog.log(LogLevel.CRIT, this,
"dropping msg that doesn't implement classify: ",
msg);
}
} catch (IOException e1) {
FVLog.log(LogLevel.WARN, this,
"got i/o error; tearing down and reconnecting: ", e1);
reconnect();
} catch (Exception e2) {
e2.printStackTrace();
FVLog.log(LogLevel.ALERT, this,
"got unknown error; tearing down and reconnecting: " , e2);
reconnect();
}
// no need to setup for next select; done in eventloop
}
| private void handleIOEvent(FVIOEvent e) {
if (!this.isConnected) {
try {
if (!this.sock.finishConnect())
return; // not done yet
} catch (IOException e1) {
FVLog.log(LogLevel.DEBUG, this, "retrying connection in ",
this.reconnectSeconds, " seconds; got: ", e1);
this.reconnectLater();
return;
}
FVLog.log(LogLevel.DEBUG, this, "connected");
this.isConnected = true;
HashMap<String, Object> info = this.getStatusInfo();
TopologyController tc = TopologyController.getRunningInstance();
if (tc != null)
tc.sliceConnectionJustChanged(info, TopologyCallback.EventType.SLICE_CONNECTED);
this.reconnectSeconds = 0;
try {
msgStream = new FVMessageAsyncStream(this.sock,
new FVMessageFactory(), this, this.stats);
} catch (IOException e1) {
FVLog.log(
LogLevel.WARN,
this,
"Trying again later; while creating OFMessageAsyncStream, got: ",
e1);
this.reconnectLater();
return;
}
sendMsg(new OFHello(), this); // send initial handshake
}
try {
if (msgStream.needsFlush()) // flush any pending messages
msgStream.flush();
List<OFMessage> msgs = this.msgStream.read();
// .read(FVSlicer.MessagesPerRead); // read any new
// messages
if (msgs == null)
throw new IOException("got null from read()");
for (OFMessage msg : msgs) {
FVLog.log(LogLevel.DEBUG, this, "recv from controller: ", msg);
this.stats.increment(FVStatsType.SEND, this, msg);
if ((msg instanceof SanityCheckable)
&& (!((SanityCheckable) msg).isSane())) {
FVLog.log(LogLevel.CRIT, this,
"msg failed sanity check; dropping: " + msg);
continue;
}
if (msg instanceof Slicable) {
((Slicable) msg).sliceFromController(fvClassifier, this);
// mark this channel as still alive
this.keepAlive.registerPong();
} else
FVLog.log(LogLevel.CRIT, this,
"dropping msg that doesn't implement classify: ",
msg);
}
} catch (IOException e1) {
FVLog.log(LogLevel.WARN, this,
"got i/o error; tearing down and reconnecting: ", e1);
reconnect();
} catch (Exception e2) {
e2.printStackTrace();
FVLog.log(LogLevel.ALERT, this,
"got unknown error; tearing down and reconnecting: " , e2.printStackTrace());
reconnect();
}
// no need to setup for next select; done in eventloop
}
|
diff --git a/src/features/gui/explorer/PreprocessPanel.java b/src/features/gui/explorer/PreprocessPanel.java
index 5b09d08..8abf342 100644
--- a/src/features/gui/explorer/PreprocessPanel.java
+++ b/src/features/gui/explorer/PreprocessPanel.java
@@ -1,1658 +1,1660 @@
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* PreprocessPanel.java
* Copyright (C) 2003 University of Waikato, Hamilton, New Zealand
*
*/
package features.gui.explorer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileFilter;
import features.core.Attribute;
import features.core.Capabilities;
import features.core.CapabilitiesHandler;
import features.core.Instance;
import features.core.Instances;
import features.core.OptionHandler;
import features.core.Utils;
import features.core.converters.AbstractFileLoader;
import features.core.converters.AbstractFileSaver;
import features.core.converters.ConverterUtils;
import features.core.converters.Loader;
import features.core.converters.SerializedInstancesLoader;
import features.core.converters.URLSourcedLoader;
import features.datagenerators.DataGenerator;
import features.experiment.InstanceQuery;
import features.filters.Filter;
import features.filters.SupervisedFilter;
import features.filters.unsupervised.attribute.Remove;
import features.gui.AttributeSelectionPanel;
import features.gui.AttributeSummaryPanel;
import features.gui.AttributeVisualizationPanel;
import features.gui.ConverterFileChooser;
import features.gui.GenericObjectEditor;
import features.gui.InstancesSummaryPanel;
import features.gui.Logger;
import features.gui.PropertyDialog;
import features.gui.PropertyPanel;
import features.gui.SysErrLog;
import features.gui.TaskLogger;
import features.gui.ViewerDialog;
import features.gui.explorer.Explorer.CapabilitiesFilterChangeEvent;
import features.gui.explorer.Explorer.CapabilitiesFilterChangeListener;
import features.gui.explorer.Explorer.ExplorerPanel;
import features.gui.explorer.Explorer.LogHandler;
import features.gui.sql.SqlViewerDialog;
/**
* This panel controls simple preprocessing of instances. Summary
* information on instances and attributes is shown. Filters may be
* configured to alter the set of instances. Altered instances may
* also be saved.
*
* @author Richard Kirkby ([email protected])
* @author Len Trigg ([email protected])
* @version $Revision: 8007 $
*/
public class PreprocessPanel
extends JPanel
implements CapabilitiesFilterChangeListener, ExplorerPanel, LogHandler {
/** for serialization */
private static final long serialVersionUID = 6764850273874813049L;
/** Displays simple stats on the working instances */
protected InstancesSummaryPanel m_InstSummaryPanel =
new InstancesSummaryPanel();
/** Click to load base instances from a file */
protected JButton m_OpenFileBut = new JButton(Messages.getInstance().getString("PreprocessPanel_OpenFileBut_JButton_Text"));
/** Click to load base instances from a URL */
protected JButton m_OpenURLBut = new JButton(Messages.getInstance().getString("PreprocessPanel_OpenURLBut_JButton_Text"));
/** Click to load base instances from a Database */
protected JButton m_OpenDBBut = new JButton(Messages.getInstance().getString("PreprocessPanel_OpenDBBut_JButton_Text"));
/** Click to generate artificial data */
protected JButton m_GenerateBut = new JButton(Messages.getInstance().getString("PreprocessPanel_GenerateBut_JButton_Text"));
/** Click to revert back to the last saved point */
protected JButton m_UndoBut = new JButton(Messages.getInstance().getString("PreprocessPanel_UndoBut_JButton_Text"));
/** Click to open the current instances in a viewer */
protected JButton m_EditBut = new JButton(Messages.getInstance().getString("PreprocessPanel_EditBut_JButton_Text"));
/** Click to apply filters and save the results */
protected JButton m_SaveBut = new JButton(Messages.getInstance().getString("PreprocessPanel_SaveBut_JButton_Text"));
/** Panel to let the user toggle attributes */
protected AttributeSelectionPanel m_AttPanel = new AttributeSelectionPanel();
/** Button for removing attributes */
protected JButton m_RemoveButton = new JButton(Messages.getInstance().getString("PreprocessPanel_RemoveButton_JButton_Text"));
/** Button for doing feature selection */
protected JButton m_FeatureSelectionButton = new JButton("Apply Feature Selection");
/** Displays summary stats on the selected attribute */
protected AttributeSummaryPanel m_AttSummaryPanel =
new AttributeSummaryPanel();
/** Lets the user configure the filter */
protected GenericObjectEditor m_FilterEditor =
new GenericObjectEditor();
/** Filter configuration */
protected PropertyPanel m_FilterPanel = new PropertyPanel(m_FilterEditor);
/** Click to apply filters and save the results */
protected JButton m_ApplyFilterBut = new JButton(Messages.getInstance().getString("PreprocessPanel_ApplyFilterBut_JButton_Text"));
/** The file chooser for selecting data files */
protected ConverterFileChooser m_FileChooser
= new ConverterFileChooser(new File(ExplorerDefaults.getInitialDirectory()));
/** Stores the last URL that instances were loaded from */
protected String m_LastURL = "http://";
/** Stores the last sql query executed */
protected String m_SQLQ = new String("SELECT * FROM ?");
/** The working instances */
protected Instances m_Instances;
/** The last generator that was selected */
protected DataGenerator m_DataGenerator = null;
/** The visualization of the attribute values */
protected AttributeVisualizationPanel m_AttVisualizePanel =
new AttributeVisualizationPanel();
/** Keeps track of undo points */
protected File[] m_tempUndoFiles = new File[20]; // set number of undo ops here
/** The next available slot for an undo point */
protected int m_tempUndoIndex = 0;
/**
* Manages sending notifications to people when we change the set of
* working instances.
*/
protected PropertyChangeSupport m_Support = new PropertyChangeSupport(this);
/** A thread for loading/saving instances from a file or URL */
protected Thread m_IOThread;
/** The message logger */
protected Logger m_Log = new SysErrLog();
/** the parent frame */
protected Explorer m_Explorer = null;
static {
GenericObjectEditor.registerEditors();
}
/**
* Creates the instances panel with no initial instances.
*/
public PreprocessPanel() {
// Create/Configure/Connect components
m_FilterEditor.setClassType(features.filters.Filter.class);
if (ExplorerDefaults.getFilter() != null)
m_FilterEditor.setValue(ExplorerDefaults.getFilter());
m_FilterEditor.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
m_ApplyFilterBut.setEnabled(getInstances() != null);
Capabilities currentCapabilitiesFilter = m_FilterEditor.getCapabilitiesFilter();
Filter filter = (Filter) m_FilterEditor.getValue();
Capabilities currentFilterCapabilities = null;
if (filter != null && currentCapabilitiesFilter != null &&
(filter instanceof CapabilitiesHandler)) {
currentFilterCapabilities = ((CapabilitiesHandler)filter).getCapabilities();
if (!currentFilterCapabilities.supportsMaybe(currentCapabilitiesFilter) &&
!currentFilterCapabilities.supports(currentCapabilitiesFilter)) {
try {
filter.setInputFormat(getInstances());
} catch (Exception ex) {
m_ApplyFilterBut.setEnabled(false);
}
}
}
}
});
m_OpenFileBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_OpenFileBut_SetToolTipText_Text"));
m_OpenURLBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_OpenURLBut_SetToolTipText_Text"));
m_OpenDBBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_OpenDBBut_SetToolTipText_Text"));
m_GenerateBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_GenerateBut_SetToolTipText_Text"));
m_UndoBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_UndoBut_SetToolTipText_Text"));
m_UndoBut.setEnabled(ExplorerDefaults.get("enableUndo", "true").equalsIgnoreCase("true"));
if (!m_UndoBut.isEnabled()) {
m_UndoBut.setToolTipText("Undo is disabled - " +
"see features.gui.explorer.Explorer.props to enable");
}
m_EditBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_EditBut_SetToolTipText_Text"));
m_SaveBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_SaveBut_SetToolTipText_Text"));
m_ApplyFilterBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ApplyFilterBut_SetToolTipText_Text"));
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
m_OpenURLBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setInstancesFromURLQ();
}
});
m_OpenDBBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SqlViewerDialog dialog = new SqlViewerDialog(null);
dialog.setVisible(true);
if (dialog.getReturnValue() == JOptionPane.OK_OPTION)
setInstancesFromDBQ(dialog.getURL(), dialog.getUser(),
dialog.getPassword(), dialog.getQuery());
}
});
m_OpenFileBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setInstancesFromFileQ();
}
});
m_GenerateBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
generateInstances();
}
});
m_UndoBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
undo();
}
});
m_EditBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
edit();
}
});
m_SaveBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveWorkingInstancesToFileQ();
}
});
m_ApplyFilterBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applyFilter((Filter) m_FilterEditor.getValue());
}
});
m_AttPanel.getSelectionModel()
.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
ListSelectionModel lm = (ListSelectionModel) e.getSource();
for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) {
if (lm.isSelectedIndex(i)) {
m_AttSummaryPanel.setAttribute(i);
m_AttVisualizePanel.setAttribute(i);
break;
}
}
}
}
});
m_InstSummaryPanel.setBorder(BorderFactory.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_InstSummaryPanel_BorderFactoryCreateTitledBorder_Text")));
JPanel attStuffHolderPanel = new JPanel();
attStuffHolderPanel.setBorder(BorderFactory
.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_AttStuffHolderPanel_BorderFactoryCreateTitledBorder_Text")));
attStuffHolderPanel.setLayout(new BorderLayout());
attStuffHolderPanel.add(m_AttPanel, BorderLayout.CENTER);
m_RemoveButton.setEnabled(false);
m_RemoveButton.setToolTipText(Messages.getInstance().getString("PreprocessPanel_RemoveButton_SetToolTipText_Text"));
m_RemoveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Remove r = new Remove();
int [] selected = m_AttPanel.getSelectedAttributes();
if (selected.length == 0) {
return;
}
if (selected.length == m_Instances.numAttributes()) {
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_First"));
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_First"));
return;
}
r.setAttributeIndicesArray(selected);
applyFilter(r);
} catch (Exception ex) {
if (m_Log instanceof TaskLogger) {
((TaskLogger)m_Log).taskFinished();
}
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Third")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_Second") + ex.getMessage());
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_Second"));
}
}
});
m_FeatureSelectionButton.setEnabled(false);
m_FeatureSelectionButton.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_SetToolTipText_Text"));
m_FeatureSelectionButton.addActionListener(new ActionListener() {
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
try {
+ //attribute map stores mappingbetween attributes and information gain
Map<Attribute, Double> attributeMap = new HashMap<Attribute, Double>();
int classIndex = m_Instances.numAttributes() - 1;
List<String> classValues = new ArrayList<String>();
Map<String, Integer> classSamples = new HashMap<String, Integer>();
Enumeration classAttrValues = m_Instances.attribute(classIndex).enumerateValues();
while(classAttrValues.hasMoreElements()) {
String attrValue = classAttrValues.nextElement().toString();
classValues.add(attrValue);
classSamples.put(attrValue, 0);
}
/*Enumeration<Attribute> enu = m_Instances.enumerateAttributes();
while (enu.hasMoreElements()) {
Attribute attribute = enu.nextElement();
attributeMap.put(attribute.name(), 0.0);
}*/
for (int i = 0; i < m_Instances.numInstances(); i++) {
Instance currentInst = m_Instances.instance(i);
if (currentInst.isMissing(classIndex)) {
break;
}
String instClassValue = currentInst.stringValue(classIndex);
if(classSamples.containsKey(instClassValue)) {
int currCount = classSamples.get(instClassValue).intValue();
classSamples.put(instClassValue, new Integer(currCount+1));
} else {
System.out.println("ERROR -- Something is wrong, check again");
}
}
double sampleClassInformation = 0.0;
Iterator it2 = classSamples.entrySet().iterator();
int totalInstances = m_Instances.numInstances();
for (Entry<String, Integer> entry : classSamples.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue()); // Change this to whatever you need
try {
int currClassValue = entry.getValue().intValue();
double temp = currClassValue * 1.0 / totalInstances;
- temp = temp * (Math.log10(temp) / Math.log10(2));
+ if( temp > 0)
+ temp = temp * (Math.log10(temp) / Math.log10(2));
sampleClassInformation +=temp;
} catch (NumberFormatException ne) {
System.out.println("Caught number format exception at line 415" + ne);
}
}
sampleClassInformation *= -1;
System.out.println("The sample class information is " + sampleClassInformation);
Enumeration<Attribute> enu = m_Instances.enumerateAttributes();
while (enu.hasMoreElements()) {
Attribute attribute = (Attribute) enu.nextElement();
attributeMap.put(attribute, 0.0);
double attributeEntropy = 0.0;
Map<String, HashMap<String, Integer>> attrValues = new HashMap<String, HashMap<String, Integer>>();
/*iterate over the instances
* if you find the attribute value in the map increment the count
* else add and set the count to 1
*/
int setCount = 0;
if (m_Instances.numInstances() > 0) {
for (int i = 0; i < m_Instances.numInstances(); i++) {
Instance currentInst = m_Instances.instance(i);
if (currentInst.isMissing(attribute)) {
break;
}
String curr;
String classvalue = currentInst.stringValue(classIndex);
if (!attribute.isNumeric()) {
curr = currentInst.stringValue(attribute);
} else {
curr = Double.toString(currentInst.value(attribute));
}
try {
if(!attrValues.containsKey(curr)) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (Entry<String, Integer> entry : classSamples.entrySet()) {
map.put(entry.getKey(), 0);
}
//map.put(classvalue, map.get(classvalue) + 1);
attrValues.put(curr, (HashMap<String, Integer>) map);
}
@SuppressWarnings("unchecked")
Map<String, Integer> attrMap = (HashMap<String, Integer>)attrValues.get(curr);
attrMap.put(classvalue, attrMap.get(classvalue) + 1);
attrValues.put(curr, (HashMap<String, Integer>) attrMap);
} catch (Exception ek) {
System.out.println("Cannot find matching classvalue in the map");
}
setCount++;
}
for(Entry<String, HashMap<String, Integer>> setEntry : attrValues.entrySet()) {
Map<String, Integer> classSetEntry = (HashMap<String, Integer>)setEntry.getValue();
double attributeSetInformation = 0.0;
int tempSetCount = 0;
for(Entry<String,Integer> entry : classSetEntry.entrySet()) {
if (entry.getValue().intValue() > 0 ) {
tempSetCount += entry.getValue().intValue();
}
}
for(Entry<String,Integer> entry : classSetEntry.entrySet()) {
if (entry.getValue().intValue() > 0 ) {
double probability = entry.getValue().intValue() / (tempSetCount * 1.0);
probability = probability * (Math.log10(probability) / Math.log10(2));
attributeSetInformation +=probability;
}
}
attributeEntropy += (tempSetCount * 1.0 / m_Instances.numInstances()) * attributeSetInformation;
}
}
System.out.println("Done");
/*here we check for every attribute value set to
* check for class value distribution
*/
/*reset class samples*/
attributeEntropy *= -1;
attributeMap.put(attribute, attributeEntropy);
// Iterator it = attributeMap.entrySet().iterator();
// while (it.hasNext()) {
// Map.Entry pairs = (Map.Entry)it.next();
// System.out.println(pairs.getKey() + " = " + pairs.getValue());
// Attribute attr = m_Instances.attribute((String)pairs.getKey());
// Enumeration attrValues1 = m_Instances.attribute(34).enumerateValues();
// attr.enumerateValues();
// System.out.println("no problem got it");
// }
}
for(Entry<Attribute, Double> attrEntry : attributeMap.entrySet()) {
System.out.println("Attribute = " + attrEntry.getKey().name() + "::: " + attrEntry.getValue().doubleValue() + ":::" + (sampleClassInformation - attrEntry.getValue().doubleValue()));
}
/*lets remove unwanted attributes
* and perform naive bayes on remaining attributes
*/
try {
Remove r = new Remove();
int [] r1 = new int[attributeMap.size()];
Arrays.fill(r1, 0);
int selCount = 0;
for(Entry<Attribute, Double> attrEntry : attributeMap.entrySet()) {
if ((sampleClassInformation - attrEntry.getValue().doubleValue()) < 0.1) {
r1[selCount] = attrEntry.getKey().index();
selCount++;
}
}
int [] selected = new int[selCount];
System.arraycopy(r1, 0, selected, 0, selCount);
if (selected.length == 0) {
return;
}
if (selected.length == m_Instances.numAttributes()) {
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_First"));
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_First"));
return;
}
r.setAttributeIndicesArray(selected);
applyFilter(r);
} catch (Exception ex) {
if (m_Log instanceof TaskLogger) {
((TaskLogger)m_Log).taskFinished();
}
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Third")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_Second") + ex.getMessage());
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_Second"));
}
} catch (Exception e1) {
System.out.println("Main Loop");
}
}
});
JPanel p1 = new JPanel();
p1.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
p1.setLayout(new BorderLayout());
p1.add(m_RemoveButton, BorderLayout.CENTER);
p1.add(m_FeatureSelectionButton, BorderLayout.LINE_END); //sonal added functionality to remove the features with low IF
attStuffHolderPanel.add(p1, BorderLayout.SOUTH);
m_AttSummaryPanel.setBorder(BorderFactory
.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_AttSummaryPanel_BorderFactoryCreateTitledBorder_Text")));
m_UndoBut.setEnabled(false);
m_EditBut.setEnabled(false);
m_SaveBut.setEnabled(false);
m_ApplyFilterBut.setEnabled(false);
// Set up the GUI layout
JPanel buttons = new JPanel();
buttons.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
buttons.setLayout(new GridLayout(1, 6, 5, 5));
buttons.add(m_OpenFileBut);
//buttons.add(m_OpenURLBut);
//buttons.add(m_OpenDBBut);
/*buttons.add(m_GenerateBut);
buttons.add(m_UndoBut);
buttons.add(m_EditBut);
buttons.add(m_SaveBut);
*/
JPanel attInfo = new JPanel();
attInfo.setLayout(new BorderLayout());
attInfo.add(attStuffHolderPanel, BorderLayout.CENTER);
JPanel filter = new JPanel();
filter.setBorder(BorderFactory
.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_Filter_BorderFactoryCreateTitledBorder_Text")));
filter.setLayout(new BorderLayout());
filter.add(m_FilterPanel, BorderLayout.CENTER);
filter.add(m_ApplyFilterBut, BorderLayout.EAST);
JPanel attVis = new JPanel();
attVis.setLayout( new GridLayout(2,1) );
attVis.add(m_AttSummaryPanel);
JComboBox colorBox = m_AttVisualizePanel.getColorBox();
colorBox.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ColorBox_SetToolTipText_Text"));
colorBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
updateCapabilitiesFilter(m_FilterEditor.getCapabilitiesFilter());
}
}
});
final JButton visAllBut = new JButton(Messages.getInstance().getString("PreprocessPanel_VisAllBut_JButton_Text"));
visAllBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (m_Instances != null) {
try {
final features.gui.beans.AttributeSummarizer as =
new features.gui.beans.AttributeSummarizer();
as.setColoringIndex(m_AttVisualizePanel.getColoringIndex());
as.setInstances(m_Instances);
final javax.swing.JFrame jf = new javax.swing.JFrame();
jf.getContentPane().setLayout(new java.awt.BorderLayout());
jf.getContentPane().add(as, java.awt.BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
visAllBut.setEnabled(true);
jf.dispose();
}
});
jf.setSize(830,600);
jf.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
JPanel histoHolder = new JPanel();
histoHolder.setLayout(new BorderLayout());
histoHolder.add(m_AttVisualizePanel, BorderLayout.CENTER);
JPanel histoControls = new JPanel();
histoControls.setLayout(new BorderLayout());
histoControls.add(colorBox, BorderLayout.CENTER);
histoControls.add(visAllBut, BorderLayout.EAST);
histoHolder.add(histoControls, BorderLayout.NORTH);
attVis.add(histoHolder);
JPanel lhs = new JPanel();
lhs.setLayout(new BorderLayout());
lhs.add(m_InstSummaryPanel, BorderLayout.NORTH);
lhs.add(attInfo, BorderLayout.CENTER);
JPanel rhs = new JPanel();
rhs.setLayout(new BorderLayout());
//rhs.add(attVis, BorderLayout.CENTER);
JPanel relation = new JPanel();
relation.setLayout(new GridLayout(1, 2));
relation.add(lhs);
relation.add(rhs);
JPanel middle = new JPanel();
middle.setLayout(new BorderLayout());
// middle.add(filter, BorderLayout.NORTH);
middle.add(relation, BorderLayout.CENTER);
setLayout(new BorderLayout());
add(buttons, BorderLayout.NORTH);
add(middle, BorderLayout.CENTER);
}
/**
* Sets the Logger to receive informational messages
*
* @param newLog the Logger that will now get info messages
*/
public void setLog(Logger newLog) {
m_Log = newLog;
}
/**
* Tells the panel to use a new base set of instances.
*
* @param inst a set of Instances
*/
public void setInstances(Instances inst) {
m_Instances = inst;
try {
Runnable r = new Runnable() {
public void run() {
m_InstSummaryPanel.setInstances(m_Instances);
m_AttPanel.setInstances(m_Instances);
m_RemoveButton.setEnabled(true);
m_FeatureSelectionButton.setEnabled(true);
m_AttSummaryPanel.setInstances(m_Instances);
m_AttVisualizePanel.setInstances(m_Instances);
// select the first attribute in the list
m_AttPanel.getSelectionModel().setSelectionInterval(0, 0);
m_AttSummaryPanel.setAttribute(0);
m_AttVisualizePanel.setAttribute(0);
m_ApplyFilterBut.setEnabled(true);
/**
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_SetInstances_Run_Log_LogMessage_Text_First")
+ m_Instances.relationName()
+ Messages.getInstance().getString("PreprocessPanel_SetInstances_Run_Log_LogMessage_Text_Second") + m_Instances.numInstances()
+ Messages.getInstance().getString("PreprocessPanel_SetInstances_Run_Log_LogMessage_Text_Third"));
**/
m_SaveBut.setEnabled(true);
m_EditBut.setEnabled(true);
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_SetInstances_Run_Log_StatusMessage_Text_First"));
// Fire a propertychange event
m_Support.firePropertyChange("", null, null);
// notify GOEs about change
try {
// get rid of old filter settings
getExplorer().notifyCapabilitiesFilterListener(null);
int oldIndex = m_Instances.classIndex();
m_Instances.setClassIndex(m_AttVisualizePanel.getColorBox().getSelectedIndex() - 1);
// send new ones
if (ExplorerDefaults.getInitGenericObjectEditorFilter())
getExplorer().notifyCapabilitiesFilterListener(
Capabilities.forInstances(m_Instances));
else
getExplorer().notifyCapabilitiesFilterListener(
Capabilities.forInstances(new Instances(m_Instances, 0)));
m_Instances.setClassIndex(oldIndex);
}
catch (Exception e) {
e.printStackTrace();
m_Log.logMessage(e.toString());
}
}
};
if (SwingUtilities.isEventDispatchThread()) {
r.run();
} else {
SwingUtilities.invokeAndWait(r);
}
} catch (Exception ex) {
ex.printStackTrace();
/**
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstances_Run_JOptionPaneShowMessageDialog_Text_First")
+ ex,
Messages.getInstance().getString("PreprocessPanel_SetInstances_Run_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
**/
}
}
/**
* Gets the working set of instances.
*
* @return the working instances
*/
public Instances getInstances() {
return m_Instances;
}
/**
* Adds a PropertyChangeListener who will be notified of value changes.
*
* @param l a value of type 'PropertyChangeListener'
*/
public void addPropertyChangeListener(PropertyChangeListener l) {
m_Support.addPropertyChangeListener(l);
}
/**
* Removes a PropertyChangeListener.
*
* @param l a value of type 'PropertyChangeListener'
*/
public void removePropertyChangeListener(PropertyChangeListener l) {
m_Support.removePropertyChangeListener(l);
}
/**
* Passes the dataset through the filter that has been configured for use.
*
* @param filter the filter to apply
*/
protected void applyFilter(final Filter filter) {
if (m_IOThread == null) {
m_IOThread = new Thread() {
public void run() {
try {
if (filter != null) {
if (m_Log instanceof TaskLogger) {
((TaskLogger)m_Log).taskStarted();
}
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_Log_StatusMessage_Text_First")
+ filter.getClass().getName());
String cmd = filter.getClass().getName();
if (filter instanceof OptionHandler)
cmd += " " + Utils.joinOptions(((OptionHandler) filter).getOptions());
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_Log_LogMessage_Text_First") + cmd);
int classIndex = m_AttVisualizePanel.getColoringIndex();
if ((classIndex < 0) && (filter instanceof SupervisedFilter)) {
throw new IllegalArgumentException(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_IllegalArgumentException_Text"));
}
Instances copy = new Instances(m_Instances);
Enumeration<Attribute> enu = m_Instances.enumerateAttributes();
while (enu.hasMoreElements()) {
Attribute attribute = enu.nextElement();
System.out.println("Just checking for attributes inside preprocesspanel");
}
copy.setClassIndex(classIndex);
filter.setInputFormat(copy);
Instances newInstances = Filter.useFilter(copy, filter);
if (newInstances == null || newInstances.numAttributes() < 1) {
throw new Exception(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_Exception_Text"));
}
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_Log_StatusMessage_Text_Second"));
addUndoPoint();
m_AttVisualizePanel.setColoringIndex(copy.classIndex());
// if class was not set before, reset it again after use of filter
if (m_Instances.classIndex() < 0)
newInstances.setClassIndex(-1);
m_Instances = newInstances;
setInstances(m_Instances);
if (m_Log instanceof TaskLogger) {
((TaskLogger)m_Log).taskFinished();
}
}
} catch (Exception ex) {
if (m_Log instanceof TaskLogger) {
((TaskLogger)m_Log).taskFinished();
}
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_JOptionPaneShowMessageDialog_Text_First")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_Log_LogMessage_Text_Second") + ex.getMessage());
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_Log_StatusMessage_Text_Third"));
}
m_IOThread = null;
}
};
m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority
m_IOThread.start();
} else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_JOptionPaneShowMessageDialog_Text_Third"),
Messages.getInstance().getString("PreprocessPanel_ApplyFilter_Run_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* Queries the user for a file to save instances as, then saves the
* instances in a background process. This is done in the IO
* thread, and an error message is popped up if the IO thread is busy.
*/
public void saveWorkingInstancesToFileQ() {
if (m_IOThread == null) {
m_FileChooser.setCapabilitiesFilter(m_FilterEditor.getCapabilitiesFilter());
m_FileChooser.setAcceptAllFileFilterUsed(false);
int returnVal = m_FileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
Instances inst = new Instances(m_Instances);
inst.setClassIndex(m_AttVisualizePanel.getColoringIndex());
saveInstancesToFile(m_FileChooser.getSaver(), inst);
}
FileFilter temp = m_FileChooser.getFileFilter();
m_FileChooser.setAcceptAllFileFilterUsed(true);
m_FileChooser.setFileFilter(temp);
}
else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SaveWorkingInstancesToFileQ_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_SaveWorkingInstancesToFileQ_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* saves the data with the specified saver
*
* @param saver the saver to use for storing the data
* @param inst the data to save
*/
public void saveInstancesToFile(final AbstractFileSaver saver, final Instances inst) {
if (m_IOThread == null) {
m_IOThread = new Thread() {
public void run() {
try {
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_SaveInstancesToFile_Run_Log_StatusMessage_Text_First"));
saver.setInstances(inst);
saver.writeBatch();
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_SaveInstancesToFile_Run_Log_StatusMessage_Text_Second"));
}
catch (Exception ex) {
ex.printStackTrace();
m_Log.logMessage(ex.getMessage());
}
m_IOThread = null;
}
};
m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority
m_IOThread.start();
}
else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SaveInstancesToFile_Run_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_SaveInstancesToFile_Run_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* Queries the user for a file to load instances from, then loads the
* instances in a background process. This is done in the IO
* thread, and an error message is popped up if the IO thread is busy.
*/
public void setInstancesFromFileQ() {
if (m_IOThread == null) {
int returnVal = m_FileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
addUndoPoint();
}
catch (Exception ignored) {
// ignored
}
if (m_FileChooser.getLoader() == null) {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFileQ_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFileQ_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
converterQuery(m_FileChooser.getSelectedFile());
}
else {
setInstancesFromFile(m_FileChooser.getLoader());
}
}
} else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFileQ_JOptionPaneShowMessageDialog_Text_Third"),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFileQ_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* Loads instances from an SQL query the user provided with the
* SqlViewerDialog, then loads the instances in a background process. This is
* done in the IO thread, and an error message is popped up if the IO thread
* is busy.
* @param url the database URL
* @param user the user to connect as
* @param pw the password of the user
* @param query the query for retrieving instances from
*/
public void setInstancesFromDBQ(String url, String user,
String pw, String query) {
if (m_IOThread == null) {
try {
InstanceQuery InstQ = new InstanceQuery();
InstQ.setDatabaseURL(url);
InstQ.setUsername(user);
InstQ.setPassword(pw);
InstQ.setQuery(query);
// we have to disconnect, otherwise we can't change the DB!
if (InstQ.isConnected())
InstQ.disconnectFromDatabase();
InstQ.connectToDatabase();
try {
addUndoPoint();
} catch (Exception ignored) {}
setInstancesFromDB(InstQ);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDBQ_JOptionPaneShowMessageDialog_Text_First")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDBQ_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDBQ_JOptionPaneShowMessageDialog_Text_Third"),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDBQ_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* Queries the user for a URL to load instances from, then loads the
* instances in a background process. This is done in the IO
* thread, and an error message is popped up if the IO thread is busy.
*/
public void setInstancesFromURLQ() {
if (m_IOThread == null) {
try {
String urlName = (String) JOptionPane.showInputDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromURLQ_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromURLQ_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.QUESTION_MESSAGE,
null,
null,
m_LastURL);
if (urlName != null) {
m_LastURL = urlName;
URL url = new URL(urlName);
try {
addUndoPoint();
} catch (Exception ignored) {}
setInstancesFromURL(url);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromURLQ_JOptionPaneShowMessageDialog_Text_Third")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromURLQ_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromURLQ_JOptionPaneShowMessageDialog_Text_Fifth"),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromURLQ_JOptionPaneShowMessageDialog_Text_Sixth"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* sets Instances generated via DataGenerators (pops up a Dialog)
*/
public void generateInstances() {
if (m_IOThread == null) {
m_IOThread = new Thread() {
public void run() {
try {
// create dialog
final DataGeneratorPanel generatorPanel = new DataGeneratorPanel();
final JDialog dialog = new JDialog();
final JButton generateButton = new JButton(Messages.getInstance().getString("PreprocessPanel_GenerateInstances_Run_GenerateButton_JButton_Text"));
final JCheckBox showOutputCheckBox =
new JCheckBox(Messages.getInstance().getString("PreprocessPanel_GenerateInstances_Run_ShowOutputCheckBox_JCheckBox_Text"));
showOutputCheckBox.setMnemonic('S');
generatorPanel.setLog(m_Log);
generatorPanel.setGenerator(m_DataGenerator);
generatorPanel.setPreferredSize(
new Dimension(
300,
(int) generatorPanel.getPreferredSize().getHeight()));
generateButton.setMnemonic('G');
generateButton.setToolTipText(Messages.getInstance().getString("PreprocessPanel_GenerateInstances_Run_GenerateButton_SetToolTipText_Text"));
generateButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
// generate
generatorPanel.execute();
boolean generated = (generatorPanel.getInstances() != null);
if (generated)
setInstances(generatorPanel.getInstances());
// close dialog
dialog.dispose();
// get last generator
m_DataGenerator = generatorPanel.getGenerator();
// display output?
if ( (generated) && (showOutputCheckBox.isSelected()) )
showGeneratedInstances(generatorPanel.getOutput());
}
});
dialog.setTitle(Messages.getInstance().getString("PreprocessPanel_GenerateInstances_Run_Dialog_Text"));
dialog.getContentPane().add(generatorPanel, BorderLayout.CENTER);
dialog.getContentPane().add(generateButton, BorderLayout.EAST);
dialog.getContentPane().add(showOutputCheckBox, BorderLayout.SOUTH);
dialog.pack();
// display dialog
dialog.setVisible(true);
}
catch (Exception ex) {
ex.printStackTrace();
m_Log.logMessage(ex.getMessage());
}
m_IOThread = null;
}
};
m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority
m_IOThread.start();
}
else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_GenerateInstances_Run_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_GenerateInstances_Run_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* displays a dialog with the generated instances from the DataGenerator
*
* @param data the data to display
*/
protected void showGeneratedInstances(String data) {
final JDialog dialog = new JDialog();
final JButton saveButton = new JButton(Messages.getInstance().getString("PreprocessPanel_ShowGeneratedInstances_SaveButton_JButton_Text"));
final JButton closeButton = new JButton(Messages.getInstance().getString("PreprocessPanel_ShowGeneratedInstances_CloseButton_JButton_Text"));
final JTextArea textData = new JTextArea(data);
final JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.RIGHT));
textData.setEditable(false);
textData.setFont(
new Font("Monospaced", Font.PLAIN, textData.getFont().getSize()));
saveButton.setMnemonic('S');
saveButton.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ShowGeneratedInstances_SaveButton_SetToolTipText_Text"));
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
JFileChooser filechooser = new JFileChooser();
int result = filechooser.showSaveDialog(dialog);
if (result == JFileChooser.APPROVE_OPTION) {
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(
filechooser.getSelectedFile()));
writer.write(textData.getText());
writer.flush();
writer.close();
JOptionPane.showMessageDialog(
dialog,
Messages.getInstance().getString("PreprocessPanel_ShowGeneratedInstances_SaveButton_JOptionPaneShowMessageDialog_Text_First")
+ filechooser.getSelectedFile() + Messages.getInstance().getString("PreprocessPanel_ShowGeneratedInstances_SaveButton_JOptionPaneShowMessageDialog_Text_Second"),
Messages.getInstance().getString("PreprocessPanel_ShowGeneratedInstances_SaveButton_JOptionPaneShowMessageDialog_Text_Third"),
JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception e) {
e.printStackTrace();
}
dialog.dispose();
}
}
});
closeButton.setMnemonic('C');
closeButton.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ShowGeneratedInstances_CloseButton_SetToolTipText_Text"));
closeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
dialog.dispose();
}
});
panel.add(saveButton);
panel.add(closeButton);
dialog.setTitle(Messages.getInstance().getString("PreprocessPanel_ShowGeneratedInstances_Dialog_SetToolTipText_Text"));
dialog.getContentPane().add(new JScrollPane(textData), BorderLayout.CENTER);
dialog.getContentPane().add(panel, BorderLayout.SOUTH);
dialog.pack();
// make sure, it's not bigger than 80% of the screen
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int width = dialog.getWidth() > screen.getWidth()*0.8
? (int) (screen.getWidth()*0.8) : dialog.getWidth();
int height = dialog.getHeight() > screen.getHeight()*0.8
? (int) (screen.getHeight()*0.8) : dialog.getHeight();
dialog.setSize(width, height);
// display dialog
dialog.setVisible(true);
}
/**
* Pops up generic object editor with list of conversion filters
*
* @param f the File
*/
private void converterQuery(final File f) {
final GenericObjectEditor convEd = new GenericObjectEditor(true);
try {
convEd.setClassType(features.core.converters.Loader.class);
convEd.setValue(new features.core.converters.CSVLoader());
((GenericObjectEditor.GOEPanel)convEd.getCustomEditor())
.addOkListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tryConverter((Loader)convEd.getValue(), f);
}
});
} catch (Exception ex) {
}
PropertyDialog pd;
if (PropertyDialog.getParentDialog(this) != null)
pd = new PropertyDialog(PropertyDialog.getParentDialog(this), convEd, 100, 100);
else
pd = new PropertyDialog(PropertyDialog.getParentFrame(this), convEd, 100, 100);
pd.setVisible(true);
}
/**
* Applies the selected converter
*
* @param cnv the converter to apply to the input file
* @param f the input file
*/
private void tryConverter(final Loader cnv, final File f) {
if (m_IOThread == null) {
m_IOThread = new Thread() {
public void run() {
try {
cnv.setSource(f);
Instances inst = cnv.getDataSet();
setInstances(inst);
} catch (Exception ex) {
m_Log.statusMessage(cnv.getClass().getName()+Messages.getInstance().getString("PreprocessPanel_TryConverter_Log_StatusMessage_Text")
+f.getName());
JOptionPane.showMessageDialog(PreprocessPanel.this,
cnv.getClass().getName()+Messages.getInstance().getString("PreprocessPanel_TryConverter_JOptionPaneShowMessageDialog_Text_First")
+ f.getName() + Messages.getInstance().getString("PreprocessPanel_TryConverter_JOptionPaneShowMessageDialog_Text_Second")
+ Messages.getInstance().getString("PreprocessPanel_TryConverter_JOptionPaneShowMessageDialog_Text_Third") + ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_TryConverter_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.ERROR_MESSAGE);
m_IOThread = null;
converterQuery(f);
}
m_IOThread = null;
}
};
m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority
m_IOThread.start();
}
}
/**
* Loads results from a set of instances retrieved with the supplied loader.
* This is started in the IO thread, and a dialog is popped up
* if there's a problem.
*
* @param loader the loader to use
*/
public void setInstancesFromFile(final AbstractFileLoader loader) {
if (m_IOThread == null) {
m_IOThread = new Thread() {
public void run() {
try {
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_Log_StatusMessage_Text_First"));
Instances inst = loader.getDataSet();
setInstances(inst);
}
catch (Exception ex) {
m_Log.statusMessage(
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_Log_StatusMessage_Text_Second") + loader.retrieveFile() + Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_Log_StatusMessage_Text_Third")
+ loader.getFileDescription() + Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_Log_StatusMessage_Text_Fourth"));
m_IOThread = null;
if (JOptionPane.showOptionDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_JOptionPaneShowOptionDialog_Text_First") + loader.retrieveFile()
+ Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_JOptionPaneShowOptionDialog_Text_Second")
+ loader.getFileDescription()
+ Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_JOptionPaneShowOptionDialog_Text_Third")
+ Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_JOptionPaneShowOptionDialog_Text_Fourth") + ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_JOptionPaneShowOptionDialog_Text_Fifth"),
0,
JOptionPane.ERROR_MESSAGE,
null,
new String[] {Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_JOptionPaneShowOptionDialog_Text_Sixth"), Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_JOptionPaneShowOptionDialog_Text_Seventh")},
null) == 1) {
converterQuery(loader.retrieveFile());
}
}
m_IOThread = null;
}
};
m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority
m_IOThread.start();
} else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_JOptionPaneShowOptionDialog_Text_Eigth"),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromFile_Run_JOptionPaneShowOptionDialog_Text_Nineth"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* Loads instances from a database
*
* @param iq the InstanceQuery object to load from (this is assumed
* to have been already connected to a valid database).
*/
public void setInstancesFromDB(final InstanceQuery iq) {
if (m_IOThread == null) {
m_IOThread = new Thread() {
public void run() {
try {
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_Log_StatusMessage_Text_First"));
final Instances i = iq.retrieveInstances();
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setInstances(new Instances(i));
}
});
iq.disconnectFromDatabase();
} catch (Exception ex) {
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_Log_StatusMessage_Text_Second") + m_SQLQ);
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_JOptionPaneShowMessageDialog_Text_First")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
}
m_IOThread = null;
}
};
m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority
m_IOThread.start();
} else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_JOptionPaneShowMessageDialog_Text_Third"),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* Loads instances from a URL.
*
* @param u the URL to load from.
*/
public void setInstancesFromURL(final URL u) {
if (m_IOThread == null) {
m_IOThread = new Thread() {
public void run() {
try {
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_SetInstancesFromURL_Run_Log_StatusMessage_Text_First"));
AbstractFileLoader loader = ConverterUtils.getURLLoaderForFile(u.toString());
if (loader == null)
throw new Exception(Messages.getInstance().getString("PreprocessPanel_SetInstancesFromURL_Run_Exception_Text_First") + u);
((URLSourcedLoader) loader).setURL(u.toString());
setInstances(loader.getDataSet());
} catch (Exception ex) {
ex.printStackTrace();
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_SetInstancesFromURL_Run_Log_StatusMessage_Text_Second") + u);
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_JOptionPaneShowMessageDialog_Text_Fifth")
+ u + Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_JOptionPaneShowMessageDialog_Text_Sixth")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_JOptionPaneShowMessageDialog_Text_Seventh"),
JOptionPane.ERROR_MESSAGE);
}
m_IOThread = null;
}
};
m_IOThread.setPriority(Thread.MIN_PRIORITY); // UI has most priority
m_IOThread.start();
} else {
JOptionPane.showMessageDialog(this,
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_JOptionPaneShowMessageDialog_Text_Eighth"),
Messages.getInstance().getString("PreprocessPanel_SetInstancesFromDB_Run_JOptionPaneShowMessageDialog_Text_Nineth"),
JOptionPane.WARNING_MESSAGE);
}
}
/**
* Backs up the current state of the dataset, so the changes can be undone.
*
* @throws Exception if an error occurs
*/
public void addUndoPoint() throws Exception {
if (!ExplorerDefaults.get("enableUndo", "true").equalsIgnoreCase("true")) {
return;
}
if (m_Instances != null) {
// create temporary file
File tempFile = File.createTempFile("weka", SerializedInstancesLoader.FILE_EXTENSION);
tempFile.deleteOnExit();
if (!ExplorerDefaults.get("undoDirectory", "%t").equalsIgnoreCase("%t")) {
String dir = ExplorerDefaults.get("undoDirectory", "%t");
File undoDir = new File(dir);
if (undoDir.exists()) {
String fileName = tempFile.getName();
File newFile = new File(dir + File.separator + fileName);
if (undoDir.canWrite()) {
newFile.deleteOnExit();
tempFile = newFile;
} else {
System.err.println("Explorer: it doesn't look like we have permission" +
" to write to the user-specified undo directory " +
"'" + dir + "'");
}
} else {
System.err.println("Explorer: user-specified undo directory '" +
dir + "' does not exist!");
}
}
ObjectOutputStream oos =
new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(tempFile)));
oos.writeObject(m_Instances);
oos.flush();
oos.close();
// update undo file list
if (m_tempUndoFiles[m_tempUndoIndex] != null) {
// remove undo points that are too old
m_tempUndoFiles[m_tempUndoIndex].delete();
}
m_tempUndoFiles[m_tempUndoIndex] = tempFile;
if (++m_tempUndoIndex >= m_tempUndoFiles.length) {
// wrap pointer around
m_tempUndoIndex = 0;
}
m_UndoBut.setEnabled(true);
}
}
/**
* Reverts to the last backed up version of the dataset.
*/
public void undo() {
if (--m_tempUndoIndex < 0) {
// wrap pointer around
m_tempUndoIndex = m_tempUndoFiles.length-1;
}
if (m_tempUndoFiles[m_tempUndoIndex] != null) {
// load instances from the temporary file
AbstractFileLoader loader = ConverterUtils.getLoaderForFile(m_tempUndoFiles[m_tempUndoIndex]);
try {
loader.setFile(m_tempUndoFiles[m_tempUndoIndex]);
setInstancesFromFile(loader);
}
catch (Exception e) {
e.printStackTrace();
m_Log.logMessage(e.toString());
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_Undo_JOptionPaneShowMessageDialog_Text_First") + e.toString(),
Messages.getInstance().getString("PreprocessPanel_Undo_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
}
// update undo file list
m_tempUndoFiles[m_tempUndoIndex] = null;
}
// update undo button
int temp = m_tempUndoIndex-1;
if (temp < 0) {
temp = m_tempUndoFiles.length-1;
}
m_UndoBut.setEnabled(m_tempUndoFiles[temp] != null);
}
/**
* edits the current instances object in the viewer
*/
public void edit() {
ViewerDialog dialog;
int result;
Instances copy;
Instances newInstances;
final int classIndex = m_AttVisualizePanel.getColoringIndex();
copy = new Instances(m_Instances);
copy.setClassIndex(classIndex);
dialog = new ViewerDialog(null);
result = dialog.showDialog(copy);
if (result == ViewerDialog.APPROVE_OPTION) {
try {
addUndoPoint();
}
catch (Exception e) {
e.printStackTrace();
}
// if class was not set before, reset it again after use of filter
newInstances = dialog.getInstances();
if (m_Instances.classIndex() < 0)
newInstances.setClassIndex(-1);
setInstances(newInstances);
}
}
/**
* Sets the Explorer to use as parent frame (used for sending notifications
* about changes in the data)
*
* @param parent the parent frame
*/
public void setExplorer(Explorer parent) {
m_Explorer = parent;
}
/**
* returns the parent Explorer frame
*
* @return the parent
*/
public Explorer getExplorer() {
return m_Explorer;
}
/**
* updates the capabilities filter of the GOE
*
* @param filter the new filter to use
*/
protected void updateCapabilitiesFilter(Capabilities filter) {
Instances tempInst;
Capabilities filterClass;
if (filter == null) {
m_FilterEditor.setCapabilitiesFilter(new Capabilities(null));
return;
}
if (!ExplorerDefaults.getInitGenericObjectEditorFilter())
tempInst = new Instances(m_Instances, 0);
else
tempInst = new Instances(m_Instances);
tempInst.setClassIndex(m_AttVisualizePanel.getColorBox().getSelectedIndex() - 1);
try {
filterClass = Capabilities.forInstances(tempInst);
}
catch (Exception e) {
filterClass = new Capabilities(null);
}
// set new filter
m_FilterEditor.setCapabilitiesFilter(filterClass);
// check capabilities
m_ApplyFilterBut.setEnabled(true);
Capabilities currentCapabilitiesFilter = m_FilterEditor.getCapabilitiesFilter();
Filter currentFilter = (Filter) m_FilterEditor.getValue();
Capabilities currentFilterCapabilities = null;
if (currentFilter != null && currentCapabilitiesFilter != null &&
(currentFilter instanceof CapabilitiesHandler)) {
currentFilterCapabilities = ((CapabilitiesHandler)currentFilter).getCapabilities();
if (!currentFilterCapabilities.supportsMaybe(currentCapabilitiesFilter) &&
!currentFilterCapabilities.supports(currentCapabilitiesFilter)) {
try {
currentFilter.setInputFormat(getInstances());
} catch (Exception ex) {
m_ApplyFilterBut.setEnabled(false);
}
}
}
}
/**
* method gets called in case of a change event
*
* @param e the associated change event
*/
public void capabilitiesFilterChanged(CapabilitiesFilterChangeEvent e) {
if (e.getFilter() == null)
updateCapabilitiesFilter(null);
else
updateCapabilitiesFilter((Capabilities) e.getFilter().clone());
}
/**
* Returns the title for the tab in the Explorer
*
* @return the title of this tab
*/
public String getTabTitle() {
return Messages.getInstance().getString("PreprocessPanel_GetTitle_Text");
}
/**
* Returns the tooltip for the tab in the Explorer
*
* @return the tooltip of this tab
*/
public String getTabTitleToolTip() {
return Messages.getInstance().getString("PreprocessPanel_GetTabTitleToolTip_Text");
}
/**
* Tests out the instance-preprocessing panel from the command line.
*
* @param args ignored
*/
public static void main(String [] args) {
try {
final JFrame jf = new JFrame(Messages.getInstance().getString("PreprocessPanel_Main_JFRame_Text"));
jf.getContentPane().setLayout(new BorderLayout());
final PreprocessPanel sp = new PreprocessPanel();
jf.getContentPane().add(sp, BorderLayout.CENTER);
features.gui.LogPanel lp = new features.gui.LogPanel();
sp.setLog(lp);
jf.getContentPane().add(lp, BorderLayout.SOUTH);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
jf.dispose();
System.exit(0);
}
});
jf.pack();
jf.setSize(800, 600);
jf.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}
| false | true | public PreprocessPanel() {
// Create/Configure/Connect components
m_FilterEditor.setClassType(features.filters.Filter.class);
if (ExplorerDefaults.getFilter() != null)
m_FilterEditor.setValue(ExplorerDefaults.getFilter());
m_FilterEditor.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
m_ApplyFilterBut.setEnabled(getInstances() != null);
Capabilities currentCapabilitiesFilter = m_FilterEditor.getCapabilitiesFilter();
Filter filter = (Filter) m_FilterEditor.getValue();
Capabilities currentFilterCapabilities = null;
if (filter != null && currentCapabilitiesFilter != null &&
(filter instanceof CapabilitiesHandler)) {
currentFilterCapabilities = ((CapabilitiesHandler)filter).getCapabilities();
if (!currentFilterCapabilities.supportsMaybe(currentCapabilitiesFilter) &&
!currentFilterCapabilities.supports(currentCapabilitiesFilter)) {
try {
filter.setInputFormat(getInstances());
} catch (Exception ex) {
m_ApplyFilterBut.setEnabled(false);
}
}
}
}
});
m_OpenFileBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_OpenFileBut_SetToolTipText_Text"));
m_OpenURLBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_OpenURLBut_SetToolTipText_Text"));
m_OpenDBBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_OpenDBBut_SetToolTipText_Text"));
m_GenerateBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_GenerateBut_SetToolTipText_Text"));
m_UndoBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_UndoBut_SetToolTipText_Text"));
m_UndoBut.setEnabled(ExplorerDefaults.get("enableUndo", "true").equalsIgnoreCase("true"));
if (!m_UndoBut.isEnabled()) {
m_UndoBut.setToolTipText("Undo is disabled - " +
"see features.gui.explorer.Explorer.props to enable");
}
m_EditBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_EditBut_SetToolTipText_Text"));
m_SaveBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_SaveBut_SetToolTipText_Text"));
m_ApplyFilterBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ApplyFilterBut_SetToolTipText_Text"));
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
m_OpenURLBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setInstancesFromURLQ();
}
});
m_OpenDBBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SqlViewerDialog dialog = new SqlViewerDialog(null);
dialog.setVisible(true);
if (dialog.getReturnValue() == JOptionPane.OK_OPTION)
setInstancesFromDBQ(dialog.getURL(), dialog.getUser(),
dialog.getPassword(), dialog.getQuery());
}
});
m_OpenFileBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setInstancesFromFileQ();
}
});
m_GenerateBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
generateInstances();
}
});
m_UndoBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
undo();
}
});
m_EditBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
edit();
}
});
m_SaveBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveWorkingInstancesToFileQ();
}
});
m_ApplyFilterBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applyFilter((Filter) m_FilterEditor.getValue());
}
});
m_AttPanel.getSelectionModel()
.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
ListSelectionModel lm = (ListSelectionModel) e.getSource();
for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) {
if (lm.isSelectedIndex(i)) {
m_AttSummaryPanel.setAttribute(i);
m_AttVisualizePanel.setAttribute(i);
break;
}
}
}
}
});
m_InstSummaryPanel.setBorder(BorderFactory.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_InstSummaryPanel_BorderFactoryCreateTitledBorder_Text")));
JPanel attStuffHolderPanel = new JPanel();
attStuffHolderPanel.setBorder(BorderFactory
.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_AttStuffHolderPanel_BorderFactoryCreateTitledBorder_Text")));
attStuffHolderPanel.setLayout(new BorderLayout());
attStuffHolderPanel.add(m_AttPanel, BorderLayout.CENTER);
m_RemoveButton.setEnabled(false);
m_RemoveButton.setToolTipText(Messages.getInstance().getString("PreprocessPanel_RemoveButton_SetToolTipText_Text"));
m_RemoveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Remove r = new Remove();
int [] selected = m_AttPanel.getSelectedAttributes();
if (selected.length == 0) {
return;
}
if (selected.length == m_Instances.numAttributes()) {
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_First"));
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_First"));
return;
}
r.setAttributeIndicesArray(selected);
applyFilter(r);
} catch (Exception ex) {
if (m_Log instanceof TaskLogger) {
((TaskLogger)m_Log).taskFinished();
}
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Third")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_Second") + ex.getMessage());
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_Second"));
}
}
});
m_FeatureSelectionButton.setEnabled(false);
m_FeatureSelectionButton.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_SetToolTipText_Text"));
m_FeatureSelectionButton.addActionListener(new ActionListener() {
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
try {
Map<Attribute, Double> attributeMap = new HashMap<Attribute, Double>();
int classIndex = m_Instances.numAttributes() - 1;
List<String> classValues = new ArrayList<String>();
Map<String, Integer> classSamples = new HashMap<String, Integer>();
Enumeration classAttrValues = m_Instances.attribute(classIndex).enumerateValues();
while(classAttrValues.hasMoreElements()) {
String attrValue = classAttrValues.nextElement().toString();
classValues.add(attrValue);
classSamples.put(attrValue, 0);
}
/*Enumeration<Attribute> enu = m_Instances.enumerateAttributes();
while (enu.hasMoreElements()) {
Attribute attribute = enu.nextElement();
attributeMap.put(attribute.name(), 0.0);
}*/
for (int i = 0; i < m_Instances.numInstances(); i++) {
Instance currentInst = m_Instances.instance(i);
if (currentInst.isMissing(classIndex)) {
break;
}
String instClassValue = currentInst.stringValue(classIndex);
if(classSamples.containsKey(instClassValue)) {
int currCount = classSamples.get(instClassValue).intValue();
classSamples.put(instClassValue, new Integer(currCount+1));
} else {
System.out.println("ERROR -- Something is wrong, check again");
}
}
double sampleClassInformation = 0.0;
Iterator it2 = classSamples.entrySet().iterator();
int totalInstances = m_Instances.numInstances();
for (Entry<String, Integer> entry : classSamples.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue()); // Change this to whatever you need
try {
int currClassValue = entry.getValue().intValue();
double temp = currClassValue * 1.0 / totalInstances;
temp = temp * (Math.log10(temp) / Math.log10(2));
sampleClassInformation +=temp;
} catch (NumberFormatException ne) {
System.out.println("Caught number format exception at line 415" + ne);
}
}
sampleClassInformation *= -1;
System.out.println("The sample class information is " + sampleClassInformation);
Enumeration<Attribute> enu = m_Instances.enumerateAttributes();
while (enu.hasMoreElements()) {
Attribute attribute = (Attribute) enu.nextElement();
attributeMap.put(attribute, 0.0);
double attributeEntropy = 0.0;
Map<String, HashMap<String, Integer>> attrValues = new HashMap<String, HashMap<String, Integer>>();
/*iterate over the instances
* if you find the attribute value in the map increment the count
* else add and set the count to 1
*/
int setCount = 0;
if (m_Instances.numInstances() > 0) {
for (int i = 0; i < m_Instances.numInstances(); i++) {
Instance currentInst = m_Instances.instance(i);
if (currentInst.isMissing(attribute)) {
break;
}
String curr;
String classvalue = currentInst.stringValue(classIndex);
if (!attribute.isNumeric()) {
curr = currentInst.stringValue(attribute);
} else {
curr = Double.toString(currentInst.value(attribute));
}
try {
if(!attrValues.containsKey(curr)) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (Entry<String, Integer> entry : classSamples.entrySet()) {
map.put(entry.getKey(), 0);
}
//map.put(classvalue, map.get(classvalue) + 1);
attrValues.put(curr, (HashMap<String, Integer>) map);
}
@SuppressWarnings("unchecked")
Map<String, Integer> attrMap = (HashMap<String, Integer>)attrValues.get(curr);
attrMap.put(classvalue, attrMap.get(classvalue) + 1);
attrValues.put(curr, (HashMap<String, Integer>) attrMap);
} catch (Exception ek) {
System.out.println("Cannot find matching classvalue in the map");
}
setCount++;
}
for(Entry<String, HashMap<String, Integer>> setEntry : attrValues.entrySet()) {
Map<String, Integer> classSetEntry = (HashMap<String, Integer>)setEntry.getValue();
double attributeSetInformation = 0.0;
int tempSetCount = 0;
for(Entry<String,Integer> entry : classSetEntry.entrySet()) {
if (entry.getValue().intValue() > 0 ) {
tempSetCount += entry.getValue().intValue();
}
}
for(Entry<String,Integer> entry : classSetEntry.entrySet()) {
if (entry.getValue().intValue() > 0 ) {
double probability = entry.getValue().intValue() / (tempSetCount * 1.0);
probability = probability * (Math.log10(probability) / Math.log10(2));
attributeSetInformation +=probability;
}
}
attributeEntropy += (tempSetCount * 1.0 / m_Instances.numInstances()) * attributeSetInformation;
}
}
System.out.println("Done");
/*here we check for every attribute value set to
* check for class value distribution
*/
/*reset class samples*/
attributeEntropy *= -1;
attributeMap.put(attribute, attributeEntropy);
// Iterator it = attributeMap.entrySet().iterator();
// while (it.hasNext()) {
// Map.Entry pairs = (Map.Entry)it.next();
// System.out.println(pairs.getKey() + " = " + pairs.getValue());
// Attribute attr = m_Instances.attribute((String)pairs.getKey());
// Enumeration attrValues1 = m_Instances.attribute(34).enumerateValues();
// attr.enumerateValues();
// System.out.println("no problem got it");
// }
}
for(Entry<Attribute, Double> attrEntry : attributeMap.entrySet()) {
System.out.println("Attribute = " + attrEntry.getKey().name() + "::: " + attrEntry.getValue().doubleValue() + ":::" + (sampleClassInformation - attrEntry.getValue().doubleValue()));
}
/*lets remove unwanted attributes
* and perform naive bayes on remaining attributes
*/
try {
Remove r = new Remove();
int [] r1 = new int[attributeMap.size()];
Arrays.fill(r1, 0);
int selCount = 0;
for(Entry<Attribute, Double> attrEntry : attributeMap.entrySet()) {
if ((sampleClassInformation - attrEntry.getValue().doubleValue()) < 0.1) {
r1[selCount] = attrEntry.getKey().index();
selCount++;
}
}
int [] selected = new int[selCount];
System.arraycopy(r1, 0, selected, 0, selCount);
if (selected.length == 0) {
return;
}
if (selected.length == m_Instances.numAttributes()) {
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_First"));
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_First"));
return;
}
r.setAttributeIndicesArray(selected);
applyFilter(r);
} catch (Exception ex) {
if (m_Log instanceof TaskLogger) {
((TaskLogger)m_Log).taskFinished();
}
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Third")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_Second") + ex.getMessage());
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_Second"));
}
} catch (Exception e1) {
System.out.println("Main Loop");
}
}
});
JPanel p1 = new JPanel();
p1.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
p1.setLayout(new BorderLayout());
p1.add(m_RemoveButton, BorderLayout.CENTER);
p1.add(m_FeatureSelectionButton, BorderLayout.LINE_END); //sonal added functionality to remove the features with low IF
attStuffHolderPanel.add(p1, BorderLayout.SOUTH);
m_AttSummaryPanel.setBorder(BorderFactory
.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_AttSummaryPanel_BorderFactoryCreateTitledBorder_Text")));
m_UndoBut.setEnabled(false);
m_EditBut.setEnabled(false);
m_SaveBut.setEnabled(false);
m_ApplyFilterBut.setEnabled(false);
// Set up the GUI layout
JPanel buttons = new JPanel();
buttons.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
buttons.setLayout(new GridLayout(1, 6, 5, 5));
buttons.add(m_OpenFileBut);
//buttons.add(m_OpenURLBut);
//buttons.add(m_OpenDBBut);
/*buttons.add(m_GenerateBut);
buttons.add(m_UndoBut);
buttons.add(m_EditBut);
buttons.add(m_SaveBut);
*/
JPanel attInfo = new JPanel();
attInfo.setLayout(new BorderLayout());
attInfo.add(attStuffHolderPanel, BorderLayout.CENTER);
JPanel filter = new JPanel();
filter.setBorder(BorderFactory
.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_Filter_BorderFactoryCreateTitledBorder_Text")));
filter.setLayout(new BorderLayout());
filter.add(m_FilterPanel, BorderLayout.CENTER);
filter.add(m_ApplyFilterBut, BorderLayout.EAST);
JPanel attVis = new JPanel();
attVis.setLayout( new GridLayout(2,1) );
attVis.add(m_AttSummaryPanel);
JComboBox colorBox = m_AttVisualizePanel.getColorBox();
colorBox.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ColorBox_SetToolTipText_Text"));
colorBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
updateCapabilitiesFilter(m_FilterEditor.getCapabilitiesFilter());
}
}
});
final JButton visAllBut = new JButton(Messages.getInstance().getString("PreprocessPanel_VisAllBut_JButton_Text"));
visAllBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (m_Instances != null) {
try {
final features.gui.beans.AttributeSummarizer as =
new features.gui.beans.AttributeSummarizer();
as.setColoringIndex(m_AttVisualizePanel.getColoringIndex());
as.setInstances(m_Instances);
final javax.swing.JFrame jf = new javax.swing.JFrame();
jf.getContentPane().setLayout(new java.awt.BorderLayout());
jf.getContentPane().add(as, java.awt.BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
visAllBut.setEnabled(true);
jf.dispose();
}
});
jf.setSize(830,600);
jf.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
JPanel histoHolder = new JPanel();
histoHolder.setLayout(new BorderLayout());
histoHolder.add(m_AttVisualizePanel, BorderLayout.CENTER);
JPanel histoControls = new JPanel();
histoControls.setLayout(new BorderLayout());
histoControls.add(colorBox, BorderLayout.CENTER);
histoControls.add(visAllBut, BorderLayout.EAST);
histoHolder.add(histoControls, BorderLayout.NORTH);
attVis.add(histoHolder);
JPanel lhs = new JPanel();
lhs.setLayout(new BorderLayout());
lhs.add(m_InstSummaryPanel, BorderLayout.NORTH);
lhs.add(attInfo, BorderLayout.CENTER);
JPanel rhs = new JPanel();
rhs.setLayout(new BorderLayout());
//rhs.add(attVis, BorderLayout.CENTER);
JPanel relation = new JPanel();
relation.setLayout(new GridLayout(1, 2));
relation.add(lhs);
relation.add(rhs);
JPanel middle = new JPanel();
middle.setLayout(new BorderLayout());
// middle.add(filter, BorderLayout.NORTH);
middle.add(relation, BorderLayout.CENTER);
setLayout(new BorderLayout());
add(buttons, BorderLayout.NORTH);
add(middle, BorderLayout.CENTER);
}
| public PreprocessPanel() {
// Create/Configure/Connect components
m_FilterEditor.setClassType(features.filters.Filter.class);
if (ExplorerDefaults.getFilter() != null)
m_FilterEditor.setValue(ExplorerDefaults.getFilter());
m_FilterEditor.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
m_ApplyFilterBut.setEnabled(getInstances() != null);
Capabilities currentCapabilitiesFilter = m_FilterEditor.getCapabilitiesFilter();
Filter filter = (Filter) m_FilterEditor.getValue();
Capabilities currentFilterCapabilities = null;
if (filter != null && currentCapabilitiesFilter != null &&
(filter instanceof CapabilitiesHandler)) {
currentFilterCapabilities = ((CapabilitiesHandler)filter).getCapabilities();
if (!currentFilterCapabilities.supportsMaybe(currentCapabilitiesFilter) &&
!currentFilterCapabilities.supports(currentCapabilitiesFilter)) {
try {
filter.setInputFormat(getInstances());
} catch (Exception ex) {
m_ApplyFilterBut.setEnabled(false);
}
}
}
}
});
m_OpenFileBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_OpenFileBut_SetToolTipText_Text"));
m_OpenURLBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_OpenURLBut_SetToolTipText_Text"));
m_OpenDBBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_OpenDBBut_SetToolTipText_Text"));
m_GenerateBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_GenerateBut_SetToolTipText_Text"));
m_UndoBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_UndoBut_SetToolTipText_Text"));
m_UndoBut.setEnabled(ExplorerDefaults.get("enableUndo", "true").equalsIgnoreCase("true"));
if (!m_UndoBut.isEnabled()) {
m_UndoBut.setToolTipText("Undo is disabled - " +
"see features.gui.explorer.Explorer.props to enable");
}
m_EditBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_EditBut_SetToolTipText_Text"));
m_SaveBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_SaveBut_SetToolTipText_Text"));
m_ApplyFilterBut.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ApplyFilterBut_SetToolTipText_Text"));
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
m_OpenURLBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setInstancesFromURLQ();
}
});
m_OpenDBBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SqlViewerDialog dialog = new SqlViewerDialog(null);
dialog.setVisible(true);
if (dialog.getReturnValue() == JOptionPane.OK_OPTION)
setInstancesFromDBQ(dialog.getURL(), dialog.getUser(),
dialog.getPassword(), dialog.getQuery());
}
});
m_OpenFileBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setInstancesFromFileQ();
}
});
m_GenerateBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
generateInstances();
}
});
m_UndoBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
undo();
}
});
m_EditBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
edit();
}
});
m_SaveBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveWorkingInstancesToFileQ();
}
});
m_ApplyFilterBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applyFilter((Filter) m_FilterEditor.getValue());
}
});
m_AttPanel.getSelectionModel()
.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
ListSelectionModel lm = (ListSelectionModel) e.getSource();
for (int i = e.getFirstIndex(); i <= e.getLastIndex(); i++) {
if (lm.isSelectedIndex(i)) {
m_AttSummaryPanel.setAttribute(i);
m_AttVisualizePanel.setAttribute(i);
break;
}
}
}
}
});
m_InstSummaryPanel.setBorder(BorderFactory.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_InstSummaryPanel_BorderFactoryCreateTitledBorder_Text")));
JPanel attStuffHolderPanel = new JPanel();
attStuffHolderPanel.setBorder(BorderFactory
.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_AttStuffHolderPanel_BorderFactoryCreateTitledBorder_Text")));
attStuffHolderPanel.setLayout(new BorderLayout());
attStuffHolderPanel.add(m_AttPanel, BorderLayout.CENTER);
m_RemoveButton.setEnabled(false);
m_RemoveButton.setToolTipText(Messages.getInstance().getString("PreprocessPanel_RemoveButton_SetToolTipText_Text"));
m_RemoveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Remove r = new Remove();
int [] selected = m_AttPanel.getSelectedAttributes();
if (selected.length == 0) {
return;
}
if (selected.length == m_Instances.numAttributes()) {
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_First"));
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_First"));
return;
}
r.setAttributeIndicesArray(selected);
applyFilter(r);
} catch (Exception ex) {
if (m_Log instanceof TaskLogger) {
((TaskLogger)m_Log).taskFinished();
}
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Third")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_Second") + ex.getMessage());
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_Second"));
}
}
});
m_FeatureSelectionButton.setEnabled(false);
m_FeatureSelectionButton.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ApplyFilter_SetToolTipText_Text"));
m_FeatureSelectionButton.addActionListener(new ActionListener() {
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
try {
//attribute map stores mappingbetween attributes and information gain
Map<Attribute, Double> attributeMap = new HashMap<Attribute, Double>();
int classIndex = m_Instances.numAttributes() - 1;
List<String> classValues = new ArrayList<String>();
Map<String, Integer> classSamples = new HashMap<String, Integer>();
Enumeration classAttrValues = m_Instances.attribute(classIndex).enumerateValues();
while(classAttrValues.hasMoreElements()) {
String attrValue = classAttrValues.nextElement().toString();
classValues.add(attrValue);
classSamples.put(attrValue, 0);
}
/*Enumeration<Attribute> enu = m_Instances.enumerateAttributes();
while (enu.hasMoreElements()) {
Attribute attribute = enu.nextElement();
attributeMap.put(attribute.name(), 0.0);
}*/
for (int i = 0; i < m_Instances.numInstances(); i++) {
Instance currentInst = m_Instances.instance(i);
if (currentInst.isMissing(classIndex)) {
break;
}
String instClassValue = currentInst.stringValue(classIndex);
if(classSamples.containsKey(instClassValue)) {
int currCount = classSamples.get(instClassValue).intValue();
classSamples.put(instClassValue, new Integer(currCount+1));
} else {
System.out.println("ERROR -- Something is wrong, check again");
}
}
double sampleClassInformation = 0.0;
Iterator it2 = classSamples.entrySet().iterator();
int totalInstances = m_Instances.numInstances();
for (Entry<String, Integer> entry : classSamples.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue()); // Change this to whatever you need
try {
int currClassValue = entry.getValue().intValue();
double temp = currClassValue * 1.0 / totalInstances;
if( temp > 0)
temp = temp * (Math.log10(temp) / Math.log10(2));
sampleClassInformation +=temp;
} catch (NumberFormatException ne) {
System.out.println("Caught number format exception at line 415" + ne);
}
}
sampleClassInformation *= -1;
System.out.println("The sample class information is " + sampleClassInformation);
Enumeration<Attribute> enu = m_Instances.enumerateAttributes();
while (enu.hasMoreElements()) {
Attribute attribute = (Attribute) enu.nextElement();
attributeMap.put(attribute, 0.0);
double attributeEntropy = 0.0;
Map<String, HashMap<String, Integer>> attrValues = new HashMap<String, HashMap<String, Integer>>();
/*iterate over the instances
* if you find the attribute value in the map increment the count
* else add and set the count to 1
*/
int setCount = 0;
if (m_Instances.numInstances() > 0) {
for (int i = 0; i < m_Instances.numInstances(); i++) {
Instance currentInst = m_Instances.instance(i);
if (currentInst.isMissing(attribute)) {
break;
}
String curr;
String classvalue = currentInst.stringValue(classIndex);
if (!attribute.isNumeric()) {
curr = currentInst.stringValue(attribute);
} else {
curr = Double.toString(currentInst.value(attribute));
}
try {
if(!attrValues.containsKey(curr)) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (Entry<String, Integer> entry : classSamples.entrySet()) {
map.put(entry.getKey(), 0);
}
//map.put(classvalue, map.get(classvalue) + 1);
attrValues.put(curr, (HashMap<String, Integer>) map);
}
@SuppressWarnings("unchecked")
Map<String, Integer> attrMap = (HashMap<String, Integer>)attrValues.get(curr);
attrMap.put(classvalue, attrMap.get(classvalue) + 1);
attrValues.put(curr, (HashMap<String, Integer>) attrMap);
} catch (Exception ek) {
System.out.println("Cannot find matching classvalue in the map");
}
setCount++;
}
for(Entry<String, HashMap<String, Integer>> setEntry : attrValues.entrySet()) {
Map<String, Integer> classSetEntry = (HashMap<String, Integer>)setEntry.getValue();
double attributeSetInformation = 0.0;
int tempSetCount = 0;
for(Entry<String,Integer> entry : classSetEntry.entrySet()) {
if (entry.getValue().intValue() > 0 ) {
tempSetCount += entry.getValue().intValue();
}
}
for(Entry<String,Integer> entry : classSetEntry.entrySet()) {
if (entry.getValue().intValue() > 0 ) {
double probability = entry.getValue().intValue() / (tempSetCount * 1.0);
probability = probability * (Math.log10(probability) / Math.log10(2));
attributeSetInformation +=probability;
}
}
attributeEntropy += (tempSetCount * 1.0 / m_Instances.numInstances()) * attributeSetInformation;
}
}
System.out.println("Done");
/*here we check for every attribute value set to
* check for class value distribution
*/
/*reset class samples*/
attributeEntropy *= -1;
attributeMap.put(attribute, attributeEntropy);
// Iterator it = attributeMap.entrySet().iterator();
// while (it.hasNext()) {
// Map.Entry pairs = (Map.Entry)it.next();
// System.out.println(pairs.getKey() + " = " + pairs.getValue());
// Attribute attr = m_Instances.attribute((String)pairs.getKey());
// Enumeration attrValues1 = m_Instances.attribute(34).enumerateValues();
// attr.enumerateValues();
// System.out.println("no problem got it");
// }
}
for(Entry<Attribute, Double> attrEntry : attributeMap.entrySet()) {
System.out.println("Attribute = " + attrEntry.getKey().name() + "::: " + attrEntry.getValue().doubleValue() + ":::" + (sampleClassInformation - attrEntry.getValue().doubleValue()));
}
/*lets remove unwanted attributes
* and perform naive bayes on remaining attributes
*/
try {
Remove r = new Remove();
int [] r1 = new int[attributeMap.size()];
Arrays.fill(r1, 0);
int selCount = 0;
for(Entry<Attribute, Double> attrEntry : attributeMap.entrySet()) {
if ((sampleClassInformation - attrEntry.getValue().doubleValue()) < 0.1) {
r1[selCount] = attrEntry.getKey().index();
selCount++;
}
}
int [] selected = new int[selCount];
System.arraycopy(r1, 0, selected, 0, selCount);
if (selected.length == 0) {
return;
}
if (selected.length == m_Instances.numAttributes()) {
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_First"),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Second"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_First"));
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_First"));
return;
}
r.setAttributeIndicesArray(selected);
applyFilter(r);
} catch (Exception ex) {
if (m_Log instanceof TaskLogger) {
((TaskLogger)m_Log).taskFinished();
}
// Pop up an error optionpane
JOptionPane.showMessageDialog(PreprocessPanel.this,
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Third")
+ ex.getMessage(),
Messages.getInstance().getString("PreprocessPanel_JOptionPaneShowMessageDialog_Text_Fourth"),
JOptionPane.ERROR_MESSAGE);
m_Log.logMessage(Messages.getInstance().getString("PreprocessPanel_Log_LogMessage_Text_Second") + ex.getMessage());
m_Log.statusMessage(Messages.getInstance().getString("PreprocessPanel_Log_StatusMessage_Text_Second"));
}
} catch (Exception e1) {
System.out.println("Main Loop");
}
}
});
JPanel p1 = new JPanel();
p1.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
p1.setLayout(new BorderLayout());
p1.add(m_RemoveButton, BorderLayout.CENTER);
p1.add(m_FeatureSelectionButton, BorderLayout.LINE_END); //sonal added functionality to remove the features with low IF
attStuffHolderPanel.add(p1, BorderLayout.SOUTH);
m_AttSummaryPanel.setBorder(BorderFactory
.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_AttSummaryPanel_BorderFactoryCreateTitledBorder_Text")));
m_UndoBut.setEnabled(false);
m_EditBut.setEnabled(false);
m_SaveBut.setEnabled(false);
m_ApplyFilterBut.setEnabled(false);
// Set up the GUI layout
JPanel buttons = new JPanel();
buttons.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
buttons.setLayout(new GridLayout(1, 6, 5, 5));
buttons.add(m_OpenFileBut);
//buttons.add(m_OpenURLBut);
//buttons.add(m_OpenDBBut);
/*buttons.add(m_GenerateBut);
buttons.add(m_UndoBut);
buttons.add(m_EditBut);
buttons.add(m_SaveBut);
*/
JPanel attInfo = new JPanel();
attInfo.setLayout(new BorderLayout());
attInfo.add(attStuffHolderPanel, BorderLayout.CENTER);
JPanel filter = new JPanel();
filter.setBorder(BorderFactory
.createTitledBorder(Messages.getInstance().getString("PreprocessPanel_Filter_BorderFactoryCreateTitledBorder_Text")));
filter.setLayout(new BorderLayout());
filter.add(m_FilterPanel, BorderLayout.CENTER);
filter.add(m_ApplyFilterBut, BorderLayout.EAST);
JPanel attVis = new JPanel();
attVis.setLayout( new GridLayout(2,1) );
attVis.add(m_AttSummaryPanel);
JComboBox colorBox = m_AttVisualizePanel.getColorBox();
colorBox.setToolTipText(Messages.getInstance().getString("PreprocessPanel_ColorBox_SetToolTipText_Text"));
colorBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
updateCapabilitiesFilter(m_FilterEditor.getCapabilitiesFilter());
}
}
});
final JButton visAllBut = new JButton(Messages.getInstance().getString("PreprocessPanel_VisAllBut_JButton_Text"));
visAllBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (m_Instances != null) {
try {
final features.gui.beans.AttributeSummarizer as =
new features.gui.beans.AttributeSummarizer();
as.setColoringIndex(m_AttVisualizePanel.getColoringIndex());
as.setInstances(m_Instances);
final javax.swing.JFrame jf = new javax.swing.JFrame();
jf.getContentPane().setLayout(new java.awt.BorderLayout());
jf.getContentPane().add(as, java.awt.BorderLayout.CENTER);
jf.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
visAllBut.setEnabled(true);
jf.dispose();
}
});
jf.setSize(830,600);
jf.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
JPanel histoHolder = new JPanel();
histoHolder.setLayout(new BorderLayout());
histoHolder.add(m_AttVisualizePanel, BorderLayout.CENTER);
JPanel histoControls = new JPanel();
histoControls.setLayout(new BorderLayout());
histoControls.add(colorBox, BorderLayout.CENTER);
histoControls.add(visAllBut, BorderLayout.EAST);
histoHolder.add(histoControls, BorderLayout.NORTH);
attVis.add(histoHolder);
JPanel lhs = new JPanel();
lhs.setLayout(new BorderLayout());
lhs.add(m_InstSummaryPanel, BorderLayout.NORTH);
lhs.add(attInfo, BorderLayout.CENTER);
JPanel rhs = new JPanel();
rhs.setLayout(new BorderLayout());
//rhs.add(attVis, BorderLayout.CENTER);
JPanel relation = new JPanel();
relation.setLayout(new GridLayout(1, 2));
relation.add(lhs);
relation.add(rhs);
JPanel middle = new JPanel();
middle.setLayout(new BorderLayout());
// middle.add(filter, BorderLayout.NORTH);
middle.add(relation, BorderLayout.CENTER);
setLayout(new BorderLayout());
add(buttons, BorderLayout.NORTH);
add(middle, BorderLayout.CENTER);
}
|
diff --git a/src/test/java/com/jayway/maven/plugins/android/AndroidSdkTest.java b/src/test/java/com/jayway/maven/plugins/android/AndroidSdkTest.java
index a8c83390..d868af85 100644
--- a/src/test/java/com/jayway/maven/plugins/android/AndroidSdkTest.java
+++ b/src/test/java/com/jayway/maven/plugins/android/AndroidSdkTest.java
@@ -1,122 +1,126 @@
/*
* Copyright (C) 2009 Jayway AB
*
* 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.jayway.maven.plugins.android;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import org.codehaus.plexus.util.ReflectionUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Excercises the {@link AndroidSdk} class.
*
* @author [email protected]
* @author Manfred Moser <[email protected]>
*/
public class AndroidSdkTest {
private SdkTestSupport sdkTestSupport;
@Before
public void setUp(){
sdkTestSupport = new SdkTestSupport();
}
@Test
public void givenToolAdbThenPathIsPlatformTools() {
final String pathForTool =sdkTestSupport.getSdk_with_platform_1_5().getPathForTool("adb");
Assert.assertEquals(new File(sdkTestSupport.getEnv_ANDROID_HOME() + "/platform-tools").getAbsolutePath(), new File(pathForTool).getParentFile().getAbsolutePath());
}
@Test
public void givenToolAndroidThenPathIsCommon() {
final String pathForTool =sdkTestSupport.getSdk_with_platform_1_5().getPathForTool("android");
Assert.assertEquals(new File(sdkTestSupport.getEnv_ANDROID_HOME() + "/tools").getAbsolutePath(), new File(pathForTool).getParentFile().getAbsolutePath());
}
@Test
public void givenToolAaptAndPlatform1dot5ThenPathIsPlatformTools() {
final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3");
final String pathForTool = sdk.getPathForTool("aapt");
Assert.assertEquals(new File(sdkTestSupport.getEnv_ANDROID_HOME() + "/platform-tools"), new File(pathForTool).getParentFile());
}
@Test(expected = InvalidSdkException.class)
public void givenInvalidSdkPathThenException() throws IOException {
new AndroidSdk(File.createTempFile("android-maven-plugin", "test"), null).getLayout();
}
@Test(expected = InvalidSdkException.class)
public void givenInvalidPlatformStringThenException() throws IOException {
final AndroidSdk sdk = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "invalidplatform");
}
@Test
public void givenDefaultSdkThenLayoutIs23(){
Assert.assertEquals(sdkTestSupport.getSdk_with_platform_default().getLayout(), AndroidSdk.Layout.LAYOUT_2_3);
}
@Test
public void givenPlatform1dot5ThenPlatformis1dot5() throws IllegalAccessException {
final File path = (File) ReflectionUtils.getValueIncludingSuperclasses("sdkPath",sdkTestSupport.getSdk_with_platform_1_5());
Assert.assertEquals(new File(path, "/platforms/android-3"),sdkTestSupport.getSdk_with_platform_1_5().getPlatform());
}
@Test
public void givenPlatformNullThenPlatformisSomethingValidLooking() throws IllegalAccessException, URISyntaxException {
final File path = (File) ReflectionUtils.getValueIncludingSuperclasses("sdkPath",sdkTestSupport.getSdk_with_platform_default());
final File platform = sdkTestSupport.getSdk_with_platform_default().getPlatform();
final String platformPath = platform.getAbsolutePath();
final String pathPath = path.getAbsolutePath();
final String regex = new File(pathPath + "/platforms/android-.*").toURI().toString();
Assert.assertTrue(new File(platformPath).toURI().toString().matches(regex));
}
/**
* Test all available platforms and api level versions. All have to be installed locally
* for this test to pass including the obsolete ones.
*/
@Test
public void validPlatformsAndApiLevels() {
final AndroidSdk sdk3 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3");
final AndroidSdk sdk4 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "4");
final AndroidSdk sdk7 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "7");
final AndroidSdk sdk8 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "8");
- final AndroidSdk sdk9 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "9");
final AndroidSdk sdk10 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "10");
final AndroidSdk sdk11 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "11");
+ final AndroidSdk sdk12 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "12");
+ final AndroidSdk sdk13 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "13");
+ final AndroidSdk sdk14 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "14");
final AndroidSdk sdk1_5 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.5");
final AndroidSdk sdk1_6 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.6");
final AndroidSdk sdk2_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.1");
final AndroidSdk sdk2_2 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.2");
- final AndroidSdk sdk2_3_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.3.1");
+ final AndroidSdk sdk2_3 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.3.3");
final AndroidSdk sdk3_0 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3.0");
final AndroidSdk sdk3_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3.1");
+ final AndroidSdk sdk3_2 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3.2");
+ final AndroidSdk sdk4_0 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "4.0");
}
@Test(expected = InvalidSdkException.class)
public void invalidPlatformAndApiLevels() {
final AndroidSdk invalid = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "invalid");
}
}
| false | true | public void validPlatformsAndApiLevels() {
final AndroidSdk sdk3 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3");
final AndroidSdk sdk4 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "4");
final AndroidSdk sdk7 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "7");
final AndroidSdk sdk8 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "8");
final AndroidSdk sdk9 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "9");
final AndroidSdk sdk10 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "10");
final AndroidSdk sdk11 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "11");
final AndroidSdk sdk1_5 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.5");
final AndroidSdk sdk1_6 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.6");
final AndroidSdk sdk2_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.1");
final AndroidSdk sdk2_2 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.2");
final AndroidSdk sdk2_3_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.3.1");
final AndroidSdk sdk3_0 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3.0");
final AndroidSdk sdk3_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3.1");
}
| public void validPlatformsAndApiLevels() {
final AndroidSdk sdk3 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3");
final AndroidSdk sdk4 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "4");
final AndroidSdk sdk7 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "7");
final AndroidSdk sdk8 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "8");
final AndroidSdk sdk10 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "10");
final AndroidSdk sdk11 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "11");
final AndroidSdk sdk12 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "12");
final AndroidSdk sdk13 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "13");
final AndroidSdk sdk14 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "14");
final AndroidSdk sdk1_5 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.5");
final AndroidSdk sdk1_6 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "1.6");
final AndroidSdk sdk2_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.1");
final AndroidSdk sdk2_2 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.2");
final AndroidSdk sdk2_3 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "2.3.3");
final AndroidSdk sdk3_0 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3.0");
final AndroidSdk sdk3_1 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3.1");
final AndroidSdk sdk3_2 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "3.2");
final AndroidSdk sdk4_0 = new AndroidSdk(new File(sdkTestSupport.getEnv_ANDROID_HOME()), "4.0");
}
|
diff --git a/src/main/Start.java b/src/main/Start.java
index 51c0098..06097f4 100755
--- a/src/main/Start.java
+++ b/src/main/Start.java
@@ -1,87 +1,87 @@
package main;
import main.core.Protein;
import main.core.Structure;
import main.estimation.MatthewsCorrelationCoefficient;
import main.estimation.Q3;
import main.prediction.Gor3;
import main.statistics.AminoAcidStatistics;
import main.statistics.ChouFasman;
import main.tools.Loader;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*/
public class Start {
public static void main(String[] args) {
Loader loader = new Loader("dssp_info.csv");
List<Protein> proteinListDssp = loader.readFile();
loader = new Loader("stride_info.csv");
List<Protein> proteinListStride = loader.readFile();
System.out.println("DSSP amino acid frequencies:");
System.out.println(AminoAcidStatistics.getAminoAcidNameSortStats(proteinListDssp));
System.out.println("STRIDE amino acid frequencies:");
System.out.println(AminoAcidStatistics.getAminoAcidNameSortStats(proteinListStride));
ChouFasman chouFasmanDssp = new ChouFasman(proteinListDssp);
System.out.println("DSSP amino acids propensities:");
System.out.println(chouFasmanDssp.getAminoAcidsPropensitiesString());
ChouFasman chouFasmanStride = new ChouFasman(proteinListStride);
System.out.println("STRIDE amino acids propensities:");
System.out.println(chouFasmanStride.getAminoAcidsPropensitiesString());
System.out.println(" DSSP STRIDE");
double dsspSum = 0;
double strideSum = 0;
for (int i = 0; i < proteinListDssp.size(); i++) {
Protein proteinDssp = proteinListDssp.remove(0);
chouFasmanDssp = new ChouFasman(proteinListDssp);
Gor3 gor3Dssp = new Gor3(chouFasmanDssp);
Protein predictedProteinDssp = gor3Dssp.makePrediction(proteinDssp);
Protein proteinStride = proteinListStride.remove(0);
chouFasmanStride = new ChouFasman(proteinListStride);
Gor3 gor3Stride = new Gor3(chouFasmanStride);
Protein predictedProteinStride = gor3Stride.makePrediction(proteinStride);
// for(Structure structure : proteinDssp.getProteinStructure()){
// if(structure!=null)System.out.print(structure.toString().substring(0, 1));else
// System.out.print(" ");
// }
// System.out.println();
// for(Structure structure : predictedProteinDssp.getProteinStructure()){
// if(structure!=null)System.out.print(structure.toString().substring(0, 1));
// }
// System.out.println();
System.out.println(proteinDssp.getPdbCode() + "_" + proteinDssp.getPdbChainCode());
System.out.println(String.format("Q3: %1$.2f%% %2$.2f%%", Q3.getQ3Quality(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure()) * 100, Q3.getQ3Quality(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure()) * 100));
dsspSum += Q3.getQ3Quality(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure()) * 100;
strideSum += Q3.getQ3Quality(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure()) * 100;
- String mccHelixDssp = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.HELIX) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.HELIX));
- String mccBetaDssp = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.BETA) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.BETA));
- String mccCoilDssp = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.COIL) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.COIL));
- String mccHelixStride = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.HELIX) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.HELIX));
- String mccBetaStride = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.BETA) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.BETA));
- String mccCoilStride = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.COIL) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.COIL));
+ String mccHelixDssp = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.HELIX));
+ String mccBetaDssp = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.BETA));
+ String mccCoilDssp = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.COIL));
+ String mccHelixStride = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.HELIX));
+ String mccBetaStride = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.BETA));
+ String mccCoilStride = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.COIL));
System.out.println(String.format("MCC HELIX: %1$s %2$s", mccHelixDssp, mccHelixStride));
System.out.println(String.format("MCC BETA: %1$s %2$s", mccBetaDssp, mccBetaStride));
System.out.println(String.format("MCC COIL: %1$s %2$s", mccCoilDssp, mccCoilStride));
proteinListDssp.add(proteinDssp);
proteinListStride.add(proteinStride);
}
System.out.println(String.format("DSSP average: %1$.3f%%", dsspSum / proteinListDssp.size()));
System.out.println(String.format("STRIDE average: %1$.3f%%", strideSum / proteinListStride.size()));
}
}
| true | true | public static void main(String[] args) {
Loader loader = new Loader("dssp_info.csv");
List<Protein> proteinListDssp = loader.readFile();
loader = new Loader("stride_info.csv");
List<Protein> proteinListStride = loader.readFile();
System.out.println("DSSP amino acid frequencies:");
System.out.println(AminoAcidStatistics.getAminoAcidNameSortStats(proteinListDssp));
System.out.println("STRIDE amino acid frequencies:");
System.out.println(AminoAcidStatistics.getAminoAcidNameSortStats(proteinListStride));
ChouFasman chouFasmanDssp = new ChouFasman(proteinListDssp);
System.out.println("DSSP amino acids propensities:");
System.out.println(chouFasmanDssp.getAminoAcidsPropensitiesString());
ChouFasman chouFasmanStride = new ChouFasman(proteinListStride);
System.out.println("STRIDE amino acids propensities:");
System.out.println(chouFasmanStride.getAminoAcidsPropensitiesString());
System.out.println(" DSSP STRIDE");
double dsspSum = 0;
double strideSum = 0;
for (int i = 0; i < proteinListDssp.size(); i++) {
Protein proteinDssp = proteinListDssp.remove(0);
chouFasmanDssp = new ChouFasman(proteinListDssp);
Gor3 gor3Dssp = new Gor3(chouFasmanDssp);
Protein predictedProteinDssp = gor3Dssp.makePrediction(proteinDssp);
Protein proteinStride = proteinListStride.remove(0);
chouFasmanStride = new ChouFasman(proteinListStride);
Gor3 gor3Stride = new Gor3(chouFasmanStride);
Protein predictedProteinStride = gor3Stride.makePrediction(proteinStride);
// for(Structure structure : proteinDssp.getProteinStructure()){
// if(structure!=null)System.out.print(structure.toString().substring(0, 1));else
// System.out.print(" ");
// }
// System.out.println();
// for(Structure structure : predictedProteinDssp.getProteinStructure()){
// if(structure!=null)System.out.print(structure.toString().substring(0, 1));
// }
// System.out.println();
System.out.println(proteinDssp.getPdbCode() + "_" + proteinDssp.getPdbChainCode());
System.out.println(String.format("Q3: %1$.2f%% %2$.2f%%", Q3.getQ3Quality(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure()) * 100, Q3.getQ3Quality(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure()) * 100));
dsspSum += Q3.getQ3Quality(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure()) * 100;
strideSum += Q3.getQ3Quality(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure()) * 100;
String mccHelixDssp = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.HELIX) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.HELIX));
String mccBetaDssp = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.BETA) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.BETA));
String mccCoilDssp = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.COIL) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.COIL));
String mccHelixStride = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.HELIX) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.HELIX));
String mccBetaStride = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.BETA) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.BETA));
String mccCoilStride = (MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.COIL) < 0) ? "error" : String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.COIL));
System.out.println(String.format("MCC HELIX: %1$s %2$s", mccHelixDssp, mccHelixStride));
System.out.println(String.format("MCC BETA: %1$s %2$s", mccBetaDssp, mccBetaStride));
System.out.println(String.format("MCC COIL: %1$s %2$s", mccCoilDssp, mccCoilStride));
proteinListDssp.add(proteinDssp);
proteinListStride.add(proteinStride);
}
System.out.println(String.format("DSSP average: %1$.3f%%", dsspSum / proteinListDssp.size()));
System.out.println(String.format("STRIDE average: %1$.3f%%", strideSum / proteinListStride.size()));
}
| public static void main(String[] args) {
Loader loader = new Loader("dssp_info.csv");
List<Protein> proteinListDssp = loader.readFile();
loader = new Loader("stride_info.csv");
List<Protein> proteinListStride = loader.readFile();
System.out.println("DSSP amino acid frequencies:");
System.out.println(AminoAcidStatistics.getAminoAcidNameSortStats(proteinListDssp));
System.out.println("STRIDE amino acid frequencies:");
System.out.println(AminoAcidStatistics.getAminoAcidNameSortStats(proteinListStride));
ChouFasman chouFasmanDssp = new ChouFasman(proteinListDssp);
System.out.println("DSSP amino acids propensities:");
System.out.println(chouFasmanDssp.getAminoAcidsPropensitiesString());
ChouFasman chouFasmanStride = new ChouFasman(proteinListStride);
System.out.println("STRIDE amino acids propensities:");
System.out.println(chouFasmanStride.getAminoAcidsPropensitiesString());
System.out.println(" DSSP STRIDE");
double dsspSum = 0;
double strideSum = 0;
for (int i = 0; i < proteinListDssp.size(); i++) {
Protein proteinDssp = proteinListDssp.remove(0);
chouFasmanDssp = new ChouFasman(proteinListDssp);
Gor3 gor3Dssp = new Gor3(chouFasmanDssp);
Protein predictedProteinDssp = gor3Dssp.makePrediction(proteinDssp);
Protein proteinStride = proteinListStride.remove(0);
chouFasmanStride = new ChouFasman(proteinListStride);
Gor3 gor3Stride = new Gor3(chouFasmanStride);
Protein predictedProteinStride = gor3Stride.makePrediction(proteinStride);
// for(Structure structure : proteinDssp.getProteinStructure()){
// if(structure!=null)System.out.print(structure.toString().substring(0, 1));else
// System.out.print(" ");
// }
// System.out.println();
// for(Structure structure : predictedProteinDssp.getProteinStructure()){
// if(structure!=null)System.out.print(structure.toString().substring(0, 1));
// }
// System.out.println();
System.out.println(proteinDssp.getPdbCode() + "_" + proteinDssp.getPdbChainCode());
System.out.println(String.format("Q3: %1$.2f%% %2$.2f%%", Q3.getQ3Quality(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure()) * 100, Q3.getQ3Quality(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure()) * 100));
dsspSum += Q3.getQ3Quality(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure()) * 100;
strideSum += Q3.getQ3Quality(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure()) * 100;
String mccHelixDssp = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.HELIX));
String mccBetaDssp = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.BETA));
String mccCoilDssp = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinDssp.getProteinStructure(), predictedProteinDssp.getProteinStructure(), Structure.COIL));
String mccHelixStride = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.HELIX));
String mccBetaStride = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.BETA));
String mccCoilStride = String.format("%1$.3f", MatthewsCorrelationCoefficient.getMatthewsCorrelationCoefficient(proteinStride.getProteinStructure(), predictedProteinStride.getProteinStructure(), Structure.COIL));
System.out.println(String.format("MCC HELIX: %1$s %2$s", mccHelixDssp, mccHelixStride));
System.out.println(String.format("MCC BETA: %1$s %2$s", mccBetaDssp, mccBetaStride));
System.out.println(String.format("MCC COIL: %1$s %2$s", mccCoilDssp, mccCoilStride));
proteinListDssp.add(proteinDssp);
proteinListStride.add(proteinStride);
}
System.out.println(String.format("DSSP average: %1$.3f%%", dsspSum / proteinListDssp.size()));
System.out.println(String.format("STRIDE average: %1$.3f%%", strideSum / proteinListStride.size()));
}
|
diff --git a/core/src/main/java/org/acegisecurity/ui/savedrequest/SavedRequest.java b/core/src/main/java/org/acegisecurity/ui/savedrequest/SavedRequest.java
index 4f8618912..8dd714bc7 100644
--- a/core/src/main/java/org/acegisecurity/ui/savedrequest/SavedRequest.java
+++ b/core/src/main/java/org/acegisecurity/ui/savedrequest/SavedRequest.java
@@ -1,339 +1,346 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.ui.savedrequest;
import org.acegisecurity.util.PortResolver;
import org.acegisecurity.util.UrlUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
/**
* Represents central information from a <code>HttpServletRequest</code>.<p>This class is used by {@link
* org.acegisecurity.ui.AbstractProcessingFilter} and {@link org.acegisecurity.wrapper.SavedRequestAwareWrapper} to
* reproduce the request after successful authentication. An instance of this class is stored at the time of an
* authentication exception by {@link org.acegisecurity.ui.ExceptionTranslationFilter}.</p>
* <p><em>IMPLEMENTATION NOTE</em>: It is assumed that this object is accessed only from the context of a single
* thread, so no synchronization around internal collection classes is performed.</p>
* <p>This class is based on code in Apache Tomcat.</p>
*
* @author Craig McClanahan
* @author Andrey Grebnev
* @author Ben Alex
* @version $Id$
*/
public class SavedRequest implements java.io.Serializable {
//~ Static fields/initializers =====================================================================================
protected static final Log logger = LogFactory.getLog(SavedRequest.class);
//~ Instance fields ================================================================================================
private ArrayList cookies = new ArrayList();
private ArrayList locales = new ArrayList();
private Map headers = new TreeMap(String.CASE_INSENSITIVE_ORDER);
private Map parameters = new TreeMap(String.CASE_INSENSITIVE_ORDER);
private String contextPath;
private String method;
private String pathInfo;
private String queryString;
private String requestURI;
private String requestURL;
private String scheme;
private String serverName;
private String servletPath;
private int serverPort;
//~ Constructors ===================================================================================================
public SavedRequest(HttpServletRequest request, PortResolver portResolver) {
Assert.notNull(request, "Request required");
Assert.notNull(portResolver, "PortResolver required");
// Cookies
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
this.addCookie(cookies[i]);
}
}
// Headers
Enumeration names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Enumeration values = request.getHeaders(name);
while (values.hasMoreElements()) {
String value = (String) values.nextElement();
this.addHeader(name, value);
}
}
// Locales
Enumeration locales = request.getLocales();
while (locales.hasMoreElements()) {
Locale locale = (Locale) locales.nextElement();
this.addLocale(locale);
}
// Parameters
Map parameters = request.getParameterMap();
Iterator paramNames = parameters.keySet().iterator();
while (paramNames.hasNext()) {
String paramName = (String) paramNames.next();
- String[] paramValues = (String[]) parameters.get(paramName);
- this.addParameter(paramName, paramValues);
+ Object o = parameters.get(paramName);
+ if (o instanceof String[]) {
+ String[] paramValues = (String[]) o;
+ this.addParameter(paramName, paramValues);
+ } else {
+ if (logger.isWarnEnabled()) {
+ logger.warn("ServletRequest.getParameterMap() returned non-String array");
+ }
+ }
}
// Primitives
this.method = request.getMethod();
this.pathInfo = request.getPathInfo();
this.queryString = request.getQueryString();
this.requestURI = request.getRequestURI();
this.serverPort = portResolver.getServerPort(request);
this.requestURL = request.getRequestURL().toString();
this.scheme = request.getScheme();
this.serverName = request.getServerName();
this.contextPath = request.getContextPath();
this.servletPath = request.getServletPath();
}
//~ Methods ========================================================================================================
private void addCookie(Cookie cookie) {
cookies.add(new SavedCookie(cookie));
}
private void addHeader(String name, String value) {
ArrayList values = (ArrayList) headers.get(name);
if (values == null) {
values = new ArrayList();
headers.put(name, values);
}
values.add(value);
}
private void addLocale(Locale locale) {
locales.add(locale);
}
private void addParameter(String name, String[] values) {
parameters.put(name, values);
}
/**
* Determines if the current request matches the <code>SavedRequest</code>. All URL arguments are
* considered, but <em>not</em> method (POST/GET), cookies, locales, headers or parameters.
*
* @param request DOCUMENT ME!
* @param portResolver DOCUMENT ME!
* @return DOCUMENT ME!
*/
public boolean doesRequestMatch(HttpServletRequest request, PortResolver portResolver) {
Assert.notNull(request, "Request required");
Assert.notNull(portResolver, "PortResolver required");
if (!propertyEquals("pathInfo", this.pathInfo, request.getPathInfo())) {
return false;
}
if (!propertyEquals("queryString", this.queryString, request.getQueryString())) {
return false;
}
if (!propertyEquals("requestURI", this.requestURI, request.getRequestURI())) {
return false;
}
if (!propertyEquals("serverPort", new Integer(this.serverPort), new Integer(portResolver.getServerPort(request))))
{
return false;
}
if (!propertyEquals("requestURL", this.requestURL, request.getRequestURL().toString())) {
return false;
}
if (!propertyEquals("scheme", this.scheme, request.getScheme())) {
return false;
}
if (!propertyEquals("serverName", this.serverName, request.getServerName())) {
return false;
}
if (!propertyEquals("contextPath", this.contextPath, request.getContextPath())) {
return false;
}
if (!propertyEquals("servletPath", this.servletPath, request.getServletPath())) {
return false;
}
return true;
}
public String getContextPath() {
return contextPath;
}
public List getCookies() {
List cookieList = new ArrayList(cookies.size());
for (Iterator iterator = cookies.iterator(); iterator.hasNext();) {
SavedCookie savedCookie = (SavedCookie) iterator.next();
cookieList.add(savedCookie.getCookie());
}
return cookieList;
}
/**
* Indicates the URL that the user agent used for this request.
*
* @return the full URL of this request
*/
public String getFullRequestUrl() {
return UrlUtils.getFullRequestUrl(this);
}
public Iterator getHeaderNames() {
return (headers.keySet().iterator());
}
public Iterator getHeaderValues(String name) {
ArrayList values = (ArrayList) headers.get(name);
if (values == null) {
return ((new ArrayList()).iterator());
} else {
return (values.iterator());
}
}
public Iterator getLocales() {
return (locales.iterator());
}
public String getMethod() {
return (this.method);
}
public Map getParameterMap() {
return parameters;
}
public Iterator getParameterNames() {
return (parameters.keySet().iterator());
}
public String[] getParameterValues(String name) {
return ((String[]) parameters.get(name));
}
public String getPathInfo() {
return pathInfo;
}
public String getQueryString() {
return (this.queryString);
}
public String getRequestURI() {
return (this.requestURI);
}
public String getRequestURL() {
return requestURL;
}
/**
* Obtains the web application-specific fragment of the URL.
*
* @return the URL, excluding any server name, context path or servlet path
*/
public String getRequestUrl() {
return UrlUtils.getRequestUrl(this);
}
public String getScheme() {
return scheme;
}
public String getServerName() {
return serverName;
}
public int getServerPort() {
return serverPort;
}
public String getServletPath() {
return servletPath;
}
private boolean propertyEquals(String log, Object arg1, Object arg2) {
if ((arg1 == null) && (arg2 == null)) {
if (logger.isDebugEnabled()) {
logger.debug(log + ": both null (property equals)");
}
return true;
}
if (((arg1 == null) && (arg2 != null)) || ((arg1 != null) && (arg2 == null))) {
if (logger.isDebugEnabled()) {
logger.debug(log + ": arg1=" + arg1 + "; arg2=" + arg2 + " (property not equals)");
}
return false;
}
if (arg1.equals(arg2)) {
if (logger.isDebugEnabled()) {
logger.debug(log + ": arg1=" + arg1 + "; arg2=" + arg2 + " (property equals)");
}
return true;
} else {
if (logger.isDebugEnabled()) {
logger.debug(log + ": arg1=" + arg1 + "; arg2=" + arg2 + " (property not equals)");
}
return false;
}
}
public String toString() {
return "SavedRequest[" + getFullRequestUrl() + "]";
}
}
| true | true | public SavedRequest(HttpServletRequest request, PortResolver portResolver) {
Assert.notNull(request, "Request required");
Assert.notNull(portResolver, "PortResolver required");
// Cookies
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
this.addCookie(cookies[i]);
}
}
// Headers
Enumeration names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Enumeration values = request.getHeaders(name);
while (values.hasMoreElements()) {
String value = (String) values.nextElement();
this.addHeader(name, value);
}
}
// Locales
Enumeration locales = request.getLocales();
while (locales.hasMoreElements()) {
Locale locale = (Locale) locales.nextElement();
this.addLocale(locale);
}
// Parameters
Map parameters = request.getParameterMap();
Iterator paramNames = parameters.keySet().iterator();
while (paramNames.hasNext()) {
String paramName = (String) paramNames.next();
String[] paramValues = (String[]) parameters.get(paramName);
this.addParameter(paramName, paramValues);
}
// Primitives
this.method = request.getMethod();
this.pathInfo = request.getPathInfo();
this.queryString = request.getQueryString();
this.requestURI = request.getRequestURI();
this.serverPort = portResolver.getServerPort(request);
this.requestURL = request.getRequestURL().toString();
this.scheme = request.getScheme();
this.serverName = request.getServerName();
this.contextPath = request.getContextPath();
this.servletPath = request.getServletPath();
}
| public SavedRequest(HttpServletRequest request, PortResolver portResolver) {
Assert.notNull(request, "Request required");
Assert.notNull(portResolver, "PortResolver required");
// Cookies
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
this.addCookie(cookies[i]);
}
}
// Headers
Enumeration names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Enumeration values = request.getHeaders(name);
while (values.hasMoreElements()) {
String value = (String) values.nextElement();
this.addHeader(name, value);
}
}
// Locales
Enumeration locales = request.getLocales();
while (locales.hasMoreElements()) {
Locale locale = (Locale) locales.nextElement();
this.addLocale(locale);
}
// Parameters
Map parameters = request.getParameterMap();
Iterator paramNames = parameters.keySet().iterator();
while (paramNames.hasNext()) {
String paramName = (String) paramNames.next();
Object o = parameters.get(paramName);
if (o instanceof String[]) {
String[] paramValues = (String[]) o;
this.addParameter(paramName, paramValues);
} else {
if (logger.isWarnEnabled()) {
logger.warn("ServletRequest.getParameterMap() returned non-String array");
}
}
}
// Primitives
this.method = request.getMethod();
this.pathInfo = request.getPathInfo();
this.queryString = request.getQueryString();
this.requestURI = request.getRequestURI();
this.serverPort = portResolver.getServerPort(request);
this.requestURL = request.getRequestURL().toString();
this.scheme = request.getScheme();
this.serverName = request.getServerName();
this.contextPath = request.getContextPath();
this.servletPath = request.getServletPath();
}
|
diff --git a/feeder-sns-parent/feeder-sns-twitter/src/main/java/org/komusubi/feeder/sns/twitter/Twitter4j.java b/feeder-sns-parent/feeder-sns-twitter/src/main/java/org/komusubi/feeder/sns/twitter/Twitter4j.java
index b84808d..3945bb0 100644
--- a/feeder-sns-parent/feeder-sns-twitter/src/main/java/org/komusubi/feeder/sns/twitter/Twitter4j.java
+++ b/feeder-sns-parent/feeder-sns-twitter/src/main/java/org/komusubi/feeder/sns/twitter/Twitter4j.java
@@ -1,112 +1,115 @@
/*
* 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.komusubi.feeder.sns.twitter;
import org.komusubi.feeder.model.Message;
import org.komusubi.feeder.model.Message.Script;
import org.komusubi.feeder.model.Topic;
import org.komusubi.feeder.model.Topics;
import org.komusubi.feeder.sns.History;
import org.komusubi.feeder.sns.SocialNetwork;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
/**
* @author jun.ozeki
*/
public class Twitter4j implements SocialNetwork {
private static final Logger logger = LoggerFactory.getLogger(Twitter4j.class);
private Twitter twitter;
private boolean outputConsole = Boolean.getBoolean("tweet.console");
/**
* create new instance.
*/
public Twitter4j() {
this(TwitterFactory.getSingleton());
}
/**
* create new instance for unit test
* @param twitter
*/
// package
Twitter4j(Twitter twitter) {
this.twitter = twitter;
}
/**
* @see org.komusubi.feeder.sns.SocialNetwork#post(org.komusubi.feeder.model.Message)
*/
@Override
public void post(Message message) {
tweet(message);
}
/**
* @see org.komusubi.feeder.sns.SocialNetwork#post(Topic topic)
*/
@Override
public void post(Topic topic) {
tweet(topic.message());
}
@Override
public void post(Topics<? extends Topic> topics) {
for (Topic t: topics)
post(t);
}
/**
* tweet.
* @param message
*/
public void tweet(Message message) {
try {
+ Status result = null;
for (Script script: message) {
if (outputConsole) {
- System.out.printf("tweet: %s%n", script.trimedLine());
+ System.out.printf("tweet(length:%d): %s%n", script.codePointCount(), script.trimedLine());
} else {
StatusUpdate status = new StatusUpdate(script.trimedLine());
- logger.info("tweet : {}", status.getStatus());
- Status result = twitter.updateStatus(status);
+ if (result != null) {
+ status.inReplyToStatusId(result.getId());
+ }
+ logger.info("tweet({}) : {}", script.codePointCount(), status.getStatus());
+ result = twitter.updateStatus(status);
}
- logger.info("script codepoint length: {}", script.codePointCount());
}
} catch (TwitterException e) {
throw new Twitter4jException(e);
}
}
/**
* @see org.komusubi.feeder.sns.SocialNetwork#history()
*/
@Override
public History history() {
return new TweetHistory(twitter);
}
}
| false | true | public void tweet(Message message) {
try {
for (Script script: message) {
if (outputConsole) {
System.out.printf("tweet: %s%n", script.trimedLine());
} else {
StatusUpdate status = new StatusUpdate(script.trimedLine());
logger.info("tweet : {}", status.getStatus());
Status result = twitter.updateStatus(status);
}
logger.info("script codepoint length: {}", script.codePointCount());
}
} catch (TwitterException e) {
throw new Twitter4jException(e);
}
}
| public void tweet(Message message) {
try {
Status result = null;
for (Script script: message) {
if (outputConsole) {
System.out.printf("tweet(length:%d): %s%n", script.codePointCount(), script.trimedLine());
} else {
StatusUpdate status = new StatusUpdate(script.trimedLine());
if (result != null) {
status.inReplyToStatusId(result.getId());
}
logger.info("tweet({}) : {}", script.codePointCount(), status.getStatus());
result = twitter.updateStatus(status);
}
}
} catch (TwitterException e) {
throw new Twitter4jException(e);
}
}
|
diff --git a/src/net/fred/feedex/activity/MainActivity.java b/src/net/fred/feedex/activity/MainActivity.java
index ad1b5e9..ae9e566 100644
--- a/src/net/fred/feedex/activity/MainActivity.java
+++ b/src/net/fred/feedex/activity/MainActivity.java
@@ -1,297 +1,297 @@
/**
* FeedEx
*
* Copyright (c) 2012-2013 Frederic Julian
*
* 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 net.fred.feedex.activity;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import net.fred.feedex.Constants;
import net.fred.feedex.MainApplication;
import net.fred.feedex.PrefUtils;
import net.fred.feedex.R;
import net.fred.feedex.UiUtils;
import net.fred.feedex.fragment.EntriesListFragment;
import net.fred.feedex.fragment.FeedsListFragment;
import net.fred.feedex.provider.FeedData.EntryColumns;
import net.fred.feedex.service.FetcherService;
import net.fred.feedex.service.RefreshService;
import java.lang.reflect.Method;
import java.util.Locale;
import java.util.Random;
public class MainActivity extends ProgressFragmentActivity implements ActionBar.TabListener, LoaderManager.LoaderCallbacks<Cursor> {
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private ActionMode mActionMode;
static NotificationManager mNotificationManager = (NotificationManager) MainApplication.getAppContext().getSystemService(
Context.NOTIFICATION_SERVICE);
private final SharedPreferences.OnSharedPreferenceChangeListener isRefreshingListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (PrefUtils.IS_REFRESHING.equals(key)) {
getProgressBar().setVisibility(PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false) ? View.VISIBLE : View.GONE);
}
}
};
private final int loaderId = new Random().nextInt();
@Override
protected void onCreate(Bundle savedInstanceState) {
UiUtils.setPreferenceTheme(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Hack to always show the tabs under the actionbar
try {
Method setHasEmbeddedTabsMethod = actionBar.getClass().getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
setHasEmbeddedTabsMethod.setAccessible(true);
setHasEmbeddedTabsMethod.invoke(actionBar, false);
} catch (Exception ignored) {
}
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
/*
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the sections. We use a {@link
* android.support.v4.app.FragmentPagerAdapter} derivative, which will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(sectionsPagerAdapter);
+ int currentTab = PrefUtils.getInteger(PrefUtils.CURRENT_TAB_IDX, 0);
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < sectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
- actionBar.addTab(actionBar.newTab().setText(sectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
+ actionBar.addTab(actionBar.newTab().setText(sectionsPagerAdapter.getPageTitle(i)).setTabListener(this), currentTab == i ? true : false);
}
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
PrefUtils.putInteger(PrefUtils.CURRENT_TAB_IDX, position);
invalidateOptionsMenu(); // Do not do it into onTabSelected()!
}
});
- actionBar.setSelectedNavigationItem(PrefUtils.getInteger(PrefUtils.CURRENT_TAB_IDX, 0));
if (PrefUtils.getBoolean(PrefUtils.REFRESH_ENABLED, true)) {
// starts the service independent to this activity
startService(new Intent(this, RefreshService.class));
} else {
stopService(new Intent(this, RefreshService.class));
}
if (PrefUtils.getBoolean(PrefUtils.REFRESH_ON_OPEN_ENABLED, false)) {
if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false)) {
startService(new Intent(MainActivity.this, FetcherService.class).setAction(FetcherService.ACTION_REFRESH_FEEDS));
}
}
getSupportLoaderManager().initLoader(loaderId, null, this);
}
@Override
protected void onResume() {
super.onResume();
getProgressBar().setVisibility(PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false) ? View.VISIBLE : View.GONE);
PrefUtils.registerOnSharedPreferenceChangeListener(isRefreshingListener);
if (mNotificationManager != null) {
mNotificationManager.cancel(0);
}
}
@Override
protected void onPause() {
if (mActionMode != null) {
mActionMode.finish();
}
PrefUtils.unregisterOnSharedPreferenceChangeListener(isRefreshingListener);
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// HACK to get the good fragment...
getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + getActionBar().getSelectedNavigationIndex())
.onCreateOptionsMenu(menu, getMenuInflater());
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// HACK to get the good fragment...
getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + getActionBar().getSelectedNavigationIndex())
.onOptionsItemSelected(item);
return true;
}
@Override
public void onActionModeFinished(ActionMode mode) {
mActionMode = null;
super.onActionModeFinished(mode);
}
@Override
public void onActionModeStarted(ActionMode mode) {
mActionMode = mode;
super.onActionModeStarted(mode);
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
if (mActionMode != null) {
mActionMode.finish();
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the sections/tabs/pages.
*/
private static class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (position) {
case 0:
fragment = new FeedsListFragment();
break;
case 1:
fragment = new EntriesListFragment();
args.putParcelable(EntriesListFragment.ARG_URI, EntryColumns.CONTENT_URI);
args.putBoolean(EntriesListFragment.ARG_SHOW_FEED_INFO, true);
fragment.setArguments(args);
break;
case 2:
fragment = new EntriesListFragment();
args.putParcelable(EntriesListFragment.ARG_URI, EntryColumns.FAVORITES_CONTENT_URI);
args.putBoolean(EntriesListFragment.ARG_SHOW_FEED_INFO, true);
fragment.setArguments(args);
break;
default:
break;
}
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return MainApplication.getAppContext().getString(R.string.overview).toUpperCase(Locale.getDefault());
case 1: {
return MainApplication.getAppContext().getString(R.string.all).toUpperCase(Locale.getDefault());
}
case 2:
return MainApplication.getAppContext().getString(R.string.favorites).toUpperCase(Locale.getDefault());
}
return null;
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader = new CursorLoader(this, EntryColumns.CONTENT_URI, new String[]{"COUNT(*)"}, EntryColumns.WHERE_UNREAD, null,
null);
cursorLoader.setUpdateThrottle(Constants.UPDATE_THROTTLE_DELAY);
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data.moveToFirst()) {
int nbUnread = data.getInt(0);
if (nbUnread > 0)
getActionBar().getTabAt(1).setText(getString(R.string.all).toUpperCase(Locale.getDefault()) + " (" + data.getInt(0) + ')');
else
getActionBar().getTabAt(1).setText(getString(R.string.all).toUpperCase(Locale.getDefault()));
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
UiUtils.setPreferenceTheme(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Hack to always show the tabs under the actionbar
try {
Method setHasEmbeddedTabsMethod = actionBar.getClass().getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
setHasEmbeddedTabsMethod.setAccessible(true);
setHasEmbeddedTabsMethod.invoke(actionBar, false);
} catch (Exception ignored) {
}
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
/*
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the sections. We use a {@link
* android.support.v4.app.FragmentPagerAdapter} derivative, which will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(sectionsPagerAdapter);
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < sectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab().setText(sectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
PrefUtils.putInteger(PrefUtils.CURRENT_TAB_IDX, position);
invalidateOptionsMenu(); // Do not do it into onTabSelected()!
}
});
actionBar.setSelectedNavigationItem(PrefUtils.getInteger(PrefUtils.CURRENT_TAB_IDX, 0));
if (PrefUtils.getBoolean(PrefUtils.REFRESH_ENABLED, true)) {
// starts the service independent to this activity
startService(new Intent(this, RefreshService.class));
} else {
stopService(new Intent(this, RefreshService.class));
}
if (PrefUtils.getBoolean(PrefUtils.REFRESH_ON_OPEN_ENABLED, false)) {
if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false)) {
startService(new Intent(MainActivity.this, FetcherService.class).setAction(FetcherService.ACTION_REFRESH_FEEDS));
}
}
getSupportLoaderManager().initLoader(loaderId, null, this);
}
| protected void onCreate(Bundle savedInstanceState) {
UiUtils.setPreferenceTheme(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Hack to always show the tabs under the actionbar
try {
Method setHasEmbeddedTabsMethod = actionBar.getClass().getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
setHasEmbeddedTabsMethod.setAccessible(true);
setHasEmbeddedTabsMethod.invoke(actionBar, false);
} catch (Exception ignored) {
}
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
/*
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the sections. We use a {@link
* android.support.v4.app.FragmentPagerAdapter} derivative, which will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(sectionsPagerAdapter);
int currentTab = PrefUtils.getInteger(PrefUtils.CURRENT_TAB_IDX, 0);
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < sectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab().setText(sectionsPagerAdapter.getPageTitle(i)).setTabListener(this), currentTab == i ? true : false);
}
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
PrefUtils.putInteger(PrefUtils.CURRENT_TAB_IDX, position);
invalidateOptionsMenu(); // Do not do it into onTabSelected()!
}
});
if (PrefUtils.getBoolean(PrefUtils.REFRESH_ENABLED, true)) {
// starts the service independent to this activity
startService(new Intent(this, RefreshService.class));
} else {
stopService(new Intent(this, RefreshService.class));
}
if (PrefUtils.getBoolean(PrefUtils.REFRESH_ON_OPEN_ENABLED, false)) {
if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false)) {
startService(new Intent(MainActivity.this, FetcherService.class).setAction(FetcherService.ACTION_REFRESH_FEEDS));
}
}
getSupportLoaderManager().initLoader(loaderId, null, this);
}
|
diff --git a/domains/notification/email/src/main/java/org/openengsb/domains/notification/email/EmailServiceManager.java b/domains/notification/email/src/main/java/org/openengsb/domains/notification/email/EmailServiceManager.java
index 33f9a7610..55994b239 100644
--- a/domains/notification/email/src/main/java/org/openengsb/domains/notification/email/EmailServiceManager.java
+++ b/domains/notification/email/src/main/java/org/openengsb/domains/notification/email/EmailServiceManager.java
@@ -1,156 +1,156 @@
/**
Copyright 2010 OpenEngSB Division, Vienna University of Technology
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openengsb.domains.notification.email;
import org.openengsb.core.config.Domain;
import org.openengsb.core.config.ServiceManager;
import org.openengsb.core.config.descriptor.AttributeDefinition;
import org.openengsb.core.config.descriptor.ServiceDescriptor;
import org.openengsb.core.config.util.BundleStrings;
import org.openengsb.domains.notification.implementation.NotificationDomain;
import org.openengsb.domains.notification.email.internal.EmailNotifier;
import org.osgi.framework.BundleContext;
import org.springframework.osgi.context.BundleContextAware;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Map;
public class EmailServiceManager implements ServiceManager, BundleContextAware {
private BundleContext bundleContext;
private BundleStrings strings;
private final Map<String, EmailNotifier> services = new HashMap<String, EmailNotifier>();
@Override
public ServiceDescriptor getDescriptor() {
return getDescriptor(Locale.getDefault());
}
@Override
public ServiceDescriptor getDescriptor(Locale locale) {
return ServiceDescriptor.builder()
.id(EmailNotifier.class.getName())
.implementsInterface(NotificationDomain.class.getName())
.type(EmailNotifier.class)
.name(strings.getString("email.name", locale))
.description(strings.getString("email.description", locale))
.attribute(AttributeDefinition.builder()
.id("user")
- .name(strings.getString("username.outputMode.username", locale))
+ .name(strings.getString("username.outputMode", locale))
.description(strings.getString("username.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("password")
.name(strings.getString("password.outputMode", locale))
.description(strings.getString("password.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpAuth")
.name(strings.getString("mail.smtp.auth.outputMode", locale))
.description(strings.getString("mail.smtp.auth.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpUser")
.name(strings.getString("mail.smtp.user.outputMode", locale))
.description(strings.getString("mail.smtp.user.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpPort")
.name(strings.getString("mail.smtp.port.outputMode", locale))
.description(strings.getString("mail.smtp.port.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpHost")
.name(strings.getString("mail.smtp.host.outputMode", locale))
.description(strings.getString("mail.smtp.host.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.build();
}
@Override
public void update(String id, Map<String, String> attributes) {
boolean isNew = false;
EmailNotifier en = null;
synchronized (services) {
en = services.get(id);
if (en == null) {
en = new EmailNotifier(id);
services.put(id, en);
isNew = true;
}
if (attributes.containsKey("user")) {
en.setUser(attributes.get("user"));
}
if (attributes.containsKey("password")) {
en.setPassword(attributes.get("password"));
}
if (attributes.containsKey("smtpAuth")) {
en.setSmtpAuth(attributes.get("smtpAuth"));
}
if (attributes.containsKey("smtpUser")) {
en.setSmtpUser(attributes.get("smtpUser"));
}
if (attributes.containsKey("smtpHost")) {
en.setSmtpHost(attributes.get("smtpHost"));
}
if (attributes.containsKey("smtpPort")) {
en.setSmtpPort(attributes.get("smtpPort"));
}
}
if (isNew) {
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("id", id);
props.put("domain", NotificationDomain.class.getName());
props.put("class", EmailNotifier.class.getName());
bundleContext.registerService(new String[]{EmailNotifier.class.getName(), NotificationDomain.class.getName(),
Domain.class.getName()},
en, props);
}
}
@Override
public void delete(String id) {
synchronized (services) {
services.remove(id);
}
}
public void init() {
strings = new BundleStrings(bundleContext.getBundle());
}
@Override
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
| true | true | public ServiceDescriptor getDescriptor(Locale locale) {
return ServiceDescriptor.builder()
.id(EmailNotifier.class.getName())
.implementsInterface(NotificationDomain.class.getName())
.type(EmailNotifier.class)
.name(strings.getString("email.name", locale))
.description(strings.getString("email.description", locale))
.attribute(AttributeDefinition.builder()
.id("user")
.name(strings.getString("username.outputMode.username", locale))
.description(strings.getString("username.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("password")
.name(strings.getString("password.outputMode", locale))
.description(strings.getString("password.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpAuth")
.name(strings.getString("mail.smtp.auth.outputMode", locale))
.description(strings.getString("mail.smtp.auth.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpUser")
.name(strings.getString("mail.smtp.user.outputMode", locale))
.description(strings.getString("mail.smtp.user.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpPort")
.name(strings.getString("mail.smtp.port.outputMode", locale))
.description(strings.getString("mail.smtp.port.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpHost")
.name(strings.getString("mail.smtp.host.outputMode", locale))
.description(strings.getString("mail.smtp.host.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.build();
}
| public ServiceDescriptor getDescriptor(Locale locale) {
return ServiceDescriptor.builder()
.id(EmailNotifier.class.getName())
.implementsInterface(NotificationDomain.class.getName())
.type(EmailNotifier.class)
.name(strings.getString("email.name", locale))
.description(strings.getString("email.description", locale))
.attribute(AttributeDefinition.builder()
.id("user")
.name(strings.getString("username.outputMode", locale))
.description(strings.getString("username.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("password")
.name(strings.getString("password.outputMode", locale))
.description(strings.getString("password.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpAuth")
.name(strings.getString("mail.smtp.auth.outputMode", locale))
.description(strings.getString("mail.smtp.auth.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpUser")
.name(strings.getString("mail.smtp.user.outputMode", locale))
.description(strings.getString("mail.smtp.user.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpPort")
.name(strings.getString("mail.smtp.port.outputMode", locale))
.description(strings.getString("mail.smtp.port.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.attribute(AttributeDefinition.builder()
.id("smtpHost")
.name(strings.getString("mail.smtp.host.outputMode", locale))
.description(strings.getString("mail.smtp.host.outputMode.description", locale))
.defaultValue("")
.required()
.build())
.build();
}
|
diff --git a/Core/src/com/ushahidi/android/app/About.java b/Core/src/com/ushahidi/android/app/About.java
index 8e8e64d2..bfece931 100644
--- a/Core/src/com/ushahidi/android/app/About.java
+++ b/Core/src/com/ushahidi/android/app/About.java
@@ -1,137 +1,137 @@
/**
** Copyright (c) 2010 Ushahidi Inc
** All rights reserved
** Contact: [email protected]
** Website: http://www.ushahidi.com
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: http://www.gnu.org/licenses/lgpl.html.
**
**
** If you have questions regarding the use of this file, please contact
** Ushahidi developers at [email protected].
**
**/
package com.ushahidi.android.app;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class About extends Dashboard {
private static final int HOME = Menu.FIRST + 1;
private static final int SETTINGS = Menu.FIRST + 2;
private static final int GOTOHOME = 0;
private static final int REQUEST_CODE_SETTINGS = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
setTitleFromActivityLabel(R.id.title_text);
//SEARCH
ImageButton searchButton = (ImageButton) findViewById(R.id.search_report_btn);
- if (!TextUtils.isEmpty(getString(R.string.default_deployment))) {
+ if (!TextUtils.isEmpty(getString(R.string.deployment_url))) {
searchButton.setVisibility(View.GONE);
}
else {
searchButton.setVisibility(View.VISIBLE);
}
//VERSION
TextView version = (TextView) findViewById(R.id.version);
try {
version.setText(getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName);
}
catch (NameNotFoundException e) {
Log.e("About", "NameNotFoundException", e);
version.setText("");
}
//BUTTONS
setButtonVisibility((Button)findViewById(R.id.media_link), getString(R.string.media_url));
setButtonVisibility((Button)findViewById(R.id.team_link), getString(R.string.team_url));
setButtonVisibility((Button)findViewById(R.id.twitter_link), getString(R.string.twitter_url));
setButtonVisibility((Button)findViewById(R.id.facebook_link), getString(R.string.facebook_url));
setButtonVisibility((Button)findViewById(R.id.contact_link), getString(R.string.contact_url));
}
// override the prompt display so it doesn't show a prompt
@Override
public void promptForDeployment() {}
private void setButtonVisibility(final Button button, final String url) {
if (!TextUtils.isEmpty(url)) {
button.setVisibility(View.VISIBLE);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url)));
}
});
}
else {
button.setVisibility(View.GONE);
}
}
private void populateMenu(Menu menu) {
MenuItem i;
i = menu.add(Menu.NONE, HOME, Menu.NONE, R.string.menu_home);
i.setIcon(R.drawable.menu_home);
i = menu.add(Menu.NONE, SETTINGS, Menu.NONE, R.string.menu_settings);
i.setIcon(R.drawable.menu_about);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
populateMenu(menu);
return (super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// applyMenuChoice(item);
return (applyMenuChoice(item) || super.onOptionsItemSelected(item));
}
private boolean applyMenuChoice(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case HOME:
intent = new Intent(About.this, Dashboard.class);
startActivityForResult(intent, GOTOHOME);
return true;
case SETTINGS:
intent = new Intent(About.this, Settings.class);
// Make it a subactivity so we know when it returns
startActivityForResult(intent, REQUEST_CODE_SETTINGS);
return (true);
}
return false;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
setTitleFromActivityLabel(R.id.title_text);
//SEARCH
ImageButton searchButton = (ImageButton) findViewById(R.id.search_report_btn);
if (!TextUtils.isEmpty(getString(R.string.default_deployment))) {
searchButton.setVisibility(View.GONE);
}
else {
searchButton.setVisibility(View.VISIBLE);
}
//VERSION
TextView version = (TextView) findViewById(R.id.version);
try {
version.setText(getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName);
}
catch (NameNotFoundException e) {
Log.e("About", "NameNotFoundException", e);
version.setText("");
}
//BUTTONS
setButtonVisibility((Button)findViewById(R.id.media_link), getString(R.string.media_url));
setButtonVisibility((Button)findViewById(R.id.team_link), getString(R.string.team_url));
setButtonVisibility((Button)findViewById(R.id.twitter_link), getString(R.string.twitter_url));
setButtonVisibility((Button)findViewById(R.id.facebook_link), getString(R.string.facebook_url));
setButtonVisibility((Button)findViewById(R.id.contact_link), getString(R.string.contact_url));
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
setTitleFromActivityLabel(R.id.title_text);
//SEARCH
ImageButton searchButton = (ImageButton) findViewById(R.id.search_report_btn);
if (!TextUtils.isEmpty(getString(R.string.deployment_url))) {
searchButton.setVisibility(View.GONE);
}
else {
searchButton.setVisibility(View.VISIBLE);
}
//VERSION
TextView version = (TextView) findViewById(R.id.version);
try {
version.setText(getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName);
}
catch (NameNotFoundException e) {
Log.e("About", "NameNotFoundException", e);
version.setText("");
}
//BUTTONS
setButtonVisibility((Button)findViewById(R.id.media_link), getString(R.string.media_url));
setButtonVisibility((Button)findViewById(R.id.team_link), getString(R.string.team_url));
setButtonVisibility((Button)findViewById(R.id.twitter_link), getString(R.string.twitter_url));
setButtonVisibility((Button)findViewById(R.id.facebook_link), getString(R.string.facebook_url));
setButtonVisibility((Button)findViewById(R.id.contact_link), getString(R.string.contact_url));
}
|
diff --git a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
index 71ed3e4..c294ceb 100644
--- a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
+++ b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
@@ -1,372 +1,375 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server.movement;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.game.GameObject;
import de._13ducks.cor.game.Moveable;
import de._13ducks.cor.game.SimplePosition;
import de._13ducks.cor.networks.server.behaviour.ServerBehaviour;
import de._13ducks.cor.game.server.ServerCore;
import java.util.List;
/**
* Lowlevel-Movemanagement
*
* Verwaltet die reine Bewegung einer einzelnen Einheit.
* Kümmert sich nicht weiter um Formationen/Kampf oder ähnliches.
* Erhält vom übergeordneten MidLevelManager einen Richtungsvektor und eine Zielkoordinate.
* Läuft dann dort hin. Tut sonst nichts.
* Hat exklusive Kontrolle über die Einheitenposition.
* Weigert sich, sich schneller als die maximale Einheitengeschwindigkeit zu bewegen.
* Dadurch werden Sprünge verhindert.
*
* Wenn eine Kollision festgestellt wird, wird der überliegende GroupManager gefragt was zu tun ist.
* Der GroupManager entscheidet dann über die Ausweichroute oder lässt uns warten.
*/
public class ServerBehaviourMove extends ServerBehaviour {
private Moveable caster2;
private SimplePosition target;
private double speed;
private boolean stopUnit = false;
private long lastTick;
private SimplePosition clientTarget;
private MovementMap moveMap;
/**
* Die Systemzeit zu dem Zeitpunkt, an dem mit dem Warten begonnen wurde
*/
private long waitStartTime;
/**
* Gibt an, ob gerade gewartet wird
* (z.B. wenn etwas im WEg steht und man wartet bis es den WEg freimacht)
*/
private boolean wait;
/**
* Die Zeit, die gewartet wird (in Nanosekunden) (eine milliarde ist eine sekunde)
*/
private static final long waitTime = 1000000000;
/**
* Wird für die Abstandssuche benötigt. Falls jemals eine Einheit größer ist, MUSS dieser Wert auch erhöht werden.
*/
private static final double maxRadius = 4;
/**
* Eine minimale Distanz, die Einheiten beim Aufstellen wegen einer Kollision berücksichtigen.
* Damit wird verhindert, dass aufgrund von Rundungsfehlern Kolision auf ursprünlich als frei
* eingestuften Flächen berechnet wird.
*/
public static final double MIN_DISTANCE = 0.1;
public ServerBehaviourMove(ServerCore.InnerServer newinner, GameObject caster1, Moveable caster2, MovementMap moveMap) {
super(newinner, caster1, 1, 20, true);
this.caster2 = caster2;
this.moveMap = moveMap;
}
@Override
public void activate() {
active = true;
trigger();
}
@Override
public void deactivate() {
active = false;
}
@Override
public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
long ticktime = System.nanoTime();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
boolean stillColliding = false;
for (Moveable m : moveMap.moversAroundPoint(newpos, caster2.getRadius() + maxRadius, caster2.getMyPoly())) {
+ if (m.equals(caster2)) {
+ continue;
+ }
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) {
stillColliding = true;
break;
}
}
if (stillColliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
wait = false;
// Ticktime manipulieren.
lastTick = System.nanoTime();
trigger();
return;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (!stopUnit) {
// Echtzeitkollision:
for (Moveable m : moveMap.moversAroundPoint(newpos, this.caster2.getRadius() + maxRadius, caster2.getMyPoly())) {
if (m.equals(caster2)) {
continue;
}
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) {
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, m);
double distanceToObstacle = (float) this.caster2.getRadius() + (float) m.getRadius() + (float) MIN_DISTANCE;
Vector origin = new Vector(-vec.getY(), vec.getX());
Edge edge = new Edge(m.getPrecisePosition().toNode(), m.getPrecisePosition().add(origin.toFPP()).toNode());
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(vec.toFPP()).toNode());
SimplePosition p = edge.endlessIntersection(edge2);
double distance = m.getPrecisePosition().getDistance(p.toFPP());
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
FloatingPointPosition nextnewpos = p.toVector().add(vec.getInverted().normalize().multiply(b)).toFPP();
if (nextnewpos.toVector().isValid() && checkPosition(nextnewpos)) {
newpos = nextnewpos;
} else {
System.out.println("WARNING: Ugly back-stop!");
newpos = oldPos.toFPP();
}
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + m + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Bricht die Bewegung vollständig ab.
System.out.println("STOP-COLLISION " + caster2 + " with " + m);
stopUnit = true;
}
break;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if (vec.isOpposite(nextVec) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target.toFPP());
SimplePosition oldTar = target;
// Neuen Wegpunkt anfordern:
if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Herausfinden, ob der Sektor gewechselt wurde
SimplePosition newTar = target;
if (newTar instanceof Node && oldTar instanceof Node) {
// Nur in diesem Fall kommt ein Sektorwechsel in Frage
FreePolygon sector = commonSector((Node) newTar, (Node) oldTar);
// Sektor geändert?
if (!sector.equals(caster2.getMyPoly())) {
caster2.setMyPoly(sector);
}
}
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.nanoTime();
}
}
}
@Override
public void gotSignal(byte[] packet) {
}
@Override
public void pause() {
caster2.pause();
}
@Override
public void unpause() {
caster2.unpause();
}
/**
* Setzt den Zielvektor für diese Einheit.
* Es wird nicht untersucht, ob das Ziel in irgendeiner Weise ok ist, die Einheit beginnt sofort loszulaufen.
* In der Regel sollte noch eine Geschwindigkeit angegeben werden.
* Wehrt sich gegen nicht existente Ziele.
* @param pos die Zielposition, wird auf direktem Weg angesteuert.
*/
public synchronized void setTargetVector(SimplePosition pos) {
if (pos == null) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to null");
}
if (!pos.toVector().isValid()) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to invalid position");
}
target = pos;
lastTick = System.nanoTime();
clientTarget = Vector.ZERO;
activate();
}
/**
* Setzt den Zielvektor und die Geschwindigkeit und startet die Bewegung sofort.
* @param pos die Zielposition
* @param speed die Geschwindigkeit
*/
public synchronized void setTargetVector(SimplePosition pos, double speed) {
changeSpeed(speed);
setTargetVector(pos);
}
/**
* Ändert die Geschwindigkeit während des Laufens.
* Speed wird verkleinert, wenn der Wert über dem Einheiten-Maximum liegen würde
* @param speed Die Einheitengeschwindigkeit
*/
public synchronized void changeSpeed(double speed) {
if (speed > 0 && speed <= caster2.getSpeed()) {
this.speed = speed;
}
trigger();
}
public boolean isMoving() {
return target != null;
}
/**
* Stoppt die Einheit innerhalb eines Ticks.
*/
public synchronized void stopImmediately() {
stopUnit = true;
trigger();
}
/**
* Findet einen Sektor, den beide Knoten gemeinsam haben
* @param n1 Knoten 1
* @param n2 Knoten 2
*/
private FreePolygon commonSector(Node n1, Node n2) {
for (FreePolygon poly : n1.getPolygons()) {
if (n2.getPolygons().contains(poly)) {
return poly;
}
}
return null;
}
/**
* Berechnet den Winkel zwischen zwei Vektoren
* @param vector_1
* @param vector_2
* @return
*/
public double getAngle(FloatingPointPosition vector_1, FloatingPointPosition vector_2) {
double scalar = ((vector_1.getfX() * vector_2.getfX()) + (vector_1.getfY() * vector_2.getfY()));
double vector_1_lenght = Math.sqrt((vector_1.getfX() * vector_1.getfX()) + vector_2.getfY() * vector_1.getfY());
double vector_2_lenght = Math.sqrt((vector_2.getfX() * vector_2.getfX()) + vector_2.getfY() * vector_2.getfY());
double lenght = vector_1_lenght * vector_2_lenght;
double angle = Math.acos((scalar / lenght));
return angle;
}
/**
* Überprüft auf RTC mit Zielposition
* @param pos die zu testende Position
* @return true, wenn frei
*/
private boolean checkPosition(FloatingPointPosition pos) {
List<Moveable> movers = moveMap.moversAroundPoint(pos, caster2.getRadius() + maxRadius);
movers.remove(caster2);
for (Moveable m : movers) {
if (m.getPrecisePosition().getDistance(pos) < (m.getRadius() + caster2.getRadius())) {
return false;
}
}
return true;
}
}
| true | true | public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
long ticktime = System.nanoTime();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
boolean stillColliding = false;
for (Moveable m : moveMap.moversAroundPoint(newpos, caster2.getRadius() + maxRadius, caster2.getMyPoly())) {
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) {
stillColliding = true;
break;
}
}
if (stillColliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
wait = false;
// Ticktime manipulieren.
lastTick = System.nanoTime();
trigger();
return;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (!stopUnit) {
// Echtzeitkollision:
for (Moveable m : moveMap.moversAroundPoint(newpos, this.caster2.getRadius() + maxRadius, caster2.getMyPoly())) {
if (m.equals(caster2)) {
continue;
}
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) {
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, m);
double distanceToObstacle = (float) this.caster2.getRadius() + (float) m.getRadius() + (float) MIN_DISTANCE;
Vector origin = new Vector(-vec.getY(), vec.getX());
Edge edge = new Edge(m.getPrecisePosition().toNode(), m.getPrecisePosition().add(origin.toFPP()).toNode());
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(vec.toFPP()).toNode());
SimplePosition p = edge.endlessIntersection(edge2);
double distance = m.getPrecisePosition().getDistance(p.toFPP());
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
FloatingPointPosition nextnewpos = p.toVector().add(vec.getInverted().normalize().multiply(b)).toFPP();
if (nextnewpos.toVector().isValid() && checkPosition(nextnewpos)) {
newpos = nextnewpos;
} else {
System.out.println("WARNING: Ugly back-stop!");
newpos = oldPos.toFPP();
}
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + m + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Bricht die Bewegung vollständig ab.
System.out.println("STOP-COLLISION " + caster2 + " with " + m);
stopUnit = true;
}
break;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if (vec.isOpposite(nextVec) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target.toFPP());
SimplePosition oldTar = target;
// Neuen Wegpunkt anfordern:
if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Herausfinden, ob der Sektor gewechselt wurde
SimplePosition newTar = target;
if (newTar instanceof Node && oldTar instanceof Node) {
// Nur in diesem Fall kommt ein Sektorwechsel in Frage
FreePolygon sector = commonSector((Node) newTar, (Node) oldTar);
// Sektor geändert?
if (!sector.equals(caster2.getMyPoly())) {
caster2.setMyPoly(sector);
}
}
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.nanoTime();
}
}
}
| public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
FloatingPointPosition oldPos = caster2.getPrecisePosition();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
long ticktime = System.nanoTime();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
boolean stillColliding = false;
for (Moveable m : moveMap.moversAroundPoint(newpos, caster2.getRadius() + maxRadius, caster2.getMyPoly())) {
if (m.equals(caster2)) {
continue;
}
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) {
stillColliding = true;
break;
}
}
if (stillColliding) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
wait = false;
// Ticktime manipulieren.
lastTick = System.nanoTime();
trigger();
return;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (!stopUnit) {
// Echtzeitkollision:
for (Moveable m : moveMap.moversAroundPoint(newpos, this.caster2.getRadius() + maxRadius, caster2.getMyPoly())) {
if (m.equals(caster2)) {
continue;
}
if (m.getPrecisePosition().getDistance(newpos) < (m.getRadius() + this.caster2.getRadius())) {
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, m);
double distanceToObstacle = (float) this.caster2.getRadius() + (float) m.getRadius() + (float) MIN_DISTANCE;
Vector origin = new Vector(-vec.getY(), vec.getX());
Edge edge = new Edge(m.getPrecisePosition().toNode(), m.getPrecisePosition().add(origin.toFPP()).toNode());
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(vec.toFPP()).toNode());
SimplePosition p = edge.endlessIntersection(edge2);
double distance = m.getPrecisePosition().getDistance(p.toFPP());
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
FloatingPointPosition nextnewpos = p.toVector().add(vec.getInverted().normalize().multiply(b)).toFPP();
if (nextnewpos.toVector().isValid() && checkPosition(nextnewpos)) {
newpos = nextnewpos;
} else {
System.out.println("WARNING: Ugly back-stop!");
newpos = oldPos.toFPP();
}
if (wait) {
waitStartTime = System.nanoTime();
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + m + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Bricht die Bewegung vollständig ab.
System.out.println("STOP-COLLISION " + caster2 + " with " + m);
stopUnit = true;
}
break;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
if (vec.isOpposite(nextVec) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
caster2.setMainPosition(target.toFPP());
SimplePosition oldTar = target;
// Neuen Wegpunkt anfordern:
if (!stopUnit && !caster2.getMidLevelManager().reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
} else {
// Herausfinden, ob der Sektor gewechselt wurde
SimplePosition newTar = target;
if (newTar instanceof Node && oldTar instanceof Node) {
// Nur in diesem Fall kommt ein Sektorwechsel in Frage
FreePolygon sector = commonSector((Node) newTar, (Node) oldTar);
// Sektor geändert?
if (!sector.equals(caster2.getMyPoly())) {
caster2.setMyPoly(sector);
}
}
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
caster2.setMainPosition(newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
caster2.setMainPosition(newpos);
lastTick = System.nanoTime();
}
}
}
|
diff --git a/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/NuGet.java b/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/NuGet.java
index a9bb269b..421d5e8a 100644
--- a/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/NuGet.java
+++ b/nuget-tests/src/jetbrains/buildServer/nuget/tests/integration/NuGet.java
@@ -1,44 +1,44 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.nuget.tests.integration;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import java.io.File;
/**
* Created by Eugene Petrenko ([email protected])
* Date: 31.08.11 10:39
*/
public enum NuGet {
NuGet_1_4,
NuGet_1_5,
;
@NotNull
public File getPath() {
switch (this) {
case NuGet_1_4:
return FileUtil.getCanonicalFile(new File("./nuget-tests/testData/nuget/1.4/NuGet.exe"));
case NuGet_1_5:
- return FileUtil.getCanonicalFile(new File("./nuget-tests/testData/nuget/1.4/NuGet.exe"));
+ return FileUtil.getCanonicalFile(new File("./nuget-tests/testData/nuget/1.5/NuGet.exe"));
default:
throw new IllegalArgumentException("Failed to find nuget " + this);
}
}
}
| true | true | public File getPath() {
switch (this) {
case NuGet_1_4:
return FileUtil.getCanonicalFile(new File("./nuget-tests/testData/nuget/1.4/NuGet.exe"));
case NuGet_1_5:
return FileUtil.getCanonicalFile(new File("./nuget-tests/testData/nuget/1.4/NuGet.exe"));
default:
throw new IllegalArgumentException("Failed to find nuget " + this);
}
}
| public File getPath() {
switch (this) {
case NuGet_1_4:
return FileUtil.getCanonicalFile(new File("./nuget-tests/testData/nuget/1.4/NuGet.exe"));
case NuGet_1_5:
return FileUtil.getCanonicalFile(new File("./nuget-tests/testData/nuget/1.5/NuGet.exe"));
default:
throw new IllegalArgumentException("Failed to find nuget " + this);
}
}
|
diff --git a/src/uk/me/parabola/mkgmap/combiners/TdbBuilder.java b/src/uk/me/parabola/mkgmap/combiners/TdbBuilder.java
index 161c00ba..2965d6c5 100644
--- a/src/uk/me/parabola/mkgmap/combiners/TdbBuilder.java
+++ b/src/uk/me/parabola/mkgmap/combiners/TdbBuilder.java
@@ -1,265 +1,265 @@
/*
* Copyright (C) 2007 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* Author: Steve Ratcliffe
* Create date: Dec 9, 2007
*/
package uk.me.parabola.mkgmap.combiners;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import uk.me.parabola.imgfmt.ExitException;
import uk.me.parabola.imgfmt.FileExistsException;
import uk.me.parabola.imgfmt.FileNotWritableException;
import uk.me.parabola.imgfmt.FileSystemParam;
import uk.me.parabola.imgfmt.app.Area;
import uk.me.parabola.imgfmt.app.Coord;
import uk.me.parabola.imgfmt.app.map.Map;
import uk.me.parabola.log.Logger;
import uk.me.parabola.mkgmap.CommandArgs;
import uk.me.parabola.mkgmap.build.MapBuilder;
import uk.me.parabola.mkgmap.general.MapShape;
import uk.me.parabola.tdbfmt.DetailMapBlock;
import uk.me.parabola.tdbfmt.TdbFile;
/**
* Build the TDB file and the overview map.
*
* @author Steve Ratcliffe
*/
public class TdbBuilder implements Combiner {
private static final Logger log = Logger.getLogger(TdbBuilder.class);
private OverviewMap overviewSource;
private TdbFile tdb;
private int parent = 63240000;
private String overviewMapname;
private String overviewMapnumber;
private String areaName;
private int tdbVersion;
/**
* Initialise by saving all the information we require from the command line
* args.
*
* @param args The command line arguments as they are at the end of the list.
* In otherwords if the same argument appears more than once, then it will
*/
public void init(CommandArgs args) {
overviewMapname = args.get("overview-mapname", "osmmap");
overviewMapnumber = args.get("overview-mapnumber", "63240000");
try {
parent = Integer.parseInt(overviewMapnumber);
} catch (NumberFormatException e) {
log.debug("overview map number not an integer", overviewMapnumber);
}
areaName = args.get("area-name", "Overview Map");
int familyId = args.get("family-id", 0);
int productId = args.get("product-id", 1);
short productVersion = (short)args.get("product-version", 100);
String seriesName = args.get("series-name", "OSM map");
String familyName = args.get("family-name", "OSM map");
// Versin 4 is the default. If you really want v3 then the tdb-v3
// option can be used.
if (args.exists("tdb-v3")) {
tdbVersion = TdbFile.TDB_V3;
} else {
tdbVersion = TdbFile.TDB_V407;
}
tdb = new TdbFile(tdbVersion);
tdb.setProductInfo(familyId, productId, productVersion, seriesName,
familyName, areaName);
}
/**
* Called at the end of every map that is to be combined. We only deal
* with IMG files and ignore everything else.
*
* @param finfo Information on the file.
*/
public void onMapEnd(FileInfo finfo) {
if (!finfo.isImg())
return;
addToTdb(finfo);
addToOverviewMap(finfo);
}
/**
* Add the information about the current map to the tdb file.
*
* @param finfo Information about the current .img file.
*/
private void addToTdb(FileInfo finfo) {
DetailMapBlock detail = new DetailMapBlock(tdbVersion);
detail.setArea(finfo.getBounds());
String mapname = finfo.getMapname();
String mapdesc = finfo.getDescription();
detail.setMapName(mapname, mapname);
String desc = mapdesc + " (" + mapname + ')';
detail.setDescription(desc);
detail.setLblDataSize(finfo.getLblsize());
detail.setTreDataSize(finfo.getTresize());
detail.setRgnDataSize(finfo.getRgnsize());
detail.setNetDataSize(finfo.getNetsize());
detail.setNodDataSize(finfo.getNodsize());
log.info("overview-mapname", overviewMapname);
log.info("overview-mapnumber", parent);
detail.setParentMapNumber(parent);
tdb.addDetail(detail);
String[] msgs = finfo.getCopyrights();
for (String m : msgs)
tdb.addCopyright(m);
}
/**
* Add an individual .img file to the overview map.
*
* @param finfo Information about an individual map.
*/
private void addToOverviewMap(FileInfo finfo) {
Area bounds = finfo.getBounds();
//System.out.printf("overview shift %d\n", overviewSource.getShift());
int overviewMask = ((1 << overviewSource.getShift()) - 1);
//System.out.printf("mask %x\n", overviewMask);
//System.out.println("overviewSource.getShift() = " + overviewSource.getShift());
- int maxLon = roundUp(bounds.getMaxLong(), overviewMask);
+ int maxLon = roundDown(bounds.getMaxLong(), overviewMask);
int maxLat = roundUp(bounds.getMaxLat(), overviewMask);
- int minLat = roundDown(bounds.getMinLat(), overviewMask);
+ int minLat = roundUp(bounds.getMinLat(), overviewMask);
int minLon = roundDown(bounds.getMinLong(), overviewMask);
//System.out.printf("maxLat 0x%x, modified=0x%x\n", bounds.getMaxLat(), maxLat);
//System.out.printf("maxLat %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLat()), Utils.toDegrees(maxLat));
//System.out.printf("minLat 0x%x, modified=0x%x\n", bounds.getMinLat(), minLat);
//System.out.printf("minLat %f, modified=%f\n", Utils.toDegrees(bounds.getMinLat()), Utils.toDegrees(minLat));
//System.out.printf("maxLon 0x%x, modified=0x%x\n", bounds.getMaxLong(), maxLon);
//System.out.printf("maxLon %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLong()), Utils.toDegrees(maxLon));
//System.out.printf("minLon 0x%x, modified=0x%x\n", bounds.getMinLong(), minLon);
//System.out.printf("minLon %f, modified=%f\n", Utils.toDegrees(bounds.getMinLong()), Utils.toDegrees(minLon));
// Add a background polygon for this map.
List<Coord> points = new ArrayList<Coord>();
Coord start = new Coord(minLat, minLon);
points.add(start);
overviewSource.addToBounds(start);
Coord co = new Coord(maxLat, minLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(maxLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(minLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
points.add(start);
// Create the background rectangle
MapShape bg = new MapShape();
bg.setType(0x4a);
bg.setPoints(points);
bg.setMinResolution(10);
bg.setName(finfo.getDescription() + '\u001d' + finfo.getMapname());
overviewSource.addShape(bg);
}
private int roundUp(int len, int overviewMask) {
//System.out.printf("before up 0x%x\n", len);
if (len > 0)
return (len + overviewMask) & ~overviewMask;
else
return len & ~overviewMask;
}
private int roundDown(int len, int overviewMask) {
//System.out.printf("before down 0x%x\n", len);
if (len > 0)
return len & ~overviewMask;
else
return -(-len +overviewMask & ~overviewMask);
}
/**
* Called when all the .img files have been processed. We finish up and
* create the TDB file and the overview map.
*/
public void onFinish() {
log.debug("finishing overview");
// We can set the overall bounds easily as it was calcualted as part of
// the overview map.
tdb.setOverview(overviewMapname, overviewSource.getBounds(), overviewMapnumber);
writeTdbFile();
writeOverviewMap();
}
/**
* Write out the overview map.
*/
private void writeOverviewMap() {
MapBuilder mb = new MapBuilder();
mb.setEnableLineCleanFilters(false);
FileSystemParam params = new FileSystemParam();
params.setBlockSize(512);
params.setMapDescription(areaName);
try {
Map map = Map.createMap(overviewMapname, params, overviewMapnumber);
mb.makeMap(map, overviewSource);
map.close();
} catch (FileExistsException e) {
throw new ExitException("Could not create overview map", e);
} catch (FileNotWritableException e) {
throw new ExitException("Could not write to overview map", e);
}
}
/**
* Write out the TDB file at the end of processing.
*/
private void writeTdbFile() {
try {
tdb.write(overviewMapname + ".tdb");
} catch (IOException e) {
log.error("tdb write", e);
throw new ExitException("Could not write the TDB file", e);
}
}
public void setOverviewSource(OverviewMap overviewSource) {
this.overviewSource = overviewSource;
}
}
| false | true | private void addToOverviewMap(FileInfo finfo) {
Area bounds = finfo.getBounds();
//System.out.printf("overview shift %d\n", overviewSource.getShift());
int overviewMask = ((1 << overviewSource.getShift()) - 1);
//System.out.printf("mask %x\n", overviewMask);
//System.out.println("overviewSource.getShift() = " + overviewSource.getShift());
int maxLon = roundUp(bounds.getMaxLong(), overviewMask);
int maxLat = roundUp(bounds.getMaxLat(), overviewMask);
int minLat = roundDown(bounds.getMinLat(), overviewMask);
int minLon = roundDown(bounds.getMinLong(), overviewMask);
//System.out.printf("maxLat 0x%x, modified=0x%x\n", bounds.getMaxLat(), maxLat);
//System.out.printf("maxLat %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLat()), Utils.toDegrees(maxLat));
//System.out.printf("minLat 0x%x, modified=0x%x\n", bounds.getMinLat(), minLat);
//System.out.printf("minLat %f, modified=%f\n", Utils.toDegrees(bounds.getMinLat()), Utils.toDegrees(minLat));
//System.out.printf("maxLon 0x%x, modified=0x%x\n", bounds.getMaxLong(), maxLon);
//System.out.printf("maxLon %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLong()), Utils.toDegrees(maxLon));
//System.out.printf("minLon 0x%x, modified=0x%x\n", bounds.getMinLong(), minLon);
//System.out.printf("minLon %f, modified=%f\n", Utils.toDegrees(bounds.getMinLong()), Utils.toDegrees(minLon));
// Add a background polygon for this map.
List<Coord> points = new ArrayList<Coord>();
Coord start = new Coord(minLat, minLon);
points.add(start);
overviewSource.addToBounds(start);
Coord co = new Coord(maxLat, minLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(maxLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(minLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
points.add(start);
// Create the background rectangle
MapShape bg = new MapShape();
bg.setType(0x4a);
bg.setPoints(points);
bg.setMinResolution(10);
bg.setName(finfo.getDescription() + '\u001d' + finfo.getMapname());
overviewSource.addShape(bg);
}
| private void addToOverviewMap(FileInfo finfo) {
Area bounds = finfo.getBounds();
//System.out.printf("overview shift %d\n", overviewSource.getShift());
int overviewMask = ((1 << overviewSource.getShift()) - 1);
//System.out.printf("mask %x\n", overviewMask);
//System.out.println("overviewSource.getShift() = " + overviewSource.getShift());
int maxLon = roundDown(bounds.getMaxLong(), overviewMask);
int maxLat = roundUp(bounds.getMaxLat(), overviewMask);
int minLat = roundUp(bounds.getMinLat(), overviewMask);
int minLon = roundDown(bounds.getMinLong(), overviewMask);
//System.out.printf("maxLat 0x%x, modified=0x%x\n", bounds.getMaxLat(), maxLat);
//System.out.printf("maxLat %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLat()), Utils.toDegrees(maxLat));
//System.out.printf("minLat 0x%x, modified=0x%x\n", bounds.getMinLat(), minLat);
//System.out.printf("minLat %f, modified=%f\n", Utils.toDegrees(bounds.getMinLat()), Utils.toDegrees(minLat));
//System.out.printf("maxLon 0x%x, modified=0x%x\n", bounds.getMaxLong(), maxLon);
//System.out.printf("maxLon %f, modified=%f\n", Utils.toDegrees(bounds.getMaxLong()), Utils.toDegrees(maxLon));
//System.out.printf("minLon 0x%x, modified=0x%x\n", bounds.getMinLong(), minLon);
//System.out.printf("minLon %f, modified=%f\n", Utils.toDegrees(bounds.getMinLong()), Utils.toDegrees(minLon));
// Add a background polygon for this map.
List<Coord> points = new ArrayList<Coord>();
Coord start = new Coord(minLat, minLon);
points.add(start);
overviewSource.addToBounds(start);
Coord co = new Coord(maxLat, minLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(maxLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
co = new Coord(minLat, maxLon);
points.add(co);
overviewSource.addToBounds(co);
points.add(start);
// Create the background rectangle
MapShape bg = new MapShape();
bg.setType(0x4a);
bg.setPoints(points);
bg.setMinResolution(10);
bg.setName(finfo.getDescription() + '\u001d' + finfo.getMapname());
overviewSource.addShape(bg);
}
|
diff --git a/src/portal-collector/src/com/trendmicro/tme/portal/ExchangeMetricCollector.java b/src/portal-collector/src/com/trendmicro/tme/portal/ExchangeMetricCollector.java
index 58b343b..ffa6132 100644
--- a/src/portal-collector/src/com/trendmicro/tme/portal/ExchangeMetricCollector.java
+++ b/src/portal-collector/src/com/trendmicro/tme/portal/ExchangeMetricCollector.java
@@ -1,170 +1,170 @@
package com.trendmicro.tme.portal;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.mail.Session;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.googlecode.jmxtrans.JmxTransformer;
import com.googlecode.jmxtrans.model.JmxProcess;
import com.googlecode.jmxtrans.model.Query;
import com.googlecode.jmxtrans.model.Server;
import com.googlecode.jmxtrans.util.ValidationException;
import com.trendmicro.codi.ZKSessionManager;
import com.trendmicro.tme.mfr.BrokerFarm;
import com.trendmicro.mist.proto.ZooKeeperInfo.Broker;
public class ExchangeMetricCollector {
private static final String CONFIG_PATH = System.getProperty("com.trendmicro.tme.portal.collector.conf", "/opt/trend/tme/conf/portal-collector/portal-collector.properties");
private static final Logger logger = LoggerFactory.getLogger(ExchangeMetricCollector.class);
private BrokerFarm brokerFarm;
private ExchangeMetricWriter writer;
private ExchangeMetricArchiver archiver;
private Query createQuery() {
Query query = new Query();
query.setObj("com.sun.messaging.jms.server:type=Destination,subtype=*,desttype=*,name=*");
query.addAttr("NumMsgs");
query.addAttr("NumMsgsIn");
query.addAttr("NumMsgsOut");
query.addAttr("NumMsgsPendingAcks");
query.addAttr("NumConsumers");
query.addAttr("NumProducers");
query.addAttr("MsgBytesIn");
query.addAttr("MsgBytesOut");
query.addAttr("TotalMsgBytes");
query.addAttr("MaxNumMsgs");
query.addAttr("MaxTotalMsgBytes");
query.addAttr("LimitBehavior");
query.addOutputWriter(writer);
return query;
}
public ExchangeMetricCollector(BrokerFarm brokerFarm, ExchangeMetricWriter writer, ExchangeMetricArchiver archiver) {
this.brokerFarm = brokerFarm;
this.writer = writer;
this.archiver = archiver;
}
private String getJMXUrl(String broker) {
Socket sock = new Socket();
try {
sock.connect(new InetSocketAddress(broker, 7676));
String url = null;
for(String line : IOUtils.toString(sock.getInputStream()).split("\n")) {
if(line.startsWith("jmxrmi rmi JMX")) {
url = line.substring(line.indexOf('=') + 1, line.length() - 1);
break;
}
}
logger.info("jmxurl of broker {} = {}", broker, url);
return url;
}
catch(Exception e) {
logger.error(e.getMessage(), e);
return null;
}
finally {
try {
IOUtils.closeQuietly(sock.getInputStream());
IOUtils.closeQuietly(sock.getOutputStream());
sock.close();
}
catch(IOException e) {
}
}
}
public void run() {
logger.info("Exchange Metric Collector started");
while(true) {
JmxProcess jmxProcess = new JmxProcess();
for(Broker broker : brokerFarm.getAllBrokers().values()) {
if(broker.getStatus() == Broker.Status.ONLINE) {
Server server = new Server();
server.setHost(broker.getHost());
server.setUsername("admin");
server.setPassword("admin");
String jmxurl = getJMXUrl(broker.getHost());
if(jmxurl == null) {
logger.error("cannot obtain JMX URL from broker {}", broker.getHost());
continue;
}
server.setUrl(jmxurl);
try {
server.addQuery(createQuery());
}
catch(ValidationException e) {
e.printStackTrace();
}
jmxProcess.addServer(server);
}
}
JmxTransformer transformer = new JmxTransformer();
try {
transformer.setRunEndlessly(false);
transformer.executeStandalone(jmxProcess);
Thread.sleep(10000);
}
catch(Exception e) {
logger.error("Error to collect metrics: ", e);
}
archiver.execute();
}
}
public static void main(String[] args) {
try {
Properties prop = new Properties();
prop.load(new FileInputStream(CONFIG_PATH));
// Let the system properties override the ones in the config file
prop.putAll(System.getProperties());
String zkQuorum = prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.quorum");
int zkTimeout = Integer.valueOf(prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.timeout"));
ZKSessionManager.initialize(zkQuorum + prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.tmeroot"), zkTimeout);
if(!ZKSessionManager.instance().waitConnected(zkTimeout)) {
throw new Exception("Cannot connect to ZooKeeper Quorom " + zkQuorum);
}
String receiversStr = prop.getProperty("com.trendmicro.tme.portal.collector.alert.receiver", "").trim();
List<String> receivers;
if(receiversStr.isEmpty()) {
receivers = new ArrayList<String>();
}
else {
receivers = Arrays.asList(receiversStr.split(","));
}
Session mailSession = null;
- if(receivers.isEmpty()) {
+ if(!receivers.isEmpty()) {
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", prop.getProperty("com.trendmicro.tme.portal.collector.alert.smtp", "localhost"));
mailSession = Session.getInstance(mailProps, null);
}
ExchangeMetricWriter writer = new ExchangeMetricWriter(receivers, Integer.valueOf(prop.getProperty("com.trendmicro.tme.portal.collector.alert.interval", "60")), mailSession);
writer.addSetting("templateFile", prop.getProperty("com.trendmicro.tme.portal.collector.template"));
writer.addSetting("outputPath", prop.getProperty("com.trendmicro.tme.portal.collector.outputdir"));
ExchangeMetricArchiver archiver = new ExchangeMetricArchiver((String) prop.getProperty("com.trendmicro.tme.portal.collector.outputdir"), (String) prop.getProperty("com.trendmicro.tme.portal.collector.archiver.maxrecords"), Integer.valueOf((String) prop.getProperty("com.trendmicro.tme.portal.collector.archiver.interval")));
ExchangeMetricCollector collector = new ExchangeMetricCollector(new BrokerFarm(), writer, archiver);
collector.run();
}
catch(Exception e) {
e.printStackTrace();
logger.error("Portal Collector startup error: ", e);
System.exit(-1);
}
}
}
| true | true | public static void main(String[] args) {
try {
Properties prop = new Properties();
prop.load(new FileInputStream(CONFIG_PATH));
// Let the system properties override the ones in the config file
prop.putAll(System.getProperties());
String zkQuorum = prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.quorum");
int zkTimeout = Integer.valueOf(prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.timeout"));
ZKSessionManager.initialize(zkQuorum + prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.tmeroot"), zkTimeout);
if(!ZKSessionManager.instance().waitConnected(zkTimeout)) {
throw new Exception("Cannot connect to ZooKeeper Quorom " + zkQuorum);
}
String receiversStr = prop.getProperty("com.trendmicro.tme.portal.collector.alert.receiver", "").trim();
List<String> receivers;
if(receiversStr.isEmpty()) {
receivers = new ArrayList<String>();
}
else {
receivers = Arrays.asList(receiversStr.split(","));
}
Session mailSession = null;
if(receivers.isEmpty()) {
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", prop.getProperty("com.trendmicro.tme.portal.collector.alert.smtp", "localhost"));
mailSession = Session.getInstance(mailProps, null);
}
ExchangeMetricWriter writer = new ExchangeMetricWriter(receivers, Integer.valueOf(prop.getProperty("com.trendmicro.tme.portal.collector.alert.interval", "60")), mailSession);
writer.addSetting("templateFile", prop.getProperty("com.trendmicro.tme.portal.collector.template"));
writer.addSetting("outputPath", prop.getProperty("com.trendmicro.tme.portal.collector.outputdir"));
ExchangeMetricArchiver archiver = new ExchangeMetricArchiver((String) prop.getProperty("com.trendmicro.tme.portal.collector.outputdir"), (String) prop.getProperty("com.trendmicro.tme.portal.collector.archiver.maxrecords"), Integer.valueOf((String) prop.getProperty("com.trendmicro.tme.portal.collector.archiver.interval")));
ExchangeMetricCollector collector = new ExchangeMetricCollector(new BrokerFarm(), writer, archiver);
collector.run();
}
catch(Exception e) {
e.printStackTrace();
logger.error("Portal Collector startup error: ", e);
System.exit(-1);
}
}
| public static void main(String[] args) {
try {
Properties prop = new Properties();
prop.load(new FileInputStream(CONFIG_PATH));
// Let the system properties override the ones in the config file
prop.putAll(System.getProperties());
String zkQuorum = prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.quorum");
int zkTimeout = Integer.valueOf(prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.timeout"));
ZKSessionManager.initialize(zkQuorum + prop.getProperty("com.trendmicro.tme.portal.collector.zookeeper.tmeroot"), zkTimeout);
if(!ZKSessionManager.instance().waitConnected(zkTimeout)) {
throw new Exception("Cannot connect to ZooKeeper Quorom " + zkQuorum);
}
String receiversStr = prop.getProperty("com.trendmicro.tme.portal.collector.alert.receiver", "").trim();
List<String> receivers;
if(receiversStr.isEmpty()) {
receivers = new ArrayList<String>();
}
else {
receivers = Arrays.asList(receiversStr.split(","));
}
Session mailSession = null;
if(!receivers.isEmpty()) {
Properties mailProps = new Properties();
mailProps.put("mail.smtp.host", prop.getProperty("com.trendmicro.tme.portal.collector.alert.smtp", "localhost"));
mailSession = Session.getInstance(mailProps, null);
}
ExchangeMetricWriter writer = new ExchangeMetricWriter(receivers, Integer.valueOf(prop.getProperty("com.trendmicro.tme.portal.collector.alert.interval", "60")), mailSession);
writer.addSetting("templateFile", prop.getProperty("com.trendmicro.tme.portal.collector.template"));
writer.addSetting("outputPath", prop.getProperty("com.trendmicro.tme.portal.collector.outputdir"));
ExchangeMetricArchiver archiver = new ExchangeMetricArchiver((String) prop.getProperty("com.trendmicro.tme.portal.collector.outputdir"), (String) prop.getProperty("com.trendmicro.tme.portal.collector.archiver.maxrecords"), Integer.valueOf((String) prop.getProperty("com.trendmicro.tme.portal.collector.archiver.interval")));
ExchangeMetricCollector collector = new ExchangeMetricCollector(new BrokerFarm(), writer, archiver);
collector.run();
}
catch(Exception e) {
e.printStackTrace();
logger.error("Portal Collector startup error: ", e);
System.exit(-1);
}
}
|
diff --git a/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/STextTypesCollector.java b/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/STextTypesCollector.java
index 6daa9af0..d061c25f 100644
--- a/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/STextTypesCollector.java
+++ b/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/STextTypesCollector.java
@@ -1,125 +1,125 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 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.equinox.bidi.internal;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.bidi.custom.STextTypeHandler;
/**
* Provides services related to registered structured text handlers.
*/
public class STextTypesCollector implements IRegistryEventListener {
private static final String EXT_POINT = "org.eclipse.equinox.bidi.bidiTypes"; //$NON-NLS-1$
private static final String CE_NAME = "typeDescription"; //$NON-NLS-1$
private static final String ATTR_TYPE = "type"; //$NON-NLS-1$
private static final String ATTR_HANDLER = "class"; //$NON-NLS-1$
private Map types;
private Map factories;
static private STextTypesCollector instance = new STextTypesCollector();
private STextTypesCollector() {
IExtensionRegistry registry = RegistryFactory.getRegistry();
registry.addListener(this, EXT_POINT);
}
/**
* @return a static instance.
*/
static public STextTypesCollector getInstance() {
return instance;
}
/**
* @return a list of all the registered structured text handler types.
*/
public String[] getTypes() {
if (types == null)
read();
int size = types.size();
String[] result = new String[size];
types.keySet().toArray(result);
return result;
}
/**
* @param type the identifier for a structured text handler.
*
* @return the structured text handler instance.
*/
public STextTypeHandler getHandler(String type) {
if (types == null)
read();
Object handler = types.get(type);
if (handler instanceof STextTypeHandler)
return (STextTypeHandler) handler;
return null;
}
private void read() {
if (types == null)
types = new HashMap();
else
types.clear();
if (factories == null)
factories = new HashMap();
else
factories.clear();
IExtensionRegistry registry = RegistryFactory.getRegistry();
IExtensionPoint extPoint = registry.getExtensionPoint(EXT_POINT);
IExtension[] extensions = extPoint.getExtensions();
for (int i = 0; i < extensions.length; i++) {
IConfigurationElement[] confElements = extensions[i].getConfigurationElements();
for (int j = 0; j < confElements.length; j++) {
- if (CE_NAME != confElements[j].getName())
+ if (!CE_NAME.equals(confElements[j].getName()))
STextActivator.logError("BiDi types: unexpected element name " + confElements[j].getName(), new IllegalArgumentException()); //$NON-NLS-1$
String type = confElements[j].getAttribute(ATTR_TYPE);
Object handler;
try {
handler = confElements[j].createExecutableExtension(ATTR_HANDLER);
} catch (CoreException e) {
STextActivator.logError("BiDi types: unable to create handler for " + type, e); //$NON-NLS-1$
continue;
}
types.put(type, handler);
factories.put(type, confElements[j]);
}
}
}
public void added(IExtension[] extensions) {
types = null;
factories = null;
}
public void removed(IExtension[] extensions) {
types = null;
factories = null;
}
public void added(IExtensionPoint[] extensionPoints) {
types = null;
factories = null;
}
public void removed(IExtensionPoint[] extensionPoints) {
types = null;
factories = null;
}
}
| true | true | private void read() {
if (types == null)
types = new HashMap();
else
types.clear();
if (factories == null)
factories = new HashMap();
else
factories.clear();
IExtensionRegistry registry = RegistryFactory.getRegistry();
IExtensionPoint extPoint = registry.getExtensionPoint(EXT_POINT);
IExtension[] extensions = extPoint.getExtensions();
for (int i = 0; i < extensions.length; i++) {
IConfigurationElement[] confElements = extensions[i].getConfigurationElements();
for (int j = 0; j < confElements.length; j++) {
if (CE_NAME != confElements[j].getName())
STextActivator.logError("BiDi types: unexpected element name " + confElements[j].getName(), new IllegalArgumentException()); //$NON-NLS-1$
String type = confElements[j].getAttribute(ATTR_TYPE);
Object handler;
try {
handler = confElements[j].createExecutableExtension(ATTR_HANDLER);
} catch (CoreException e) {
STextActivator.logError("BiDi types: unable to create handler for " + type, e); //$NON-NLS-1$
continue;
}
types.put(type, handler);
factories.put(type, confElements[j]);
}
}
}
| private void read() {
if (types == null)
types = new HashMap();
else
types.clear();
if (factories == null)
factories = new HashMap();
else
factories.clear();
IExtensionRegistry registry = RegistryFactory.getRegistry();
IExtensionPoint extPoint = registry.getExtensionPoint(EXT_POINT);
IExtension[] extensions = extPoint.getExtensions();
for (int i = 0; i < extensions.length; i++) {
IConfigurationElement[] confElements = extensions[i].getConfigurationElements();
for (int j = 0; j < confElements.length; j++) {
if (!CE_NAME.equals(confElements[j].getName()))
STextActivator.logError("BiDi types: unexpected element name " + confElements[j].getName(), new IllegalArgumentException()); //$NON-NLS-1$
String type = confElements[j].getAttribute(ATTR_TYPE);
Object handler;
try {
handler = confElements[j].createExecutableExtension(ATTR_HANDLER);
} catch (CoreException e) {
STextActivator.logError("BiDi types: unable to create handler for " + type, e); //$NON-NLS-1$
continue;
}
types.put(type, handler);
factories.put(type, confElements[j]);
}
}
}
|
diff --git a/src/main/java/nl/giantit/minecraft/giantpm/core/Updater/Config/confUpdate.java b/src/main/java/nl/giantit/minecraft/giantpm/core/Updater/Config/confUpdate.java
index fddaef5..d05fe8a 100644
--- a/src/main/java/nl/giantit/minecraft/giantpm/core/Updater/Config/confUpdate.java
+++ b/src/main/java/nl/giantit/minecraft/giantpm/core/Updater/Config/confUpdate.java
@@ -1,48 +1,49 @@
package nl.giantit.minecraft.giantpm.core.Updater.Config;
import nl.giantit.minecraft.giantpm.GiantPM;
import nl.giantit.minecraft.giantpm.core.Updater.iUpdater;
import org.bukkit.configuration.file.FileConfiguration;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
public class confUpdate implements iUpdater {
private void export(File file, FileConfiguration c) {
try {
InputStream iS = new ByteArrayInputStream(c.saveToString().replace("\n", "\r\n").replace(" ", " ").getBytes("UTF-8"));
GiantPM.getPlugin().extract(file, iS);
}catch(UnsupportedEncodingException e) {
GiantPM.getPlugin().getLogger().severe("Failed to update config file!");
if(c.getBoolean("GiantTitle.global.debug", true) == true) {
GiantPM.getPlugin().getLogger().log(Level.INFO, e.getMessage(), e);
}
}
}
public void update0_3(FileConfiguration c) {
c.set("GiantPM.global.opHasPerms", null);
c.set("GiantPM.permissions.permissionsEngine", null);
c.set("GiantPM.permissions.Engine", "SPERM");
c.set("GiantPM.permissions.opHasPerms", true);
c.createSection("GiantPM.messaging.admin");
c.set("GiantPM.messaging.admin.group", "admin");
+ c.set("GiantPM.messaging.playsoundonreceived", true);
c.set("GiantPM.global.version", 0.3);
this.export(new File(GiantPM.getPlugin().getDir(), "conf.yml"), c);
}
public void Update(double curV, FileConfiguration c) {
if (curV < 0.3) {
GiantPM.getPlugin().getLogger().info("Your conf.yml has ran out of date. Updating to 0.3!");
update0_3(c);
}
}
}
| true | true | public void update0_3(FileConfiguration c) {
c.set("GiantPM.global.opHasPerms", null);
c.set("GiantPM.permissions.permissionsEngine", null);
c.set("GiantPM.permissions.Engine", "SPERM");
c.set("GiantPM.permissions.opHasPerms", true);
c.createSection("GiantPM.messaging.admin");
c.set("GiantPM.messaging.admin.group", "admin");
c.set("GiantPM.global.version", 0.3);
this.export(new File(GiantPM.getPlugin().getDir(), "conf.yml"), c);
}
| public void update0_3(FileConfiguration c) {
c.set("GiantPM.global.opHasPerms", null);
c.set("GiantPM.permissions.permissionsEngine", null);
c.set("GiantPM.permissions.Engine", "SPERM");
c.set("GiantPM.permissions.opHasPerms", true);
c.createSection("GiantPM.messaging.admin");
c.set("GiantPM.messaging.admin.group", "admin");
c.set("GiantPM.messaging.playsoundonreceived", true);
c.set("GiantPM.global.version", 0.3);
this.export(new File(GiantPM.getPlugin().getDir(), "conf.yml"), c);
}
|
diff --git a/src/java/org/jivesoftware/openfire/clearspace/ClearspaceAdminProvider.java b/src/java/org/jivesoftware/openfire/clearspace/ClearspaceAdminProvider.java
index a0e4ef2b..d22c307f 100644
--- a/src/java/org/jivesoftware/openfire/clearspace/ClearspaceAdminProvider.java
+++ b/src/java/org/jivesoftware/openfire/clearspace/ClearspaceAdminProvider.java
@@ -1,87 +1,92 @@
/**
* $Revision$
* $Date$
*
* Copyright (C) 2005-2008 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution, or a commercial license
* agreement with Jive.
*/
package org.jivesoftware.openfire.clearspace;
import org.jivesoftware.openfire.admin.AdminProvider;
import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET;
import static org.jivesoftware.openfire.clearspace.WSUtils.parseStringArray;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.util.Log;
import org.xmpp.packet.JID;
import org.dom4j.Element;
import java.util.List;
import java.util.ArrayList;
/**
* Handles retrieving list of admins from Clearspace.
*
* @author Daniel Henninger
*/
public class ClearspaceAdminProvider implements AdminProvider {
// The UserService webservice url prefix
protected static final String PERMISSION_URL_PREFIX = "permissionService/";
long SYSTEM_ADMIN_PERM = 0x800000000000000L;
public ClearspaceAdminProvider() {
}
/**
* The clearspace provider pulls the admin list from the userPermissions web service
* @see org.jivesoftware.openfire.admin.AdminProvider#getAdmins()
*/
public List<JID> getAdmins() {
try {
String path = PERMISSION_URL_PREFIX + "userPermissions/"+SYSTEM_ADMIN_PERM+"/true";
Log.debug("ClearspaceAdminProvider: permissions query url is: "+path);
Element element = ClearspaceManager.getInstance().executeRequest(GET, path);
List<JID> admins = new ArrayList<JID>();
for (String idStr : parseStringArray(element)) {
Log.debug("Admin provider got ID number "+idStr);
Long id = Long.valueOf(idStr);
try {
String username = ClearspaceManager.getInstance().getUsernameByID(id);
Log.debug("Admin provider mapped to username "+username);
admins.add(XMPPServer.getInstance().createJID(username, null));
}
catch (UserNotFoundException e) {
// Hrm. Got a response back that turned out not to exist? This is "broken".
}
}
return admins;
- } catch (Exception e) {
+ }
+ catch (ConnectException e) {
+ Log.error(e);
+ return new ArrayList();
+ }
+ catch (Exception e) {
// It is not supported exception, wrap it into an UnsupportedOperationException
throw new UnsupportedOperationException("Unexpected error", e);
}
}
/**
* The clearspace provider does not allow setting admin lists from this interface
* @see org.jivesoftware.openfire.admin.AdminProvider#setAdmins(java.util.List)
*/
public void setAdmins(List<JID> admins) {
// Silently do nothing. This shouldn't come up, but more inportantly, we don't want to bother Clearspace.
}
/**
* The clearspace provider is read only
* @see org.jivesoftware.openfire.admin.AdminProvider#isReadOnly()
*/
public boolean isReadOnly() {
return true;
}
}
| true | true | public List<JID> getAdmins() {
try {
String path = PERMISSION_URL_PREFIX + "userPermissions/"+SYSTEM_ADMIN_PERM+"/true";
Log.debug("ClearspaceAdminProvider: permissions query url is: "+path);
Element element = ClearspaceManager.getInstance().executeRequest(GET, path);
List<JID> admins = new ArrayList<JID>();
for (String idStr : parseStringArray(element)) {
Log.debug("Admin provider got ID number "+idStr);
Long id = Long.valueOf(idStr);
try {
String username = ClearspaceManager.getInstance().getUsernameByID(id);
Log.debug("Admin provider mapped to username "+username);
admins.add(XMPPServer.getInstance().createJID(username, null));
}
catch (UserNotFoundException e) {
// Hrm. Got a response back that turned out not to exist? This is "broken".
}
}
return admins;
} catch (Exception e) {
// It is not supported exception, wrap it into an UnsupportedOperationException
throw new UnsupportedOperationException("Unexpected error", e);
}
}
| public List<JID> getAdmins() {
try {
String path = PERMISSION_URL_PREFIX + "userPermissions/"+SYSTEM_ADMIN_PERM+"/true";
Log.debug("ClearspaceAdminProvider: permissions query url is: "+path);
Element element = ClearspaceManager.getInstance().executeRequest(GET, path);
List<JID> admins = new ArrayList<JID>();
for (String idStr : parseStringArray(element)) {
Log.debug("Admin provider got ID number "+idStr);
Long id = Long.valueOf(idStr);
try {
String username = ClearspaceManager.getInstance().getUsernameByID(id);
Log.debug("Admin provider mapped to username "+username);
admins.add(XMPPServer.getInstance().createJID(username, null));
}
catch (UserNotFoundException e) {
// Hrm. Got a response back that turned out not to exist? This is "broken".
}
}
return admins;
}
catch (ConnectException e) {
Log.error(e);
return new ArrayList();
}
catch (Exception e) {
// It is not supported exception, wrap it into an UnsupportedOperationException
throw new UnsupportedOperationException("Unexpected error", e);
}
}
|
diff --git a/src/main/java/vazkii/tinkerer/common/block/tile/peripheral/PeripheralAspectContainer.java b/src/main/java/vazkii/tinkerer/common/block/tile/peripheral/PeripheralAspectContainer.java
index b0ec2b71..67bb86e3 100644
--- a/src/main/java/vazkii/tinkerer/common/block/tile/peripheral/PeripheralAspectContainer.java
+++ b/src/main/java/vazkii/tinkerer/common/block/tile/peripheral/PeripheralAspectContainer.java
@@ -1,102 +1,102 @@
/**
* This class was created by <Vazkii>. It's distributed as
* part of the ThaumicTinkerer Mod.
*
* ThaumicTinkerer is Open Source and distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
*
* ThaumicTinkerer is a Derivative Work on Thaumcraft 4.
* Thaumcraft 4 (c) Azanor 2012
* (http://www.minecraftforum.net/topic/1585216-)
*
* File Created @ [13 Sep 2013, 00:58:21 (GMT)]
*/
package vazkii.tinkerer.common.block.tile.peripheral;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.nbt.NBTTagCompound;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.IAspectContainer;
import dan200.computer.api.IComputerAccess;
import dan200.computer.api.IHostedPeripheral;
import dan200.computer.api.ILuaContext;
public class PeripheralAspectContainer implements IHostedPeripheral {
IAspectContainer container;
public PeripheralAspectContainer(IAspectContainer container) {
this.container = container;
}
@Override
public String getType() {
return "tt_aspectContainer";
}
@Override
public String[] getMethodNames() {
return new String[] { "getAspects", "getAspectCount" };
}
@Override
public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception {
switch(method) {
case 0 : {
- List returnStuff = new ArrayList();
- if(container.getAspects() == null)
+ List<String> returnStuff = new ArrayList<String>();
+ if(container.getAspects() == null || container.getAspects().size()==0)
return new String[0];
for(Aspect aspect : container.getAspects().getAspectsSorted())
returnStuff.add(aspect.getTag());
return returnStuff.toArray();
}
case 1 : {
String aspectName = (String) arguments[0];
Aspect aspect = Aspect.getAspect(aspectName);
if(container.getAspects() == null)
return new Object[] { 0 };
return new Object[] { container.getAspects().getAmount(aspect) };
}
}
return null;
}
@Override
public boolean canAttachToSide(int side) {
return true;
}
@Override
public void attach(IComputerAccess computer) {
// NO-OP
}
@Override
public void detach(IComputerAccess computer) {
// NO-OP
}
@Override
public void update() {
// NO-OP
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound) {
// NO-OP
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound) {
// NO-OP
}
}
| true | true | public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception {
switch(method) {
case 0 : {
List returnStuff = new ArrayList();
if(container.getAspects() == null)
return new String[0];
for(Aspect aspect : container.getAspects().getAspectsSorted())
returnStuff.add(aspect.getTag());
return returnStuff.toArray();
}
case 1 : {
String aspectName = (String) arguments[0];
Aspect aspect = Aspect.getAspect(aspectName);
if(container.getAspects() == null)
return new Object[] { 0 };
return new Object[] { container.getAspects().getAmount(aspect) };
}
}
return null;
}
| public Object[] callMethod(IComputerAccess computer, ILuaContext context, int method, Object[] arguments) throws Exception {
switch(method) {
case 0 : {
List<String> returnStuff = new ArrayList<String>();
if(container.getAspects() == null || container.getAspects().size()==0)
return new String[0];
for(Aspect aspect : container.getAspects().getAspectsSorted())
returnStuff.add(aspect.getTag());
return returnStuff.toArray();
}
case 1 : {
String aspectName = (String) arguments[0];
Aspect aspect = Aspect.getAspect(aspectName);
if(container.getAspects() == null)
return new Object[] { 0 };
return new Object[] { container.getAspects().getAmount(aspect) };
}
}
return null;
}
|
diff --git a/araqne-dom/src/main/java/org/araqne/dom/script/InitialSchema.java b/araqne-dom/src/main/java/org/araqne/dom/script/InitialSchema.java
index 347313e6..fad0906c 100644
--- a/araqne-dom/src/main/java/org/araqne/dom/script/InitialSchema.java
+++ b/araqne-dom/src/main/java/org/araqne/dom/script/InitialSchema.java
@@ -1,257 +1,257 @@
/*
* Copyright 2011 Future Systems
*
* 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.araqne.dom.script;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.araqne.api.ScriptContext;
import org.araqne.dom.api.AreaApi;
import org.araqne.dom.api.GlobalConfigApi;
import org.araqne.dom.api.OrganizationApi;
import org.araqne.dom.api.ProgramApi;
import org.araqne.dom.api.RoleApi;
import org.araqne.dom.api.UserApi;
import org.araqne.dom.model.Admin;
import org.araqne.dom.model.Area;
import org.araqne.dom.model.Organization;
import org.araqne.dom.model.Permission;
import org.araqne.dom.model.Program;
import org.araqne.dom.model.ProgramPack;
import org.araqne.dom.model.ProgramProfile;
import org.araqne.dom.model.Role;
import org.araqne.dom.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InitialSchema {
private static final Logger logger = LoggerFactory.getLogger(InitialSchema.class);
private static final String SCHEMA_VERSION = "1";
private static final String DEFAULT_DOMAIN = "localhost";
public static void generate(ScriptContext context, GlobalConfigApi globalConfigApi, OrganizationApi orgApi, RoleApi roleApi,
ProgramApi programApi, AreaApi areaApi, UserApi userApi) {
// TODO: check schema version, add vendor & applications
Object schemaVersion = globalConfigApi.getConfig("initial_schema_version");
if (!SCHEMA_VERSION.equals(schemaVersion)) {
logger.info("araqne dom: begin initialize schema");
createOrganization(context, orgApi);
createArea(context, areaApi);
createPrograms(context, orgApi, programApi);
createRoles(context, roleApi);
createAdmin(context, userApi, roleApi, programApi);
try {
globalConfigApi.setConfig("initial_schema_version", SCHEMA_VERSION, true);
} catch (Exception e) {
logger.error("araqne dom: initial schema version setting failed", e);
context.println("initial schema version setting failed");
}
}
}
public static void createOrganization(ScriptContext context, OrganizationApi orgApi) {
if (orgApi.findOrganization(DEFAULT_DOMAIN) != null)
return;
Organization organization = new Organization();
organization.setDomain(DEFAULT_DOMAIN);
organization.setName(DEFAULT_DOMAIN);
organization.setEnabled(true);
try {
orgApi.createOrganization(organization);
} catch (Exception e) {
logger.error("araqne dom: organization initialize failed", e);
context.println("organization initialize failed");
}
}
public static void createArea(ScriptContext context, AreaApi areaApi) {
if (areaApi.findArea(DEFAULT_DOMAIN, "abb0de7a-eccb-4b51-a2e1-68d193e5e391") != null)
return;
Area area = new Area();
area.setGuid("abb0de7a-eccb-4b51-a2e1-68d193e5e391");
area.setName("/");
try {
areaApi.createArea(DEFAULT_DOMAIN, area);
} catch (Exception e) {
logger.error("araqne dom: area initialize failed", e);
context.println("area initialize failed");
}
}
public static void createPrograms(ScriptContext context, OrganizationApi orgApi, ProgramApi programApi) {
if (programApi.findProgramPack(DEFAULT_DOMAIN, "System") == null) {
Map<String, String> displayNames = new HashMap<String, String>();
displayNames.put("en", "System");
displayNames.put("ko", "시스템");
ProgramPack pack = new ProgramPack();
pack.setName("System");
pack.setDisplayNames(displayNames);
pack.setDll("system");
pack.setSeq(1);
try {
programApi.createProgramPack(DEFAULT_DOMAIN, pack);
} catch (Exception e) {
logger.error("araqne dom: program pack initialize failed", e);
context.println("program pack initialize failed");
}
}
Program home = createProgram(context, programApi, "Home", "Home", "홈", "starter", 1);
Program dashBoard = createProgram(context, programApi, "Dashboard", "Dashboard", "대시보드", "dashboard", 2);
Program account = createProgram(context, programApi, "Account", "Account", "계정관리", "orgchart", 3);
- Program auditLog = createProgram(context, programApi, "Auditlog", "Auditlog", "감사로그", "auditlog", 4);
+ Program auditLog = createProgram(context, programApi, "Audit Log", "Audit Log", "감사로그", "auditlog", 4);
Program taskManager = createProgram(context, programApi, "Task Manager", "Task Manager", "작업관리자", "taskmanager", 5);
Program run = createProgram(context, programApi, "Run", "Run", "실행", "run", 6);
Program devConsole = createProgram(context, programApi, "Developer Console", "Developer Console", "개발자콘솔", "devconsole",
7);
List<Program> allPrograms = new ArrayList<Program>();
allPrograms.add(home);
allPrograms.add(dashBoard);
allPrograms.add(account);
allPrograms.add(auditLog);
List<Program> memberPrograms = new ArrayList<Program>();
memberPrograms.add(home);
memberPrograms.add(dashBoard);
memberPrograms.add(account);
if (programApi.findProgramProfile(DEFAULT_DOMAIN, "all") == null) {
// master
ProgramProfile allProfile = new ProgramProfile();
allProfile.setName("all");
allProfile.setPrograms(allPrograms);
// member
ProgramProfile memberProfile = new ProgramProfile();
memberProfile.setName("member");
memberProfile.setPrograms(memberPrograms);
try {
programApi.createProgramProfile(DEFAULT_DOMAIN, allProfile);
programApi.createProgramProfile(DEFAULT_DOMAIN, memberProfile);
} catch (Exception e) {
logger.error("araqne dom: program profile initialize failed", e);
context.println("program profile pack initialize failed");
}
orgApi.setOrganizationParameter(DEFAULT_DOMAIN, "default_program_profile_id", "all");
}
}
private static Program createProgram(ScriptContext context, ProgramApi programApi, String name, String enName, String koName,
String type, int seq) {
if (programApi.findProgram(DEFAULT_DOMAIN, "System", name) != null)
return programApi.findProgram(DEFAULT_DOMAIN, "System", name);
Map<String, String> displayNames = new HashMap<String, String>();
displayNames.put("en", enName);
displayNames.put("ko", koName);
Program program = new Program();
program.setPack("System");
program.setName(name);
program.setDisplayNames(displayNames);
program.setPath(type);
program.setSeq(seq);
program.setVisible(true);
try {
programApi.createProgram(DEFAULT_DOMAIN, program);
} catch (Exception e) {
logger.error("araqne dom: program initialize failed", e);
context.println("program initialize failed");
}
return program;
}
public static void createRoles(ScriptContext context, RoleApi roleApi) {
Role master = createRole(context, roleApi, "master", 4);
addPermission(master, "dom", "admin_grant");
addPermission(master, "dom", "user_edit");
addPermission(master, "dom", "config_edit");
addPermission(master, "dom", "config_view");
updateRole(context, roleApi, master);
Role admin = createRole(context, roleApi, "admin", 3);
addPermission(admin, "dom", "user_edit");
updateRole(context, roleApi, admin);
createRole(context, roleApi, "member", 2);
createRole(context, roleApi, "guest", 1);
}
private static void updateRole(ScriptContext context, RoleApi roleApi, Role master) {
try {
roleApi.updateRole(DEFAULT_DOMAIN, master);
} catch (Exception e) {
logger.error("araqne dom: master role initialize failed", e);
context.println("master role initialize failed");
}
}
private static void addPermission(Role master, String group, String name) {
Permission permission = new Permission();
permission.setGroup(group);
permission.setPermission(name);
master.getPermissions().add(permission);
}
private static Role createRole(ScriptContext context, RoleApi roleApi, String name, int level) {
if (roleApi.findRole(DEFAULT_DOMAIN, name) != null)
return roleApi.findRole(DEFAULT_DOMAIN, name);
Role role = new Role();
role.setName(name);
role.setLevel(level);
try {
roleApi.createRole(DEFAULT_DOMAIN, role);
} catch (Exception e) {
logger.error("araqne dom: role initialize failed", e);
context.println("role initialize failed");
}
return role;
}
public static void createAdmin(ScriptContext context, UserApi userApi, RoleApi roleApi, ProgramApi programApi) {
if (userApi.findUser(DEFAULT_DOMAIN, "root") != null)
return;
User user = new User();
user.setLoginName("root");
user.setName("root");
user.setPassword("araqne");
Admin admin = new Admin();
admin.setRole(roleApi.getRole(DEFAULT_DOMAIN, "master"));
admin.setProfile(programApi.getProgramProfile(DEFAULT_DOMAIN, "all"));
admin.setLang(null);
admin.setEnabled(true);
user.getExt().put("admin", admin);
try {
userApi.setSaltLength("localhost", 0);
userApi.createUser(DEFAULT_DOMAIN, user);
} catch (Exception e) {
logger.error("araqne dom: admin initialize failed", e);
context.println("admin initialize failed");
}
}
}
| true | true | public static void createPrograms(ScriptContext context, OrganizationApi orgApi, ProgramApi programApi) {
if (programApi.findProgramPack(DEFAULT_DOMAIN, "System") == null) {
Map<String, String> displayNames = new HashMap<String, String>();
displayNames.put("en", "System");
displayNames.put("ko", "시스템");
ProgramPack pack = new ProgramPack();
pack.setName("System");
pack.setDisplayNames(displayNames);
pack.setDll("system");
pack.setSeq(1);
try {
programApi.createProgramPack(DEFAULT_DOMAIN, pack);
} catch (Exception e) {
logger.error("araqne dom: program pack initialize failed", e);
context.println("program pack initialize failed");
}
}
Program home = createProgram(context, programApi, "Home", "Home", "홈", "starter", 1);
Program dashBoard = createProgram(context, programApi, "Dashboard", "Dashboard", "대시보드", "dashboard", 2);
Program account = createProgram(context, programApi, "Account", "Account", "계정관리", "orgchart", 3);
Program auditLog = createProgram(context, programApi, "Auditlog", "Auditlog", "감사로그", "auditlog", 4);
Program taskManager = createProgram(context, programApi, "Task Manager", "Task Manager", "작업관리자", "taskmanager", 5);
Program run = createProgram(context, programApi, "Run", "Run", "실행", "run", 6);
Program devConsole = createProgram(context, programApi, "Developer Console", "Developer Console", "개발자콘솔", "devconsole",
7);
List<Program> allPrograms = new ArrayList<Program>();
allPrograms.add(home);
allPrograms.add(dashBoard);
allPrograms.add(account);
allPrograms.add(auditLog);
List<Program> memberPrograms = new ArrayList<Program>();
memberPrograms.add(home);
memberPrograms.add(dashBoard);
memberPrograms.add(account);
if (programApi.findProgramProfile(DEFAULT_DOMAIN, "all") == null) {
// master
ProgramProfile allProfile = new ProgramProfile();
allProfile.setName("all");
allProfile.setPrograms(allPrograms);
// member
ProgramProfile memberProfile = new ProgramProfile();
memberProfile.setName("member");
memberProfile.setPrograms(memberPrograms);
try {
programApi.createProgramProfile(DEFAULT_DOMAIN, allProfile);
programApi.createProgramProfile(DEFAULT_DOMAIN, memberProfile);
} catch (Exception e) {
logger.error("araqne dom: program profile initialize failed", e);
context.println("program profile pack initialize failed");
}
orgApi.setOrganizationParameter(DEFAULT_DOMAIN, "default_program_profile_id", "all");
}
}
| public static void createPrograms(ScriptContext context, OrganizationApi orgApi, ProgramApi programApi) {
if (programApi.findProgramPack(DEFAULT_DOMAIN, "System") == null) {
Map<String, String> displayNames = new HashMap<String, String>();
displayNames.put("en", "System");
displayNames.put("ko", "시스템");
ProgramPack pack = new ProgramPack();
pack.setName("System");
pack.setDisplayNames(displayNames);
pack.setDll("system");
pack.setSeq(1);
try {
programApi.createProgramPack(DEFAULT_DOMAIN, pack);
} catch (Exception e) {
logger.error("araqne dom: program pack initialize failed", e);
context.println("program pack initialize failed");
}
}
Program home = createProgram(context, programApi, "Home", "Home", "홈", "starter", 1);
Program dashBoard = createProgram(context, programApi, "Dashboard", "Dashboard", "대시보드", "dashboard", 2);
Program account = createProgram(context, programApi, "Account", "Account", "계정관리", "orgchart", 3);
Program auditLog = createProgram(context, programApi, "Audit Log", "Audit Log", "감사로그", "auditlog", 4);
Program taskManager = createProgram(context, programApi, "Task Manager", "Task Manager", "작업관리자", "taskmanager", 5);
Program run = createProgram(context, programApi, "Run", "Run", "실행", "run", 6);
Program devConsole = createProgram(context, programApi, "Developer Console", "Developer Console", "개발자콘솔", "devconsole",
7);
List<Program> allPrograms = new ArrayList<Program>();
allPrograms.add(home);
allPrograms.add(dashBoard);
allPrograms.add(account);
allPrograms.add(auditLog);
List<Program> memberPrograms = new ArrayList<Program>();
memberPrograms.add(home);
memberPrograms.add(dashBoard);
memberPrograms.add(account);
if (programApi.findProgramProfile(DEFAULT_DOMAIN, "all") == null) {
// master
ProgramProfile allProfile = new ProgramProfile();
allProfile.setName("all");
allProfile.setPrograms(allPrograms);
// member
ProgramProfile memberProfile = new ProgramProfile();
memberProfile.setName("member");
memberProfile.setPrograms(memberPrograms);
try {
programApi.createProgramProfile(DEFAULT_DOMAIN, allProfile);
programApi.createProgramProfile(DEFAULT_DOMAIN, memberProfile);
} catch (Exception e) {
logger.error("araqne dom: program profile initialize failed", e);
context.println("program profile pack initialize failed");
}
orgApi.setOrganizationParameter(DEFAULT_DOMAIN, "default_program_profile_id", "all");
}
}
|
diff --git a/fap/app/jobs/NotificarAlertasAnotacionesFAP.java b/fap/app/jobs/NotificarAlertasAnotacionesFAP.java
index 717a32ee..c15dd7ae 100644
--- a/fap/app/jobs/NotificarAlertasAnotacionesFAP.java
+++ b/fap/app/jobs/NotificarAlertasAnotacionesFAP.java
@@ -1,83 +1,83 @@
package jobs;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.joda.time.DateTime;
import com.jamonapi.utils.Logger;
import emails.Mails;
import es.gobcan.eadmon.aed.ws.dominio.Solicitud;
import models.AdministracionFapJobs;
import models.AnotacionFAP;
import models.DatosAnotaciones;
import models.SolicitudGenerica;
import models.TableKeyValue;
import play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesSupport;
import play.db.jpa.GenericModel.JPAQuery;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import play.jobs.*;
import properties.FapProperties;
@Every("1h")
public class NotificarAlertasAnotacionesFAP extends Job implements LocalVariablesSupport {
static Integer tiempoRefresco = 1;
@Transactional
public void doJob() {
if (AdministracionFapJobs.all() != null) {
AdministracionFapJobs job = AdministracionFapJobs.all().first();
if ((job.notificarAlertasAnotaciones != null) && (job.notificarAlertasAnotaciones == true)) {
if ((job.valorNotificarAlertasAnotaciones != null) && (tiempoRefresco.equals(job.valorNotificarAlertasAnotaciones))){
tiempoRefresco=1;
List<AnotacionFAP> anotaciones = new ArrayList<AnotacionFAP>();
try {
play.Logger.info("Comprobando alertas anotaciones pendientes a las: " + new DateTime().toString());
anotaciones = AnotacionFAP.find("select anotacion from AnotacionFAP anotacion where ((anotacion.alertaNotificada is NULL) or (anotacion.alertaNotificada = false))").fetch();
} catch (Exception ex) {
play.Logger.error(ex, "Error al consultar las alertas de anotaciones que no han expirado.");
return;
}
for (AnotacionFAP anotacion : anotaciones) {
try {
- if (anotacion.fechaAlerta.isBeforeNow()) {
+ if (anotacion.fechaAlerta!=null && anotacion.fechaAlerta.isBeforeNow()) {
play.Logger.info("Correo send to:" + anotacion.personaAsunto.email);
play.Logger.info("Fecha:" + anotacion.fecha);
play.Logger.info("Fecha Alerta:" + anotacion.fechaAlerta);
play.Logger.info("Titulo:" + anotacion.tituloanotacion);
play.Logger.info("Descripción:" + anotacion.descripcion);
SolicitudGenerica solicitud = SolicitudGenerica.find("select solicitud from SolicitudGenerica solicitud join solicitud.datosAnotaciones datosAnotaciones where datosAnotaciones.id=(select datoAnotacion.id from DatosAnotaciones datoAnotacion join datoAnotacion.anotaciones anotaciones where anotaciones.id=?)", anotacion.id).first();
if (solicitud != null){
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("anotacion", anotacion);
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("solicitud", solicitud);
- Mails.enviar("anotacion", anotacion, solicitud);
+ Mails.enviar(FapProperties.get("fap.seguimiento.alerta.identificadoremail") , anotacion, solicitud);
anotacion.alertaNotificada = true;
anotacion.save();
play.Logger.debug("Nueva notificación de expiración de una alerta: email");
}
else {
play.Logger.error("No se pudo enviar el correo de la anotación con identificador '" + anotacion.id + "'. Debido a que la solicitud de la anotacion no se pudo recuperar.");
}
}
} catch (Exception e) {
play.Logger.error("No se pudo enviar el correo de la anotación con identificador '" + anotacion.id + "'. "+e);
}
}
return;
} else {
tiempoRefresco++;
}
}
}
}
}
| false | true | public void doJob() {
if (AdministracionFapJobs.all() != null) {
AdministracionFapJobs job = AdministracionFapJobs.all().first();
if ((job.notificarAlertasAnotaciones != null) && (job.notificarAlertasAnotaciones == true)) {
if ((job.valorNotificarAlertasAnotaciones != null) && (tiempoRefresco.equals(job.valorNotificarAlertasAnotaciones))){
tiempoRefresco=1;
List<AnotacionFAP> anotaciones = new ArrayList<AnotacionFAP>();
try {
play.Logger.info("Comprobando alertas anotaciones pendientes a las: " + new DateTime().toString());
anotaciones = AnotacionFAP.find("select anotacion from AnotacionFAP anotacion where ((anotacion.alertaNotificada is NULL) or (anotacion.alertaNotificada = false))").fetch();
} catch (Exception ex) {
play.Logger.error(ex, "Error al consultar las alertas de anotaciones que no han expirado.");
return;
}
for (AnotacionFAP anotacion : anotaciones) {
try {
if (anotacion.fechaAlerta.isBeforeNow()) {
play.Logger.info("Correo send to:" + anotacion.personaAsunto.email);
play.Logger.info("Fecha:" + anotacion.fecha);
play.Logger.info("Fecha Alerta:" + anotacion.fechaAlerta);
play.Logger.info("Titulo:" + anotacion.tituloanotacion);
play.Logger.info("Descripción:" + anotacion.descripcion);
SolicitudGenerica solicitud = SolicitudGenerica.find("select solicitud from SolicitudGenerica solicitud join solicitud.datosAnotaciones datosAnotaciones where datosAnotaciones.id=(select datoAnotacion.id from DatosAnotaciones datoAnotacion join datoAnotacion.anotaciones anotaciones where anotaciones.id=?)", anotacion.id).first();
if (solicitud != null){
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("anotacion", anotacion);
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("solicitud", solicitud);
Mails.enviar("anotacion", anotacion, solicitud);
anotacion.alertaNotificada = true;
anotacion.save();
play.Logger.debug("Nueva notificación de expiración de una alerta: email");
}
else {
play.Logger.error("No se pudo enviar el correo de la anotación con identificador '" + anotacion.id + "'. Debido a que la solicitud de la anotacion no se pudo recuperar.");
}
}
} catch (Exception e) {
play.Logger.error("No se pudo enviar el correo de la anotación con identificador '" + anotacion.id + "'. "+e);
}
}
return;
} else {
tiempoRefresco++;
}
}
}
}
| public void doJob() {
if (AdministracionFapJobs.all() != null) {
AdministracionFapJobs job = AdministracionFapJobs.all().first();
if ((job.notificarAlertasAnotaciones != null) && (job.notificarAlertasAnotaciones == true)) {
if ((job.valorNotificarAlertasAnotaciones != null) && (tiempoRefresco.equals(job.valorNotificarAlertasAnotaciones))){
tiempoRefresco=1;
List<AnotacionFAP> anotaciones = new ArrayList<AnotacionFAP>();
try {
play.Logger.info("Comprobando alertas anotaciones pendientes a las: " + new DateTime().toString());
anotaciones = AnotacionFAP.find("select anotacion from AnotacionFAP anotacion where ((anotacion.alertaNotificada is NULL) or (anotacion.alertaNotificada = false))").fetch();
} catch (Exception ex) {
play.Logger.error(ex, "Error al consultar las alertas de anotaciones que no han expirado.");
return;
}
for (AnotacionFAP anotacion : anotaciones) {
try {
if (anotacion.fechaAlerta!=null && anotacion.fechaAlerta.isBeforeNow()) {
play.Logger.info("Correo send to:" + anotacion.personaAsunto.email);
play.Logger.info("Fecha:" + anotacion.fecha);
play.Logger.info("Fecha Alerta:" + anotacion.fechaAlerta);
play.Logger.info("Titulo:" + anotacion.tituloanotacion);
play.Logger.info("Descripción:" + anotacion.descripcion);
SolicitudGenerica solicitud = SolicitudGenerica.find("select solicitud from SolicitudGenerica solicitud join solicitud.datosAnotaciones datosAnotaciones where datosAnotaciones.id=(select datoAnotacion.id from DatosAnotaciones datoAnotacion join datoAnotacion.anotaciones anotaciones where anotaciones.id=?)", anotacion.id).first();
if (solicitud != null){
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("anotacion", anotacion);
play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer.addVariable("solicitud", solicitud);
Mails.enviar(FapProperties.get("fap.seguimiento.alerta.identificadoremail") , anotacion, solicitud);
anotacion.alertaNotificada = true;
anotacion.save();
play.Logger.debug("Nueva notificación de expiración de una alerta: email");
}
else {
play.Logger.error("No se pudo enviar el correo de la anotación con identificador '" + anotacion.id + "'. Debido a que la solicitud de la anotacion no se pudo recuperar.");
}
}
} catch (Exception e) {
play.Logger.error("No se pudo enviar el correo de la anotación con identificador '" + anotacion.id + "'. "+e);
}
}
return;
} else {
tiempoRefresco++;
}
}
}
}
|
diff --git a/src/main/java/greed/code/lang/AbstractLanguage.java b/src/main/java/greed/code/lang/AbstractLanguage.java
index 531ed8f..39d249c 100644
--- a/src/main/java/greed/code/lang/AbstractLanguage.java
+++ b/src/main/java/greed/code/lang/AbstractLanguage.java
@@ -1,73 +1,77 @@
package greed.code.lang;
import greed.code.LanguageRenderer;
import greed.code.LanguageTrait;
import greed.model.Param;
import greed.model.ParamValue;
import greed.model.Primitive;
import greed.model.Type;
import java.util.ArrayList;
/**
* An base implementation of {@link LanguageRenderer} and {@link LanguageTrait}.
* <p>
* This implementation expects to support traits that are common to almost all
* languages, so that each language's trait implementation can be benefited by
* extending this class.
*
* @since 2.0
*
* @author Jongwook Choi
* @author Shiva Wu
*/
public abstract class AbstractLanguage implements LanguageTrait, LanguageRenderer {
@Override
public ParamValue parseValue(String value, Param param) {
if (!param.getType().isArray())
return new ParamValue(param, value);
value = value.trim();
value = value.substring(1, value.length() - 1);
value = value.replaceAll("\n", "");
+ value = value.trim(); //need a second trim in case it is an empty list { }
if (param.getType().getPrimitive() == Primitive.STRING) {
boolean inString = false;
ArrayList<String> valueList = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
// TODO: escape \" in string
for (int i = 0; i < value.length(); ++i) {
char c = value.charAt(i);
if (c == '"') {
if (inString) {
valueList.add('"' + buf.toString() + '"');
} else {
buf.setLength(0);
}
inString = !inString;
} else if (inString) {
buf.append(c);
}
}
return new ParamValue(param, valueList.toArray(new String[0]));
+ } else if (value.length() == 0) {
+ //Empty array
+ return new ParamValue( param, new String[]{} );
} else {
String[] valueList = value.split(",");
Param paramWithPrim = new Param(param.getName(), new Type(param.getType().getPrimitive(), 0), param.getIndex());
for (int i = 0; i < valueList.length; i++) {
valueList[i] = renderParamValue(new ParamValue(paramWithPrim, valueList[i].trim()));
}
return new ParamValue(param, valueList);
}
}
@Override
public String renderParamList(Param[] params) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < params.length; ++i) {
if (i > 0) buf.append(", ");
buf.append(renderParam(params[i]));
}
return buf.toString();
}
}
| false | true | public ParamValue parseValue(String value, Param param) {
if (!param.getType().isArray())
return new ParamValue(param, value);
value = value.trim();
value = value.substring(1, value.length() - 1);
value = value.replaceAll("\n", "");
if (param.getType().getPrimitive() == Primitive.STRING) {
boolean inString = false;
ArrayList<String> valueList = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
// TODO: escape \" in string
for (int i = 0; i < value.length(); ++i) {
char c = value.charAt(i);
if (c == '"') {
if (inString) {
valueList.add('"' + buf.toString() + '"');
} else {
buf.setLength(0);
}
inString = !inString;
} else if (inString) {
buf.append(c);
}
}
return new ParamValue(param, valueList.toArray(new String[0]));
} else {
String[] valueList = value.split(",");
Param paramWithPrim = new Param(param.getName(), new Type(param.getType().getPrimitive(), 0), param.getIndex());
for (int i = 0; i < valueList.length; i++) {
valueList[i] = renderParamValue(new ParamValue(paramWithPrim, valueList[i].trim()));
}
return new ParamValue(param, valueList);
}
}
| public ParamValue parseValue(String value, Param param) {
if (!param.getType().isArray())
return new ParamValue(param, value);
value = value.trim();
value = value.substring(1, value.length() - 1);
value = value.replaceAll("\n", "");
value = value.trim(); //need a second trim in case it is an empty list { }
if (param.getType().getPrimitive() == Primitive.STRING) {
boolean inString = false;
ArrayList<String> valueList = new ArrayList<String>();
StringBuilder buf = new StringBuilder();
// TODO: escape \" in string
for (int i = 0; i < value.length(); ++i) {
char c = value.charAt(i);
if (c == '"') {
if (inString) {
valueList.add('"' + buf.toString() + '"');
} else {
buf.setLength(0);
}
inString = !inString;
} else if (inString) {
buf.append(c);
}
}
return new ParamValue(param, valueList.toArray(new String[0]));
} else if (value.length() == 0) {
//Empty array
return new ParamValue( param, new String[]{} );
} else {
String[] valueList = value.split(",");
Param paramWithPrim = new Param(param.getName(), new Type(param.getType().getPrimitive(), 0), param.getIndex());
for (int i = 0; i < valueList.length; i++) {
valueList[i] = renderParamValue(new ParamValue(paramWithPrim, valueList[i].trim()));
}
return new ParamValue(param, valueList);
}
}
|
diff --git a/trunk/org/xbill/DNS/Tokenizer.java b/trunk/org/xbill/DNS/Tokenizer.java
index e82d2f8..00a515b 100644
--- a/trunk/org/xbill/DNS/Tokenizer.java
+++ b/trunk/org/xbill/DNS/Tokenizer.java
@@ -1,505 +1,502 @@
// Copyright (c) 2003 Brian Wellington ([email protected])
//
// Copyright (C) 2003 Nominum, Inc.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
// OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
package org.xbill.DNS;
import java.io.*;
import java.util.*;
/**
* Tokenizer is used to parse DNS records and zones from text format,
*
* @author Brian Wellington
* @author Bob Halley
*/
public class Tokenizer {
private static String delim = " \t\n;()\"";
private static String quotes = "\"";
/** End of file */
public static final int EOF = 0;
/** End of line */
public static final int EOL = 1;
/** Whitespace; only returned when wantWhitespace is set */
public static final int WHITESPACE = 2;
/** An identifier (unquoted string) */
public static final int IDENTIFIER = 3;
/** A quoted string */
public static final int QUOTED_STRING = 4;
/** A comment; only returned when wantComment is set */
public static final int COMMENT = 5;
private InputStream is;
private int ungottenChar;
private boolean ungottenToken;
private int multiline;
private boolean quoting;
private String delimiters;
private Token current;
private StringBuffer sb;
public static class Token {
/** The type of token. */
public int type;
/** The value of the token, or null for tokens without values. */
public String value;
private
Token() {
type = -1;
value = null;
}
private Token
set(int type, StringBuffer value) {
if (type < 0)
throw new IllegalArgumentException();
this.type = type;
this.value = value == null ? null : value.toString();
return this;
}
/**
* Converts the token to a string containing a representation useful
* for debugging.
*/
public String
toString() {
switch (type) {
case EOF:
return "<eof>";
case EOL:
return "<eol>";
case WHITESPACE:
return "<whitespace>";
case IDENTIFIER:
return "<identifier: " + value + ">";
case QUOTED_STRING:
return "<quoted_string: " + value + ">";
case COMMENT:
return "<comment: " + value + ">";
default:
return "<unknown>";
}
}
/** Indicates whether this token contains a string. */
public boolean
isString() {
return (type == IDENTIFIER || type == QUOTED_STRING);
}
/** Indicates whether this token contains an EOL or EOF. */
public boolean
isEOL() {
return (type == EOL || type == EOF);
}
}
/**
* Creates a Tokenizer from an arbitrary input stream.
* @param is The InputStream to tokenize.
*/
public
Tokenizer(InputStream is) {
if (is instanceof BufferedInputStream)
this.is = is;
else
this.is = new BufferedInputStream(is);
ungottenChar = -1;
ungottenToken = false;
multiline = 0;
quoting = false;
delimiters = delim;
current = new Token();
sb = new StringBuffer();
}
/**
* Creates a Tokenizer from a string.
* @param s The String to tokenize.
*/
public
Tokenizer(String s) {
this(new ByteArrayInputStream(s.getBytes()));
}
/**
* Creates a Tokenizer from a file.
* @param f The File to tokenize.
*/
public
Tokenizer(File f) throws FileNotFoundException {
this(new FileInputStream(f));
}
private int
getChar() throws IOException {
int c;
if (ungottenChar != -1) {
c = ungottenChar;
ungottenChar = -1;
} else {
c = is.read();
if (c == '\r')
c = '\n';
}
return c;
}
private void
ungetChar(int c) {
if (ungottenChar != -1)
throw new IllegalStateException
("Cannot unget multiple characters");
ungottenChar = c;
}
private int
skipWhitespace() throws IOException {
int skipped = 0;
while (true) {
int c = getChar();
if (c != ' ' && c != '\t') {
if (!(c == '\n' && multiline > 0)) {
ungetChar(c);
return skipped;
}
}
skipped++;
}
}
private void
fail(String s) throws TextParseException {
throw new TextParseException(s);
}
private void
checkUnbalancedParens() throws TextParseException {
if (multiline > 0)
fail("unbalanced parentheses");
}
/**
* Gets the next token from a tokenizer.
* @param wantWhitespace If true, leading whitespace will be returned as a
* token.
* @param wantComment If true, comments are returned as tokens.
* @return The next token in the stream.
* @throws TextParseException The input was invalid.
* @throws IOException An I/O error occurred.
*/
public Token
get(boolean wantWhitespace, boolean wantComment) throws IOException {
int type;
int c;
if (ungottenToken) {
ungottenToken = false;
if (current.type == WHITESPACE) {
if (wantWhitespace)
return current;
} else if (current.type == COMMENT) {
if (wantComment)
return current;
} else
return current;
}
int skipped = skipWhitespace();
if (skipped > 0 && wantWhitespace)
return current.set(WHITESPACE, null);
type = IDENTIFIER;
sb.setLength(0);
while (true) {
c = getChar();
if (c == -1 || delimiters.indexOf(c) != -1) {
if (c == -1) {
if (quoting)
- throw new EOFException();
+ fail("newline in quoted string");
else if (sb.length() == 0)
return current.set(EOF, null);
else
return current.set(type, sb);
}
if (sb.length() == 0) {
if (c == '(') {
multiline++;
skipWhitespace();
continue;
} else if (c == ')') {
if (multiline <= 0)
fail("invalid close " +
"parenthesis");
multiline--;
skipWhitespace();
continue;
} else if (c == '"') {
if (!quoting) {
quoting = true;
delimiters = quotes;
type = QUOTED_STRING;
} else {
quoting = false;
delimiters = delim;
skipWhitespace();
}
continue;
} else if (c == '\n') {
return current.set(EOL, null);
} else if (c == ';') {
while (true) {
c = getChar();
if (c == '\n' || c == -1)
break;
sb.append((char)c);
}
if (wantComment) {
ungetChar(c);
return current.set(COMMENT, sb);
} else if (c == -1) {
checkUnbalancedParens();
return current.set(EOF, null);
} else if (multiline > 0) {
skipWhitespace();
sb.setLength(0);
continue;
} else
return current.set(EOL, null);
} else
throw new IllegalStateException();
} else
ungetChar(c);
break;
- } else if (quoting) {
- if (c == '\\') {
- c = getChar();
- if (c == -1)
- throw new EOFException();
- } else if (c == '\n')
- fail("newline in quoted string");
+ } else if (c == '\\') {
+ c = getChar();
+ if (c == -1)
+ fail("unterminated escape sequence");
}
sb.append((char)c);
}
if (sb.length() == 0) {
checkUnbalancedParens();
return current.set(EOF, null);
}
return current.set(type, sb);
}
/**
* Gets the next token from a tokenizer, ignoring whitespace and comments.
* @return The next token in the stream.
* @throws TextParseException The input was invalid.
* @throws IOException An I/O error occurred.
*/
public Token
get() throws IOException {
return get(false, false);
}
/**
* Returns a token to the stream, so that it will be returned by the next call
* to get().
* @throws IllegalStateException There are already ungotten tokens.
*/
public void
unget() {
if (ungottenToken)
throw new IllegalStateException
("Cannot unget multiple tokens");
ungottenToken = true;
}
/**
* Gets the next token from a tokenizer and converts it to a string.
* @return The next token in the stream, as a string.
* @throws TextParseException The input was invalid or not a string.
* @throws IOException An I/O error occurred.
*/
public String
getString() throws IOException {
Token next = get();
if (!next.isString()) {
fail("expected a string");
}
return next.value;
}
/**
* Gets the next token from a tokenizer, ensures it is an unquoted string,
* and converts it to a string.
* @return The next token in the stream, as a string.
* @throws TextParseException The input was invalid or not an unquoted string.
* @throws IOException An I/O error occurred.
*/
public String
getIdentifier() throws IOException {
Token next = get();
if (next.type != IDENTIFIER) {
fail("expected an identifier");
}
return next.value;
}
/**
* Gets the next token from a tokenizer and converts it to a long.
* @return The next token in the stream, as a long.
* @throws TextParseException The input was invalid or not a long.
* @throws IOException An I/O error occurred.
*/
public long
getLong() throws IOException {
String next = getIdentifier();
if (!Character.isDigit(next.charAt(0)))
fail("expecting an integer");
try {
return Long.parseLong(next);
} catch (NumberFormatException e) {
fail("expecting an integer");
return 0;
}
}
/**
* Gets the next token from a tokenizer and converts it to an unsigned 32 bit
* integer.
* @return The next token in the stream, as an unsigned 32 bit integer.
* @throws TextParseException The input was invalid or not an unsigned 32
* bit integer.
* @throws IOException An I/O error occurred.
*/
public long
getUInt32() throws IOException {
long l = getLong();
if (l < 0 || l > 0xFFFFFFFFL)
fail("expecting an 32 bit unsigned integer");
return l;
}
/**
* Gets the next token from a tokenizer and converts it to an unsigned 16 bit
* integer.
* @return The next token in the stream, as an unsigned 16 bit integer.
* @throws TextParseException The input was invalid or not an unsigned 16
* bit integer.
* @throws IOException An I/O error occurred.
*/
public int
getUInt16() throws IOException {
long l = getLong();
if (l < 0 || l > 0xFFFFL)
fail("expecting an 16 bit unsigned integer");
return (int) l;
}
/**
* Gets the next token from a tokenizer and converts it to an unsigned 8 bit
* integer.
* @return The next token in the stream, as an unsigned 8 bit integer.
* @throws TextParseException The input was invalid or not an unsigned 8
* bit integer.
* @throws IOException An I/O error occurred.
*/
public int
getUInt8() throws IOException {
long l = getLong();
if (l < 0 || l > 0xFFL)
fail("expecting an 8 bit unsigned integer");
return (int) l;
}
/**
* Gets the next token from a tokenizer and converts it to a double.
* @return The next token in the stream, as a double.
* @throws TextParseException The input was invalid or not a double.
* @throws IOException An I/O error occurred.
*/
public double
getDouble() throws IOException {
String next = getIdentifier();
if (!Character.isDigit(next.charAt(0)))
fail("expecting an integer");
try {
return Double.parseDouble(next);
} catch (NumberFormatException e) {
fail("expecting an floating point value");
return 0;
}
}
/**
* Gets the next token from a tokenizer and converts it to an integer
* representing a TTL (which may be encoded in the BIND TTL format).
* @return The next token in the stream, as a integer.
* @throws TextParseException The input was invalid or not a valid TTL.
* @throws IOException An I/O error occurred.
* @see TTL
*/
public int
getTTL() throws IOException {
String next = getIdentifier();
try {
return TTL.parseTTL(next);
}
catch (NumberFormatException e) {
fail("invalid TTL: " + next);
return 0;
}
}
/**
* Gets the next token from a tokenizer and converts it to a name.
* @param origin The origin to append to relative names.
* @return The next token in the stream, as a name.
* @throws TextParseException The input was invalid or not a valid name.
* @throws IOException An I/O error occurred.
* @throws RelativeNameException The parsed name was relative, even with the
* origin.
* @see Name
*/
public Name
getName(Name origin) throws IOException {
Name name = Name.fromString(getIdentifier(), origin);
if (!name.isAbsolute())
throw new RelativeNameException(name);
return name;
}
/**
* Gets the next token from a tokenizer, which must be an EOL or EOF.
* @throws TextParseException The input was invalid or not an EOL or EOF token.
* @throws IOException An I/O error occurred.
*/
public void
getEOL() throws IOException {
Token next = get();
if (next.type != EOL && next.type != EOF) {
fail("expecting EOL or EOF");
}
}
}
| false | true | public Token
get(boolean wantWhitespace, boolean wantComment) throws IOException {
int type;
int c;
if (ungottenToken) {
ungottenToken = false;
if (current.type == WHITESPACE) {
if (wantWhitespace)
return current;
} else if (current.type == COMMENT) {
if (wantComment)
return current;
} else
return current;
}
int skipped = skipWhitespace();
if (skipped > 0 && wantWhitespace)
return current.set(WHITESPACE, null);
type = IDENTIFIER;
sb.setLength(0);
while (true) {
c = getChar();
if (c == -1 || delimiters.indexOf(c) != -1) {
if (c == -1) {
if (quoting)
throw new EOFException();
else if (sb.length() == 0)
return current.set(EOF, null);
else
return current.set(type, sb);
}
if (sb.length() == 0) {
if (c == '(') {
multiline++;
skipWhitespace();
continue;
} else if (c == ')') {
if (multiline <= 0)
fail("invalid close " +
"parenthesis");
multiline--;
skipWhitespace();
continue;
} else if (c == '"') {
if (!quoting) {
quoting = true;
delimiters = quotes;
type = QUOTED_STRING;
} else {
quoting = false;
delimiters = delim;
skipWhitespace();
}
continue;
} else if (c == '\n') {
return current.set(EOL, null);
} else if (c == ';') {
while (true) {
c = getChar();
if (c == '\n' || c == -1)
break;
sb.append((char)c);
}
if (wantComment) {
ungetChar(c);
return current.set(COMMENT, sb);
} else if (c == -1) {
checkUnbalancedParens();
return current.set(EOF, null);
} else if (multiline > 0) {
skipWhitespace();
sb.setLength(0);
continue;
} else
return current.set(EOL, null);
} else
throw new IllegalStateException();
} else
ungetChar(c);
break;
} else if (quoting) {
if (c == '\\') {
c = getChar();
if (c == -1)
throw new EOFException();
} else if (c == '\n')
fail("newline in quoted string");
}
sb.append((char)c);
}
if (sb.length() == 0) {
checkUnbalancedParens();
return current.set(EOF, null);
}
return current.set(type, sb);
}
| public Token
get(boolean wantWhitespace, boolean wantComment) throws IOException {
int type;
int c;
if (ungottenToken) {
ungottenToken = false;
if (current.type == WHITESPACE) {
if (wantWhitespace)
return current;
} else if (current.type == COMMENT) {
if (wantComment)
return current;
} else
return current;
}
int skipped = skipWhitespace();
if (skipped > 0 && wantWhitespace)
return current.set(WHITESPACE, null);
type = IDENTIFIER;
sb.setLength(0);
while (true) {
c = getChar();
if (c == -1 || delimiters.indexOf(c) != -1) {
if (c == -1) {
if (quoting)
fail("newline in quoted string");
else if (sb.length() == 0)
return current.set(EOF, null);
else
return current.set(type, sb);
}
if (sb.length() == 0) {
if (c == '(') {
multiline++;
skipWhitespace();
continue;
} else if (c == ')') {
if (multiline <= 0)
fail("invalid close " +
"parenthesis");
multiline--;
skipWhitespace();
continue;
} else if (c == '"') {
if (!quoting) {
quoting = true;
delimiters = quotes;
type = QUOTED_STRING;
} else {
quoting = false;
delimiters = delim;
skipWhitespace();
}
continue;
} else if (c == '\n') {
return current.set(EOL, null);
} else if (c == ';') {
while (true) {
c = getChar();
if (c == '\n' || c == -1)
break;
sb.append((char)c);
}
if (wantComment) {
ungetChar(c);
return current.set(COMMENT, sb);
} else if (c == -1) {
checkUnbalancedParens();
return current.set(EOF, null);
} else if (multiline > 0) {
skipWhitespace();
sb.setLength(0);
continue;
} else
return current.set(EOL, null);
} else
throw new IllegalStateException();
} else
ungetChar(c);
break;
} else if (c == '\\') {
c = getChar();
if (c == -1)
fail("unterminated escape sequence");
}
sb.append((char)c);
}
if (sb.length() == 0) {
checkUnbalancedParens();
return current.set(EOF, null);
}
return current.set(type, sb);
}
|
diff --git a/seqware-pipeline/src/test/java/net/sourceforge/seqware/pipeline/plugins/WorkflowStatusCheckerTest.java b/seqware-pipeline/src/test/java/net/sourceforge/seqware/pipeline/plugins/WorkflowStatusCheckerTest.java
index 33c90ed2..d45a883a 100644
--- a/seqware-pipeline/src/test/java/net/sourceforge/seqware/pipeline/plugins/WorkflowStatusCheckerTest.java
+++ b/seqware-pipeline/src/test/java/net/sourceforge/seqware/pipeline/plugins/WorkflowStatusCheckerTest.java
@@ -1,205 +1,206 @@
/*
* Copyright (C) 2013 SeqWare
*
* 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 net.sourceforge.seqware.pipeline.plugins;
import it.sauronsoftware.junique.AlreadyLockedException;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import joptsimple.OptionSet;
import net.sourceforge.seqware.common.model.WorkflowRun;
import net.sourceforge.seqware.common.model.WorkflowRunStatus;
import net.sourceforge.seqware.common.module.ReturnValue;
import net.sourceforge.seqware.common.util.filetools.FileTools;
import net.sourceforge.seqware.common.util.filetools.FileTools.LocalhostPair;
import net.sourceforge.seqware.common.util.workflowtools.WorkflowTools;
import net.sourceforge.seqware.pipeline.tools.RunLock;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
/**
*
* @author dyuen
*/
@PrepareForTest({WorkflowTools.class, FileTools.class, WorkflowStatusChecker.class})
@RunWith(PowerMockRunner.class)
public class WorkflowStatusCheckerTest{
@Mock
private Map<String, String> config;
@Mock
private OptionSet options;
@Mock
private net.sourceforge.seqware.common.metadata.Metadata metadata;
@InjectMocks
private WorkflowStatusChecker workflowStatusChecker;
@Before
public void initMocks() throws Exception{
reset(config, options, metadata);
workflowStatusChecker = new WorkflowStatusChecker(); // this is kind of hacky
// apparantly testNG retains the state of mocks and statuschecker from test to test, so we need to rebuild everything
MockitoAnnotations.initMocks(this);
when(options.has("force-host")).thenReturn(true);
when(options.valueOf("force-host")).thenReturn("localhost");
when(config.get("SW_REST_USER")).thenReturn("user");
}
@After
public void cleanMocks(){
RunLock.release();
}
@Test
public void testShouldInjectMocks(){
Assert.assertNotNull(metadata);
Assert.assertNotNull(workflowStatusChecker);
Assert.assertNotNull(workflowStatusChecker.getMetadata());
}
@Test(expected = RuntimeException.class)
public void testInitLocking(){
final ReturnValue ret1 = workflowStatusChecker.init();
Assert.assertTrue("workflowStatusChecker could not init", ret1.getExitStatus() == ReturnValue.SUCCESS);
workflowStatusChecker.init();
}
@Test
public void testEmptyRun(){
final ReturnValue ret1 = workflowStatusChecker.init();
Assert.assertTrue("workflowStatusChecker could not init", ret1.getExitStatus() == ReturnValue.SUCCESS);
final ReturnValue ret2 = workflowStatusChecker.do_run();
Assert.assertTrue("workflowStatusChecker ran properly", ret2.getExitStatus() == ReturnValue.SUCCESS);
verify(metadata).getWorkflowRunsByStatus(WorkflowRunStatus.running);
verify(metadata).getWorkflowRunsByStatus(WorkflowRunStatus.pending);
verify(metadata).getWorkflowRunsByStatus(WorkflowRunStatus.submitted_cancel);
verify(metadata).getWorkflowRunsByStatus(WorkflowRunStatus.submitted_retry);
verifyNoMoreInteractions(metadata);
}
@Test
public void testNormalRun() throws Exception{
final ReturnValue ret1 = workflowStatusChecker.init();
Assert.assertTrue("workflowStatusChecker could not init", ret1.getExitStatus() == ReturnValue.SUCCESS);
mockupFakeRuns();
final ReturnValue ret2 = workflowStatusChecker.do_run();
verifyNormalRun(ret2);
}
@Test
public void testDoubleThreadedRun() throws Exception{
final ReturnValue ret1 = workflowStatusChecker.init();
Assert.assertTrue("workflowStatusChecker could not init", ret1.getExitStatus() == ReturnValue.SUCCESS);
mockupFakeRuns();
when(options.has("threads-in-thread-pool")).thenReturn(true);
when(options.valueOf("threads-in-thread-pool")).thenReturn(2);
final ReturnValue ret2 = workflowStatusChecker.do_run();
verifyNormalRun(ret2);
}
@Test
public void testManyThreadedRun() throws Exception{
final ReturnValue ret1 = workflowStatusChecker.init();
Assert.assertTrue("workflowStatusChecker could not init", ret1.getExitStatus() == ReturnValue.SUCCESS);
mockupFakeRuns();
when(options.has("threads-in-thread-pool")).thenReturn(true);
when(options.valueOf("threads-in-thread-pool")).thenReturn(100);
final ReturnValue ret2 = workflowStatusChecker.do_run();
verifyNormalRun(ret2);
}
/**
* For testing purposes, create some workflow runs and make our mocks aware of them
* @throws Exception
*/
private void mockupFakeRuns() throws Exception {
// mock up some fake workflow_runs so that their status can be checked
List<WorkflowRun> wrList = new ArrayList<WorkflowRun>();
for (int i = 0; i < 100; i++) {
WorkflowRun wr = new WorkflowRun();
wr.setOwnerUserName("user");
wr.setWorkflowAccession(42);
wr.setWorkflowRunId(42+i);
+ wr.setSwAccession(42+i);
wr.setCommand("dummyValue");
wr.setTemplate("dummyValue");
wr.setCurrentWorkingDir("dummyValue");
wr.setDax("dummyValue");
wr.setIniFile("dummyValue");
wr.setWorkflowEngine("dummyValue");
wr.setHost("localhost");
wr.setStatusCmd("pegasus-status -l /home/seqware/pegasus-dax/seqware/pegasus/FastqQualityReportAndFilter_0.10.0/run00" + 42+i);
wrList.add(wr);
}
PowerMockito.mockStatic(FileTools.class);
when(FileTools.getLocalhost(options)).thenReturn(new LocalhostPair("localhost", new ReturnValue(ReturnValue.SUCCESS)));
when(FileTools.isFileOwner(anyString())).thenReturn(true);
when(FileTools.determineFilePermissions(anyString())).thenReturn("-rw-------");
final WorkflowTools workflowTools = mock(WorkflowTools.class);
PowerMockito.whenNew(WorkflowTools.class).withAnyArguments().thenReturn(workflowTools);
ReturnValue fakeReturn = new ReturnValue(ReturnValue.SUCCESS);
fakeReturn.setAttribute("currStep", "1");
fakeReturn.setAttribute("totalSteps", "1");
when(workflowTools.watchWorkflow(anyString(), anyString(), anyInt())).thenReturn(fakeReturn);
when(metadata.getWorkflowRunsByStatus(WorkflowRunStatus.running)).thenReturn(wrList);
}
/**
* Verify that the run returned normally and that the appropriate number of updates were make to the database
* @param ret2
*/
private void verifyNormalRun(final ReturnValue ret2) {
Assert.assertTrue("workflowStatusChecker ran properly", ret2.getExitStatus() == ReturnValue.SUCCESS);
verify(metadata).getWorkflowRunsByStatus(WorkflowRunStatus.running);
verify(metadata).getWorkflowRunsByStatus(WorkflowRunStatus.pending);
verify(metadata).getWorkflowRunsByStatus(WorkflowRunStatus.submitted_cancel);
verify(metadata).getWorkflowRunsByStatus(WorkflowRunStatus.submitted_retry);
verify(metadata, times(100)).update_workflow_run(anyInt(), anyString(), anyString(), any(WorkflowRunStatus.class), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), (Set<Integer>) anyObject());
}
}
| true | true | private void mockupFakeRuns() throws Exception {
// mock up some fake workflow_runs so that their status can be checked
List<WorkflowRun> wrList = new ArrayList<WorkflowRun>();
for (int i = 0; i < 100; i++) {
WorkflowRun wr = new WorkflowRun();
wr.setOwnerUserName("user");
wr.setWorkflowAccession(42);
wr.setWorkflowRunId(42+i);
wr.setCommand("dummyValue");
wr.setTemplate("dummyValue");
wr.setCurrentWorkingDir("dummyValue");
wr.setDax("dummyValue");
wr.setIniFile("dummyValue");
wr.setWorkflowEngine("dummyValue");
wr.setHost("localhost");
wr.setStatusCmd("pegasus-status -l /home/seqware/pegasus-dax/seqware/pegasus/FastqQualityReportAndFilter_0.10.0/run00" + 42+i);
wrList.add(wr);
}
PowerMockito.mockStatic(FileTools.class);
when(FileTools.getLocalhost(options)).thenReturn(new LocalhostPair("localhost", new ReturnValue(ReturnValue.SUCCESS)));
when(FileTools.isFileOwner(anyString())).thenReturn(true);
when(FileTools.determineFilePermissions(anyString())).thenReturn("-rw-------");
final WorkflowTools workflowTools = mock(WorkflowTools.class);
PowerMockito.whenNew(WorkflowTools.class).withAnyArguments().thenReturn(workflowTools);
ReturnValue fakeReturn = new ReturnValue(ReturnValue.SUCCESS);
fakeReturn.setAttribute("currStep", "1");
fakeReturn.setAttribute("totalSteps", "1");
when(workflowTools.watchWorkflow(anyString(), anyString(), anyInt())).thenReturn(fakeReturn);
when(metadata.getWorkflowRunsByStatus(WorkflowRunStatus.running)).thenReturn(wrList);
}
| private void mockupFakeRuns() throws Exception {
// mock up some fake workflow_runs so that their status can be checked
List<WorkflowRun> wrList = new ArrayList<WorkflowRun>();
for (int i = 0; i < 100; i++) {
WorkflowRun wr = new WorkflowRun();
wr.setOwnerUserName("user");
wr.setWorkflowAccession(42);
wr.setWorkflowRunId(42+i);
wr.setSwAccession(42+i);
wr.setCommand("dummyValue");
wr.setTemplate("dummyValue");
wr.setCurrentWorkingDir("dummyValue");
wr.setDax("dummyValue");
wr.setIniFile("dummyValue");
wr.setWorkflowEngine("dummyValue");
wr.setHost("localhost");
wr.setStatusCmd("pegasus-status -l /home/seqware/pegasus-dax/seqware/pegasus/FastqQualityReportAndFilter_0.10.0/run00" + 42+i);
wrList.add(wr);
}
PowerMockito.mockStatic(FileTools.class);
when(FileTools.getLocalhost(options)).thenReturn(new LocalhostPair("localhost", new ReturnValue(ReturnValue.SUCCESS)));
when(FileTools.isFileOwner(anyString())).thenReturn(true);
when(FileTools.determineFilePermissions(anyString())).thenReturn("-rw-------");
final WorkflowTools workflowTools = mock(WorkflowTools.class);
PowerMockito.whenNew(WorkflowTools.class).withAnyArguments().thenReturn(workflowTools);
ReturnValue fakeReturn = new ReturnValue(ReturnValue.SUCCESS);
fakeReturn.setAttribute("currStep", "1");
fakeReturn.setAttribute("totalSteps", "1");
when(workflowTools.watchWorkflow(anyString(), anyString(), anyInt())).thenReturn(fakeReturn);
when(metadata.getWorkflowRunsByStatus(WorkflowRunStatus.running)).thenReturn(wrList);
}
|
diff --git a/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java b/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java
index 6d7dab03..acb9847c 100644
--- a/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java
+++ b/server/src/de/hpi/bpmn2execpn/converter/ExecConverter.java
@@ -1,626 +1,626 @@
package de.hpi.bpmn2execpn.converter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.StringBufferInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import de.hpi.bpmn.BPMNDiagram;
import de.hpi.bpmn.DataObject;
import de.hpi.bpmn.Edge;
import de.hpi.bpmn.ExecDataObject;
import de.hpi.bpmn.IntermediateEvent;
import de.hpi.bpmn.SubProcess;
import de.hpi.bpmn.Task;
import de.hpi.bpmn2execpn.model.ExecTask;
import de.hpi.bpmn2pn.converter.Converter;
import de.hpi.bpmn2pn.model.ConversionContext;
import de.hpi.bpmn2pn.model.SubProcessPlaces;
import de.hpi.execpn.AutomaticTransition;
import de.hpi.execpn.ExecFlowRelationship;
import de.hpi.execpn.ExecPetriNet;
import de.hpi.execpn.FormTransition;
import de.hpi.execpn.TransformationTransition;
import de.hpi.execpn.impl.ExecPNFactoryImpl;
import de.hpi.execpn.pnml.Locator;
import de.hpi.petrinet.ExecPlace;
import de.hpi.petrinet.FlowRelationship;
import de.hpi.petrinet.PetriNet;
import de.hpi.petrinet.Place;
import de.hpi.petrinet.Transition;
public class ExecConverter extends Converter {
private static final boolean abortWhenFinalize = true;
private static final String baseXsltURL = "http://localhost:3000/examples/contextPlace/";
private static final String copyXsltURL = baseXsltURL + "copy_xslt.xsl";
private static final String extractDataURL = baseXsltURL + "extract_processdata.xsl";
protected String standardModel;
protected String baseFileName;
private List<ExecTask> taskList;
public ExecConverter(BPMNDiagram diagram, String modelURL) {
super(diagram, new ExecPNFactoryImpl(modelURL));
this.standardModel = modelURL;
this.taskList = new ArrayList<ExecTask>();
}
public void setBaseFileName(String basefilename) {
this.baseFileName = basefilename;
}
@Override
protected void handleDiagram(PetriNet net, ConversionContext c) {
((ExecPetriNet) net).setName(diagram.getTitle());
}
@Override
protected void createStartPlaces(PetriNet net, ConversionContext c) {
// do nothing...: we want start transitions instead of start places
}
/*
@Override
public PetriNet convert () {
// !! no start place for petrinet
// but create a start transition
ExecPetriNet pn = (ExecPetriNet) super.convert();
AutomaticTransition startTransition = addAutomaticTransition(pn, "tr_initProcess", "", "initProcess", copyXsltURL, false);
pn.setStartTransition(startTransition);
Vector <Place> dataPlaces = ExecTask.pl_dataPlaces;
for (Place place : dataPlaces)
addFlowRelationship(pn, startTransition, place);
return pn;
}
// connect startTransition with contextplaces
*/
// TODO this is a dirty hack...
@Override
protected void handleTask(PetriNet net, Task task, ConversionContext c) {
ExecTask exTask = new ExecTask();
exTask.setId(task.getId());
exTask.setLabel(task.getLabel());
// create proper model, form and bindings
String model = null;
String form = null;
String bindings = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
try {
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
Document modelDoc = parser.newDocument();
Element dataEl = modelDoc.createElement("data");
Node data = modelDoc.appendChild(dataEl);
Node metaData = data.appendChild(modelDoc.createElement("metadata"));
Node processData = data.appendChild(modelDoc.createElement("processdata"));
// create MetaData Layout for Task model
// (take attention to the fact, that the attributes are again defined in the engine)
Node startTime = metaData.appendChild(modelDoc.createElement("startTime"));
Node endTime = metaData.appendChild(modelDoc.createElement("endTime"));
Node status = metaData.appendChild(modelDoc.createElement("status"));
Node owner = metaData.appendChild(modelDoc.createElement("owner"));
Node isDelegated = metaData.appendChild(modelDoc.createElement("isDelegated"));
Node reviewRequested = metaData.appendChild(modelDoc.createElement("reviewRequested"));
Node firstOwner = metaData.appendChild(modelDoc.createElement("firstOwner"));
Node actions = metaData.appendChild(modelDoc.createElement("actions"));
// create MetaData Layout Actions, that will be logged --> here not regarded
// interrogate all incoming data objects for task, create DataPlaces for them and create Task model
List<Edge> edges_in = task.getIncomingEdges();
for (Edge edge : edges_in) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
// for incoming data objects of task: create read dependencies
addReadOnlyExecFlowRelationship(net, exTask.tr_enable, ExecTask.getDataPlace(dataObject.getId()),null);
// create XML Structure for Task
String modelXML = dataObject.getModel();
StringBufferInputStream in = new StringBufferInputStream(modelXML);
try {
//TODO why is Parser not working?
Document doc = parser.parse(in);
Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId()));
Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild();
Node child = dataTagOfDataModel.getFirstChild();
while (child != null) {
dataObjectId.appendChild(child.cloneNode(true));
child = child.getNextSibling();
};
} catch (Exception io) {
io.printStackTrace();
}
}
}
// interrogate all outgoing data objects for task and create flow relationships for them
List<Edge> edges_out = task.getOutgoingEdges();
for (Edge edge : edges_in) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
// for outgoing data objects of task: create read/write dependencies
addReadOnlyExecFlowRelationship(net, exTask.tr_enable, ExecTask.getDataPlace(dataObject.getId()),null);
addFlowRelationship(net, exTask.tr_finish, ExecTask.getDataPlace(dataObject.getId()));
addFlowRelationship(net, ExecTask.getDataPlace(dataObject.getId()), exTask.tr_finish);
}
}
// persist model and deliver URL
try {
- DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
- DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
+ //DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
+ //DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
- LSSerializer dom3Writer = implLS.createLSSerializer();
- LSOutput output=implLS.createLSOutput();
- OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml"));
- output.setByteStream(outputStream);
- dom3Writer.write(modelDoc,output);
+ //LSSerializer dom3Writer = implLS.createLSSerializer();
+ //LSOutput output=implLS.createLSOutput();
+ //OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml"));
+ //output.setByteStream(outputStream);
+ //dom3Writer.write(modelDoc,output);
} catch (Exception e) {
System.out.println("Model could not be persisted");
e.printStackTrace();
}
// // from Task model (modelDoc) extract formular and bindings
// Document formDoc = parser.newDocument();
// Document bindDoc = parser.newDocument();
// // create structure of form
// // TODO how can process be shown up? Delegated from? Delegate?
// Text text = formDoc.createTextNode(
// "<b> Logged in as user: </b>/n"+
// "<x:output ref=\"instance('output-token')/data/metadata/owner\" />/n"+
// "<x:group>/n"+
// " <x:output bind=\"delegationstate\"><h2> Delegate task </h2></x:output>/n"+
// " <x:output bind=\"executionstate\"><h2> Execute task </h2></x:output>/n"+
// " <x:output bind=\"reviewstate\"><h2> Review task </h2></x:output>/n"+
// "</x:group>/n"+
// "<br /><br />/n"+
// "<x:group ref=\"instance('ui_settings')/delegategroup\" >/n"+
// " <x:select1 ref=\"instance('output-token')/data/metadata/delegate\" class=\"delegator\"> /n"+
// " <x:label> Delegate to: </x:label>/n"+
// " <x:item>/n"+
// " <x:label>Adam</x:label>/n"+
// " <x:value>Adam</x:value> /n"+
// " </x:item>/n"+
// " <x:item>/n"+
// " <x:label>Bert</x:label>/n"+
// " <x:value>Bert</x:value>/n"+
// " </x:item>/n"+
// " <x:item>/n"+
// " <x:label>Hugo</x:label>/n"+
// " <x:value>Hugo</x:value>/n"+
// " </x:item>/n"+
// " <x:item>/n"+
// " <x:label>Rudi</x:label>/n"+
// " <x:value>Rudi</x:value>/n"+
// " </x:item> /n"+
// "</x:select1>/n"+
// "</x:group>/n"+
// "<br />/n"+
// "<x:group bind=\"fade.delegatedfrom\"><x:output ref=\"instance('output-token')/data/metadata/delegatedfrom\" class=\"delegator\">/n"+
// " <x:label> Delegated from: </x:label>/n"+
// "</x:output></x:group>/n"+
// "<br/><br />/n"+
// "<x:group bind=\"fade.message\"><x:input ref=\"instance('output-token')/data/processdata/message\" class=\"metainfo\">/n"+
// " <x:label> Message: </x:label>/n"+
// "</x:input></x:group>/n"+
// "<br/><br />/n"+
// "<x:group bind=\"fade.deadline\"><x:input ref=\"instance('output-token')/data/processdata/deadline\" class=\"metainfo\">/n"+
// " <x:label> Deadline: </x:label>/n"+
// "</x:input></x:group>/n"+
// "<br/><br />/n"+
// "<x:group bind=\"wantToReviewGroup\">/n"+
// " <x:input ref=\"instance('output-token')/data/metadata/reviewRequested\" class=\"metainfo\">/n"+
// " <x:label> Responsible: </x:label>/n"+
// " </x:input>/n"+
// "</x:group>/n"+
// "<br/><br />/n"+
// "/n"+
// "<x:group ref=\"instance('ui_settings')/delegationstate\">/n"+
// " <br/><br />/n"+
// " <div class=\"labels\"> <b>readonly readable</b> </div>/n"+
// " <br/>/n"+
// "</x:group>/n"
// );
// formDoc.appendChild(text);
// build form fields of necessary attributes
// TODO persist form and bindings and save URL
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_running = addPlace(net, "pl_running_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_context = addPlace(net, "pl_context_" + task.getId(), ExecPlace.Type.context);
// add role dependencies
String rolename = task.getRolename();
// integrate context place
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime"));
exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime"));
exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status"));
exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner"));
exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isDelegated"));
exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isreviewed"));
exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested"));
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner"));
exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions"));
//enable transition
//TODO: read/write to context place
exTask.tr_enable = addAutomaticTransition(net, "tr_enable_" + task.getId(), task.getLabel());
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable);
addFlowRelationship(net, exTask.tr_enable, exTask.pl_ready);
// allocate Transition
//TODO: change context_allocate when context place gets initialized at start of process
exTask.tr_allocate = addTransformationTransition(net, "tr_allocate_" + task.getId(), task.getLabel(),"allocate", copyXsltURL);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL);
//addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl");
exTask.tr_allocate.setRolename(rolename);
if (task.isSkippable()) {
// skip Transition
exTask.setSkippable(true);
exTask.tr_skip = addTransformationTransition(net, "tr_skip_" + task.getId(), task.getLabel(), "skip", copyXsltURL);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl");
}
// submit Transition
FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings);
submit.setAction("submit");
exTask.tr_submit = submit;
addFlowRelationship(net, exTask.pl_running, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl");
exTask.tr_submit.setRolename(rolename);
// delegate Transition
FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), task.getLabel(),model,form,bindings);
delegate.setAction("delegate");
delegate.setGuard(exTask.pl_context.getId() + ".isDelegated == 'true'");
exTask.tr_delegate = delegate;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl");
exTask.tr_delegate.setRolename(rolename);
// review Transition
FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), task.getLabel(),model,form,bindings);
review.setAction("review");
review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed == 'true'");
exTask.tr_review = review;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl");
exTask.tr_review.setRolename(rolename);
// done Transition
exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), task.getLabel());
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done);
addFlowRelationship(net, exTask.tr_done, exTask.pl_complete);
addFlowRelationship(net, exTask.pl_context, exTask.tr_done);
addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl");
exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed != 'true'");
// suspend/resume
exTask.tr_suspend = addTransformationTransition(net, "tr_suspend_" + task.getId(), task.getLabel(), "suspend", copyXsltURL);
addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl");
exTask.tr_suspend.setRolename(rolename);
// resume
exTask.tr_resume = addTransformationTransition(net, "tr_resume_" + task.getId(), task.getLabel(), "resume", copyXsltURL);
addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl");
exTask.tr_resume.setRolename(rolename);
// finish transition
exTask.tr_finish = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel());
addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl");
taskList.add(exTask);
handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c);
if (c.ancestorHasExcpH)
handleExceptions(net, task, exTask.tr_submit, c);
for (IntermediateEvent event : task.getAttachedEvents())
handleAttachedIntermediateEventForTask(net, event, c);
}
@Override
protected void handleSubProcess(PetriNet net, SubProcess process,
ConversionContext c) {
super.handleSubProcess(net, process, c);
if (process.isAdhoc()) {
handleSubProcessAdHoc(net, process, c);
}
}
// TODO: Data dependencies
// TODO missing completion condition concept
protected void handleSubProcessAdHoc(PetriNet net, SubProcess process,
ConversionContext c) {
SubProcessPlaces pl = c.getSubprocessPlaces(process);
// start and end transitions
Transition startT = addTauTransition(net, "ad-hoc_start_" + process.getId());
Transition endT = addTauTransition(net, "ad-hoc_end_" + process.getId());
Transition defaultEndT = addTauTransition(net, "ad-hoc_defaultEnd_" + process.getId());
Place execState = addPlace(net, "ad-hoc_execState_" + process.getId());
addFlowRelationship(net, pl.startP, startT);
addFlowRelationship(net, startT, execState);
addFlowRelationship(net, execState, defaultEndT);
addFlowRelationship(net, execState, endT);
addFlowRelationship(net, defaultEndT, pl.endP);
addFlowRelationship(net, endT, pl.endP);
// standard completion condition check
Place updatedState = addPlace(net, "ad-hoc_updatedState_" + process.getId());
Place ccStatus = addPlace(net, "ad-hoc_ccStatus_" + process.getId());
Transition ccCheck = addTauTransition(net, "ad-hoc_ccCheck_" + process.getId());
Transition finalize = addTauTransition(net, "ad-hoc_finalize_" + process.getId());
Transition resume = addTauTransition(net, "ad-hoc_resume_" + process.getId());
addFlowRelationship(net, updatedState, ccCheck);
addFlowRelationship(net, execState, ccCheck);
addFlowRelationship(net, ccCheck, execState);
addFlowRelationship(net, ccCheck, ccStatus);
if (process.isParallelOrdering() && abortWhenFinalize) {
// parallel ad-hoc construct with abortion of tasks when completion condition is true -------------------------------
// synchronization and completionCondition checks(enableStarting, enableFinishing)
Place enableStarting = addPlace(net, "ad-hoc_enableStarting_" + process.getId());
Place enableFinishing = addPlace(net, "ad-hoc_enableFinishing_" + process.getId());
addFlowRelationship(net, startT, enableStarting);
addFlowRelationship(net, startT, enableFinishing);
addFlowRelationship(net, enableStarting, defaultEndT);
addFlowRelationship(net, enableFinishing, defaultEndT);
addFlowRelationship(net, enableStarting, ccCheck);
addFlowRelationship(net, resume, enableStarting);
addFlowRelationship(net, resume, enableFinishing);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.tr_enable);
addFlowRelationship(net, enableStarting, exTask.tr_allocate);
addFlowRelationship(net, exTask.tr_allocate, enableStarting);
addFlowRelationship(net, enableFinishing, exTask.tr_finish);
addFlowRelationship(net, exTask.tr_finish, executed);
addFlowRelationship(net, exTask.tr_finish, updatedState);
if (exTask.isSkippable()) {
addFlowRelationship(net, enableStarting, exTask.tr_skip);
addFlowRelationship(net, exTask.tr_skip, enableStarting);
}
// finishing construct(finalize with skip, finish, abort and leave_suspend)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
Transition abort = addTauTransition(net, "ad-hoc_abort_task_" + exTask.getId());
Transition leaveSuspended = addTauTransition(net, "ad-hoc_leave_suspended_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
//TODO: remove ability to abort?
addFlowRelationship(net, enableFinalize, abort);
addFlowRelationship(net, exTask.pl_running, abort);
addFlowRelationship(net, abort, taskFinalized);
addFlowRelationship(net, enableFinalize, leaveSuspended);
addFlowRelationship(net, exTask.pl_suspended, leaveSuspended);
addFlowRelationship(net, leaveSuspended, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}else if (process.isParallelOrdering() && !abortWhenFinalize) {
// parallel ad-hoc construct, running tasks can finish on their own after completion condition is true -------------
throw new NotImplementedException();
}else {
// sequential ad-hoc construct -----------------------------------------------------------------------------------------------
// synchronization and completionCondition checks(synch, corresponds to enableStarting)
Place synch = addPlace(net, "ad-hoc_synch_" + process.getId());
addFlowRelationship(net, startT, synch);
addFlowRelationship(net, synch, defaultEndT);
addFlowRelationship(net, resume, synch);
// TODO: add guard expressions
addFlowRelationship(net, ccStatus, resume); //guard expression: ccStatus == false
addFlowRelationship(net, ccStatus, finalize); // guard expression: ccStatus == true
// task specific constructs
for (ExecTask exTask : taskList) {
// execution(enabledP, executedP, connections in between)
Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.tr_enable);
addFlowRelationship(net, synch, exTask.tr_allocate);
addFlowRelationship(net, exTask.tr_finish, executed);
addFlowRelationship(net, exTask.tr_finish, updatedState);
addFlowRelationship(net, executed, defaultEndT);
if (exTask.isSkippable()) {
addFlowRelationship(net, synch, exTask.tr_skip);
}
// finishing construct(finalize with skip, finish and abort)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skip = addTauTransition(net, "ad-hoc_skip_task_" + exTask.getId());
Transition finish = addTauTransition(net, "ad-hoc_finish_task_" + exTask.getId());
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skip);
addFlowRelationship(net, enabled, skip);
addFlowRelationship(net, skip, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}
}
@Override
protected void handleDataObject(PetriNet net, DataObject object, ConversionContext c){
try {
if (object instanceof ExecDataObject) {
ExecDataObject dataobject = (ExecDataObject) object;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
//create data place for Task
ExecPlace dataPlace = addPlace(net,"pl_data_"+dataobject.getId(), ExecPlace.Type.data);
ExecTask.addDataPlace(dataPlace);
// for data place add locators
String modelXML = dataobject.getModel();
dataPlace.setModel(modelXML);
StringBufferInputStream in = new StringBufferInputStream(modelXML);
Document doc = parser.parse(in);
Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild();
Node child = dataTagOfDataModel.getFirstChild();
while (child != null) {
dataPlace.addLocator(new Locator(
child.getNodeName(),
"xsd:string",
"/data/processdata/"+dataobject.getId()+"/"+child.getNodeName()));
child = child.getNextSibling();
};
}
} catch (Exception io) {
io.printStackTrace();
}
}
public TransformationTransition addTransformationTransition(PetriNet net, String id, String label, String action, String xsltURL) {
TransformationTransition t =((ExecPNFactoryImpl) pnfactory).createTransformationTransition();
t.setId(id);
t.setLabel(label);
t.setAction(action);
t.setXsltURL(xsltURL);
net.getTransitions().add(t);
return t;
}
public ExecFlowRelationship addExecFlowRelationship(PetriNet net,
de.hpi.petrinet.Node source, de.hpi.petrinet.Node target, String xsltURL) {
if (source == null || target == null)
return null;
ExecFlowRelationship rel = ((ExecPNFactoryImpl) pnfactory).createExecFlowRelationship();
rel.setSource(source);
rel.setTarget(target);
rel.setTransformationURL(xsltURL);
net.getFlowRelationships().add(rel);
return rel;
}
public ExecFlowRelationship addReadOnlyExecFlowRelationship(PetriNet net,
de.hpi.petrinet.Node source, de.hpi.petrinet.Node target, String xsltURL) {
ExecFlowRelationship rel = addExecFlowRelationship(net, source, target, xsltURL);
if (rel == null){
return null;
}
rel.setMode(FlowRelationship.RELATION_MODE_READTOKEN);
return rel;
}
public FormTransition addFormTransition(PetriNet net, String id, String label, String model, String form, String bindings) {
FormTransition t = ((ExecPNFactoryImpl)pnfactory).createFormTransition();
t.setId(id);
t.setLabel(label);
t.setFormURL(form);
t.setBindingsURL(bindings);
t.setModelURL(model);
net.getTransitions().add(t);
return t;
}
public AutomaticTransition addAutomaticTransition(PetriNet net, String id, String label) {
AutomaticTransition t = ((ExecPNFactoryImpl)pnfactory).createAutomaticTransition();
t.setId(id);
t.setLabel(label);
net.getTransitions().add(t);
return t;
}
public ExecPlace addPlace(PetriNet net, String id, ExecPlace.Type type) {
ExecPlace p = ((ExecPNFactoryImpl)pnfactory).createPlace();
p.setId(id);
if (type != null)
p.setType(type);
net.getPlaces().add(p);
return p;
}
}
| false | true | protected void handleTask(PetriNet net, Task task, ConversionContext c) {
ExecTask exTask = new ExecTask();
exTask.setId(task.getId());
exTask.setLabel(task.getLabel());
// create proper model, form and bindings
String model = null;
String form = null;
String bindings = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
try {
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
Document modelDoc = parser.newDocument();
Element dataEl = modelDoc.createElement("data");
Node data = modelDoc.appendChild(dataEl);
Node metaData = data.appendChild(modelDoc.createElement("metadata"));
Node processData = data.appendChild(modelDoc.createElement("processdata"));
// create MetaData Layout for Task model
// (take attention to the fact, that the attributes are again defined in the engine)
Node startTime = metaData.appendChild(modelDoc.createElement("startTime"));
Node endTime = metaData.appendChild(modelDoc.createElement("endTime"));
Node status = metaData.appendChild(modelDoc.createElement("status"));
Node owner = metaData.appendChild(modelDoc.createElement("owner"));
Node isDelegated = metaData.appendChild(modelDoc.createElement("isDelegated"));
Node reviewRequested = metaData.appendChild(modelDoc.createElement("reviewRequested"));
Node firstOwner = metaData.appendChild(modelDoc.createElement("firstOwner"));
Node actions = metaData.appendChild(modelDoc.createElement("actions"));
// create MetaData Layout Actions, that will be logged --> here not regarded
// interrogate all incoming data objects for task, create DataPlaces for them and create Task model
List<Edge> edges_in = task.getIncomingEdges();
for (Edge edge : edges_in) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
// for incoming data objects of task: create read dependencies
addReadOnlyExecFlowRelationship(net, exTask.tr_enable, ExecTask.getDataPlace(dataObject.getId()),null);
// create XML Structure for Task
String modelXML = dataObject.getModel();
StringBufferInputStream in = new StringBufferInputStream(modelXML);
try {
//TODO why is Parser not working?
Document doc = parser.parse(in);
Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId()));
Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild();
Node child = dataTagOfDataModel.getFirstChild();
while (child != null) {
dataObjectId.appendChild(child.cloneNode(true));
child = child.getNextSibling();
};
} catch (Exception io) {
io.printStackTrace();
}
}
}
// interrogate all outgoing data objects for task and create flow relationships for them
List<Edge> edges_out = task.getOutgoingEdges();
for (Edge edge : edges_in) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
// for outgoing data objects of task: create read/write dependencies
addReadOnlyExecFlowRelationship(net, exTask.tr_enable, ExecTask.getDataPlace(dataObject.getId()),null);
addFlowRelationship(net, exTask.tr_finish, ExecTask.getDataPlace(dataObject.getId()));
addFlowRelationship(net, ExecTask.getDataPlace(dataObject.getId()), exTask.tr_finish);
}
}
// persist model and deliver URL
try {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
LSSerializer dom3Writer = implLS.createLSSerializer();
LSOutput output=implLS.createLSOutput();
OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml"));
output.setByteStream(outputStream);
dom3Writer.write(modelDoc,output);
} catch (Exception e) {
System.out.println("Model could not be persisted");
e.printStackTrace();
}
// // from Task model (modelDoc) extract formular and bindings
// Document formDoc = parser.newDocument();
// Document bindDoc = parser.newDocument();
// // create structure of form
// // TODO how can process be shown up? Delegated from? Delegate?
// Text text = formDoc.createTextNode(
// "<b> Logged in as user: </b>/n"+
// "<x:output ref=\"instance('output-token')/data/metadata/owner\" />/n"+
// "<x:group>/n"+
// " <x:output bind=\"delegationstate\"><h2> Delegate task </h2></x:output>/n"+
// " <x:output bind=\"executionstate\"><h2> Execute task </h2></x:output>/n"+
// " <x:output bind=\"reviewstate\"><h2> Review task </h2></x:output>/n"+
// "</x:group>/n"+
// "<br /><br />/n"+
// "<x:group ref=\"instance('ui_settings')/delegategroup\" >/n"+
// " <x:select1 ref=\"instance('output-token')/data/metadata/delegate\" class=\"delegator\"> /n"+
// " <x:label> Delegate to: </x:label>/n"+
// " <x:item>/n"+
// " <x:label>Adam</x:label>/n"+
// " <x:value>Adam</x:value> /n"+
// " </x:item>/n"+
// " <x:item>/n"+
// " <x:label>Bert</x:label>/n"+
// " <x:value>Bert</x:value>/n"+
// " </x:item>/n"+
// " <x:item>/n"+
// " <x:label>Hugo</x:label>/n"+
// " <x:value>Hugo</x:value>/n"+
// " </x:item>/n"+
// " <x:item>/n"+
// " <x:label>Rudi</x:label>/n"+
// " <x:value>Rudi</x:value>/n"+
// " </x:item> /n"+
// "</x:select1>/n"+
// "</x:group>/n"+
// "<br />/n"+
// "<x:group bind=\"fade.delegatedfrom\"><x:output ref=\"instance('output-token')/data/metadata/delegatedfrom\" class=\"delegator\">/n"+
// " <x:label> Delegated from: </x:label>/n"+
// "</x:output></x:group>/n"+
// "<br/><br />/n"+
// "<x:group bind=\"fade.message\"><x:input ref=\"instance('output-token')/data/processdata/message\" class=\"metainfo\">/n"+
// " <x:label> Message: </x:label>/n"+
// "</x:input></x:group>/n"+
// "<br/><br />/n"+
// "<x:group bind=\"fade.deadline\"><x:input ref=\"instance('output-token')/data/processdata/deadline\" class=\"metainfo\">/n"+
// " <x:label> Deadline: </x:label>/n"+
// "</x:input></x:group>/n"+
// "<br/><br />/n"+
// "<x:group bind=\"wantToReviewGroup\">/n"+
// " <x:input ref=\"instance('output-token')/data/metadata/reviewRequested\" class=\"metainfo\">/n"+
// " <x:label> Responsible: </x:label>/n"+
// " </x:input>/n"+
// "</x:group>/n"+
// "<br/><br />/n"+
// "/n"+
// "<x:group ref=\"instance('ui_settings')/delegationstate\">/n"+
// " <br/><br />/n"+
// " <div class=\"labels\"> <b>readonly readable</b> </div>/n"+
// " <br/>/n"+
// "</x:group>/n"
// );
// formDoc.appendChild(text);
// build form fields of necessary attributes
// TODO persist form and bindings and save URL
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_running = addPlace(net, "pl_running_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_context = addPlace(net, "pl_context_" + task.getId(), ExecPlace.Type.context);
// add role dependencies
String rolename = task.getRolename();
// integrate context place
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime"));
exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime"));
exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status"));
exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner"));
exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isDelegated"));
exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isreviewed"));
exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested"));
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner"));
exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions"));
//enable transition
//TODO: read/write to context place
exTask.tr_enable = addAutomaticTransition(net, "tr_enable_" + task.getId(), task.getLabel());
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable);
addFlowRelationship(net, exTask.tr_enable, exTask.pl_ready);
// allocate Transition
//TODO: change context_allocate when context place gets initialized at start of process
exTask.tr_allocate = addTransformationTransition(net, "tr_allocate_" + task.getId(), task.getLabel(),"allocate", copyXsltURL);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL);
//addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl");
exTask.tr_allocate.setRolename(rolename);
if (task.isSkippable()) {
// skip Transition
exTask.setSkippable(true);
exTask.tr_skip = addTransformationTransition(net, "tr_skip_" + task.getId(), task.getLabel(), "skip", copyXsltURL);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl");
}
// submit Transition
FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings);
submit.setAction("submit");
exTask.tr_submit = submit;
addFlowRelationship(net, exTask.pl_running, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl");
exTask.tr_submit.setRolename(rolename);
// delegate Transition
FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), task.getLabel(),model,form,bindings);
delegate.setAction("delegate");
delegate.setGuard(exTask.pl_context.getId() + ".isDelegated == 'true'");
exTask.tr_delegate = delegate;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl");
exTask.tr_delegate.setRolename(rolename);
// review Transition
FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), task.getLabel(),model,form,bindings);
review.setAction("review");
review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed == 'true'");
exTask.tr_review = review;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl");
exTask.tr_review.setRolename(rolename);
// done Transition
exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), task.getLabel());
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done);
addFlowRelationship(net, exTask.tr_done, exTask.pl_complete);
addFlowRelationship(net, exTask.pl_context, exTask.tr_done);
addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl");
exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed != 'true'");
// suspend/resume
exTask.tr_suspend = addTransformationTransition(net, "tr_suspend_" + task.getId(), task.getLabel(), "suspend", copyXsltURL);
addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl");
exTask.tr_suspend.setRolename(rolename);
// resume
exTask.tr_resume = addTransformationTransition(net, "tr_resume_" + task.getId(), task.getLabel(), "resume", copyXsltURL);
addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl");
exTask.tr_resume.setRolename(rolename);
// finish transition
exTask.tr_finish = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel());
addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl");
taskList.add(exTask);
handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c);
if (c.ancestorHasExcpH)
handleExceptions(net, task, exTask.tr_submit, c);
for (IntermediateEvent event : task.getAttachedEvents())
handleAttachedIntermediateEventForTask(net, event, c);
}
| protected void handleTask(PetriNet net, Task task, ConversionContext c) {
ExecTask exTask = new ExecTask();
exTask.setId(task.getId());
exTask.setLabel(task.getLabel());
// create proper model, form and bindings
String model = null;
String form = null;
String bindings = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
try {
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
Document modelDoc = parser.newDocument();
Element dataEl = modelDoc.createElement("data");
Node data = modelDoc.appendChild(dataEl);
Node metaData = data.appendChild(modelDoc.createElement("metadata"));
Node processData = data.appendChild(modelDoc.createElement("processdata"));
// create MetaData Layout for Task model
// (take attention to the fact, that the attributes are again defined in the engine)
Node startTime = metaData.appendChild(modelDoc.createElement("startTime"));
Node endTime = metaData.appendChild(modelDoc.createElement("endTime"));
Node status = metaData.appendChild(modelDoc.createElement("status"));
Node owner = metaData.appendChild(modelDoc.createElement("owner"));
Node isDelegated = metaData.appendChild(modelDoc.createElement("isDelegated"));
Node reviewRequested = metaData.appendChild(modelDoc.createElement("reviewRequested"));
Node firstOwner = metaData.appendChild(modelDoc.createElement("firstOwner"));
Node actions = metaData.appendChild(modelDoc.createElement("actions"));
// create MetaData Layout Actions, that will be logged --> here not regarded
// interrogate all incoming data objects for task, create DataPlaces for them and create Task model
List<Edge> edges_in = task.getIncomingEdges();
for (Edge edge : edges_in) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
// for incoming data objects of task: create read dependencies
addReadOnlyExecFlowRelationship(net, exTask.tr_enable, ExecTask.getDataPlace(dataObject.getId()),null);
// create XML Structure for Task
String modelXML = dataObject.getModel();
StringBufferInputStream in = new StringBufferInputStream(modelXML);
try {
//TODO why is Parser not working?
Document doc = parser.parse(in);
Node dataObjectId = processData.appendChild(modelDoc.createElement(dataObject.getId()));
Node dataTagOfDataModel = doc.getDocumentElement().getFirstChild();
Node child = dataTagOfDataModel.getFirstChild();
while (child != null) {
dataObjectId.appendChild(child.cloneNode(true));
child = child.getNextSibling();
};
} catch (Exception io) {
io.printStackTrace();
}
}
}
// interrogate all outgoing data objects for task and create flow relationships for them
List<Edge> edges_out = task.getOutgoingEdges();
for (Edge edge : edges_in) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
// for outgoing data objects of task: create read/write dependencies
addReadOnlyExecFlowRelationship(net, exTask.tr_enable, ExecTask.getDataPlace(dataObject.getId()),null);
addFlowRelationship(net, exTask.tr_finish, ExecTask.getDataPlace(dataObject.getId()));
addFlowRelationship(net, ExecTask.getDataPlace(dataObject.getId()), exTask.tr_finish);
}
}
// persist model and deliver URL
try {
//DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
//DOMImplementationLS implLS = (DOMImplementationLS)registry.getDOMImplementation("LS");
//LSSerializer dom3Writer = implLS.createLSSerializer();
//LSOutput output=implLS.createLSOutput();
//OutputStream outputStream = new FileOutputStream(new File(this.baseFileName+"_"+ task.getId() +"_model"+".xml"));
//output.setByteStream(outputStream);
//dom3Writer.write(modelDoc,output);
} catch (Exception e) {
System.out.println("Model could not be persisted");
e.printStackTrace();
}
// // from Task model (modelDoc) extract formular and bindings
// Document formDoc = parser.newDocument();
// Document bindDoc = parser.newDocument();
// // create structure of form
// // TODO how can process be shown up? Delegated from? Delegate?
// Text text = formDoc.createTextNode(
// "<b> Logged in as user: </b>/n"+
// "<x:output ref=\"instance('output-token')/data/metadata/owner\" />/n"+
// "<x:group>/n"+
// " <x:output bind=\"delegationstate\"><h2> Delegate task </h2></x:output>/n"+
// " <x:output bind=\"executionstate\"><h2> Execute task </h2></x:output>/n"+
// " <x:output bind=\"reviewstate\"><h2> Review task </h2></x:output>/n"+
// "</x:group>/n"+
// "<br /><br />/n"+
// "<x:group ref=\"instance('ui_settings')/delegategroup\" >/n"+
// " <x:select1 ref=\"instance('output-token')/data/metadata/delegate\" class=\"delegator\"> /n"+
// " <x:label> Delegate to: </x:label>/n"+
// " <x:item>/n"+
// " <x:label>Adam</x:label>/n"+
// " <x:value>Adam</x:value> /n"+
// " </x:item>/n"+
// " <x:item>/n"+
// " <x:label>Bert</x:label>/n"+
// " <x:value>Bert</x:value>/n"+
// " </x:item>/n"+
// " <x:item>/n"+
// " <x:label>Hugo</x:label>/n"+
// " <x:value>Hugo</x:value>/n"+
// " </x:item>/n"+
// " <x:item>/n"+
// " <x:label>Rudi</x:label>/n"+
// " <x:value>Rudi</x:value>/n"+
// " </x:item> /n"+
// "</x:select1>/n"+
// "</x:group>/n"+
// "<br />/n"+
// "<x:group bind=\"fade.delegatedfrom\"><x:output ref=\"instance('output-token')/data/metadata/delegatedfrom\" class=\"delegator\">/n"+
// " <x:label> Delegated from: </x:label>/n"+
// "</x:output></x:group>/n"+
// "<br/><br />/n"+
// "<x:group bind=\"fade.message\"><x:input ref=\"instance('output-token')/data/processdata/message\" class=\"metainfo\">/n"+
// " <x:label> Message: </x:label>/n"+
// "</x:input></x:group>/n"+
// "<br/><br />/n"+
// "<x:group bind=\"fade.deadline\"><x:input ref=\"instance('output-token')/data/processdata/deadline\" class=\"metainfo\">/n"+
// " <x:label> Deadline: </x:label>/n"+
// "</x:input></x:group>/n"+
// "<br/><br />/n"+
// "<x:group bind=\"wantToReviewGroup\">/n"+
// " <x:input ref=\"instance('output-token')/data/metadata/reviewRequested\" class=\"metainfo\">/n"+
// " <x:label> Responsible: </x:label>/n"+
// " </x:input>/n"+
// "</x:group>/n"+
// "<br/><br />/n"+
// "/n"+
// "<x:group ref=\"instance('ui_settings')/delegationstate\">/n"+
// " <br/><br />/n"+
// " <div class=\"labels\"> <b>readonly readable</b> </div>/n"+
// " <br/>/n"+
// "</x:group>/n"
// );
// formDoc.appendChild(text);
// build form fields of necessary attributes
// TODO persist form and bindings and save URL
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_running = addPlace(net, "pl_running_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_context = addPlace(net, "pl_context_" + task.getId(), ExecPlace.Type.context);
// add role dependencies
String rolename = task.getRolename();
// integrate context place
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime"));
exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime"));
exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status"));
exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/metadata/owner"));
exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isDelegated"));
exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isreviewed"));
exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested"));
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner"));
exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions"));
//enable transition
//TODO: read/write to context place
exTask.tr_enable = addAutomaticTransition(net, "tr_enable_" + task.getId(), task.getLabel());
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable);
addFlowRelationship(net, exTask.tr_enable, exTask.pl_ready);
// allocate Transition
//TODO: change context_allocate when context place gets initialized at start of process
exTask.tr_allocate = addTransformationTransition(net, "tr_allocate_" + task.getId(), task.getLabel(),"allocate", copyXsltURL);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractDataURL);
//addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl");
exTask.tr_allocate.setRolename(rolename);
if (task.isSkippable()) {
// skip Transition
exTask.setSkippable(true);
exTask.tr_skip = addTransformationTransition(net, "tr_skip_" + task.getId(), task.getLabel(), "skip", copyXsltURL);
addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl");
}
// submit Transition
FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel(), model, form, bindings);
submit.setAction("submit");
exTask.tr_submit = submit;
addFlowRelationship(net, exTask.pl_running, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl");
exTask.tr_submit.setRolename(rolename);
// delegate Transition
FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), task.getLabel(),model,form,bindings);
delegate.setAction("delegate");
delegate.setGuard(exTask.pl_context.getId() + ".isDelegated == 'true'");
exTask.tr_delegate = delegate;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl");
exTask.tr_delegate.setRolename(rolename);
// review Transition
FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), task.getLabel(),model,form,bindings);
review.setAction("review");
review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed == 'true'");
exTask.tr_review = review;
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl");
exTask.tr_review.setRolename(rolename);
// done Transition
exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), task.getLabel());
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done);
addFlowRelationship(net, exTask.tr_done, exTask.pl_complete);
addFlowRelationship(net, exTask.pl_context, exTask.tr_done);
addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl");
exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".isReviewed != 'true'");
// suspend/resume
exTask.tr_suspend = addTransformationTransition(net, "tr_suspend_" + task.getId(), task.getLabel(), "suspend", copyXsltURL);
addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl");
exTask.tr_suspend.setRolename(rolename);
// resume
exTask.tr_resume = addTransformationTransition(net, "tr_resume_" + task.getId(), task.getLabel(), "resume", copyXsltURL);
addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl");
exTask.tr_resume.setRolename(rolename);
// finish transition
exTask.tr_finish = addAutomaticTransition(net, "tr_finish_" + task.getId(), task.getLabel());
addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl");
taskList.add(exTask);
handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c);
if (c.ancestorHasExcpH)
handleExceptions(net, task, exTask.tr_submit, c);
for (IntermediateEvent event : task.getAttachedEvents())
handleAttachedIntermediateEventForTask(net, event, c);
}
|
diff --git a/plugins/org.eclipse.tm.tcf/src/org/eclipse/tm/tcf/protocol/JSON.java b/plugins/org.eclipse.tm.tcf/src/org/eclipse/tm/tcf/protocol/JSON.java
index 88c1da7a2..676ab9f16 100644
--- a/plugins/org.eclipse.tm.tcf/src/org/eclipse/tm/tcf/protocol/JSON.java
+++ b/plugins/org.eclipse.tm.tcf/src/org/eclipse/tm/tcf/protocol/JSON.java
@@ -1,613 +1,613 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 Wind River Systems, Inc. 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tm.tcf.protocol;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* JSON is TCF preferred marshaling. This class implements generation and parsing of JSON strings.
* The code is optimized for speed since it is a time-critical part of the framework.
*
* Reading of JSON produces data structure that consists of objects of these classes:
* Boolean, Number, String, Collection, Map.
*
* Writing of JSON is supported for:
* Boolean, Number, String, char[], byte[], Object[], Collection, Map
*
* Clients can enable writing support for objects of a other classes by
* registering ObjectWriter interface implementation.
*
* @noextend This class is not intended to be subclassed by clients.
* @noinstantiate This class is not intended to be instantiated by clients.
*/
public final class JSON {
/**
* Clients implement ObjectWriter interface when they want to enable marshaling of
* object classes that are not directly supported by JSON library.
*/
public interface ObjectWriter {
void write(Object o) throws IOException;
}
private static final Map<Class<?>,ObjectWriter> object_writers = new HashMap<Class<?>,ObjectWriter>();
private static char[] tmp_buf = new char[0x1000];
private static byte[] tmp_bbf = new byte[0x1000];
private static int tmp_buf_pos;
private static Reader reader;
private static final char[] cur_buf = new char[0x1000];
private static int cur_buf_pos;
private static int cur_buf_len;
private static int cur_ch;
// This buffer is used to create nice error reports
private static final char[] err_buf = new char[100];
private static int err_buf_pos;
private static int err_buf_cnt;
/**
* Add a handler for converting objects of a particular class into JSON.
* @param cls - a class
* @param writer - ObjectWriter implementation that provides generation of JSON for a given class.
*/
public static void addObjectWriter(Class<?> cls, ObjectWriter writer) {
object_writers.put(cls, writer);
}
/**
* Write a character into JSON output buffer.
* Clients should not call this method directly, except from ObjectWriter implementation.
* @param ch
*/
public static void write(char ch) {
if (tmp_buf_pos >= tmp_buf.length) {
char[] tmp = new char[tmp_buf.length * 2];
System.arraycopy(tmp_buf, 0, tmp, 0, tmp_buf_pos);
tmp_buf = tmp;
}
tmp_buf[tmp_buf_pos++] = ch;
}
/**
* Write a string into JSON output buffer.
* The string is written "as-is". Call writeObject() to convert a String into JSON string.
* Clients should not call this method directly, except from ObjectWriter implementation.
* @param s - a string
*/
public static void write(String s) {
int l = s.length();
for (int i = 0; i < l; i++) {
char ch = s.charAt(i);
if (tmp_buf_pos >= tmp_buf.length) write(ch);
else tmp_buf[tmp_buf_pos++] = ch;
}
}
/**
* Write a non-negative integer number into JSON output buffer.
* Clients should not call this method directly, except from ObjectWriter implementation.
* @param n - a number
*/
public static void writeUInt(int n) {
assert n >= 0;
if (n >= 10) writeUInt(n / 10);
write((char)('0' + n % 10));
}
private static void read() throws IOException {
if (cur_buf_pos >= cur_buf_len) {
cur_buf_len = reader.read(cur_buf);
cur_buf_pos = 0;
if (cur_buf_len < 0) {
cur_buf_len = 0;
cur_ch = -1;
return;
}
}
cur_ch = cur_buf[cur_buf_pos++];
err_buf[err_buf_pos++] = (char)cur_ch;
if (err_buf_pos >= err_buf.length) {
err_buf_pos = 0;
err_buf_cnt++;
}
}
private static void error() throws IOException {
error("syntax error");
}
private static void error(String msg) throws IOException {
StringBuffer bf = new StringBuffer();
bf.append("JSON " + msg + ":");
int cnt = 0;
boolean nl = true;
for (int i = 0;; i++) {
char ch = 0;
if (err_buf_cnt == 0 && i < err_buf_pos) {
ch = err_buf[i];
}
else if (err_buf_cnt > 0 && i < err_buf.length) {
ch = err_buf[(err_buf_pos + i) % err_buf.length];
}
else {
int n = reader.read();
if (n < 0) break;
ch = (char)n;
}
if (nl) {
bf.append("\n ");
if (err_buf_cnt == 0) bf.append(cnt);
else bf.append('*');
bf.append(": ");
if (cnt == 0 && err_buf_cnt > 0) bf.append("...");
nl = false;
}
if (ch == 0) {
cnt++;
nl = true;
continue;
}
bf.append(ch);
}
throw new IOException(bf.toString());
}
private static int readHexDigit() throws IOException {
int n = 0;
if (cur_ch >= '0' && cur_ch <= '9') n = cur_ch - '0';
else if (cur_ch >= 'A' && cur_ch <= 'F') n = cur_ch - 'A' + 10;
else if (cur_ch >= 'a' && cur_ch <= 'f') n = cur_ch - 'a' + 10;
else error();
read();
return n;
}
private static Object readFloat(BigInteger val) throws IOException {
int scale = 0;
int fraction = 0;
if (cur_ch == '.') {
read();
while (cur_ch >= '0' && cur_ch <= '9') {
val = val.multiply(BigInteger.valueOf(10));
val = val.add(BigInteger.valueOf(cur_ch - '0'));
fraction++;
read();
}
}
if (cur_ch == 'E' || cur_ch == 'e') {
read();
boolean neg = cur_ch == '-';
if (neg || cur_ch == '+') read();
while (cur_ch >= '0' && cur_ch <= '9') {
scale = scale * 10 + cur_ch - '0';
read();
}
}
// the scale is <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
// the negative power!?!
return new BigDecimal(val, fraction - scale);
}
private static Object readNestedObject() throws IOException {
switch (cur_ch) {
case '"':
read();
tmp_buf_pos = 0;
for (;;) {
if (cur_ch <= 0) error();
if (cur_ch == '"') break;
if (cur_ch == '\\') {
read();
if (cur_ch <= 0) error();
switch (cur_ch) {
case '"':
case '\\':
case '/':
break;
case 'b':
cur_ch = '\b';
break;
case 'f':
cur_ch = '\f';
break;
case 'n':
cur_ch = '\n';
break;
case 'r':
cur_ch = '\r';
break;
case 't':
cur_ch = '\t';
break;
case 'u':
read();
int n = 0;
n |= readHexDigit() << 12;
n |= readHexDigit() << 8;
n |= readHexDigit() << 4;
n |= readHexDigit();
write((char)n);
continue;
default:
error();
break;
}
}
if (tmp_buf_pos >= tmp_buf.length) {
write((char)cur_ch);
}
else {
tmp_buf[tmp_buf_pos++] = (char)cur_ch;
}
if (cur_buf_pos >= cur_buf_len) {
read();
}
else {
cur_ch = cur_buf[cur_buf_pos++];
err_buf[err_buf_pos++] = (char)cur_ch;
if (err_buf_pos >= err_buf.length) {
err_buf_pos = 0;
err_buf_cnt++;
}
}
}
read();
return new String(tmp_buf, 0, tmp_buf_pos);
case '[':
- Collection<Object> l = new ArrayList<Object>();
+ List<Object> l = new ArrayList<Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != ']') {
for (;;) {
l.add(readNestedObject());
if (cur_ch == ']') break;
if (cur_ch != ',') error();
read();
}
}
read();
- return Collections.unmodifiableCollection(l);
+ return Collections.unmodifiableList(l);
case '{':
Map<String,Object> m = new HashMap<String,Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != '}') {
for (;;) {
String key = (String)readNestedObject();
if (cur_ch != ':') error();
read();
Object val = readNestedObject();
m.put(key, val);
if (cur_ch == '}') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableMap(m);
case 'n':
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 'l') error();
read();
return null;
case 'f':
read();
if (cur_ch != 'a') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 's') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.FALSE;
case 't':
read();
if (cur_ch != 'r') error();
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.TRUE;
default:
boolean neg = cur_ch == '-';
if (neg) read();
if (cur_ch >= '0' && cur_ch <= '9') {
int v = 0;
while (v <= 0x7fffffff / 10 - 1) {
v = v * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (neg) v = -v;
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(BigInteger.valueOf(v));
}
return Integer.valueOf(v);
}
}
long vl = v;
while (vl < 0x7fffffffffffffffl / 10 - 1) {
vl = vl * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (neg) vl = -vl;
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(BigInteger.valueOf(vl));
}
return Long.valueOf(vl);
}
}
StringBuffer sb = new StringBuffer();
if (neg) sb.append('-');
sb.append(vl);
while (true) {
sb.append(cur_ch);
read();
if (cur_ch < '0' || cur_ch > '9') {
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(new BigInteger(sb.toString()));
}
return new BigInteger(sb.toString());
}
}
}
error();
return null;
}
}
private static Object readObject() throws IOException {
Object o = readNestedObject();
if (cur_ch >= 0) error();
return o;
}
private static Object[] readSequence() throws IOException {
List<Object> l = new ArrayList<Object>();
while (cur_ch >= 0) {
if (cur_ch == 0) l.add(null);
else l.add(readNestedObject());
if (cur_ch != 0) error("missing \\0 terminator");
read();
}
return l.toArray();
}
/**
* Write an object into JSON output buffer.
* Clients should not call this method directly, except from ObjectWriter implementation.
* @param o - an object to write
*/
@SuppressWarnings("unchecked")
public static void writeObject(Object o) throws IOException {
if (o == null) {
write("null");
}
else if (o instanceof Boolean) {
write(o.toString());
}
else if (o instanceof Number) {
write(o.toString());
}
else if (o instanceof String) {
String s = (String)o;
char[] arr = new char[s.length()];
s.getChars(0, arr.length, arr, 0);
writeObject(arr);
}
else if (o instanceof char[]) {
char[] s = (char[])o;
write('"');
int l = s.length;
for (int i = 0; i < l; i++) {
char ch = s[i];
switch (ch) {
case 0:
write("\\u0000");
break;
case '\r':
write("\\r");
break;
case '\n':
write("\\n");
break;
case '\t':
write("\\t");
break;
case '\b':
write("\\b");
break;
case '\f':
write("\\f");
break;
case '"':
case '\\':
write('\\');
default:
if (tmp_buf_pos >= tmp_buf.length) write(ch);
else tmp_buf[tmp_buf_pos++] = ch;
}
}
write('"');
}
else if (o instanceof byte[]) {
write('[');
byte[] arr = (byte[])o;
boolean comma = false;
for (int i = 0; i < arr.length; i++) {
if (comma) write(',');
writeUInt(arr[i] & 0xff);
comma = true;
}
write(']');
}
else if (o instanceof Object[]) {
write('[');
Object[] arr = (Object[])o;
boolean comma = false;
for (int i = 0; i < arr.length; i++) {
if (comma) write(',');
writeObject(arr[i]);
comma = true;
}
write(']');
}
else if (o instanceof Collection) {
write('[');
boolean comma = false;
for (Iterator<Object> i = ((Collection<Object>)o).iterator(); i.hasNext();) {
if (comma) write(',');
writeObject(i.next());
comma = true;
}
write(']');
}
else if (o instanceof Map) {
Map<String,Object> map = (Map<String,Object>)o;
write('{');
boolean comma = false;
for (Iterator<Map.Entry<String,Object>> i = map.entrySet().iterator(); i.hasNext();) {
if (comma) write(',');
Map.Entry<String,Object> e = i.next();
writeObject(e.getKey());
write(':');
writeObject(e.getValue());
comma = true;
}
write('}');
}
else {
ObjectWriter writer = object_writers.get(o.getClass());
if (writer != null) {
writer.write(o);
}
else {
throw new IOException("JSON: unsupported object type");
}
}
}
private static byte[] toBytes() throws UnsupportedEncodingException {
int inp_pos = 0;
int out_pos = 0;
while (inp_pos < tmp_buf_pos) {
if (out_pos >= tmp_bbf.length - 4) {
byte[] tmp = new byte[tmp_bbf.length * 2];
System.arraycopy(tmp_bbf, 0, tmp, 0, out_pos);
tmp_bbf = tmp;
}
int ch = tmp_buf[inp_pos++];
if (ch < 0x80) {
tmp_bbf[out_pos++] = (byte)ch;
}
else if (ch < 0x800) {
tmp_bbf[out_pos++] = (byte)((ch >> 6) | 0xc0);
tmp_bbf[out_pos++] = (byte)(ch & 0x3f | 0x80);
}
else if (ch < 0x10000) {
tmp_bbf[out_pos++] = (byte)((ch >> 12) | 0xe0);
tmp_bbf[out_pos++] = (byte)((ch >> 6) & 0x3f | 0x80);
tmp_bbf[out_pos++] = (byte)(ch & 0x3f | 0x80);
}
else {
tmp_bbf[out_pos++] = (byte)((ch >> 18) | 0xf0);
tmp_bbf[out_pos++] = (byte)((ch >> 12) & 0x3f | 0x80);
tmp_bbf[out_pos++] = (byte)((ch >> 6) & 0x3f | 0x80);
tmp_bbf[out_pos++] = (byte)(ch & 0x3f | 0x80);
}
}
byte[] res = new byte[out_pos];
System.arraycopy(tmp_bbf, 0, res, 0, out_pos);
return res;
}
public static String toJSON(Object o) throws IOException {
assert Protocol.isDispatchThread();
tmp_buf_pos = 0;
writeObject(o);
return new String(tmp_buf, 0, tmp_buf_pos);
}
public static byte[] toJASONBytes(Object o) throws IOException {
assert Protocol.isDispatchThread();
tmp_buf_pos = 0;
writeObject(o);
return toBytes();
}
public static byte[] toJSONSequence(Object[] o) throws IOException {
assert Protocol.isDispatchThread();
if (o == null || o.length == 0) return null;
tmp_buf_pos = 0;
for (int i = 0; i < o.length; i++) {
writeObject(o[i]);
write((char)0);
}
return toBytes();
}
public static Object parseOne(String s) throws IOException {
assert Protocol.isDispatchThread();
if (s.length() == 0) return null;
reader = new StringReader(s);
err_buf_pos = 0;
err_buf_cnt = 0;
cur_buf_pos = 0;
cur_buf_len = 0;
read();
return readObject();
}
public static Object parseOne(byte[] b) throws IOException {
assert Protocol.isDispatchThread();
if (b.length == 0) return null;
reader = new InputStreamReader(new ByteArrayInputStream(b), "UTF8");
err_buf_pos = 0;
err_buf_cnt = 0;
cur_buf_pos = 0;
cur_buf_len = 0;
read();
return readObject();
}
public static Object[] parseSequence(byte[] b) throws IOException {
assert Protocol.isDispatchThread();
reader = new InputStreamReader(new ByteArrayInputStream(b), "UTF8");
err_buf_pos = 0;
err_buf_cnt = 0;
cur_buf_pos = 0;
cur_buf_len = 0;
read();
return readSequence();
}
}
| false | true | private static Object readNestedObject() throws IOException {
switch (cur_ch) {
case '"':
read();
tmp_buf_pos = 0;
for (;;) {
if (cur_ch <= 0) error();
if (cur_ch == '"') break;
if (cur_ch == '\\') {
read();
if (cur_ch <= 0) error();
switch (cur_ch) {
case '"':
case '\\':
case '/':
break;
case 'b':
cur_ch = '\b';
break;
case 'f':
cur_ch = '\f';
break;
case 'n':
cur_ch = '\n';
break;
case 'r':
cur_ch = '\r';
break;
case 't':
cur_ch = '\t';
break;
case 'u':
read();
int n = 0;
n |= readHexDigit() << 12;
n |= readHexDigit() << 8;
n |= readHexDigit() << 4;
n |= readHexDigit();
write((char)n);
continue;
default:
error();
break;
}
}
if (tmp_buf_pos >= tmp_buf.length) {
write((char)cur_ch);
}
else {
tmp_buf[tmp_buf_pos++] = (char)cur_ch;
}
if (cur_buf_pos >= cur_buf_len) {
read();
}
else {
cur_ch = cur_buf[cur_buf_pos++];
err_buf[err_buf_pos++] = (char)cur_ch;
if (err_buf_pos >= err_buf.length) {
err_buf_pos = 0;
err_buf_cnt++;
}
}
}
read();
return new String(tmp_buf, 0, tmp_buf_pos);
case '[':
Collection<Object> l = new ArrayList<Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != ']') {
for (;;) {
l.add(readNestedObject());
if (cur_ch == ']') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableCollection(l);
case '{':
Map<String,Object> m = new HashMap<String,Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != '}') {
for (;;) {
String key = (String)readNestedObject();
if (cur_ch != ':') error();
read();
Object val = readNestedObject();
m.put(key, val);
if (cur_ch == '}') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableMap(m);
case 'n':
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 'l') error();
read();
return null;
case 'f':
read();
if (cur_ch != 'a') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 's') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.FALSE;
case 't':
read();
if (cur_ch != 'r') error();
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.TRUE;
default:
boolean neg = cur_ch == '-';
if (neg) read();
if (cur_ch >= '0' && cur_ch <= '9') {
int v = 0;
while (v <= 0x7fffffff / 10 - 1) {
v = v * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (neg) v = -v;
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(BigInteger.valueOf(v));
}
return Integer.valueOf(v);
}
}
long vl = v;
while (vl < 0x7fffffffffffffffl / 10 - 1) {
vl = vl * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (neg) vl = -vl;
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(BigInteger.valueOf(vl));
}
return Long.valueOf(vl);
}
}
StringBuffer sb = new StringBuffer();
if (neg) sb.append('-');
sb.append(vl);
while (true) {
sb.append(cur_ch);
read();
if (cur_ch < '0' || cur_ch > '9') {
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(new BigInteger(sb.toString()));
}
return new BigInteger(sb.toString());
}
}
}
error();
return null;
}
}
| private static Object readNestedObject() throws IOException {
switch (cur_ch) {
case '"':
read();
tmp_buf_pos = 0;
for (;;) {
if (cur_ch <= 0) error();
if (cur_ch == '"') break;
if (cur_ch == '\\') {
read();
if (cur_ch <= 0) error();
switch (cur_ch) {
case '"':
case '\\':
case '/':
break;
case 'b':
cur_ch = '\b';
break;
case 'f':
cur_ch = '\f';
break;
case 'n':
cur_ch = '\n';
break;
case 'r':
cur_ch = '\r';
break;
case 't':
cur_ch = '\t';
break;
case 'u':
read();
int n = 0;
n |= readHexDigit() << 12;
n |= readHexDigit() << 8;
n |= readHexDigit() << 4;
n |= readHexDigit();
write((char)n);
continue;
default:
error();
break;
}
}
if (tmp_buf_pos >= tmp_buf.length) {
write((char)cur_ch);
}
else {
tmp_buf[tmp_buf_pos++] = (char)cur_ch;
}
if (cur_buf_pos >= cur_buf_len) {
read();
}
else {
cur_ch = cur_buf[cur_buf_pos++];
err_buf[err_buf_pos++] = (char)cur_ch;
if (err_buf_pos >= err_buf.length) {
err_buf_pos = 0;
err_buf_cnt++;
}
}
}
read();
return new String(tmp_buf, 0, tmp_buf_pos);
case '[':
List<Object> l = new ArrayList<Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != ']') {
for (;;) {
l.add(readNestedObject());
if (cur_ch == ']') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableList(l);
case '{':
Map<String,Object> m = new HashMap<String,Object>();
read();
if (cur_ch <= 0) error();
if (cur_ch != '}') {
for (;;) {
String key = (String)readNestedObject();
if (cur_ch != ':') error();
read();
Object val = readNestedObject();
m.put(key, val);
if (cur_ch == '}') break;
if (cur_ch != ',') error();
read();
}
}
read();
return Collections.unmodifiableMap(m);
case 'n':
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 'l') error();
read();
return null;
case 'f':
read();
if (cur_ch != 'a') error();
read();
if (cur_ch != 'l') error();
read();
if (cur_ch != 's') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.FALSE;
case 't':
read();
if (cur_ch != 'r') error();
read();
if (cur_ch != 'u') error();
read();
if (cur_ch != 'e') error();
read();
return Boolean.TRUE;
default:
boolean neg = cur_ch == '-';
if (neg) read();
if (cur_ch >= '0' && cur_ch <= '9') {
int v = 0;
while (v <= 0x7fffffff / 10 - 1) {
v = v * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (neg) v = -v;
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(BigInteger.valueOf(v));
}
return Integer.valueOf(v);
}
}
long vl = v;
while (vl < 0x7fffffffffffffffl / 10 - 1) {
vl = vl * 10 + (cur_ch - '0');
read();
if (cur_ch < '0' || cur_ch > '9') {
if (neg) vl = -vl;
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(BigInteger.valueOf(vl));
}
return Long.valueOf(vl);
}
}
StringBuffer sb = new StringBuffer();
if (neg) sb.append('-');
sb.append(vl);
while (true) {
sb.append(cur_ch);
read();
if (cur_ch < '0' || cur_ch > '9') {
if (cur_ch == '.' || cur_ch == 'E' || cur_ch == 'e') {
return readFloat(new BigInteger(sb.toString()));
}
return new BigInteger(sb.toString());
}
}
}
error();
return null;
}
}
|
diff --git a/hudson-core/src/main/java/hudson/cli/CopyJobCommand.java b/hudson-core/src/main/java/hudson/cli/CopyJobCommand.java
index 6d6fcdc7..3a1ab986 100644
--- a/hudson-core/src/main/java/hudson/cli/CopyJobCommand.java
+++ b/hudson-core/src/main/java/hudson/cli/CopyJobCommand.java
@@ -1,73 +1,74 @@
/*******************************************************************************
*
* Copyright (c) 2004-2010, Oracle 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:
*
*
*
*
*******************************************************************************/
package hudson.cli;
import hudson.model.Hudson;
import hudson.model.Job;
import hudson.model.TopLevelItem;
import hudson.Extension;
import static hudson.cli.UpdateJobCommand.ensureJobInTeam;
import static hudson.cli.UpdateJobCommand.validateTeam;
import hudson.model.Item;
import org.eclipse.hudson.security.team.Team;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
/**
* Copies a job from CLI.
*
* @author Kohsuke Kawaguchi
*/
@Extension
public class CopyJobCommand extends CLICommand {
@Override
public String getShortDescription() {
return "Copies a job";
}
@Argument(metaVar = "SRC", usage = "Name of the job to copy. Provide team qualified name if Team Management is enabled. Ex: team1.job1.", required = true)
public TopLevelItem src;
@Argument(metaVar = "DST", usage = "Name of the new job to be created. The job name should not be team qualified. Ex: job1 ", index = 1, required = true)
public String dst;
@Argument(metaVar = "TEAM", usage = "Team to create the job in.", index = 2, required = false)
public String team;
@Option(name = "-fs", aliases = {"--force-save"}, usage = "Force saving the destination job in order to enable build functionality.")
public boolean forceSave;
protected int run() throws Exception {
Hudson h = Hudson.getInstance();
h.checkPermission(Item.CREATE);
Team targetTeam = validateTeam(team, true, stderr);
if (team != null && targetTeam == null) {
return -1;
}
if (h.getItem(dst) != null) {
stderr.println("Job '" + dst + "' already exists");
return -1;
}
- h.copy(src, dst);
- TopLevelItem newJob = Hudson.getInstance().getItem(dst);
+ TopLevelItem newJob = h.copy(src, dst);
+ // Ensure this is a real job
+ newJob = h.getItem(newJob.getName());
ensureJobInTeam(newJob, targetTeam, dst, stderr);
if (forceSave && null != newJob) {
newJob.save();
}
return 0;
}
}
| true | true | protected int run() throws Exception {
Hudson h = Hudson.getInstance();
h.checkPermission(Item.CREATE);
Team targetTeam = validateTeam(team, true, stderr);
if (team != null && targetTeam == null) {
return -1;
}
if (h.getItem(dst) != null) {
stderr.println("Job '" + dst + "' already exists");
return -1;
}
h.copy(src, dst);
TopLevelItem newJob = Hudson.getInstance().getItem(dst);
ensureJobInTeam(newJob, targetTeam, dst, stderr);
if (forceSave && null != newJob) {
newJob.save();
}
return 0;
}
| protected int run() throws Exception {
Hudson h = Hudson.getInstance();
h.checkPermission(Item.CREATE);
Team targetTeam = validateTeam(team, true, stderr);
if (team != null && targetTeam == null) {
return -1;
}
if (h.getItem(dst) != null) {
stderr.println("Job '" + dst + "' already exists");
return -1;
}
TopLevelItem newJob = h.copy(src, dst);
// Ensure this is a real job
newJob = h.getItem(newJob.getName());
ensureJobInTeam(newJob, targetTeam, dst, stderr);
if (forceSave && null != newJob) {
newJob.save();
}
return 0;
}
|
diff --git a/org.python.pydev.debug/src/org/python/pydev/debug/core/PydevDebugPlugin.java b/org.python.pydev.debug/src/org/python/pydev/debug/core/PydevDebugPlugin.java
index 6f6466712..bae53eca2 100644
--- a/org.python.pydev.debug/src/org/python/pydev/debug/core/PydevDebugPlugin.java
+++ b/org.python.pydev.debug/src/org/python/pydev/debug/core/PydevDebugPlugin.java
@@ -1,85 +1,85 @@
package org.python.pydev.debug.core;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.plugin.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.resources.*;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.osgi.framework.BundleContext;
import org.python.pydev.ui.ImageCache;
/**
* The main plugin for Python Debugger.
*
* Standard plugin functionality: preferences, logging, some utility functions
*/
public class PydevDebugPlugin extends AbstractUIPlugin {
//The shared instance.
private static PydevDebugPlugin plugin;
public ImageCache imageCache;
public PydevDebugPlugin() {
plugin = this;
}
public void start(BundleContext context) throws Exception {
super.start(context);
imageCache = new ImageCache(PydevDebugPlugin.getDefault().getBundle().getEntry("/"));
}
public static PydevDebugPlugin getDefault() {
return plugin;
}
public static String getPluginID() {
return getDefault().getBundle().getSymbolicName();
}
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
public static ImageCache getImageCache() {
return plugin.imageCache;
}
protected void initializeDefaultPluginPreferences() {
PydevDebugPrefs.initializeDefaultPreferences(getPluginPreferences());
}
/**
* Returns the active workbench window or <code>null</code> if none
*/
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return getDefault().getWorkbench().getActiveWorkbenchWindow();
}
public static Status makeStatus(int errorLevel, String message, Throwable e) {
return new Status(errorLevel, getPluginID(), errorLevel, message, e);
}
/**
* @param errorLevel IStatus.[OK|INFO|WARNING|ERROR]
*/
public static void log(int errorLevel, String message, Throwable e) {
Status s = makeStatus(errorLevel, message, e);
getDefault().getLog().log(s);
}
public static void errorDialog(final String message, final Throwable t) {
- Display disp = Display.getCurrent();
+ Display disp = Display.getDefault();
disp.asyncExec(new Runnable() {
public void run() {
IWorkbenchWindow window = getDefault().getWorkbench().getActiveWorkbenchWindow();
Shell shell = window == null ? null : window.getShell();
if (shell != null) {
IStatus status= makeStatus(IStatus.ERROR, "Error logged from Pydev Debug: ", t);
ErrorDialog.openError(shell, "Its an error", message, status);
}
}
});
log(IStatus.ERROR, message, t);
}
}
| true | true | public static void errorDialog(final String message, final Throwable t) {
Display disp = Display.getCurrent();
disp.asyncExec(new Runnable() {
public void run() {
IWorkbenchWindow window = getDefault().getWorkbench().getActiveWorkbenchWindow();
Shell shell = window == null ? null : window.getShell();
if (shell != null) {
IStatus status= makeStatus(IStatus.ERROR, "Error logged from Pydev Debug: ", t);
ErrorDialog.openError(shell, "Its an error", message, status);
}
}
});
log(IStatus.ERROR, message, t);
}
| public static void errorDialog(final String message, final Throwable t) {
Display disp = Display.getDefault();
disp.asyncExec(new Runnable() {
public void run() {
IWorkbenchWindow window = getDefault().getWorkbench().getActiveWorkbenchWindow();
Shell shell = window == null ? null : window.getShell();
if (shell != null) {
IStatus status= makeStatus(IStatus.ERROR, "Error logged from Pydev Debug: ", t);
ErrorDialog.openError(shell, "Its an error", message, status);
}
}
});
log(IStatus.ERROR, message, t);
}
|
diff --git a/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java b/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
index b1285ea8..7133fa16 100644
--- a/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
+++ b/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
@@ -1,406 +1,399 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.policy.impl;
import java.util.List;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Rect;
import com.android.internal.widget.LockPatternUtils;
import com.android.internal.widget.PasswordEntryKeyboardView;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.provider.Settings;
import android.security.KeyStore;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.text.method.TextKeyListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.inputmethod.InputMethodSubtype;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Space;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.android.internal.R;
import com.android.internal.widget.PasswordEntryKeyboardHelper;
/**
* Displays a dialer-like interface or alphanumeric (latin-1) key entry for the user to enter
* an unlock password
*/
public class PasswordUnlockScreen extends LinearLayout implements KeyguardScreen,
OnEditorActionListener {
private static final String TAG = "PasswordUnlockScreen";
private final KeyguardUpdateMonitor mUpdateMonitor;
private final KeyguardScreenCallback mCallback;
private final boolean mIsAlpha;
private final EditText mPasswordEntry;
private final LockPatternUtils mLockPatternUtils;
private final PasswordEntryKeyboardView mKeyboardView;
private final PasswordEntryKeyboardHelper mKeyboardHelper;
private final int mCreationOrientation;
private final int mCreationHardKeyboardHidden;
private final KeyguardStatusViewManager mStatusViewManager;
private final boolean mUseSystemIME = true; // TODO: Make configurable
private boolean mResuming; // used to prevent poking the wakelock during onResume()
private boolean mQuickUnlock;
// To avoid accidental lockout due to events while the device in in the pocket, ignore
// any passwords with length less than or equal to this length.
private static final int MINIMUM_PASSWORD_LENGTH_BEFORE_REPORT = 3;
public PasswordUnlockScreen(Context context, Configuration configuration,
LockPatternUtils lockPatternUtils, KeyguardUpdateMonitor updateMonitor,
KeyguardScreenCallback callback) {
super(context);
mCreationHardKeyboardHidden = configuration.hardKeyboardHidden;
mCreationOrientation = configuration.orientation;
mUpdateMonitor = updateMonitor;
mCallback = callback;
mLockPatternUtils = lockPatternUtils;
LayoutInflater layoutInflater = LayoutInflater.from(context);
if (mCreationOrientation != Configuration.ORIENTATION_LANDSCAPE) {
layoutInflater.inflate(R.layout.keyguard_screen_password_portrait, this, true);
} else {
layoutInflater.inflate(R.layout.keyguard_screen_password_landscape, this, true);
}
mStatusViewManager = new KeyguardStatusViewManager(this, mUpdateMonitor, mLockPatternUtils,
mCallback, true);
final int quality = lockPatternUtils.getKeyguardStoredPasswordQuality();
mIsAlpha = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == quality
|| DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == quality
|| DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == quality;
mKeyboardView = (PasswordEntryKeyboardView) findViewById(R.id.keyboard);
mPasswordEntry = (EditText) findViewById(R.id.passwordEntry);
mPasswordEntry.setOnEditorActionListener(this);
mKeyboardHelper = new PasswordEntryKeyboardHelper(context, mKeyboardView, this, false);
mKeyboardHelper.setEnableHaptics(
Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, 0)
!= 0);
boolean imeOrDeleteButtonVisible = false;
if (mIsAlpha) {
// We always use the system IME for alpha keyboard, so hide lockscreen's soft keyboard
mKeyboardHelper.setKeyboardMode(PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA);
mKeyboardView.setVisibility(View.GONE);
} else {
// Use lockscreen's numeric keyboard if the physical keyboard isn't showing
mKeyboardHelper.setKeyboardMode(PasswordEntryKeyboardHelper.KEYBOARD_MODE_NUMERIC);
mKeyboardView.setVisibility(mCreationHardKeyboardHidden
== Configuration.HARDKEYBOARDHIDDEN_NO ? View.INVISIBLE : View.VISIBLE);
// The delete button is of the PIN keyboard itself in some (e.g. tablet) layouts,
// not a separate view
View pinDelete = findViewById(R.id.pinDel);
if (pinDelete != null) {
pinDelete.setVisibility(View.VISIBLE);
imeOrDeleteButtonVisible = true;
pinDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mKeyboardHelper.handleBackspace();
}
});
}
}
mPasswordEntry.requestFocus();
// This allows keyboards with overlapping qwerty/numeric keys to choose just numeric keys.
if (mIsAlpha) {
mPasswordEntry.setKeyListener(TextKeyListener.getInstance());
mPasswordEntry.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
//mStatusViewManager.setHelpMessage(R.string.keyguard_password_enter_password_code,
//KeyguardStatusViewManager.LOCK_ICON);
} else {
mPasswordEntry.setKeyListener(DigitsKeyListener.getInstance());
mPasswordEntry.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_VARIATION_PASSWORD);
//mStatusViewManager.setHelpMessage(R.string.keyguard_password_enter_pin_code,
//KeyguardStatusViewManager.LOCK_ICON);
}
// Poke the wakelock any time the text is selected or modified
mPasswordEntry.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock();
}
});
mQuickUnlock = (Settings.System.getInt(mContext.getContentResolver(), Settings.System.LOCKSCREEN_QUICK_UNLOCK_CONTROL, 0) == 1);
mPasswordEntry.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
if (!mResuming) {
mCallback.pokeWakelock();
}
- if (mQuickUnlock) {
- String entry = mPasswordEntry.getText().toString();
- if (entry.length() > MINIMUM_PASSWORD_LENGTH_BEFORE_REPORT) {
- if (mLockPatternUtils.checkPassword(entry)) {
- mCallback.keyguardDone(true);
- mCallback.reportSuccessfulUnlockAttempt();
- } else {
- mCallback.reportFailedUnlockAttempt();
- if (0 == (mUpdateMonitor.getFailedAttempts() % LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT)) {
- long deadline = mLockPatternUtils.setLockoutAttemptDeadline();
- handleAttemptLockout(deadline);
- }
+ if (mQuickUnlock) {
+ String entry = mPasswordEntry.getText().toString();
+ if (entry.length() > MINIMUM_PASSWORD_LENGTH_BEFORE_REPORT &&
+ mLockPatternUtils.checkPassword(entry)) {
+ mCallback.keyguardDone(true);
+ mCallback.reportSuccessfulUnlockAttempt();
}
}
}
- }
- });
+ });
// If there's more than one IME, enable the IME switcher button
View switchImeButton = findViewById(R.id.switch_ime_button);
final InputMethodManager imm = (InputMethodManager) getContext().getSystemService(
Context.INPUT_METHOD_SERVICE);
if (mIsAlpha && switchImeButton != null && hasMultipleEnabledIMEsOrSubtypes(imm, false)) {
switchImeButton.setVisibility(View.VISIBLE);
imeOrDeleteButtonVisible = true;
switchImeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock(); // Leave the screen on a bit longer
imm.showInputMethodPicker();
}
});
}
// If no icon is visible, reset the left margin on the password field so the text is
// still centered.
if (!imeOrDeleteButtonVisible) {
android.view.ViewGroup.LayoutParams params = mPasswordEntry.getLayoutParams();
if (params instanceof MarginLayoutParams) {
((MarginLayoutParams)params).leftMargin = 0;
mPasswordEntry.setLayoutParams(params);
}
}
}
/**
* Method adapted from com.android.inputmethod.latin.Utils
*
* @param imm The input method manager
* @param shouldIncludeAuxiliarySubtypes
* @return true if we have multiple IMEs to choose from
*/
private boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm,
final boolean shouldIncludeAuxiliarySubtypes) {
final List<InputMethodInfo> enabledImis = imm.getEnabledInputMethodList();
// Number of the filtered IMEs
int filteredImisCount = 0;
for (InputMethodInfo imi : enabledImis) {
// We can return true immediately after we find two or more filtered IMEs.
if (filteredImisCount > 1) return true;
final List<InputMethodSubtype> subtypes =
imm.getEnabledInputMethodSubtypeList(imi, true);
// IMEs that have no subtypes should be counted.
if (subtypes.isEmpty()) {
++filteredImisCount;
continue;
}
int auxCount = 0;
for (InputMethodSubtype subtype : subtypes) {
if (subtype.isAuxiliary()) {
++auxCount;
}
}
final int nonAuxCount = subtypes.size() - auxCount;
// IMEs that have one or more non-auxiliary subtypes should be counted.
// If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary
// subtypes should be counted as well.
if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) {
++filteredImisCount;
continue;
}
}
return filteredImisCount > 1
// imm.getEnabledInputMethodSubtypeList(null, false) will return the current IME's enabled
// input method subtype (The current IME should be LatinIME.)
|| imm.getEnabledInputMethodSubtypeList(null, false).size() > 1;
}
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
// send focus to the password field
return mPasswordEntry.requestFocus(direction, previouslyFocusedRect);
}
/** {@inheritDoc} */
public boolean needsInput() {
return mUseSystemIME && mIsAlpha;
}
/** {@inheritDoc} */
public void onPause() {
mStatusViewManager.onPause();
}
/** {@inheritDoc} */
public void onResume() {
mResuming = true;
// reset status
mStatusViewManager.onResume();
// start fresh
mPasswordEntry.setText("");
mPasswordEntry.requestFocus();
// if the user is currently locked out, enforce it.
long deadline = mLockPatternUtils.getLockoutAttemptDeadline();
if (deadline != 0) {
handleAttemptLockout(deadline);
}
mResuming = false;
}
/** {@inheritDoc} */
public void cleanUp() {
mUpdateMonitor.removeCallback(this);
}
private void verifyPasswordAndUnlock() {
String entry = mPasswordEntry.getText().toString();
if (mLockPatternUtils.checkPassword(entry)) {
mCallback.keyguardDone(true);
mCallback.reportSuccessfulUnlockAttempt();
mStatusViewManager.setInstructionText(null);
KeyStore.getInstance().password(entry);
} else if (entry.length() > MINIMUM_PASSWORD_LENGTH_BEFORE_REPORT ) {
// to avoid accidental lockout, only count attempts that are long enough to be a
// real password. This may require some tweaking.
mCallback.reportFailedUnlockAttempt();
if (0 == (mUpdateMonitor.getFailedAttempts()
% LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT)) {
long deadline = mLockPatternUtils.setLockoutAttemptDeadline();
handleAttemptLockout(deadline);
}
mStatusViewManager.setInstructionText(
mContext.getString(R.string.lockscreen_password_wrong));
} else if (entry.length() > 0) {
mStatusViewManager.setInstructionText(
mContext.getString(R.string.lockscreen_password_wrong));
}
mPasswordEntry.setText("");
}
// Prevent user from using the PIN/Password entry until scheduled deadline.
private void handleAttemptLockout(long elapsedRealtimeDeadline) {
mPasswordEntry.setEnabled(false);
mKeyboardView.setEnabled(false);
long elapsedRealtime = SystemClock.elapsedRealtime();
new CountDownTimer(elapsedRealtimeDeadline - elapsedRealtime, 1000) {
@Override
public void onTick(long millisUntilFinished) {
int secondsRemaining = (int) (millisUntilFinished / 1000);
String instructions = getContext().getString(
R.string.lockscreen_too_many_failed_attempts_countdown,
secondsRemaining);
mStatusViewManager.setInstructionText(instructions);
}
@Override
public void onFinish() {
mPasswordEntry.setEnabled(true);
mKeyboardView.setEnabled(true);
mStatusViewManager.resetStatusInfo();
}
}.start();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
mCallback.pokeWakelock();
return false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Configuration config = getResources().getConfiguration();
if (config.orientation != mCreationOrientation
|| config.hardKeyboardHidden != mCreationHardKeyboardHidden) {
mCallback.recreateMe(config);
}
}
/** {@inheritDoc} */
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation != mCreationOrientation
|| newConfig.hardKeyboardHidden != mCreationHardKeyboardHidden) {
mCallback.recreateMe(newConfig);
}
}
public void onKeyboardChange(boolean isKeyboardOpen) {
// Don't show the soft keyboard when the real keyboard is open
mKeyboardView.setVisibility(isKeyboardOpen ? View.INVISIBLE : View.VISIBLE);
}
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Check if this was the result of hitting the enter key
if (actionId == EditorInfo.IME_NULL || actionId == EditorInfo.IME_ACTION_DONE
|| actionId == EditorInfo.IME_ACTION_NEXT) {
verifyPasswordAndUnlock();
return true;
}
return false;
}
}
| false | true | public PasswordUnlockScreen(Context context, Configuration configuration,
LockPatternUtils lockPatternUtils, KeyguardUpdateMonitor updateMonitor,
KeyguardScreenCallback callback) {
super(context);
mCreationHardKeyboardHidden = configuration.hardKeyboardHidden;
mCreationOrientation = configuration.orientation;
mUpdateMonitor = updateMonitor;
mCallback = callback;
mLockPatternUtils = lockPatternUtils;
LayoutInflater layoutInflater = LayoutInflater.from(context);
if (mCreationOrientation != Configuration.ORIENTATION_LANDSCAPE) {
layoutInflater.inflate(R.layout.keyguard_screen_password_portrait, this, true);
} else {
layoutInflater.inflate(R.layout.keyguard_screen_password_landscape, this, true);
}
mStatusViewManager = new KeyguardStatusViewManager(this, mUpdateMonitor, mLockPatternUtils,
mCallback, true);
final int quality = lockPatternUtils.getKeyguardStoredPasswordQuality();
mIsAlpha = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == quality
|| DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == quality
|| DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == quality;
mKeyboardView = (PasswordEntryKeyboardView) findViewById(R.id.keyboard);
mPasswordEntry = (EditText) findViewById(R.id.passwordEntry);
mPasswordEntry.setOnEditorActionListener(this);
mKeyboardHelper = new PasswordEntryKeyboardHelper(context, mKeyboardView, this, false);
mKeyboardHelper.setEnableHaptics(
Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, 0)
!= 0);
boolean imeOrDeleteButtonVisible = false;
if (mIsAlpha) {
// We always use the system IME for alpha keyboard, so hide lockscreen's soft keyboard
mKeyboardHelper.setKeyboardMode(PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA);
mKeyboardView.setVisibility(View.GONE);
} else {
// Use lockscreen's numeric keyboard if the physical keyboard isn't showing
mKeyboardHelper.setKeyboardMode(PasswordEntryKeyboardHelper.KEYBOARD_MODE_NUMERIC);
mKeyboardView.setVisibility(mCreationHardKeyboardHidden
== Configuration.HARDKEYBOARDHIDDEN_NO ? View.INVISIBLE : View.VISIBLE);
// The delete button is of the PIN keyboard itself in some (e.g. tablet) layouts,
// not a separate view
View pinDelete = findViewById(R.id.pinDel);
if (pinDelete != null) {
pinDelete.setVisibility(View.VISIBLE);
imeOrDeleteButtonVisible = true;
pinDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mKeyboardHelper.handleBackspace();
}
});
}
}
mPasswordEntry.requestFocus();
// This allows keyboards with overlapping qwerty/numeric keys to choose just numeric keys.
if (mIsAlpha) {
mPasswordEntry.setKeyListener(TextKeyListener.getInstance());
mPasswordEntry.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
//mStatusViewManager.setHelpMessage(R.string.keyguard_password_enter_password_code,
//KeyguardStatusViewManager.LOCK_ICON);
} else {
mPasswordEntry.setKeyListener(DigitsKeyListener.getInstance());
mPasswordEntry.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_VARIATION_PASSWORD);
//mStatusViewManager.setHelpMessage(R.string.keyguard_password_enter_pin_code,
//KeyguardStatusViewManager.LOCK_ICON);
}
// Poke the wakelock any time the text is selected or modified
mPasswordEntry.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock();
}
});
mQuickUnlock = (Settings.System.getInt(mContext.getContentResolver(), Settings.System.LOCKSCREEN_QUICK_UNLOCK_CONTROL, 0) == 1);
mPasswordEntry.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
if (!mResuming) {
mCallback.pokeWakelock();
}
if (mQuickUnlock) {
String entry = mPasswordEntry.getText().toString();
if (entry.length() > MINIMUM_PASSWORD_LENGTH_BEFORE_REPORT) {
if (mLockPatternUtils.checkPassword(entry)) {
mCallback.keyguardDone(true);
mCallback.reportSuccessfulUnlockAttempt();
} else {
mCallback.reportFailedUnlockAttempt();
if (0 == (mUpdateMonitor.getFailedAttempts() % LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT)) {
long deadline = mLockPatternUtils.setLockoutAttemptDeadline();
handleAttemptLockout(deadline);
}
}
}
}
}
});
// If there's more than one IME, enable the IME switcher button
View switchImeButton = findViewById(R.id.switch_ime_button);
final InputMethodManager imm = (InputMethodManager) getContext().getSystemService(
Context.INPUT_METHOD_SERVICE);
if (mIsAlpha && switchImeButton != null && hasMultipleEnabledIMEsOrSubtypes(imm, false)) {
switchImeButton.setVisibility(View.VISIBLE);
imeOrDeleteButtonVisible = true;
switchImeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock(); // Leave the screen on a bit longer
imm.showInputMethodPicker();
}
});
}
// If no icon is visible, reset the left margin on the password field so the text is
// still centered.
if (!imeOrDeleteButtonVisible) {
android.view.ViewGroup.LayoutParams params = mPasswordEntry.getLayoutParams();
if (params instanceof MarginLayoutParams) {
((MarginLayoutParams)params).leftMargin = 0;
mPasswordEntry.setLayoutParams(params);
}
}
}
| public PasswordUnlockScreen(Context context, Configuration configuration,
LockPatternUtils lockPatternUtils, KeyguardUpdateMonitor updateMonitor,
KeyguardScreenCallback callback) {
super(context);
mCreationHardKeyboardHidden = configuration.hardKeyboardHidden;
mCreationOrientation = configuration.orientation;
mUpdateMonitor = updateMonitor;
mCallback = callback;
mLockPatternUtils = lockPatternUtils;
LayoutInflater layoutInflater = LayoutInflater.from(context);
if (mCreationOrientation != Configuration.ORIENTATION_LANDSCAPE) {
layoutInflater.inflate(R.layout.keyguard_screen_password_portrait, this, true);
} else {
layoutInflater.inflate(R.layout.keyguard_screen_password_landscape, this, true);
}
mStatusViewManager = new KeyguardStatusViewManager(this, mUpdateMonitor, mLockPatternUtils,
mCallback, true);
final int quality = lockPatternUtils.getKeyguardStoredPasswordQuality();
mIsAlpha = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == quality
|| DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == quality
|| DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == quality;
mKeyboardView = (PasswordEntryKeyboardView) findViewById(R.id.keyboard);
mPasswordEntry = (EditText) findViewById(R.id.passwordEntry);
mPasswordEntry.setOnEditorActionListener(this);
mKeyboardHelper = new PasswordEntryKeyboardHelper(context, mKeyboardView, this, false);
mKeyboardHelper.setEnableHaptics(
Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, 0)
!= 0);
boolean imeOrDeleteButtonVisible = false;
if (mIsAlpha) {
// We always use the system IME for alpha keyboard, so hide lockscreen's soft keyboard
mKeyboardHelper.setKeyboardMode(PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA);
mKeyboardView.setVisibility(View.GONE);
} else {
// Use lockscreen's numeric keyboard if the physical keyboard isn't showing
mKeyboardHelper.setKeyboardMode(PasswordEntryKeyboardHelper.KEYBOARD_MODE_NUMERIC);
mKeyboardView.setVisibility(mCreationHardKeyboardHidden
== Configuration.HARDKEYBOARDHIDDEN_NO ? View.INVISIBLE : View.VISIBLE);
// The delete button is of the PIN keyboard itself in some (e.g. tablet) layouts,
// not a separate view
View pinDelete = findViewById(R.id.pinDel);
if (pinDelete != null) {
pinDelete.setVisibility(View.VISIBLE);
imeOrDeleteButtonVisible = true;
pinDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mKeyboardHelper.handleBackspace();
}
});
}
}
mPasswordEntry.requestFocus();
// This allows keyboards with overlapping qwerty/numeric keys to choose just numeric keys.
if (mIsAlpha) {
mPasswordEntry.setKeyListener(TextKeyListener.getInstance());
mPasswordEntry.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
//mStatusViewManager.setHelpMessage(R.string.keyguard_password_enter_password_code,
//KeyguardStatusViewManager.LOCK_ICON);
} else {
mPasswordEntry.setKeyListener(DigitsKeyListener.getInstance());
mPasswordEntry.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_VARIATION_PASSWORD);
//mStatusViewManager.setHelpMessage(R.string.keyguard_password_enter_pin_code,
//KeyguardStatusViewManager.LOCK_ICON);
}
// Poke the wakelock any time the text is selected or modified
mPasswordEntry.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock();
}
});
mQuickUnlock = (Settings.System.getInt(mContext.getContentResolver(), Settings.System.LOCKSCREEN_QUICK_UNLOCK_CONTROL, 0) == 1);
mPasswordEntry.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
if (!mResuming) {
mCallback.pokeWakelock();
}
if (mQuickUnlock) {
String entry = mPasswordEntry.getText().toString();
if (entry.length() > MINIMUM_PASSWORD_LENGTH_BEFORE_REPORT &&
mLockPatternUtils.checkPassword(entry)) {
mCallback.keyguardDone(true);
mCallback.reportSuccessfulUnlockAttempt();
}
}
}
});
// If there's more than one IME, enable the IME switcher button
View switchImeButton = findViewById(R.id.switch_ime_button);
final InputMethodManager imm = (InputMethodManager) getContext().getSystemService(
Context.INPUT_METHOD_SERVICE);
if (mIsAlpha && switchImeButton != null && hasMultipleEnabledIMEsOrSubtypes(imm, false)) {
switchImeButton.setVisibility(View.VISIBLE);
imeOrDeleteButtonVisible = true;
switchImeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCallback.pokeWakelock(); // Leave the screen on a bit longer
imm.showInputMethodPicker();
}
});
}
// If no icon is visible, reset the left margin on the password field so the text is
// still centered.
if (!imeOrDeleteButtonVisible) {
android.view.ViewGroup.LayoutParams params = mPasswordEntry.getLayoutParams();
if (params instanceof MarginLayoutParams) {
((MarginLayoutParams)params).leftMargin = 0;
mPasswordEntry.setLayoutParams(params);
}
}
}
|
diff --git a/lucene/src/test/org/apache/lucene/index/TestStressAdvance.java b/lucene/src/test/org/apache/lucene/index/TestStressAdvance.java
index eb6e76202..7b9902326 100644
--- a/lucene/src/test/org/apache/lucene/index/TestStressAdvance.java
+++ b/lucene/src/test/org/apache/lucene/index/TestStressAdvance.java
@@ -1,132 +1,132 @@
package org.apache.lucene.index;
/**
* 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.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.lucene.util.*;
import org.apache.lucene.store.*;
import org.apache.lucene.document.*;
public class TestStressAdvance extends LuceneTestCase {
public void testStressAdvance() throws Exception {
for(int iter=0;iter<3;iter++) {
if (VERBOSE) {
System.out.println("\nTEST: iter=" + iter);
}
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random, dir);
final Set<Integer> aDocs = new HashSet<Integer>();
final Document doc = new Document();
final Field f = newField("field", "", StringField.TYPE_UNSTORED);
doc.add(f);
final Field idField = newField("id", "", StringField.TYPE_STORED);
doc.add(idField);
int num = atLeast(4097);
for(int id=0;id<num;id++) {
if (random.nextInt(4) == 3) {
f.setValue("a");
aDocs.add(id);
} else {
f.setValue("b");
}
idField.setValue(""+id);
w.addDocument(doc);
}
w.forceMerge(1);
final List<Integer> aDocIDs = new ArrayList<Integer>();
final List<Integer> bDocIDs = new ArrayList<Integer>();
- final IndexReader r = w.getReader();
+ final DirectoryReader r = w.getReader();
final int[] idToDocID = new int[r.maxDoc()];
for(int docID=0;docID<idToDocID.length;docID++) {
int id = Integer.parseInt(r.document(docID).get("id"));
if (aDocs.contains(id)) {
aDocIDs.add(docID);
} else {
bDocIDs.add(docID);
}
}
- final TermsEnum te = r.getSequentialSubReaders()[0].fields().terms("field").iterator(null);
+ final TermsEnum te = getOnlySegmentReader(r).fields().terms("field").iterator(null);
DocsEnum de = null;
for(int iter2=0;iter2<10;iter2++) {
if (VERBOSE) {
System.out.println("\nTEST: iter=" + iter + " iter2=" + iter2);
}
assertEquals(TermsEnum.SeekStatus.FOUND, te.seekCeil(new BytesRef("a")));
de = _TestUtil.docs(random, te, null, de, false);
testOne(de, aDocIDs);
assertEquals(TermsEnum.SeekStatus.FOUND, te.seekCeil(new BytesRef("b")));
de = _TestUtil.docs(random, te, null, de, false);
testOne(de, bDocIDs);
}
w.close();
r.close();
dir.close();
}
}
private void testOne(DocsEnum docs, List<Integer> expected) throws Exception {
if (VERBOSE) {
System.out.println("test");
}
int upto = -1;
while(upto < expected.size()) {
if (VERBOSE) {
System.out.println(" cycle upto=" + upto + " of " + expected.size());
}
final int docID;
if (random.nextInt(4) == 1 || upto == expected.size()-1) {
// test nextDoc()
if (VERBOSE) {
System.out.println(" do nextDoc");
}
upto++;
docID = docs.nextDoc();
} else {
// test advance()
final int inc = _TestUtil.nextInt(random, 1, expected.size()-1-upto);
if (VERBOSE) {
System.out.println(" do advance inc=" + inc);
}
upto += inc;
docID = docs.advance(expected.get(upto));
}
if (upto == expected.size()) {
if (VERBOSE) {
System.out.println(" expect docID=" + DocsEnum.NO_MORE_DOCS + " actual=" + docID);
}
assertEquals(DocsEnum.NO_MORE_DOCS, docID);
} else {
if (VERBOSE) {
System.out.println(" expect docID=" + expected.get(upto) + " actual=" + docID);
}
assertTrue(docID != DocsEnum.NO_MORE_DOCS);
assertEquals(expected.get(upto).intValue(), docID);
}
}
}
}
| false | true | public void testStressAdvance() throws Exception {
for(int iter=0;iter<3;iter++) {
if (VERBOSE) {
System.out.println("\nTEST: iter=" + iter);
}
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random, dir);
final Set<Integer> aDocs = new HashSet<Integer>();
final Document doc = new Document();
final Field f = newField("field", "", StringField.TYPE_UNSTORED);
doc.add(f);
final Field idField = newField("id", "", StringField.TYPE_STORED);
doc.add(idField);
int num = atLeast(4097);
for(int id=0;id<num;id++) {
if (random.nextInt(4) == 3) {
f.setValue("a");
aDocs.add(id);
} else {
f.setValue("b");
}
idField.setValue(""+id);
w.addDocument(doc);
}
w.forceMerge(1);
final List<Integer> aDocIDs = new ArrayList<Integer>();
final List<Integer> bDocIDs = new ArrayList<Integer>();
final IndexReader r = w.getReader();
final int[] idToDocID = new int[r.maxDoc()];
for(int docID=0;docID<idToDocID.length;docID++) {
int id = Integer.parseInt(r.document(docID).get("id"));
if (aDocs.contains(id)) {
aDocIDs.add(docID);
} else {
bDocIDs.add(docID);
}
}
final TermsEnum te = r.getSequentialSubReaders()[0].fields().terms("field").iterator(null);
DocsEnum de = null;
for(int iter2=0;iter2<10;iter2++) {
if (VERBOSE) {
System.out.println("\nTEST: iter=" + iter + " iter2=" + iter2);
}
assertEquals(TermsEnum.SeekStatus.FOUND, te.seekCeil(new BytesRef("a")));
de = _TestUtil.docs(random, te, null, de, false);
testOne(de, aDocIDs);
assertEquals(TermsEnum.SeekStatus.FOUND, te.seekCeil(new BytesRef("b")));
de = _TestUtil.docs(random, te, null, de, false);
testOne(de, bDocIDs);
}
w.close();
r.close();
dir.close();
}
}
| public void testStressAdvance() throws Exception {
for(int iter=0;iter<3;iter++) {
if (VERBOSE) {
System.out.println("\nTEST: iter=" + iter);
}
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random, dir);
final Set<Integer> aDocs = new HashSet<Integer>();
final Document doc = new Document();
final Field f = newField("field", "", StringField.TYPE_UNSTORED);
doc.add(f);
final Field idField = newField("id", "", StringField.TYPE_STORED);
doc.add(idField);
int num = atLeast(4097);
for(int id=0;id<num;id++) {
if (random.nextInt(4) == 3) {
f.setValue("a");
aDocs.add(id);
} else {
f.setValue("b");
}
idField.setValue(""+id);
w.addDocument(doc);
}
w.forceMerge(1);
final List<Integer> aDocIDs = new ArrayList<Integer>();
final List<Integer> bDocIDs = new ArrayList<Integer>();
final DirectoryReader r = w.getReader();
final int[] idToDocID = new int[r.maxDoc()];
for(int docID=0;docID<idToDocID.length;docID++) {
int id = Integer.parseInt(r.document(docID).get("id"));
if (aDocs.contains(id)) {
aDocIDs.add(docID);
} else {
bDocIDs.add(docID);
}
}
final TermsEnum te = getOnlySegmentReader(r).fields().terms("field").iterator(null);
DocsEnum de = null;
for(int iter2=0;iter2<10;iter2++) {
if (VERBOSE) {
System.out.println("\nTEST: iter=" + iter + " iter2=" + iter2);
}
assertEquals(TermsEnum.SeekStatus.FOUND, te.seekCeil(new BytesRef("a")));
de = _TestUtil.docs(random, te, null, de, false);
testOne(de, aDocIDs);
assertEquals(TermsEnum.SeekStatus.FOUND, te.seekCeil(new BytesRef("b")));
de = _TestUtil.docs(random, te, null, de, false);
testOne(de, bDocIDs);
}
w.close();
r.close();
dir.close();
}
}
|
diff --git a/src/main/java/com/cluedoassist/Accusation.java b/src/main/java/com/cluedoassist/Accusation.java
index 61418e1..ca44d34 100644
--- a/src/main/java/com/cluedoassist/Accusation.java
+++ b/src/main/java/com/cluedoassist/Accusation.java
@@ -1,25 +1,35 @@
package com.cluedoassist;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.io.Serializable;
public final class Accusation implements LogEntry {
public final String asker;
public final List<Card> cards;
public Accusation(String asker, List<Card> cards) {
+ if (asker == null || "".equals(asker)) {
+ throw new IllegalArgumentException("asker can't be null or empty");
+ }
+ if (cards == null) {
+ throw new IllegalArgumentException("cards can't be null");
+ }
+ if (cards.size() != 3) {
+ throw new IllegalArgumentException(
+ "there should be exactly three cards");
+ }
this.asker = asker;
this.cards = Collections.unmodifiableList(new ArrayList<Card>(cards));
}
@Override
public String toString() {
return "Accusation: " + asker + " " + cards;
}
}
| true | true | public Accusation(String asker, List<Card> cards) {
this.asker = asker;
this.cards = Collections.unmodifiableList(new ArrayList<Card>(cards));
}
| public Accusation(String asker, List<Card> cards) {
if (asker == null || "".equals(asker)) {
throw new IllegalArgumentException("asker can't be null or empty");
}
if (cards == null) {
throw new IllegalArgumentException("cards can't be null");
}
if (cards.size() != 3) {
throw new IllegalArgumentException(
"there should be exactly three cards");
}
this.asker = asker;
this.cards = Collections.unmodifiableList(new ArrayList<Card>(cards));
}
|
diff --git a/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/Data/Result.java b/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/Data/Result.java
index 43ac068..5ac2308 100644
--- a/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/Data/Result.java
+++ b/ToureNPlaner/src/de/uni/stuttgart/informatik/ToureNPlaner/Data/Result.java
@@ -1,124 +1,126 @@
package de.uni.stuttgart.informatik.ToureNPlaner.Data;
import de.uni.stuttgart.informatik.ToureNPlaner.Net.JacksonManager;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.ObjectMapper;
import org.mapsforge.core.GeoPoint;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Result implements Serializable {
private GeoPoint[][] way;
private ArrayList<ResultNode> points;
private int version = 0;
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public GeoPoint[][] getWay() {
return way;
}
public ArrayList<ResultNode> getPoints() {
return points;
}
static void jacksonParse(JsonParser jp, ArrayList<ArrayList<GeoPoint>> ways, ArrayList<ResultNode> points) throws IOException {
int lt = 0, ln = 0;
int id = 0;
while (jp.nextToken() != JsonToken.END_OBJECT) {
if ("constraints".equals(jp.getCurrentName())) {
// consume
while (jp.nextToken() != JsonToken.END_OBJECT && jp.getCurrentToken() != JsonToken.VALUE_NULL) {
}
}
if ("misc".equals(jp.getCurrentName())) {
// consume
while (jp.nextToken() != JsonToken.END_OBJECT && jp.getCurrentToken() != JsonToken.VALUE_NULL) {
}
}
if ("points".equals(jp.getCurrentName())) {
if (jp.nextToken() == JsonToken.START_ARRAY) {
while (jp.nextToken() != JsonToken.END_ARRAY) {
while (jp.nextToken() != JsonToken.END_OBJECT) {
if (jp.getCurrentName().equals("lt")) {
jp.nextToken();
lt = jp.getIntValue();
} else if (jp.getCurrentName().equals("ln")) {
jp.nextToken();
ln = jp.getIntValue();
} else if (jp.getCurrentName().equals("id")) {
jp.nextToken();
id = jp.getIntValue();
}
}
points.add(new ResultNode(id, lt, ln));
}
}
}
if ("way".equals(jp.getCurrentName())) {
if (jp.nextToken() == JsonToken.START_ARRAY) {
JsonToken curr;
while ((curr = jp.nextToken()) != JsonToken.END_ARRAY) {
if (curr == JsonToken.START_ARRAY) {
ArrayList<GeoPoint> currentWay = new ArrayList<GeoPoint>();
- ways.add(currentWay);
while (jp.nextToken() != JsonToken.END_ARRAY) {
while (jp.nextToken() != JsonToken.END_OBJECT) {
if (jp.getCurrentName().equals("lt")) {
jp.nextToken();
lt = jp.getIntValue() / 10;
} else if (jp.getCurrentName().equals("ln")) {
jp.nextToken();
ln = jp.getIntValue() / 10;
}
}
currentWay.add(new GeoPoint(lt, ln));
}
- // duplicate the last one
- if (ways.size() > 1) {
- ArrayList<GeoPoint> second_last = ways.get(ways.size() - 2);
- ArrayList<GeoPoint> last = ways.get(ways.size() - 1);
- second_last.add(last.get(0));
- }
+ if(!currentWay.isEmpty()) {
+ ways.add(currentWay);
+ // duplicate the last one
+ if (ways.size() > 1) {
+ ArrayList<GeoPoint> second_last = ways.get(ways.size() - 2);
+ ArrayList<GeoPoint> last = ways.get(ways.size() - 1);
+ second_last.add(last.get(0));
+ }
+ }
}
}
}
}
}
}
public static Result parse(JacksonManager.ContentType type, InputStream stream) throws IOException {
Result result = new Result();
ArrayList<ArrayList<GeoPoint>> ways = new ArrayList<ArrayList<GeoPoint>>();
ArrayList<ResultNode> points = new ArrayList<ResultNode>();
ObjectMapper mapper = JacksonManager.getMapper(type);
JsonParser jp = mapper.getJsonFactory().createJsonParser(stream);
try {
jacksonParse(jp, ways, points);
} finally {
jp.close();
}
int size = ways.size();
result.way = new GeoPoint[size][];
for (int i = 0; i < size; i++) {
result.way[i] = ways.get(i).toArray(new GeoPoint[ways.get(i).size()]);
}
result.points = points;
return result;
}
}
| false | true | static void jacksonParse(JsonParser jp, ArrayList<ArrayList<GeoPoint>> ways, ArrayList<ResultNode> points) throws IOException {
int lt = 0, ln = 0;
int id = 0;
while (jp.nextToken() != JsonToken.END_OBJECT) {
if ("constraints".equals(jp.getCurrentName())) {
// consume
while (jp.nextToken() != JsonToken.END_OBJECT && jp.getCurrentToken() != JsonToken.VALUE_NULL) {
}
}
if ("misc".equals(jp.getCurrentName())) {
// consume
while (jp.nextToken() != JsonToken.END_OBJECT && jp.getCurrentToken() != JsonToken.VALUE_NULL) {
}
}
if ("points".equals(jp.getCurrentName())) {
if (jp.nextToken() == JsonToken.START_ARRAY) {
while (jp.nextToken() != JsonToken.END_ARRAY) {
while (jp.nextToken() != JsonToken.END_OBJECT) {
if (jp.getCurrentName().equals("lt")) {
jp.nextToken();
lt = jp.getIntValue();
} else if (jp.getCurrentName().equals("ln")) {
jp.nextToken();
ln = jp.getIntValue();
} else if (jp.getCurrentName().equals("id")) {
jp.nextToken();
id = jp.getIntValue();
}
}
points.add(new ResultNode(id, lt, ln));
}
}
}
if ("way".equals(jp.getCurrentName())) {
if (jp.nextToken() == JsonToken.START_ARRAY) {
JsonToken curr;
while ((curr = jp.nextToken()) != JsonToken.END_ARRAY) {
if (curr == JsonToken.START_ARRAY) {
ArrayList<GeoPoint> currentWay = new ArrayList<GeoPoint>();
ways.add(currentWay);
while (jp.nextToken() != JsonToken.END_ARRAY) {
while (jp.nextToken() != JsonToken.END_OBJECT) {
if (jp.getCurrentName().equals("lt")) {
jp.nextToken();
lt = jp.getIntValue() / 10;
} else if (jp.getCurrentName().equals("ln")) {
jp.nextToken();
ln = jp.getIntValue() / 10;
}
}
currentWay.add(new GeoPoint(lt, ln));
}
// duplicate the last one
if (ways.size() > 1) {
ArrayList<GeoPoint> second_last = ways.get(ways.size() - 2);
ArrayList<GeoPoint> last = ways.get(ways.size() - 1);
second_last.add(last.get(0));
}
}
}
}
}
}
}
| static void jacksonParse(JsonParser jp, ArrayList<ArrayList<GeoPoint>> ways, ArrayList<ResultNode> points) throws IOException {
int lt = 0, ln = 0;
int id = 0;
while (jp.nextToken() != JsonToken.END_OBJECT) {
if ("constraints".equals(jp.getCurrentName())) {
// consume
while (jp.nextToken() != JsonToken.END_OBJECT && jp.getCurrentToken() != JsonToken.VALUE_NULL) {
}
}
if ("misc".equals(jp.getCurrentName())) {
// consume
while (jp.nextToken() != JsonToken.END_OBJECT && jp.getCurrentToken() != JsonToken.VALUE_NULL) {
}
}
if ("points".equals(jp.getCurrentName())) {
if (jp.nextToken() == JsonToken.START_ARRAY) {
while (jp.nextToken() != JsonToken.END_ARRAY) {
while (jp.nextToken() != JsonToken.END_OBJECT) {
if (jp.getCurrentName().equals("lt")) {
jp.nextToken();
lt = jp.getIntValue();
} else if (jp.getCurrentName().equals("ln")) {
jp.nextToken();
ln = jp.getIntValue();
} else if (jp.getCurrentName().equals("id")) {
jp.nextToken();
id = jp.getIntValue();
}
}
points.add(new ResultNode(id, lt, ln));
}
}
}
if ("way".equals(jp.getCurrentName())) {
if (jp.nextToken() == JsonToken.START_ARRAY) {
JsonToken curr;
while ((curr = jp.nextToken()) != JsonToken.END_ARRAY) {
if (curr == JsonToken.START_ARRAY) {
ArrayList<GeoPoint> currentWay = new ArrayList<GeoPoint>();
while (jp.nextToken() != JsonToken.END_ARRAY) {
while (jp.nextToken() != JsonToken.END_OBJECT) {
if (jp.getCurrentName().equals("lt")) {
jp.nextToken();
lt = jp.getIntValue() / 10;
} else if (jp.getCurrentName().equals("ln")) {
jp.nextToken();
ln = jp.getIntValue() / 10;
}
}
currentWay.add(new GeoPoint(lt, ln));
}
if(!currentWay.isEmpty()) {
ways.add(currentWay);
// duplicate the last one
if (ways.size() > 1) {
ArrayList<GeoPoint> second_last = ways.get(ways.size() - 2);
ArrayList<GeoPoint> last = ways.get(ways.size() - 1);
second_last.add(last.get(0));
}
}
}
}
}
}
}
}
|
diff --git a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/ClinincalStatusComboAction.java b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/ClinincalStatusComboAction.java
index e9d583233..106f8c991 100644
--- a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/ClinincalStatusComboAction.java
+++ b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/ClinincalStatusComboAction.java
@@ -1,142 +1,142 @@
package edu.wustl.catissuecore.action;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONArray;
import org.json.JSONObject;
import edu.wustl.catissuecore.bizlogic.SPPBizLogic;
import edu.wustl.catissuecore.util.global.AppUtility;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.util.logger.Logger;
public class ClinincalStatusComboAction extends BaseAction
{
private transient final Logger logger = Logger.getCommonLogger(ClinincalStatusComboAction.class);
@Override
protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
String limit = request.getParameter("limit");
String query = request.getParameter("query");
String start = request.getParameter("start");
final String showOption = request.getParameter("showOption");
- if(limit.equals(null))
+ if(null==limit || limit.equalsIgnoreCase("") || limit.equalsIgnoreCase(" "))
{
limit="0";
}
- if(start.equals(null))
+ if(null==start || start.equalsIgnoreCase("") || start.equalsIgnoreCase(" "))
{
start="0";
}
final Integer limitFetch = Integer.parseInt(limit);
final Integer startFetch = Integer.parseInt(start);
final String requestFor = request.getParameter("requestFor");
List clinicalStatusList = null;
SPPBizLogic sppBizLogic = new SPPBizLogic();
if("specimenClass".equals(requestFor))
{
clinicalStatusList = AppUtility.getSpecimenClassList();
}
else if("specimenType".equals(requestFor))
{
String specimenClass = request.getParameter("selSpecClass");
clinicalStatusList = AppUtility.getSpecimenTypes(specimenClass);
}
else if("storageLocation".equals(requestFor))
{
clinicalStatusList = new LinkedList();
clinicalStatusList.add(new NameValueBean("Virtual", "Virtual"));
clinicalStatusList.add(new NameValueBean("Auto", "Auto"));
clinicalStatusList.add(new NameValueBean("Manual", "Manual"));
}
else if("specimenEvent".equals(requestFor))
{
String processingSPP = request.getParameter("processingSPPName");
clinicalStatusList = sppBizLogic.getAllEventsForSPP(processingSPP);
}
else if("processingSPP".equals(requestFor))
{
clinicalStatusList = sppBizLogic.getAllSPPNames();
}
else
{
clinicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(
Constants.CDE_NAME_CLINICAL_STATUS, null);
}
final JSONObject jsonObject = getClinicalStatusData(limitFetch,
startFetch, clinicalStatusList, query,showOption);
response.setContentType("text/javascript");
final PrintWriter out = response.getWriter();
out.write(jsonObject.toString());
return null;
}
private JSONObject getClinicalStatusData(Integer limitFetch,
Integer startFetch, List clinicalStatusList, String query,
String showOption) {
JSONObject jsonObject = null;
JSONArray jsonArray = null;
try
{
jsonArray = new JSONArray();
jsonObject = new JSONObject();
jsonObject.put("totalCount", new Integer(clinicalStatusList.size()));
final ListIterator iterator = clinicalStatusList.listIterator(startFetch);
final Integer total = limitFetch + startFetch;
// 1st record in List has value -1, so startFetch is incremented and
// made to fetch data from 2nd element from the List
startFetch++;
boolean flag = false;
while (startFetch < total + 1)
{
if (iterator.hasNext())
{
final NameValueBean nameValueBean = (NameValueBean) iterator.next();
if ( query == null
|| nameValueBean.getName().toLowerCase().contains(query.toLowerCase()))
{
final JSONObject innerJsonObject = new JSONObject();
// nameValueBean = (NameValueBean) iterator.next();
innerJsonObject.put("field", nameValueBean.getName());
innerJsonObject.put("id", nameValueBean.getValue());
jsonArray.put(innerJsonObject);
flag = true;
}
else if (flag)
{
break;
}
}
startFetch++;
}
jsonObject.put("row", jsonArray);
}
catch (final Exception e)
{
this.logger.error(e.getMessage(), e);
e.printStackTrace();
//System.out.println(e);
}
return jsonObject;
}
}
| false | true | protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
String limit = request.getParameter("limit");
String query = request.getParameter("query");
String start = request.getParameter("start");
final String showOption = request.getParameter("showOption");
if(limit.equals(null))
{
limit="0";
}
if(start.equals(null))
{
start="0";
}
final Integer limitFetch = Integer.parseInt(limit);
final Integer startFetch = Integer.parseInt(start);
final String requestFor = request.getParameter("requestFor");
List clinicalStatusList = null;
SPPBizLogic sppBizLogic = new SPPBizLogic();
if("specimenClass".equals(requestFor))
{
clinicalStatusList = AppUtility.getSpecimenClassList();
}
else if("specimenType".equals(requestFor))
{
String specimenClass = request.getParameter("selSpecClass");
clinicalStatusList = AppUtility.getSpecimenTypes(specimenClass);
}
else if("storageLocation".equals(requestFor))
{
clinicalStatusList = new LinkedList();
clinicalStatusList.add(new NameValueBean("Virtual", "Virtual"));
clinicalStatusList.add(new NameValueBean("Auto", "Auto"));
clinicalStatusList.add(new NameValueBean("Manual", "Manual"));
}
else if("specimenEvent".equals(requestFor))
{
String processingSPP = request.getParameter("processingSPPName");
clinicalStatusList = sppBizLogic.getAllEventsForSPP(processingSPP);
}
else if("processingSPP".equals(requestFor))
{
clinicalStatusList = sppBizLogic.getAllSPPNames();
}
else
{
clinicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(
Constants.CDE_NAME_CLINICAL_STATUS, null);
}
final JSONObject jsonObject = getClinicalStatusData(limitFetch,
startFetch, clinicalStatusList, query,showOption);
response.setContentType("text/javascript");
final PrintWriter out = response.getWriter();
out.write(jsonObject.toString());
return null;
}
| protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
String limit = request.getParameter("limit");
String query = request.getParameter("query");
String start = request.getParameter("start");
final String showOption = request.getParameter("showOption");
if(null==limit || limit.equalsIgnoreCase("") || limit.equalsIgnoreCase(" "))
{
limit="0";
}
if(null==start || start.equalsIgnoreCase("") || start.equalsIgnoreCase(" "))
{
start="0";
}
final Integer limitFetch = Integer.parseInt(limit);
final Integer startFetch = Integer.parseInt(start);
final String requestFor = request.getParameter("requestFor");
List clinicalStatusList = null;
SPPBizLogic sppBizLogic = new SPPBizLogic();
if("specimenClass".equals(requestFor))
{
clinicalStatusList = AppUtility.getSpecimenClassList();
}
else if("specimenType".equals(requestFor))
{
String specimenClass = request.getParameter("selSpecClass");
clinicalStatusList = AppUtility.getSpecimenTypes(specimenClass);
}
else if("storageLocation".equals(requestFor))
{
clinicalStatusList = new LinkedList();
clinicalStatusList.add(new NameValueBean("Virtual", "Virtual"));
clinicalStatusList.add(new NameValueBean("Auto", "Auto"));
clinicalStatusList.add(new NameValueBean("Manual", "Manual"));
}
else if("specimenEvent".equals(requestFor))
{
String processingSPP = request.getParameter("processingSPPName");
clinicalStatusList = sppBizLogic.getAllEventsForSPP(processingSPP);
}
else if("processingSPP".equals(requestFor))
{
clinicalStatusList = sppBizLogic.getAllSPPNames();
}
else
{
clinicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(
Constants.CDE_NAME_CLINICAL_STATUS, null);
}
final JSONObject jsonObject = getClinicalStatusData(limitFetch,
startFetch, clinicalStatusList, query,showOption);
response.setContentType("text/javascript");
final PrintWriter out = response.getWriter();
out.write(jsonObject.toString());
return null;
}
|
diff --git a/beam-visat-rcp/src/main/java/org/esa/beam/visat/VisatMain.java b/beam-visat-rcp/src/main/java/org/esa/beam/visat/VisatMain.java
index fec0b7ee1..186c37cd3 100644
--- a/beam-visat-rcp/src/main/java/org/esa/beam/visat/VisatMain.java
+++ b/beam-visat-rcp/src/main/java/org/esa/beam/visat/VisatMain.java
@@ -1,180 +1,180 @@
/*
* $Id: VisatMain.java,v 1.7 2007/03/28 12:47:52 norman Exp $
*
* Copyright (C) 2002 by Brockmann Consult ([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. This program is distributed in the hope it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.esa.beam.visat;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.core.runtime.RuntimeRunnable;
import com.jidesoft.utils.Lm;
import com.jidesoft.utils.SystemInfo;
import org.esa.beam.framework.dataio.ProductIO;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.ui.BasicApp;
import org.esa.beam.framework.ui.UIUtils;
import org.esa.beam.framework.ui.application.ApplicationDescriptor;
import org.esa.beam.util.Debug;
import org.esa.beam.visat.actions.session.OpenSessionAction;
import org.esa.beam.BeamUiActivator;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.media.jai.JAI;
import javax.media.jai.util.ImagingListener;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Locale;
/**
* The startup class for VISAT. It provides the <code>main</code> method for the application.
* <p/>
* <p>The VISAT application accepts the following command line options: <ld> <li> <code>-d</code> or
* <code>--debug</code> sets VISAT into debugging mode <li> <code>-l <i>file</i></code> or <code>--logfile
* <i>file</i></code> sets the logfile for VISAT to <i>file</i> </ld>
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class VisatMain implements RuntimeRunnable {
/**
* Entry point for the VISAT application called by the Ceres runtime.
*
* @param argument a {@code String[]} containing the command line arguments
* @param progressMonitor a progress monitor
* @throws Exception if an error occurs
*/
public void run(Object argument, ProgressMonitor progressMonitor) throws Exception {
String[] args = new String[0];
if (argument instanceof String[]) {
args = (String[]) argument;
}
Locale.setDefault(Locale.UK); // Force usage of British English locale
Lm.verifyLicense("Brockmann Consult", "BEAM", "lCzfhklpZ9ryjomwWxfdupxIcuIoCxg2");
if (SystemInfo.isMacOSX()) {
if (System.getProperty("com.apple.macos.useScreenMenuBar") == null) {
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
}
if (System.getProperty("apple.laf.useScreenMenuBar") == null) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
if (System.getProperty("apple.awt.brushMetalLook") == null) {
System.setProperty("apple.awt.brushMetalLook", "true");
}
}
final ApplicationDescriptor applicationDescriptor = BeamUiActivator.getInstance().getApplicationDescriptor();
if (applicationDescriptor == null) {
throw new IllegalStateException(String.format("Application descriptor not found for applicationId='%s'.",
BeamUiActivator.getInstance().getApplicationId()));
}
boolean debugEnabled = false;
ArrayList<String> productFilepathList = new ArrayList<String>();
String sessionFile = null;
for (String arg : args) {
if (arg.startsWith("-")) {
if (arg.equals("-d") || arg.equals("--debug")) {
debugEnabled = true;
} else {
System.err.printf("%s error: illegal option '" + arg + "'", applicationDescriptor.getDisplayName());
return;
}
- } if (arg.endsWith(OpenSessionAction.SESSION_FILE_FILTER.getDefaultExtension())) {
+ } else if (arg.endsWith(OpenSessionAction.SESSION_FILE_FILTER.getDefaultExtension())) {
sessionFile = arg;
} else {
productFilepathList.add(arg);
}
}
Debug.setEnabled(debugEnabled);
if (debugEnabled) {
JAI.getDefaultInstance().setImagingListener(new ImagingListener() {
public boolean errorOccurred(String message, Throwable thrown, Object where, boolean isRetryable) throws RuntimeException {
Debug.trace("JAI Error: " + message);
Debug.trace(thrown);
return false;
}
});
}
final VisatApp app = createApplication(applicationDescriptor);
app.startUp(progressMonitor);
openSession(app, sessionFile);
openProducts(app, productFilepathList);
}
protected VisatApp createApplication(ApplicationDescriptor applicationDescriptor) {
return new VisatApp(applicationDescriptor);
}
private void openSession(VisatApp app, String sessionFile) {
if (sessionFile != null && !(sessionFile.trim().isEmpty())) {
final OpenSessionAction action = (OpenSessionAction) app.getCommandManager().getCommand(OpenSessionAction.ID);
action.openSession(app, new File(sessionFile));
}
}
private static void openProducts(VisatApp app, ArrayList<String> productFilepathList) {
for (String productFilepath : productFilepathList) {
openProduct(app, productFilepath);
}
}
private static void openProduct(final VisatApp app, final String productFilepath) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIUtils.setRootFrameWaitCursor(app.getMainFrame());
try {
openProductImpl(app, productFilepath);
} finally {
UIUtils.setRootFrameDefaultCursor(app.getMainFrame());
}
}
});
}
private static void openProductImpl(VisatApp app, final String productFilepath) {
final File productFile = new File(productFilepath);
final Product product;
try {
product = ProductIO.readProduct(productFile, null);
if (product == null) {
final MessageFormat mf = new MessageFormat("No reader found for data product\n''{0}''."); /*I18N*/
final Object[] args = new Object[]{productFile.getPath()};
showError(app, mf.format(args));
return;
}
} catch (IOException e) {
final MessageFormat mf = new MessageFormat("I/O error while opening file\n{0}:\n{1}"); /*I18N*/
final Object[] args = new Object[]{productFile.getPath(), e.getMessage()};
showError(app, mf.format(args));
return;
}
app.addProduct(product);
}
private static void showError(BasicApp app, final String message) {
JOptionPane.showMessageDialog(null,
message,
app.getAppName(),
JOptionPane.ERROR_MESSAGE);
}
}
| true | true | public void run(Object argument, ProgressMonitor progressMonitor) throws Exception {
String[] args = new String[0];
if (argument instanceof String[]) {
args = (String[]) argument;
}
Locale.setDefault(Locale.UK); // Force usage of British English locale
Lm.verifyLicense("Brockmann Consult", "BEAM", "lCzfhklpZ9ryjomwWxfdupxIcuIoCxg2");
if (SystemInfo.isMacOSX()) {
if (System.getProperty("com.apple.macos.useScreenMenuBar") == null) {
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
}
if (System.getProperty("apple.laf.useScreenMenuBar") == null) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
if (System.getProperty("apple.awt.brushMetalLook") == null) {
System.setProperty("apple.awt.brushMetalLook", "true");
}
}
final ApplicationDescriptor applicationDescriptor = BeamUiActivator.getInstance().getApplicationDescriptor();
if (applicationDescriptor == null) {
throw new IllegalStateException(String.format("Application descriptor not found for applicationId='%s'.",
BeamUiActivator.getInstance().getApplicationId()));
}
boolean debugEnabled = false;
ArrayList<String> productFilepathList = new ArrayList<String>();
String sessionFile = null;
for (String arg : args) {
if (arg.startsWith("-")) {
if (arg.equals("-d") || arg.equals("--debug")) {
debugEnabled = true;
} else {
System.err.printf("%s error: illegal option '" + arg + "'", applicationDescriptor.getDisplayName());
return;
}
} if (arg.endsWith(OpenSessionAction.SESSION_FILE_FILTER.getDefaultExtension())) {
sessionFile = arg;
} else {
productFilepathList.add(arg);
}
}
Debug.setEnabled(debugEnabled);
if (debugEnabled) {
JAI.getDefaultInstance().setImagingListener(new ImagingListener() {
public boolean errorOccurred(String message, Throwable thrown, Object where, boolean isRetryable) throws RuntimeException {
Debug.trace("JAI Error: " + message);
Debug.trace(thrown);
return false;
}
});
}
final VisatApp app = createApplication(applicationDescriptor);
app.startUp(progressMonitor);
openSession(app, sessionFile);
openProducts(app, productFilepathList);
}
| public void run(Object argument, ProgressMonitor progressMonitor) throws Exception {
String[] args = new String[0];
if (argument instanceof String[]) {
args = (String[]) argument;
}
Locale.setDefault(Locale.UK); // Force usage of British English locale
Lm.verifyLicense("Brockmann Consult", "BEAM", "lCzfhklpZ9ryjomwWxfdupxIcuIoCxg2");
if (SystemInfo.isMacOSX()) {
if (System.getProperty("com.apple.macos.useScreenMenuBar") == null) {
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
}
if (System.getProperty("apple.laf.useScreenMenuBar") == null) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
if (System.getProperty("apple.awt.brushMetalLook") == null) {
System.setProperty("apple.awt.brushMetalLook", "true");
}
}
final ApplicationDescriptor applicationDescriptor = BeamUiActivator.getInstance().getApplicationDescriptor();
if (applicationDescriptor == null) {
throw new IllegalStateException(String.format("Application descriptor not found for applicationId='%s'.",
BeamUiActivator.getInstance().getApplicationId()));
}
boolean debugEnabled = false;
ArrayList<String> productFilepathList = new ArrayList<String>();
String sessionFile = null;
for (String arg : args) {
if (arg.startsWith("-")) {
if (arg.equals("-d") || arg.equals("--debug")) {
debugEnabled = true;
} else {
System.err.printf("%s error: illegal option '" + arg + "'", applicationDescriptor.getDisplayName());
return;
}
} else if (arg.endsWith(OpenSessionAction.SESSION_FILE_FILTER.getDefaultExtension())) {
sessionFile = arg;
} else {
productFilepathList.add(arg);
}
}
Debug.setEnabled(debugEnabled);
if (debugEnabled) {
JAI.getDefaultInstance().setImagingListener(new ImagingListener() {
public boolean errorOccurred(String message, Throwable thrown, Object where, boolean isRetryable) throws RuntimeException {
Debug.trace("JAI Error: " + message);
Debug.trace(thrown);
return false;
}
});
}
final VisatApp app = createApplication(applicationDescriptor);
app.startUp(progressMonitor);
openSession(app, sessionFile);
openProducts(app, productFilepathList);
}
|
diff --git a/src/com/jumpandrun/GameScreen.java b/src/com/jumpandrun/GameScreen.java
index d6a59a8..500dbc3 100644
--- a/src/com/jumpandrun/GameScreen.java
+++ b/src/com/jumpandrun/GameScreen.java
@@ -1,931 +1,930 @@
package com.jumpandrun;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.music.AudioEventListener;
import com.music.BofEvent;
import com.music.NoteJumper;
import com.music.RhythmAudio;
import com.music.TickEvent;
public class GameScreen extends DefaultScreen implements InputProcessor {
PerspectiveCamera cam;
SpriteBatch batch;
SpriteBatch fontBatch;
BitmapFont font;
public static RhythmAudio ra = new RhythmAudio();
float startTime = 0;
float enemySpawnTime = MathUtils.random(0, 10);
float delta = 0;
boolean enemySpawnSwitch = false;
//DEBUG values
float renderTimeBench = 0;
float physicTimeBench = 0;
float musicTimeBench = 0;
float startTimeBench = 0;
float endTimeBench = 0;
// GLES20
Matrix4 model = new Matrix4().idt();
Matrix4 tmp = new Matrix4().idt();
private ShaderProgram transShader;
private ShaderProgram bloomShader;
private ShaderProgram tvShader;
Mesh blockModel;
Mesh playerModel;
Mesh targetModel;
Mesh quadModel;
Mesh wireCubeModel;
Mesh sphereModel;
Mesh sphereSliceModel;
Mesh torusModel;
FrameBuffer frameBuffer;
FrameBuffer frameBufferVert;
FrameBuffer frameBufferFull;
float angleXBack = 0;
float angleYBack = 0;
float angleXFront = 0;
float angleYFront = 0;
Vector3 tmpVector3 = new Vector3();
Vector2 tmpVector2 = new Vector2();
private float accumulator = 0;
private float bloomFactor = 0;
private float disortFactor = 0;
private float highlightTimer = 0;
private int highlightCnt = 1000;
Array<NoteJumper> noteJumpers = new Array<NoteJumper>();
private int songcounter = 0;
private float blockani = 0, jumpani = 0;
private AudioEventListener audioListener = new AudioEventListener() {
@Override
public void onEvent(TickEvent te) {
if(te.isFullNote()) {
Resources.getInstance().jumpblock.play();
GameInstance.getInstance().activateJumpBlocks();
GameInstance.getInstance().addPowerUp();
}
long freq = (long)(te.getFullTicks()*4/Math.pow(2,songcounter));
if( freq < te.getFullTicks()*4/Math.pow(2,2))
freq = (long)(te.getFullTicks()*4/Math.pow(2,3));
if(te.getCustomNote(freq) == 0) {
//enemySpawnSwitch = ch6;
GameInstance.getInstance().addEnemy();
if(highlightCnt>500) {
highlightCnt = 0;
}
}
blockani = te.getCustomNote(freq);
jumpani = te.getCustomNote((long)(te.getFullTicks()));
if(te.getTick()%3072 == 0) {
float ppos = GameInstance.getInstance().player.position.y;
songcounter = (int) ((ppos + 1195)/140);
songcounter %= 6;
System.out.println("songcounter" + ppos+ " tick: " + te.getTick());
ra.gotoTick(songcounter*3072);
if(songcounter == 0)
Resources.getInstance().song01.play();
else if(songcounter == 1)
Resources.getInstance().song02.play();
else if(songcounter == 2)
Resources.getInstance().song03.play();
else if(songcounter == 3)
Resources.getInstance().song04.play();
else if(songcounter == 4)
Resources.getInstance().song05.play();
else if(songcounter == 5)
Resources.getInstance().song06.play();
}
}
@Override
public void onMidiEvent(Array<BofEvent> events, long tick) {
for (BofEvent me : events) {
if (me.type == BofEvent.NOTE_ON) {
noteJumpers.add(new NoteJumper(me, tick));
}
}
}
};
private float animateFont = 2.0f;
private int score = 0;
private boolean bulletSplash = false;
private float shakeCam = 0;
public GameScreen(Game game) {
super(game);
GameInstance.getInstance().resetGame();
cam = new PerspectiveCamera(60, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(23, -15,29f);
cam.direction.set(0, 0, -1);
cam.up.set(0, 1, 0);
cam.near = 1f;
cam.far = 1000;
Gdx.input.setInputProcessor(this);
batch = new SpriteBatch();
batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
font = new BitmapFont();
blockModel = Resources.getInstance().blockModel;
playerModel = Resources.getInstance().playerModel;
targetModel = Resources.getInstance().targetModel;
quadModel = Resources.getInstance().quadModel;
wireCubeModel = Resources.getInstance().wireCubeModel;
sphereModel = Resources.getInstance().sphereModel;
sphereSliceModel = Resources.getInstance().sphereSliceModel;
torusModel = Resources.getInstance().torusModel;
transShader = Resources.getInstance().transShader;
bloomShader = Resources.getInstance().bloomShader;
tvShader = Resources.getInstance().tvShader;
ra.loadMidi("./data/song.mid");
ra.registerBeatListener(audioListener);
ra.play();
//Resources.getInstance().music.play();
initRender();
}
public void initRender() {
Gdx.gl20.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch = new SpriteBatch();
batch.getProjectionMatrix().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
fontBatch = new SpriteBatch();
fontBatch.getProjectionMatrix().setToOrtho2D(0, 0,800, 480);
font = new BitmapFont();
font.setScale(2.0f);
frameBuffer = new FrameBuffer(Format.RGB565, Resources.getInstance().m_i32TexSize, Resources.getInstance().m_i32TexSize, false);
frameBufferVert = new FrameBuffer(Format.RGB565, Resources.getInstance().m_i32TexSize, Resources.getInstance().m_i32TexSize, false);
frameBufferFull = new FrameBuffer(Format.RGB565, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
}
@Override
public void resize(int width, int height) {
initRender();
cam = new PerspectiveCamera(60, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(21, -15,29f);
cam.direction.set(0, 0, -1);
cam.up.set(0, 1, 0);
cam.near = 1f;
cam.far = 1000;
}
@Override
public void show() {
}
// @Override
// public void render(float deltaTime) {
// accumulator += deltaTime;
// while(accumulator > 1.0f / 60.0f) {
// fixedTimeStepRender();
// accumulator -= 1.0f / 60.0f;
// if(accumulator>0) Gdx.app.log("", "framedrop " + accumulator);
// }
//
// }
public void render(float deltaTime) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
ra.update();
{ //remove obsolete NoteJumper
for(NoteJumper nj: noteJumpers) {
if(!nj.bofNote.isPlayedAt(ra.getTick())) {
nj.alive = false;
//// Gdx.app.log("", nj.bofNote.getNote() + "");
// if(nj.bofNote.getNote()<40) {
// GameInstance.getInstance().addPowerUp(nj.posA.x,nj.posA.y);
// }
}
}
//remove from array
boolean found;
do {
found = false;
for(int i = 0; i < noteJumpers.size; i++) {
if(noteJumpers.get(i) != null && noteJumpers.get(i).alive == false) {
noteJumpers.removeIndex(i);
found = true;
break;
}
}
}while(found);
}
startTime+=deltaTime;
delta = deltaTime;
enemySpawnTime -=deltaTime;
// if(enemySpawnTime<0) {
// enemySpawnTime = MathUtils.random(0, 10f);
// GameInstance.getInstance().addEnemy();
// }
angleXBack += MathUtils.sin(startTime) * delta * 10f;
angleYBack += MathUtils.cos(startTime) * delta * 5f;
angleXFront += MathUtils.sin(startTime) * delta * 10f;
angleYFront += MathUtils.cos(startTime) * delta* 5f;
startTimeBench = System.nanoTime();
if(GameInstance.getInstance().player.position.y<-1185.0) {
cam.position.set(cam.position.x, -1185.0f, 29);
} else {
cam.position.set(cam.position.x, GameInstance.getInstance().player.position.y, 29);
}
if(shakeCam>0) {
cam.rotate(MathUtils.sin(shakeCam)/10.f, 0, 0, 1);
shakeCam = Math.max(0, shakeCam - (deltaTime*100f));
} else {
cam.up.set(0,1,0);
}
cam.update();
if (Resources.getInstance().bloomOnOff) {
frameBuffer.begin();
renderBackground();
renderScene();
frameBuffer.end();
// PostProcessing
Gdx.gl.glDisable(GL20.GL_CULL_FACE);
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDisable(GL20.GL_BLEND);
for (int i = 0; i < GameInstance.getInstance().bullets.size; ++i) {
Ammo bullet = GameInstance.getInstance().bullets.get(i);
bulletSplash = false;
if(bullet instanceof Rocket) {
if(((Rocket) bullet).hit) {
disortFactor=1;
bulletSplash = true;
if(shakeCam==0) {
shakeCam = 20;
}
}
}
if(bullet instanceof Mine) {
if(((Mine) bullet).hit) {
disortFactor=1;
bulletSplash = true;
if(shakeCam==0) {
shakeCam = 20;
}
}
}
}
if(bulletSplash) {
disortFactor = Math.max(0, disortFactor - (deltaTime*5.f));
}
frameBuffer.getColorBufferTexture().bind(0);
bloomShader.begin();
bloomShader.setUniformi("sTexture", 0);
bloomShader.setUniformf("bloomFactor", Helper.map((MathUtils.sin(startTime * 3f) * delta * 50f) + 0.5f, 0, 1, 0.65f, 0.70f + (bloomFactor/5.f)));
frameBufferVert.begin();
bloomShader.setUniformf("TexelOffsetX", Resources.getInstance().m_fTexelOffset);
bloomShader.setUniformf("TexelOffsetY", 0.0f);
quadModel.render(bloomShader, GL20.GL_TRIANGLE_STRIP);
frameBufferVert.end();
frameBufferVert.getColorBufferTexture().bind(0);
frameBuffer.begin();
bloomShader.setUniformf("TexelOffsetX", 0.0f);
bloomShader.setUniformf("TexelOffsetY", Resources.getInstance().m_fTexelOffset);
quadModel.render(bloomShader, GL20.GL_TRIANGLE_STRIP);
frameBuffer.end();
bloomShader.end();
}
if(!Resources.getInstance().bloomOnOff) {
// render scene again
renderScene();
} else {
frameBufferFull.begin();
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderScene();
Gdx.gl.glDisable(GL20.GL_CULL_FACE);
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDisable(GL20.GL_BLEND);
batch.enableBlending();
batch.setBlendFunction(GL20.GL_ONE, GL20.GL_ONE);
batch.begin();
batch.draw(frameBuffer.getColorBufferTexture(), 0, 0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight(),0,0,frameBuffer.getWidth(),frameBuffer.getHeight(),false,true);
batch.end();
frameBufferFull.end();
frameBufferFull.getColorBufferTexture().bind(0);
tvShader.begin();
tvShader.setUniformf("time", startTime);
tvShader.setUniformf("disort", 0.002f+ (disortFactor/400.f));
tvShader.setUniformi("sampler0", 0);
tvShader.setUniformf("resolution", Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
quadModel.render(tvShader,GL20.GL_TRIANGLE_FAN);
tvShader.end();
}
endTimeBench = (System.nanoTime() - startTimeBench) / 1000000000.0f;
renderTimeBench = endTimeBench;
startTimeBench = System.nanoTime();
GameInstance.getInstance().update(deltaTime);
endTimeBench = (System.nanoTime() - startTimeBench) / 1000000000.0f;
physicTimeBench = endTimeBench;
bloomFactor = Math.max(0, bloomFactor - deltaTime);
disortFactor = Math.max(0, disortFactor - deltaTime);
highlightTimer -= delta;
if(highlightTimer<0) {
highlightCnt++;
highlightTimer = 0.0001f;
}
fontBatch.begin();
if (GameInstance.getInstance().showWeaponTextYAnimate < Gdx.graphics.getHeight()+100) {
if (GameInstance.getInstance().player.weapon instanceof MachineGun) {
font.draw(fontBatch, "Machinegun", 300, 250
+ GameInstance.getInstance().showWeaponTextYAnimate);
} else if (GameInstance.getInstance().player.weapon instanceof RocketLauncher) {
font.draw(fontBatch, "Rocket Launcher", 300, 250
+ GameInstance.getInstance().showWeaponTextYAnimate);
} else if (GameInstance.getInstance().player.weapon instanceof MinesLauncher) {
font.draw(fontBatch, "Mines Launcher", 300, 250
+ GameInstance.getInstance().showWeaponTextYAnimate);
}
GameInstance.getInstance().showWeaponTextYAnimate = Math.min(Gdx.graphics.getHeight()+100, GameInstance.getInstance().showWeaponTextYAnimate + (deltaTime*300f));
}
font.setScale(animateFont);
if(this.score != GameInstance.getInstance().score) {
animateFont = 3;
this.score = GameInstance.getInstance().score;
}
animateFont = Math.max(1.0f, animateFont - (deltaTime*10.f));
font.draw(fontBatch, score+" Points", 680, 480);
if(GameInstance.getInstance().currentHigh >= GameInstance.getInstance().recordHigh) {
font.draw(fontBatch, GameInstance.getInstance().currentHigh+"m - NEW RECORD! " + Gdx.graphics.getFramesPerSecond(), 30, 480);
} else {
font.draw(fontBatch, GameInstance.getInstance().currentHigh+"m - Record: " + GameInstance.getInstance().recordHigh + "m " + Gdx.graphics.getFramesPerSecond(), 30, 480);
}
fontBatch.end();
}
private void renderScene() {
Gdx.gl.glEnable(GL20.GL_CULL_FACE);
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
Gdx.gl20.glEnable(GL20.GL_BLEND);
Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
transShader.begin();
transShader.setUniformMatrix("VPMatrix", cam.combined);
//render boxes
for (int i =0; i<GameInstance.getInstance().blocks.size ; ++i) {
Block block = GameInstance.getInstance().blocks.get(i);
if(block.id == highlightCnt) {
block.highlightAnimate = 0.4f;
}
block.highlightAnimate = Math.max(0, block.highlightAnimate - delta);
if(cam.frustum.sphereInFrustum(tmpVector3.set(block.position.x, block.position.y, 0),1f)) {
model.idt();
if(block instanceof JumpBlock) {
//TODO quick hack
JumpBlock jumbBlock = (JumpBlock)block;
jumbBlock.update();
tmp.setToTranslation(jumbBlock.position.x, jumbBlock.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().jumpBlockColor[0], Resources.getInstance().jumpBlockColor[1], Resources.getInstance().jumpBlockColor[2], Resources.getInstance().jumpBlockColor[3] + jumbBlock.jumpAnim + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().jumpBlockEdgeColor[0], Resources.getInstance().jumpBlockEdgeColor[1],Resources.getInstance().jumpBlockEdgeColor[2], Resources.getInstance().jumpBlockEdgeColor[3] + jumbBlock.jumpAnim);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
{
- jumpani = 1- jumpani;
model.idt();
- tmp.setToTranslation(jumbBlock.position.x, jumbBlock.position.y+(1-jumpani), 0);
+ tmp.setToTranslation(jumbBlock.position.x, jumbBlock.position.y+(jumpani), 0);
model.mul(tmp);
- tmp.setToScaling(0.95f, 0.95f*jumpani, 0.95f);
+ tmp.setToScaling(0.90f, 0.95f*(1-jumpani), 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().jumpBlockColor[0], Resources.getInstance().jumpBlockColor[1], Resources.getInstance().jumpBlockColor[2], Resources.getInstance().jumpBlockColor[3] + jumbBlock.jumpAnim + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().jumpBlockEdgeColor[0], Resources.getInstance().jumpBlockEdgeColor[1],Resources.getInstance().jumpBlockEdgeColor[2], Resources.getInstance().jumpBlockEdgeColor[3] + jumbBlock.jumpAnim);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
}
} else if(block instanceof EnemySpawner) {
tmp.setToTranslation(block.position.x, block.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.8f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().enemySpawnerColor[0], Resources.getInstance().enemySpawnerColor[1]*blockani, Resources.getInstance().enemySpawnerColor[2], blockani);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().enemySpawnerEdgeColor[0], Resources.getInstance().enemySpawnerEdgeColor[1],Resources.getInstance().enemySpawnerEdgeColor[2], Resources.getInstance().enemySpawnerEdgeColor[3]);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
} else {
tmp.setToTranslation(block.position.x, block.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().blockColor[0], Resources.getInstance().blockColor[1], Resources.getInstance().blockColor[2], Resources.getInstance().blockColor[3] + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().blockEdgeColor[0], Resources.getInstance().blockEdgeColor[1],Resources.getInstance().blockEdgeColor[2], Resources.getInstance().blockEdgeColor[3]);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
}
// render powerUps
for (int i = 0; i < GameInstance.getInstance().powerUps.size; ++i) {
PowerUp powerUp = GameInstance.getInstance().powerUps.get(i);
if (cam.frustum.sphereInFrustum(tmpVector3.set(powerUp.position.x, powerUp.position.y, 0), 1f)) {
model.idt();
tmp.setToTranslation(powerUp.position.x, powerUp.position.y, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, MathUtils.radiansToDegrees * powerUp.angle);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().powerUpColor[0], Resources.getInstance().powerUpColor[1],
Resources.getInstance().powerUpColor[2], Math.min(powerUp.depth,Resources.getInstance().powerUpColor[3]));
playerModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().powerUpEdgeColor[0], Resources.getInstance().powerUpEdgeColor[1],
Resources.getInstance().powerUpEdgeColor[2], Math.min(powerUp.depth,Resources.getInstance().powerUpEdgeColor[3]));
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
// render enemies
for (int i = 0; i < GameInstance.getInstance().enemies.size; ++i) {
Enemy enemy = GameInstance.getInstance().enemies.get(i);
if (cam.frustum.sphereInFrustum(tmpVector3.set(enemy.position.x, enemy.position.y, 0), 1f)) {
model.idt();
tmp.setToTranslation(enemy.position.x, enemy.position.y, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, enemy.angle);
model.mul(tmp);
tmp.setToScaling(0.95f*enemy.size, 0.95f*enemy.size, 0.95f*enemy.size);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().enemyColor[0]+(enemy.hitAnimate*2), Resources.getInstance().enemyColor[1]+(enemy.hitAnimate*2),
Resources.getInstance().enemyColor[2]+(enemy.hitAnimate*2), Resources.getInstance().enemyColor[3]+(enemy.hitAnimate*2) - enemy.dyingAnimate);
playerModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().enemyEdgeColor[0], Resources.getInstance().enemyEdgeColor[1],
Resources.getInstance().enemyEdgeColor[2], Resources.getInstance().enemyEdgeColor[3]- enemy.dyingAnimate);
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
for (int i = 0; i < GameInstance.getInstance().bullets.size; ++i) {
Ammo bullet = GameInstance.getInstance().bullets.get(i);
if (cam.frustum.sphereInFrustum(tmpVector3.set(bullet.position.x, bullet.position.y, 0), 1f)) {
model.idt();
tmp.setToTranslation(bullet.position.x, bullet.position.y, 0);
model.mul(tmp);
//tmp.setToRotation(Vector3.Z, MathUtils.radiansToDegrees * bullet.angle);
//model.mul(tmp);
tmp.setToScaling(bullet.size,bullet.size,bullet.size);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().bulletColor[0], Resources.getInstance().bulletColor[1],
Resources.getInstance().bulletColor[2], Resources.getInstance().bulletColor[3]);
playerModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().bulletEdgeColor[0], Resources.getInstance().bulletEdgeColor[1],
Resources.getInstance().bulletEdgeColor[2], Resources.getInstance().bulletEdgeColor[3]);
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
//render player
{
tmp.idt();
model.idt();
tmp.setToScaling(1f, 1f, 1f);
model.mul(tmp);
tmp.setToTranslation(GameInstance.getInstance().player.position.x + GameInstance.getInstance().player.xdir*0.8f, GameInstance.getInstance().player.position.y-0.8f, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, GameInstance.getInstance().player.angle);
model.mul(tmp);
tmp.setToRotation(Vector3.X, angleXBack);
model.mul(tmp);
tmp.setToRotation(Vector3.Y, angleYBack);
model.mul(tmp);
tmp.setToScaling(0.5f, 0.5f, 0.5f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color",Resources.getInstance().playerColor[0], Resources.getInstance().playerColor[1], Resources.getInstance().playerColor[2], Resources.getInstance().playerColor[3]);
playerModel.render(transShader, GL20.GL_TRIANGLES);
tmp.idt();
model.idt();
tmp.setToScaling(1f, 1f, 1f);
model.mul(tmp);
tmp.setToTranslation(GameInstance.getInstance().player.position.x, GameInstance.getInstance().player.position.y-0.8f, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, GameInstance.getInstance().player.angle);
model.mul(tmp);
tmp.setToRotation(Vector3.X, angleXBack);
model.mul(tmp);
tmp.setToRotation(Vector3.Y, angleYBack);
model.mul(tmp);
tmp.setToScaling(1.0f, 1.0f, 1.0f);
model.mul(tmp);
//render hull
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color",Resources.getInstance().playerEdgeColor[0], Resources.getInstance().playerEdgeColor[1], Resources.getInstance().playerEdgeColor[2], Resources.getInstance().playerEdgeColor[3]);
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
transShader.end();
}
private void renderBackground() {
Gdx.gl.glEnable(GL20.GL_CULL_FACE);
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
Gdx.gl20.glEnable(GL20.GL_BLEND);
Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
transShader.begin();
transShader.setUniformMatrix("VPMatrix", cam.combined);
for(NoteJumper nj: noteJumpers) {
if(!nj.bofNote.isPlayedAt(ra.getTick())) {
nj.alive = false;
continue;
}
tmp.idt();
model.idt();
float move = (float) (1-Math.pow(nj.bofNote.getFraction(ra.getTick())-1, 4));
float move2 = (float) (1-Math.pow(nj.bofNote.getFraction(ra.getTick())-1, 2));
float length = (1-move);
Vector2 pos = new Vector2(nj.posA);
pos.x = nj.posA.x*(1-move) + nj.posB.x*(move);
pos.y = nj.posA.y*(1-move) + nj.posB.y*(move);
tmp.setToTranslation(nj.posA.x,cam.position.y + nj.posA.y, -1-nj.bofNote.getChannel()*0);
model.mul(tmp);
Vector2 dist = new Vector2(nj.posB);
dist = dist.sub(nj.posA);
dist = dist.nor();
float rotate = (float) (Math.atan2(dist.y, dist.x)/Math.PI*180.0);
tmp.setToRotation(new Vector3(0f,0f,1f), rotate);//+(float)county);
model.mul(tmp);
tmp.setToTranslation(nj.posA.dst(nj.posB)*move+0*length/2f,0, -1);
model.mul(tmp);
tmp.setToScaling(length, 0.1f+nj.bofNote.getVelocity(), 0.1f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", 1,1,1,1);
blockModel.render(transShader, GL20.GL_TRIANGLES);
///////////////////////////////////
tmp.idt();
model.idt();
move = nj.bofNote.getFraction(ra.getTick());//(float) (1-Math.pow(nj.bofNote.getFraction(tick)-1, 2));
pos = new Vector2(nj.posA);
pos.x = nj.posA.x*(1-move) + nj.posB.x*(move);
pos.y = nj.posA.y*(1-move) + nj.posB.y*(move);
tmp.setToTranslation(nj.posA.x,cam.position.y + nj.posA.y, 10f);
model.mul(tmp);
tmp.setToRotation(new Vector3(1f,0f, 0f), 90);
model.mul(tmp);
float factor = (float) (nj.bofNote.getDuration()/150.0);
tmp.setToScaling(0.5f+move*2*factor,0.5f+move*2*factor,0.5f+move*2*factor);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", 1,1,1,1-move);//1*(nj.bofNote.getChannel()%2),1*(nj.bofNote.getChannel()%3),0,(1-nj.bofNote.getFraction(ra.getTick()))*nj.bofNote.getVelocity());
torusModel.render(transShader, GL20.GL_TRIANGLES);
}
/*
// render plane background
for (int x = -0; x < 50; x = x +2) {
for (int z = -10; z < 10; z = z +2) {
model.idt();
tmp.setToTranslation(x, -25, z);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().blockBackgroundColor[0], Resources.getInstance().blockBackgroundColor[1],
Resources.getInstance().blockBackgroundColor[2], Resources.getInstance().blockBackgroundColor[3] - Helper.map(z, 10, -20, 0, 1.0f));
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().blockBackgroundEdgeColor[0], Resources.getInstance().blockBackgroundEdgeColor[1],
Resources.getInstance().blockBackgroundEdgeColor[2], Resources.getInstance().blockBackgroundEdgeColor[3] - Helper.map(z, 10, -20, 0, 1.0f));
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
// render static boxes
for (int i = 0; i < GameInstance.getInstance().background.backgroundBlocks.size; ++i) {
Block block = GameInstance.getInstance().background.backgroundBlocks.get(i);
model.idt();
tmp.setToTranslation(block.position.x, block.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().blockBackgroundColor[0], Resources.getInstance().blockBackgroundColor[1],
Resources.getInstance().blockBackgroundColor[2], Resources.getInstance().blockBackgroundColor[3] + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().blockBackgroundEdgeColor[0], Resources.getInstance().blockBackgroundEdgeColor[1],
Resources.getInstance().blockBackgroundEdgeColor[2], Resources.getInstance().blockBackgroundEdgeColor[3]);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
}
// render move boxes
for (int i = 0; i < GameInstance.getInstance().background.backgroundMoveBlocks.size; ++i) {
Block block = GameInstance.getInstance().background.backgroundMoveBlocks.get(i);
model.idt();
tmp.setToTranslation(block.position.x, block.position.y, 0);
model.mul(tmp);
block.angle += MathUtils.sin(startTime) * delta * 10f;
tmp.setToRotation(Vector3.Y, block.angle);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().blockBackgroundColor[0], Resources.getInstance().blockBackgroundColor[1],
Resources.getInstance().blockBackgroundColor[2], Resources.getInstance().blockBackgroundColor[3] + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().blockBackgroundEdgeColor[0], Resources.getInstance().blockBackgroundEdgeColor[1],
Resources.getInstance().blockBackgroundEdgeColor[2], Resources.getInstance().blockBackgroundEdgeColor[3]);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
}*/
transShader.end();
}
@Override
public boolean keyDown(int keycode) {
if(keycode == Keys.W) GameInstance.getInstance().player.jump = true;
if (keycode == Keys.ESCAPE) {
game.setScreen(new MainMenu(game));
}
if (keycode == Keys.R) {
GameInstance.getInstance().addEnemy();
}
if (keycode == Keys.S) {
ra.saveMidi();
}
if (keycode == Keys.Z) {
GameInstance.getInstance().addPowerUp();
}
if (keycode == Keys.F1) {
Resources.getInstance().prefs.putBoolean("bloom", !Resources.getInstance().prefs.getBoolean("bloom"));
Resources.getInstance().bloomOnOff = !Resources.getInstance().prefs.getBoolean("bloom");
Resources.getInstance().prefs.flush();
}
if (keycode == Keys.T) {
GameInstance.getInstance().changeWeapon();
}
if (keycode == Input.Keys.F) {
if(Gdx.app.getType() == ApplicationType.Desktop) {
if(!org.lwjgl.opengl.Display.isFullscreen()) {
Gdx.graphics.setDisplayMode(Gdx.graphics.getDesktopDisplayMode().width, Gdx.graphics.getDesktopDisplayMode().height, true);
} else {
Gdx.graphics.setDisplayMode(800,480, false);
}
}
Resources.getInstance().prefs.putBoolean("fullscreen", !Resources.getInstance().prefs.getBoolean("fullscreen"));
Resources.getInstance().fullscreenOnOff = !Resources.getInstance().prefs.getBoolean("fullscreen");
Resources.getInstance().prefs.flush();
}
return false;
}
@Override
public boolean keyUp(int keycode) {
if(keycode == Keys.W) GameInstance.getInstance().player.jump = false;
return false;
}
Vector2 last = null;
Vector3 point = new Vector3();
@Override
public boolean touchDown(int x, int y, int pointerId, int button) {
return false;
}
@Override
public void hide() {
System.out.println("dispose game screen");
ra.stop();
}
public float MidiToFrequenc(float note) {
return (float) (Math.pow(2, (note - 9) / 12.0) * 440);
}
@Override
public boolean keyTyped(char arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean scrolled(int arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDragged(int arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchMoved(int arg0, int arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchUp(int arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
return false;
}
}
| false | true | private void renderScene() {
Gdx.gl.glEnable(GL20.GL_CULL_FACE);
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
Gdx.gl20.glEnable(GL20.GL_BLEND);
Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
transShader.begin();
transShader.setUniformMatrix("VPMatrix", cam.combined);
//render boxes
for (int i =0; i<GameInstance.getInstance().blocks.size ; ++i) {
Block block = GameInstance.getInstance().blocks.get(i);
if(block.id == highlightCnt) {
block.highlightAnimate = 0.4f;
}
block.highlightAnimate = Math.max(0, block.highlightAnimate - delta);
if(cam.frustum.sphereInFrustum(tmpVector3.set(block.position.x, block.position.y, 0),1f)) {
model.idt();
if(block instanceof JumpBlock) {
//TODO quick hack
JumpBlock jumbBlock = (JumpBlock)block;
jumbBlock.update();
tmp.setToTranslation(jumbBlock.position.x, jumbBlock.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().jumpBlockColor[0], Resources.getInstance().jumpBlockColor[1], Resources.getInstance().jumpBlockColor[2], Resources.getInstance().jumpBlockColor[3] + jumbBlock.jumpAnim + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().jumpBlockEdgeColor[0], Resources.getInstance().jumpBlockEdgeColor[1],Resources.getInstance().jumpBlockEdgeColor[2], Resources.getInstance().jumpBlockEdgeColor[3] + jumbBlock.jumpAnim);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
{
jumpani = 1- jumpani;
model.idt();
tmp.setToTranslation(jumbBlock.position.x, jumbBlock.position.y+(1-jumpani), 0);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f*jumpani, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().jumpBlockColor[0], Resources.getInstance().jumpBlockColor[1], Resources.getInstance().jumpBlockColor[2], Resources.getInstance().jumpBlockColor[3] + jumbBlock.jumpAnim + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().jumpBlockEdgeColor[0], Resources.getInstance().jumpBlockEdgeColor[1],Resources.getInstance().jumpBlockEdgeColor[2], Resources.getInstance().jumpBlockEdgeColor[3] + jumbBlock.jumpAnim);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
}
} else if(block instanceof EnemySpawner) {
tmp.setToTranslation(block.position.x, block.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.8f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().enemySpawnerColor[0], Resources.getInstance().enemySpawnerColor[1]*blockani, Resources.getInstance().enemySpawnerColor[2], blockani);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().enemySpawnerEdgeColor[0], Resources.getInstance().enemySpawnerEdgeColor[1],Resources.getInstance().enemySpawnerEdgeColor[2], Resources.getInstance().enemySpawnerEdgeColor[3]);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
} else {
tmp.setToTranslation(block.position.x, block.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().blockColor[0], Resources.getInstance().blockColor[1], Resources.getInstance().blockColor[2], Resources.getInstance().blockColor[3] + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().blockEdgeColor[0], Resources.getInstance().blockEdgeColor[1],Resources.getInstance().blockEdgeColor[2], Resources.getInstance().blockEdgeColor[3]);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
}
// render powerUps
for (int i = 0; i < GameInstance.getInstance().powerUps.size; ++i) {
PowerUp powerUp = GameInstance.getInstance().powerUps.get(i);
if (cam.frustum.sphereInFrustum(tmpVector3.set(powerUp.position.x, powerUp.position.y, 0), 1f)) {
model.idt();
tmp.setToTranslation(powerUp.position.x, powerUp.position.y, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, MathUtils.radiansToDegrees * powerUp.angle);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().powerUpColor[0], Resources.getInstance().powerUpColor[1],
Resources.getInstance().powerUpColor[2], Math.min(powerUp.depth,Resources.getInstance().powerUpColor[3]));
playerModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().powerUpEdgeColor[0], Resources.getInstance().powerUpEdgeColor[1],
Resources.getInstance().powerUpEdgeColor[2], Math.min(powerUp.depth,Resources.getInstance().powerUpEdgeColor[3]));
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
// render enemies
for (int i = 0; i < GameInstance.getInstance().enemies.size; ++i) {
Enemy enemy = GameInstance.getInstance().enemies.get(i);
if (cam.frustum.sphereInFrustum(tmpVector3.set(enemy.position.x, enemy.position.y, 0), 1f)) {
model.idt();
tmp.setToTranslation(enemy.position.x, enemy.position.y, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, enemy.angle);
model.mul(tmp);
tmp.setToScaling(0.95f*enemy.size, 0.95f*enemy.size, 0.95f*enemy.size);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().enemyColor[0]+(enemy.hitAnimate*2), Resources.getInstance().enemyColor[1]+(enemy.hitAnimate*2),
Resources.getInstance().enemyColor[2]+(enemy.hitAnimate*2), Resources.getInstance().enemyColor[3]+(enemy.hitAnimate*2) - enemy.dyingAnimate);
playerModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().enemyEdgeColor[0], Resources.getInstance().enemyEdgeColor[1],
Resources.getInstance().enemyEdgeColor[2], Resources.getInstance().enemyEdgeColor[3]- enemy.dyingAnimate);
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
for (int i = 0; i < GameInstance.getInstance().bullets.size; ++i) {
Ammo bullet = GameInstance.getInstance().bullets.get(i);
if (cam.frustum.sphereInFrustum(tmpVector3.set(bullet.position.x, bullet.position.y, 0), 1f)) {
model.idt();
tmp.setToTranslation(bullet.position.x, bullet.position.y, 0);
model.mul(tmp);
//tmp.setToRotation(Vector3.Z, MathUtils.radiansToDegrees * bullet.angle);
//model.mul(tmp);
tmp.setToScaling(bullet.size,bullet.size,bullet.size);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().bulletColor[0], Resources.getInstance().bulletColor[1],
Resources.getInstance().bulletColor[2], Resources.getInstance().bulletColor[3]);
playerModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().bulletEdgeColor[0], Resources.getInstance().bulletEdgeColor[1],
Resources.getInstance().bulletEdgeColor[2], Resources.getInstance().bulletEdgeColor[3]);
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
//render player
{
tmp.idt();
model.idt();
tmp.setToScaling(1f, 1f, 1f);
model.mul(tmp);
tmp.setToTranslation(GameInstance.getInstance().player.position.x + GameInstance.getInstance().player.xdir*0.8f, GameInstance.getInstance().player.position.y-0.8f, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, GameInstance.getInstance().player.angle);
model.mul(tmp);
tmp.setToRotation(Vector3.X, angleXBack);
model.mul(tmp);
tmp.setToRotation(Vector3.Y, angleYBack);
model.mul(tmp);
tmp.setToScaling(0.5f, 0.5f, 0.5f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color",Resources.getInstance().playerColor[0], Resources.getInstance().playerColor[1], Resources.getInstance().playerColor[2], Resources.getInstance().playerColor[3]);
playerModel.render(transShader, GL20.GL_TRIANGLES);
tmp.idt();
model.idt();
tmp.setToScaling(1f, 1f, 1f);
model.mul(tmp);
tmp.setToTranslation(GameInstance.getInstance().player.position.x, GameInstance.getInstance().player.position.y-0.8f, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, GameInstance.getInstance().player.angle);
model.mul(tmp);
tmp.setToRotation(Vector3.X, angleXBack);
model.mul(tmp);
tmp.setToRotation(Vector3.Y, angleYBack);
model.mul(tmp);
tmp.setToScaling(1.0f, 1.0f, 1.0f);
model.mul(tmp);
//render hull
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color",Resources.getInstance().playerEdgeColor[0], Resources.getInstance().playerEdgeColor[1], Resources.getInstance().playerEdgeColor[2], Resources.getInstance().playerEdgeColor[3]);
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
transShader.end();
}
| private void renderScene() {
Gdx.gl.glEnable(GL20.GL_CULL_FACE);
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
Gdx.gl20.glEnable(GL20.GL_BLEND);
Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
transShader.begin();
transShader.setUniformMatrix("VPMatrix", cam.combined);
//render boxes
for (int i =0; i<GameInstance.getInstance().blocks.size ; ++i) {
Block block = GameInstance.getInstance().blocks.get(i);
if(block.id == highlightCnt) {
block.highlightAnimate = 0.4f;
}
block.highlightAnimate = Math.max(0, block.highlightAnimate - delta);
if(cam.frustum.sphereInFrustum(tmpVector3.set(block.position.x, block.position.y, 0),1f)) {
model.idt();
if(block instanceof JumpBlock) {
//TODO quick hack
JumpBlock jumbBlock = (JumpBlock)block;
jumbBlock.update();
tmp.setToTranslation(jumbBlock.position.x, jumbBlock.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().jumpBlockColor[0], Resources.getInstance().jumpBlockColor[1], Resources.getInstance().jumpBlockColor[2], Resources.getInstance().jumpBlockColor[3] + jumbBlock.jumpAnim + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().jumpBlockEdgeColor[0], Resources.getInstance().jumpBlockEdgeColor[1],Resources.getInstance().jumpBlockEdgeColor[2], Resources.getInstance().jumpBlockEdgeColor[3] + jumbBlock.jumpAnim);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
{
model.idt();
tmp.setToTranslation(jumbBlock.position.x, jumbBlock.position.y+(jumpani), 0);
model.mul(tmp);
tmp.setToScaling(0.90f, 0.95f*(1-jumpani), 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().jumpBlockColor[0], Resources.getInstance().jumpBlockColor[1], Resources.getInstance().jumpBlockColor[2], Resources.getInstance().jumpBlockColor[3] + jumbBlock.jumpAnim + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().jumpBlockEdgeColor[0], Resources.getInstance().jumpBlockEdgeColor[1],Resources.getInstance().jumpBlockEdgeColor[2], Resources.getInstance().jumpBlockEdgeColor[3] + jumbBlock.jumpAnim);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
}
} else if(block instanceof EnemySpawner) {
tmp.setToTranslation(block.position.x, block.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.8f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().enemySpawnerColor[0], Resources.getInstance().enemySpawnerColor[1]*blockani, Resources.getInstance().enemySpawnerColor[2], blockani);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().enemySpawnerEdgeColor[0], Resources.getInstance().enemySpawnerEdgeColor[1],Resources.getInstance().enemySpawnerEdgeColor[2], Resources.getInstance().enemySpawnerEdgeColor[3]);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
} else {
tmp.setToTranslation(block.position.x, block.position.y, 0);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().blockColor[0], Resources.getInstance().blockColor[1], Resources.getInstance().blockColor[2], Resources.getInstance().blockColor[3] + block.highlightAnimate);
blockModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color",Resources.getInstance().blockEdgeColor[0], Resources.getInstance().blockEdgeColor[1],Resources.getInstance().blockEdgeColor[2], Resources.getInstance().blockEdgeColor[3]);
wireCubeModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
}
// render powerUps
for (int i = 0; i < GameInstance.getInstance().powerUps.size; ++i) {
PowerUp powerUp = GameInstance.getInstance().powerUps.get(i);
if (cam.frustum.sphereInFrustum(tmpVector3.set(powerUp.position.x, powerUp.position.y, 0), 1f)) {
model.idt();
tmp.setToTranslation(powerUp.position.x, powerUp.position.y, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, MathUtils.radiansToDegrees * powerUp.angle);
model.mul(tmp);
tmp.setToScaling(0.95f, 0.95f, 0.95f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().powerUpColor[0], Resources.getInstance().powerUpColor[1],
Resources.getInstance().powerUpColor[2], Math.min(powerUp.depth,Resources.getInstance().powerUpColor[3]));
playerModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().powerUpEdgeColor[0], Resources.getInstance().powerUpEdgeColor[1],
Resources.getInstance().powerUpEdgeColor[2], Math.min(powerUp.depth,Resources.getInstance().powerUpEdgeColor[3]));
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
// render enemies
for (int i = 0; i < GameInstance.getInstance().enemies.size; ++i) {
Enemy enemy = GameInstance.getInstance().enemies.get(i);
if (cam.frustum.sphereInFrustum(tmpVector3.set(enemy.position.x, enemy.position.y, 0), 1f)) {
model.idt();
tmp.setToTranslation(enemy.position.x, enemy.position.y, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, enemy.angle);
model.mul(tmp);
tmp.setToScaling(0.95f*enemy.size, 0.95f*enemy.size, 0.95f*enemy.size);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().enemyColor[0]+(enemy.hitAnimate*2), Resources.getInstance().enemyColor[1]+(enemy.hitAnimate*2),
Resources.getInstance().enemyColor[2]+(enemy.hitAnimate*2), Resources.getInstance().enemyColor[3]+(enemy.hitAnimate*2) - enemy.dyingAnimate);
playerModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().enemyEdgeColor[0], Resources.getInstance().enemyEdgeColor[1],
Resources.getInstance().enemyEdgeColor[2], Resources.getInstance().enemyEdgeColor[3]- enemy.dyingAnimate);
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
for (int i = 0; i < GameInstance.getInstance().bullets.size; ++i) {
Ammo bullet = GameInstance.getInstance().bullets.get(i);
if (cam.frustum.sphereInFrustum(tmpVector3.set(bullet.position.x, bullet.position.y, 0), 1f)) {
model.idt();
tmp.setToTranslation(bullet.position.x, bullet.position.y, 0);
model.mul(tmp);
//tmp.setToRotation(Vector3.Z, MathUtils.radiansToDegrees * bullet.angle);
//model.mul(tmp);
tmp.setToScaling(bullet.size,bullet.size,bullet.size);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color", Resources.getInstance().bulletColor[0], Resources.getInstance().bulletColor[1],
Resources.getInstance().bulletColor[2], Resources.getInstance().bulletColor[3]);
playerModel.render(transShader, GL20.GL_TRIANGLES);
transShader.setUniformf("a_color", Resources.getInstance().bulletEdgeColor[0], Resources.getInstance().bulletEdgeColor[1],
Resources.getInstance().bulletEdgeColor[2], Resources.getInstance().bulletEdgeColor[3]);
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
}
//render player
{
tmp.idt();
model.idt();
tmp.setToScaling(1f, 1f, 1f);
model.mul(tmp);
tmp.setToTranslation(GameInstance.getInstance().player.position.x + GameInstance.getInstance().player.xdir*0.8f, GameInstance.getInstance().player.position.y-0.8f, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, GameInstance.getInstance().player.angle);
model.mul(tmp);
tmp.setToRotation(Vector3.X, angleXBack);
model.mul(tmp);
tmp.setToRotation(Vector3.Y, angleYBack);
model.mul(tmp);
tmp.setToScaling(0.5f, 0.5f, 0.5f);
model.mul(tmp);
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color",Resources.getInstance().playerColor[0], Resources.getInstance().playerColor[1], Resources.getInstance().playerColor[2], Resources.getInstance().playerColor[3]);
playerModel.render(transShader, GL20.GL_TRIANGLES);
tmp.idt();
model.idt();
tmp.setToScaling(1f, 1f, 1f);
model.mul(tmp);
tmp.setToTranslation(GameInstance.getInstance().player.position.x, GameInstance.getInstance().player.position.y-0.8f, 0);
model.mul(tmp);
tmp.setToRotation(Vector3.Z, GameInstance.getInstance().player.angle);
model.mul(tmp);
tmp.setToRotation(Vector3.X, angleXBack);
model.mul(tmp);
tmp.setToRotation(Vector3.Y, angleYBack);
model.mul(tmp);
tmp.setToScaling(1.0f, 1.0f, 1.0f);
model.mul(tmp);
//render hull
transShader.setUniformMatrix("MMatrix", model);
transShader.setUniformf("a_color",Resources.getInstance().playerEdgeColor[0], Resources.getInstance().playerEdgeColor[1], Resources.getInstance().playerEdgeColor[2], Resources.getInstance().playerEdgeColor[3]);
playerModel.render(transShader, GL20.GL_LINE_STRIP);
}
transShader.end();
}
|
diff --git a/Bukkit/Metrics.java b/Bukkit/Metrics.java
index b83ac8c..47ecbd3 100644
--- a/Bukkit/Metrics.java
+++ b/Bukkit/Metrics.java
@@ -1,272 +1,272 @@
/*
* Copyright 2011 Tyler Blair. 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.
*
* 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 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* Tooling to post to metrics.griefcraft.com
*/
public class Metrics {
/**
* Interface used to collect custom data for a plugin
*/
public static abstract class Plotter {
/**
* Get the column name for the plotted point
*
* @return the plotted point's column name
*/
public abstract String getColumnName();
/**
* Get the current value for the plotted point
*
* @return
*/
public abstract int getValue();
/**
* Called after the website graphs have been updated
*/
public void reset() {
}
@Override
public int hashCode() {
return getColumnName().hashCode() + getValue();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Plotter)) {
return false;
}
Plotter plotter = (Plotter) object;
return plotter.getColumnName().equals(getColumnName()) && plotter.getValue() == getValue();
}
}
/**
* The metrics revision number
*/
private final static int REVISION = 4;
/**
* The base url of the metrics domain
*/
private static final String BASE_URL = "http://metrics.griefcraft.com";
/**
* The url used to report a server's status
*/
private static final String REPORT_URL = "/report/%s";
/**
* The file where guid and opt out is stored in
*/
private static final String CONFIG_FILE = "plugins/PluginMetrics/config.yml";
/**
* Interval of time to ping in minutes
*/
private final static int PING_INTERVAL = 10;
/**
* A map of the custom data plotters for plugins
*/
private Map<Plugin, Set<Plotter>> customData = Collections.synchronizedMap(new HashMap<Plugin, Set<Plotter>>());
/**
* The plugin configuration file
*/
private final YamlConfiguration configuration;
/**
* Unique server id
*/
private String guid;
public Metrics() throws IOException {
// load the config
File file = new File(CONFIG_FILE);
configuration = YamlConfiguration.loadConfiguration(file);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://metrics.griefcraft.com").copyDefaults(true);
configuration.save(file);
}
// Load the guid then
guid = configuration.getString("guid");
}
/**
* Adds a custom data plotter for a given plugin
*
* @param plugin
* @param plotter
*/
public void addCustomData(Plugin plugin, Plotter plotter) {
Set<Plotter> plotters = customData.get(plugin);
if (plotters == null) {
plotters = Collections.synchronizedSet(new LinkedHashSet<Plotter>());
customData.put(plugin, plotters);
}
plotters.add(plotter);
}
/**
* Begin measuring a plugin
*
* @param plugin
*/
public void beginMeasuringPlugin(final Plugin plugin) throws IOException {
// Did we opt out?
if (configuration.getBoolean("opt-out", false)) {
return;
}
// First tell the server about us
postPlugin(plugin, false);
// Ping the server in intervals
plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() {
public void run() {
try {
postPlugin(plugin, true);
} catch (IOException e) {
System.out.println("[Metrics] " + e.getMessage());
}
}
}, PING_INTERVAL * 1200, PING_INTERVAL * 1200);
}
/**
* Generic method that posts a plugin to the metrics website
*
* @param plugin
*/
private void postPlugin(Plugin plugin, boolean isPing) throws IOException {
// Construct the post data
String response = "ERR No response";
String data = encode("guid") + '=' + encode(guid)
+ '&' + encode("version") + '=' + encode(plugin.getDescription().getVersion())
+ '&' + encode("server") + '=' + encode(Bukkit.getVersion())
+ '&' + encode("players") + '=' + encode(String.valueOf(Bukkit.getServer().getOnlinePlayers().length))
+ '&' + encode("revision") + '=' + encode(REVISION + "");
// If we're pinging, append it
if (isPing) {
data += '&' + encode("ping") + '=' + encode("true");
}
// Add any custom data (if applicable)
Set<Plotter> plotters = customData.get(plugin);
if (plotters != null) {
for (Plotter plotter : plotters) {
- data += "&" + encode ("Custom" + plotter.getColumnName())
+ data += "&" + encode("Custom" + plotter.getColumnName())
+ "=" + encode(Integer.toString(plotter.getValue()));
}
}
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName()));
// Connect to the website
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
// Write the data
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
// Now read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
response = reader.readLine();
// close resources
writer.close();
reader.close();
- if (response.startsWith("ERR")){
+ if (response.startsWith("ERR")) {
throw new IOException(response); //Throw the exception
} else {
// Is this the first update this hour?
if (response.contains("OK This is your first update this hour")) {
if (plotters != null) {
for (Plotter plotter : plotters) {
plotter.reset();
}
}
}
}
//if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right
}
/**
* Encode text as UTF-8
*
* @param text
* @return
*/
private static String encode(String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
}
| false | true | private void postPlugin(Plugin plugin, boolean isPing) throws IOException {
// Construct the post data
String response = "ERR No response";
String data = encode("guid") + '=' + encode(guid)
+ '&' + encode("version") + '=' + encode(plugin.getDescription().getVersion())
+ '&' + encode("server") + '=' + encode(Bukkit.getVersion())
+ '&' + encode("players") + '=' + encode(String.valueOf(Bukkit.getServer().getOnlinePlayers().length))
+ '&' + encode("revision") + '=' + encode(REVISION + "");
// If we're pinging, append it
if (isPing) {
data += '&' + encode("ping") + '=' + encode("true");
}
// Add any custom data (if applicable)
Set<Plotter> plotters = customData.get(plugin);
if (plotters != null) {
for (Plotter plotter : plotters) {
data += "&" + encode ("Custom" + plotter.getColumnName())
+ "=" + encode(Integer.toString(plotter.getValue()));
}
}
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName()));
// Connect to the website
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
// Write the data
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
// Now read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
response = reader.readLine();
// close resources
writer.close();
reader.close();
if (response.startsWith("ERR")){
throw new IOException(response); //Throw the exception
} else {
// Is this the first update this hour?
if (response.contains("OK This is your first update this hour")) {
if (plotters != null) {
for (Plotter plotter : plotters) {
plotter.reset();
}
}
}
}
//if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right
}
| private void postPlugin(Plugin plugin, boolean isPing) throws IOException {
// Construct the post data
String response = "ERR No response";
String data = encode("guid") + '=' + encode(guid)
+ '&' + encode("version") + '=' + encode(plugin.getDescription().getVersion())
+ '&' + encode("server") + '=' + encode(Bukkit.getVersion())
+ '&' + encode("players") + '=' + encode(String.valueOf(Bukkit.getServer().getOnlinePlayers().length))
+ '&' + encode("revision") + '=' + encode(REVISION + "");
// If we're pinging, append it
if (isPing) {
data += '&' + encode("ping") + '=' + encode("true");
}
// Add any custom data (if applicable)
Set<Plotter> plotters = customData.get(plugin);
if (plotters != null) {
for (Plotter plotter : plotters) {
data += "&" + encode("Custom" + plotter.getColumnName())
+ "=" + encode(Integer.toString(plotter.getValue()));
}
}
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName()));
// Connect to the website
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
// Write the data
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
// Now read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
response = reader.readLine();
// close resources
writer.close();
reader.close();
if (response.startsWith("ERR")) {
throw new IOException(response); //Throw the exception
} else {
// Is this the first update this hour?
if (response.contains("OK This is your first update this hour")) {
if (plotters != null) {
for (Plotter plotter : plotters) {
plotter.reset();
}
}
}
}
//if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right
}
|
diff --git a/Poker/src/poker/arturka/Game.java b/Poker/src/poker/arturka/Game.java
index 3bca7af..10d3974 100644
--- a/Poker/src/poker/arturka/Game.java
+++ b/Poker/src/poker/arturka/Game.java
@@ -1,140 +1,140 @@
package poker.arturka;
import commands.FRCallCommand;
import commands.FRCheckCommand;
import commands.FlopCommand;
import commands.TurnRiverCommand;
import message.data.ClientResponse;
import poker.server.Room;
import message.data.ClientTurn;
import java.util.ArrayList;
import java.util.List;
public class Game implements Runnable {
private Deck deck;
private Players players;
private int blind;
private List<Card> table;
private int maxBet;
private int state;
private Room room;
public Game(Room room){
deck=new Deck();
players=new Players();
blind=30;
maxBet=0;
table=new ArrayList<Card>();
state=0;
this.room=room;
for(int id: room.getUsers()){
players.addPlayer(id);
}
}
private void splitPot(){
}
private void endGame(){
if (players.playersLeft().size()>1){
}else{
}
}
private boolean raiseBet(int playerPot){
if (playerPot>maxBet){
maxBet=playerPot;
return true;
}else{
return false;
}
}
public void run() {
// for(int id: Room.getUsers()){
// players.addPlayer(id);
// }
players.nextDealer();
Player nextPlayer=players.getNextPlayer(players.getDealer());
if (!nextPlayer.bet(blind/2)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
nextPlayer=players.getNextPlayer(nextPlayer);
if (!nextPlayer.bet(blind)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
deck.shuffleDeck();
Player currentPlayer=players.getNextPlayer(players.getDealer());
do{
currentPlayer.giveCards(deck.getTopCard(),deck.getTopCard());
}while(players.getDealer()!=currentPlayer);
Player firstBetter=players.getNextPlayer(nextPlayer);
//todo abstractions, rewrite to actual methods
Player better=firstBetter;
ClientResponse move;
while(state<4){
do{
if(!better.hasFolded()&&better.getCash()>0){
if(better.getBet()==maxBet){
move = room.sendToUser(better.getId(),new FRCheckCommand());
}else{
move = room.sendToUser(better.getId(),new FRCallCommand());
}
switch(move.turn){
case FOLD:
better.toggleFold();
continue;
case CHECK:
continue;
case CALL:
better.bet(maxBet-better.getBet());
continue;
case RAISE:
better.bet(move.getBet());
raiseBet(better.getBet());
firstBetter=better;
continue;
case EXIT:
better.toggleFold();
players.removePlayer(better.getId());
}
if(players.playersLeft().size()<2){
endGame();
}
}
better=players.getNextPlayer(better);
}while (better==firstBetter);
switch (state){
case 0:
table.add(deck.getTopCard());
table.add(deck.getTopCard());
table.add(deck.getTopCard());
room.Broadcast(new FlopCommand(table.get(0),table.get(1),table.get(2)));
state++;
break;
case 1:
deck.getTopCard();
table.add(deck.getTopCard());
- room.Broadcast(new TurnRiverCommand(table.get(3),TurnRiverCommand.RorT.Turn));
+ room.Broadcast(new TurnRiverCommand(table.get(3),TurnRiverCommand.RorT.TURN));
state++;
break;
case 2:
deck.getTopCard();
table.add(deck.getTopCard());
- room.Broadcast(new TurnRiverCommand(table.get(4),TurnRiverCommand.RorT.River));
+ room.Broadcast(new TurnRiverCommand(table.get(4),TurnRiverCommand.RorT.RIVER));
state++;
break;
default:
state++;
}
}
endGame();
}
}
| false | true | public void run() {
// for(int id: Room.getUsers()){
// players.addPlayer(id);
// }
players.nextDealer();
Player nextPlayer=players.getNextPlayer(players.getDealer());
if (!nextPlayer.bet(blind/2)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
nextPlayer=players.getNextPlayer(nextPlayer);
if (!nextPlayer.bet(blind)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
deck.shuffleDeck();
Player currentPlayer=players.getNextPlayer(players.getDealer());
do{
currentPlayer.giveCards(deck.getTopCard(),deck.getTopCard());
}while(players.getDealer()!=currentPlayer);
Player firstBetter=players.getNextPlayer(nextPlayer);
//todo abstractions, rewrite to actual methods
Player better=firstBetter;
ClientResponse move;
while(state<4){
do{
if(!better.hasFolded()&&better.getCash()>0){
if(better.getBet()==maxBet){
move = room.sendToUser(better.getId(),new FRCheckCommand());
}else{
move = room.sendToUser(better.getId(),new FRCallCommand());
}
switch(move.turn){
case FOLD:
better.toggleFold();
continue;
case CHECK:
continue;
case CALL:
better.bet(maxBet-better.getBet());
continue;
case RAISE:
better.bet(move.getBet());
raiseBet(better.getBet());
firstBetter=better;
continue;
case EXIT:
better.toggleFold();
players.removePlayer(better.getId());
}
if(players.playersLeft().size()<2){
endGame();
}
}
better=players.getNextPlayer(better);
}while (better==firstBetter);
switch (state){
case 0:
table.add(deck.getTopCard());
table.add(deck.getTopCard());
table.add(deck.getTopCard());
room.Broadcast(new FlopCommand(table.get(0),table.get(1),table.get(2)));
state++;
break;
case 1:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(3),TurnRiverCommand.RorT.Turn));
state++;
break;
case 2:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(4),TurnRiverCommand.RorT.River));
state++;
break;
default:
state++;
}
}
endGame();
}
| public void run() {
// for(int id: Room.getUsers()){
// players.addPlayer(id);
// }
players.nextDealer();
Player nextPlayer=players.getNextPlayer(players.getDealer());
if (!nextPlayer.bet(blind/2)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
nextPlayer=players.getNextPlayer(nextPlayer);
if (!nextPlayer.bet(blind)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
deck.shuffleDeck();
Player currentPlayer=players.getNextPlayer(players.getDealer());
do{
currentPlayer.giveCards(deck.getTopCard(),deck.getTopCard());
}while(players.getDealer()!=currentPlayer);
Player firstBetter=players.getNextPlayer(nextPlayer);
//todo abstractions, rewrite to actual methods
Player better=firstBetter;
ClientResponse move;
while(state<4){
do{
if(!better.hasFolded()&&better.getCash()>0){
if(better.getBet()==maxBet){
move = room.sendToUser(better.getId(),new FRCheckCommand());
}else{
move = room.sendToUser(better.getId(),new FRCallCommand());
}
switch(move.turn){
case FOLD:
better.toggleFold();
continue;
case CHECK:
continue;
case CALL:
better.bet(maxBet-better.getBet());
continue;
case RAISE:
better.bet(move.getBet());
raiseBet(better.getBet());
firstBetter=better;
continue;
case EXIT:
better.toggleFold();
players.removePlayer(better.getId());
}
if(players.playersLeft().size()<2){
endGame();
}
}
better=players.getNextPlayer(better);
}while (better==firstBetter);
switch (state){
case 0:
table.add(deck.getTopCard());
table.add(deck.getTopCard());
table.add(deck.getTopCard());
room.Broadcast(new FlopCommand(table.get(0),table.get(1),table.get(2)));
state++;
break;
case 1:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(3),TurnRiverCommand.RorT.TURN));
state++;
break;
case 2:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(4),TurnRiverCommand.RorT.RIVER));
state++;
break;
default:
state++;
}
}
endGame();
}
|
diff --git a/loci/formats/out/OMETiffWriter.java b/loci/formats/out/OMETiffWriter.java
index 7b7dc62f6..659ab33ec 100644
--- a/loci/formats/out/OMETiffWriter.java
+++ b/loci/formats/out/OMETiffWriter.java
@@ -1,77 +1,84 @@
//
// OMETiffWriter.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This 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 Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.out;
import java.io.IOException;
import loci.formats.*;
import loci.formats.meta.MetadataRetrieve;
/**
* OMETiffWriter is the file format writer for OME-TIFF files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/out/OMETiffWriter.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/out/OMETiffWriter.java">SVN</a></dd></dl>
*/
public class OMETiffWriter extends TiffWriter {
// -- Constructor --
public OMETiffWriter() {
super("OME-TIFF", new String[] {"ome.tif", "ome.tiff"});
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
if (out != null) out.close();
out = null;
if (currentId != null) {
// extract OME-XML string from metadata object
MetadataRetrieve retrieve = getMetadataRetrieve();
String xml = MetadataTools.getOMEXML(retrieve);
// insert TiffData element
int pix = xml.indexOf("<Pixels ");
- int end = xml.indexOf("/>", pix);
- xml = xml.substring(0, end) + "><TiffData/></Pixels>" +
- xml.substring(end + 2);
+ int end = xml.indexOf("</Pixels>", pix);
+ if (end != -1) {
+ xml = xml.substring(0, end) + "<TiffData/></Pixels>" +
+ xml.substring(end + 9);
+ }
+ else {
+ end = xml.indexOf("/>", pix);
+ xml = xml.substring(0, end) + "><TiffData/></Pixels>" +
+ xml.substring(end + 2);
+ }
// write OME-XML to the first IFD's comment
try {
TiffTools.overwriteComment(currentId, xml);
}
catch (FormatException exc) {
IOException io =
new IOException("Unable to append OME-XML comment");
io.initCause(exc);
throw io;
}
}
super.close();
}
}
| true | true | public void close() throws IOException {
if (out != null) out.close();
out = null;
if (currentId != null) {
// extract OME-XML string from metadata object
MetadataRetrieve retrieve = getMetadataRetrieve();
String xml = MetadataTools.getOMEXML(retrieve);
// insert TiffData element
int pix = xml.indexOf("<Pixels ");
int end = xml.indexOf("/>", pix);
xml = xml.substring(0, end) + "><TiffData/></Pixels>" +
xml.substring(end + 2);
// write OME-XML to the first IFD's comment
try {
TiffTools.overwriteComment(currentId, xml);
}
catch (FormatException exc) {
IOException io =
new IOException("Unable to append OME-XML comment");
io.initCause(exc);
throw io;
}
}
super.close();
}
| public void close() throws IOException {
if (out != null) out.close();
out = null;
if (currentId != null) {
// extract OME-XML string from metadata object
MetadataRetrieve retrieve = getMetadataRetrieve();
String xml = MetadataTools.getOMEXML(retrieve);
// insert TiffData element
int pix = xml.indexOf("<Pixels ");
int end = xml.indexOf("</Pixels>", pix);
if (end != -1) {
xml = xml.substring(0, end) + "<TiffData/></Pixels>" +
xml.substring(end + 9);
}
else {
end = xml.indexOf("/>", pix);
xml = xml.substring(0, end) + "><TiffData/></Pixels>" +
xml.substring(end + 2);
}
// write OME-XML to the first IFD's comment
try {
TiffTools.overwriteComment(currentId, xml);
}
catch (FormatException exc) {
IOException io =
new IOException("Unable to append OME-XML comment");
io.initCause(exc);
throw io;
}
}
super.close();
}
|
diff --git a/src/main/java/org/freenetproject/plugin/infocalypse_webui/ui/fcp/FCPHandler.java b/src/main/java/org/freenetproject/plugin/infocalypse_webui/ui/fcp/FCPHandler.java
index 9865518..8ac1bc8 100644
--- a/src/main/java/org/freenetproject/plugin/infocalypse_webui/ui/fcp/FCPHandler.java
+++ b/src/main/java/org/freenetproject/plugin/infocalypse_webui/ui/fcp/FCPHandler.java
@@ -1,106 +1,106 @@
package org.freenetproject.plugin.infocalypse_webui.ui.fcp;
import freenet.pluginmanager.FredPluginFCP;
import freenet.pluginmanager.PluginNotFoundException;
import freenet.pluginmanager.PluginReplySender;
import freenet.support.SimpleFieldSet;
import freenet.support.api.Bucket;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Tracks session state and dispatches messages to specific handlers.
*/
public class FCPHandler implements FredPluginFCP {
/*
* TODO: Where to keep state, like which sessions are still considered connected? Hm, that should be any message.
* Still, where to keep state when it is needed? Per message type doesn't seem to make sense. It depends on the
* type of state and where it's needed, so perhaps that remains to be seen when actual functionality comes into
* the fold.
*
* Is connectedness only a UI thing? It would make sense if any message causes reconnection,
* and there isn't yet an apparent reason why a session would carry its own state.
*
* So Infocalypse sends Ping, which merits no response, and ClearToSend, which replies with whatever user request
* from the UI?
*
* TODO: Does it make sense to only allow one session at once? Is there a less ugly way to implement a timeout?
*/
/**
* Seconds before an FCP connection to Infocalypse is considered timed out.
*/
public static final long fcpTimeout = 5;
private String connectedIdentifier;
private final ScheduledThreadPoolExecutor executor;
private ScheduledFuture future;
public FCPHandler() {
executor = new ScheduledThreadPoolExecutor(1);
}
@Override
- public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) {
- // TODO: What to do with accesstype?
+ public void handle(PluginReplySender replySender, SimpleFieldSet params, Bucket data, int accessType) {
+ // TODO: What to do with accessType?
synchronized (executor) {
if (connectedIdentifier == null) {
- connectedIdentifier = replysender.getIdentifier();
- } else if (!connectedIdentifier.equals(replysender.getIdentifier())) {
+ connectedIdentifier = replySender.getIdentifier();
+ } else if (!connectedIdentifier.equals(replySender.getIdentifier())) {
// A different identifier is already connected.
SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "Error");
sfs.putOverwrite("Description", "An Infocalypse session is already connected: " + connectedIdentifier);
try {
- replysender.send(sfs);
+ replySender.send(sfs);
} catch (PluginNotFoundException e) {
// TODO: Lazy error handling. Look into real logging.
System.err.println("Cannot find plugin / connection closed: " + e);
}
return;
} else {
// This identifier was already connected.
- assert connectedIdentifier.equals(replysender.getIdentifier());
+ assert connectedIdentifier.equals(replySender.getIdentifier());
// In order to be connected the timeout should already be scheduled.
assert future != null;
future.cancel(false);
}
future = executor.schedule(new Runnable() {
@Override
public void run() {
synchronized (executor) {
connectedIdentifier = null;
}
}
}, fcpTimeout, TimeUnit.SECONDS);
}
final String messageName = params.get("Message");
final MessageHandler handler;
if ("Ping".equals(messageName)) {
handler = new Ping();
} else {
handler = new Unknown();
}
try {
- replysender.send(handler.reply(params));
+ replySender.send(handler.reply(params));
} catch (PluginNotFoundException e) {
// TODO: Copy and paste from above. Wrapper, rearrange control flow, or just put up with it?
System.err.println("Cannot find plugin / connection closed: " + e);
}
}
/**
* @return the identifier of the connected session, or null if no session is connected.
*/
public String getConnectedIdentifier() {
synchronized (executor) {
return connectedIdentifier;
}
}
}
| false | true | public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) {
// TODO: What to do with accesstype?
synchronized (executor) {
if (connectedIdentifier == null) {
connectedIdentifier = replysender.getIdentifier();
} else if (!connectedIdentifier.equals(replysender.getIdentifier())) {
// A different identifier is already connected.
SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "Error");
sfs.putOverwrite("Description", "An Infocalypse session is already connected: " + connectedIdentifier);
try {
replysender.send(sfs);
} catch (PluginNotFoundException e) {
// TODO: Lazy error handling. Look into real logging.
System.err.println("Cannot find plugin / connection closed: " + e);
}
return;
} else {
// This identifier was already connected.
assert connectedIdentifier.equals(replysender.getIdentifier());
// In order to be connected the timeout should already be scheduled.
assert future != null;
future.cancel(false);
}
future = executor.schedule(new Runnable() {
@Override
public void run() {
synchronized (executor) {
connectedIdentifier = null;
}
}
}, fcpTimeout, TimeUnit.SECONDS);
}
final String messageName = params.get("Message");
final MessageHandler handler;
if ("Ping".equals(messageName)) {
handler = new Ping();
} else {
handler = new Unknown();
}
try {
replysender.send(handler.reply(params));
} catch (PluginNotFoundException e) {
// TODO: Copy and paste from above. Wrapper, rearrange control flow, or just put up with it?
System.err.println("Cannot find plugin / connection closed: " + e);
}
}
| public void handle(PluginReplySender replySender, SimpleFieldSet params, Bucket data, int accessType) {
// TODO: What to do with accessType?
synchronized (executor) {
if (connectedIdentifier == null) {
connectedIdentifier = replySender.getIdentifier();
} else if (!connectedIdentifier.equals(replySender.getIdentifier())) {
// A different identifier is already connected.
SimpleFieldSet sfs = new SimpleFieldSet(true);
sfs.putOverwrite("Message", "Error");
sfs.putOverwrite("Description", "An Infocalypse session is already connected: " + connectedIdentifier);
try {
replySender.send(sfs);
} catch (PluginNotFoundException e) {
// TODO: Lazy error handling. Look into real logging.
System.err.println("Cannot find plugin / connection closed: " + e);
}
return;
} else {
// This identifier was already connected.
assert connectedIdentifier.equals(replySender.getIdentifier());
// In order to be connected the timeout should already be scheduled.
assert future != null;
future.cancel(false);
}
future = executor.schedule(new Runnable() {
@Override
public void run() {
synchronized (executor) {
connectedIdentifier = null;
}
}
}, fcpTimeout, TimeUnit.SECONDS);
}
final String messageName = params.get("Message");
final MessageHandler handler;
if ("Ping".equals(messageName)) {
handler = new Ping();
} else {
handler = new Unknown();
}
try {
replySender.send(handler.reply(params));
} catch (PluginNotFoundException e) {
// TODO: Copy and paste from above. Wrapper, rearrange control flow, or just put up with it?
System.err.println("Cannot find plugin / connection closed: " + e);
}
}
|
diff --git a/src/me/corriekay/pppopp3/warp/WarpHandler.java b/src/me/corriekay/pppopp3/warp/WarpHandler.java
index 0615092..4c80315 100644
--- a/src/me/corriekay/pppopp3/warp/WarpHandler.java
+++ b/src/me/corriekay/pppopp3/warp/WarpHandler.java
@@ -1,559 +1,564 @@
package me.corriekay.pppopp3.warp;
import java.util.*;
import me.corriekay.pppopp3.Mane;
import me.corriekay.pppopp3.events.JoinEvent;
import me.corriekay.pppopp3.events.QuitEvent;
import me.corriekay.pppopp3.modules.Equestria;
import me.corriekay.pppopp3.ponyville.Pony;
import me.corriekay.pppopp3.ponyville.Ponyville;
import me.corriekay.pppopp3.utils.PSCmdExe;
import org.bukkit.*;
import org.bukkit.World.Environment;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class WarpHandler extends PSCmdExe{
private static WarpHandler wh;
private HashMap<String,WarpList> warpHandler = new HashMap<String,WarpList>();
private HashMap<String,QueuedWarp> warpQueues = new HashMap<String,QueuedWarp>();
private HashMap<String,String> tpQueues = new HashMap<String,String>();
private HashMap<String,Location> homes = new HashMap<String,Location>();
private HashMap<String,Location> backs = new HashMap<String,Location>();
private final int warpCount;
private HashMap<World,Location> spawns = new HashMap<World,Location>();
//private static WarpHandler wh;
public WarpHandler() throws Exception{
super("WarpHandler", "gw", "pw", "pwlist", "pwdel", "pwset", "gwset", "gwdel", "pwplayer", "tp", "tpa", "tpd", "tphere", "home", "sethome", "back", "spawn", "setspawn", "top");
wh = this;
FileConfiguration config = getNamedConfig("warps.yml");
buildWarpList(config);
for(Player player : Bukkit.getOnlinePlayers()) {
warpHandler.put(player.getName(), getPlayerWarps(player));
loadHome(player);
loadBack(player);
}
methodMap.put(EntityDamageByEntityEvent.class, this.getClass().getMethod("onDamage", EntityDamageEvent.class));
Bukkit.getScheduler().scheduleSyncRepeatingTask(Mane.getInstance(), new Runnable() {
@Override
public void run(){
HashSet<String> removeMe = new HashSet<String>();
for(String name : warpQueues.keySet()) {
QueuedWarp qw = warpQueues.get(name);
if(qw.countdown()) {
removeMe.add(name);
}
}
for(String name : removeMe) {
warpQueues.remove(name);
}
}
}, 0, 20);
warpCount = config.getInt("warpCount", 7);
for(World w : Equestria.get().getParentWorlds()) {
Location spawn = getLocFromList((ArrayList<String>)config.getStringList("spawns." + w.getName()));
if(spawn == null) {
spawns.put(w, w.getSpawnLocation());
config.set("spawns." + w.getName(), getListFromLoc(w.getSpawnLocation()));
} else {
spawns.put(w, spawn);
}
}
saveNamedConfig("warps.yml", config);
}
private void buildWarpList(FileConfiguration config){
HashMap<String,Warp> globalWarpsMap = new HashMap<String,Warp>();
for(String warpName : config.getConfigurationSection("warps").getKeys(false)) {
globalWarpsMap.put(warpName, new Warp(warpName, getLocFromList(config.getStringList("warps." + warpName))));
}
WarpList global = new WarpList(globalWarpsMap);
warpHandler.put("global", global);
}
private WarpList getPlayerWarps(Player player){
Pony pony = Ponyville.getPony(player);
HashMap<String,Location> warps = pony.getAllNamedWarps();
HashMap<String,Warp> warpsList = new HashMap<String,Warp>();
for(String name : warps.keySet()) {
warpsList.put(name, new Warp(name, warps.get(name)));
}
return new WarpList(warpsList);
}
private void loadHome(Player player){
Pony pony = Ponyville.getPony(player);
Location loc = pony.getHomeWarp();
homes.put(player.getName(), loc);
}
private void loadBack(Player player){
Pony pony = Ponyville.getPony(player);
Location loc = pony.getBackWarp();
homes.put(player.getName(), loc);
}
private Location getLocFromList(List<String> list){
try {
String w;
double x, y, z;
float p, yaw;
w = list.get(0);
x = Double.parseDouble(list.get(1));
y = Double.parseDouble(list.get(2));
z = Double.parseDouble(list.get(3));
p = Float.parseFloat(list.get(4));
yaw = Float.parseFloat(list.get(5));
Location l = new Location(Bukkit.getWorld(w), x, y, z);
l.setPitch(p);
l.setYaw(yaw);
return l;
} catch(Exception e) {
return null;
}
}
private ArrayList<String> getListFromLoc(Location loc){
try {
ArrayList<String> list = new ArrayList<String>();
list.add(loc.getWorld().getName());
list.add(loc.getX() + "");
list.add(loc.getY() + "");
list.add(loc.getZ() + "");
list.add(loc.getPitch() + "");
list.add(loc.getYaw() + "");
return list;
} catch(Exception e) {
return null;
}
}
public boolean handleCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equals("warpdebug")) {
for(String warpCategory : warpHandler.keySet()) {
System.out.print(warpCategory + ":");
WarpList wl = warpHandler.get(warpCategory);
for(String warp : wl.warps()) {
System.out.print(warp);
}
}
}
if(cmd.getName().equals("pwlist")) {
WarpList global = warpHandler.get("global");
if(global.size() > 0) {
String gWarps = ChatColor.RED + "Global Warps: ";
for(String warp : global.warps()) {
gWarps += ChatColor.RED + warp + ChatColor.WHITE + ", ";
}
gWarps = gWarps.substring(0, gWarps.length() - 4);
sendMessage(sender, "Heres a list of global warps!");
sender.sendMessage(gWarps);
}
if(sender instanceof Player) {
Player player = (Player)sender;
WarpList pWarps = warpHandler.get(player.getName());
if(pWarps.size() > 0) {
String pWarp = ChatColor.RED + "Private Warps: ";
for(String warp : pWarps.warps()) {
pWarp += ChatColor.RED + warp + ChatColor.WHITE + ", ";
}
pWarp = pWarp.substring(0, pWarp.length() - 4);
sendMessage(player, "Heres a list of your private warps!");
player.sendMessage(pWarp);
}
}
return true;
}
Player player;
if(sender instanceof Player) {
player = (Player)sender;
} else {
sendMessage(sender, notPlayer);
return true;
}
if(cmd.getName().equals("top")) {
Location loc = player.getLocation();
int y = loc.getWorld().getHighestBlockYAt(loc);
loc.setY(y);
player.teleport(loc);
return true;
}
if(cmd.getName().equals("spawn")) {
World w = player.getWorld();
if(args.length > 0) {
w = Bukkit.getWorld(args[0]);
}
w = Equestria.get().getParentWorld(w);
+ Location l = spawns.get(w);
+ if(l == null) {
+ sendMessage(player, "Spawn not found!");
+ return true;
+ }
queueWarp(player, spawns.get(w));
return true;
}
if(cmd.getName().equals("setspawn")) {
World w = player.getWorld();
if(w.getEnvironment() != Environment.NORMAL) {
sendMessage(player, "The spawn is located in the overworld silly!");
return true;
}
Location l = player.getLocation();
ArrayList<String> loc = getListFromLoc(l);
sendMessage(player, "Spawn set!");
World parent = Equestria.get().getParentWorld(w);
spawns.put(parent, l);
FileConfiguration config = getNamedConfig("warps.yml");
config.set("spawns." + parent.getName(), loc);
saveNamedConfig("warps.yml", config);
return true;
}
if(cmd.getName().equals("tpa")) {
String target = tpQueues.get(player.getName());
if(target == null) {
sendMessage(player, "Uh oh! no teleport request!");
return true;
}
Player targetP;
targetP = Bukkit.getPlayerExact(target);
if(targetP == null) {
sendMessage(player, "Uh oh, no teleport request!");
return true;
}
tpQueues.remove(player.getName());
sendMessage(player, "Teleport request accepted!");
sendMessage(targetP, "Teleport request accepted!");
queueWarp(targetP, player.getLocation());
return true;
}
if(cmd.getName().equals("tpd")) {
String requester = tpQueues.get(player.getName());
if(requester == null) {
sendMessage(player, "Uh oh, no teleport request!");
return true;
}
Player targetP = Bukkit.getPlayerExact(requester);
if(targetP != null) {
sendMessage(targetP, "Teleport request denied from " + player.getDisplayName() + "!");
}
sendMessage(player, "Teleport request denied!");
tpQueues.remove(player.getName());
return true;
}
if(cmd.getName().equals("home")) {
Location home = homes.get(player.getName());
if(home == null) {
sendMessage(player, "Uh oh, you have no home set! Try setting a home with /sethome!");
return true;
}
queueWarp(player, home);
return true;
}
if(cmd.getName().equals("sethome")) {
Pony pony = Ponyville.getPony(player);
pony.setHomeWarp(player.getLocation());
pony.save();
homes.put(player.getName(), player.getLocation());
sendMessage(player, "Woo hoo! home set! Shall we throw a housewarming party?");
return true;
}
if(cmd.getName().equals("back")) {
Location back = backs.get(player.getName());
if(back != null) {
queueWarp(player, back);
return true;
} else {
sendMessage(player, "Hey, silly! You havnt warped anywhere yet!");
return true;
}
}
if(cmd.getName().equals("pwplayer")) {
if(args.length < 2) {
sendMessage(player, "Heres a list of pwplayer commands!");
sendMessage(player, "/pwplayer <player> list - This lists their warps!");
sendMessage(player, "/pwplayer <player> <warpname> - This teleports to one of their warps!");
sendMessage(player, "/pwplayer <player> offline - This teleports to the location they last logged off at!");
sendMessage(player, "/pwplayer <player> home - This teleports to their home location!");
sendMessage(player, "/pwplayer <player> back - This teleports to their back location!");
return true;
}
OfflinePlayer target = getOnlineOfflinePlayer(args[0], player);
if(target == null) {
return true;
}
Pony pony = Ponyville.getOfflinePony(target.getName());
if(args[1].equals("list")) {
ArrayList<String> warps = new ArrayList<String>();
warps.addAll(pony.getAllNamedWarps().keySet());
Collections.sort(warps);
if(warps.size() < 1) {
sendMessage(player, "That player doesnt have any warps... YET!");
return true;
}
String warpstring = "";
for(String warp : warps) {
warpstring += ChatColor.LIGHT_PURPLE + warp + ChatColor.WHITE + ", ";
}
warpstring = warpstring.substring(0, warpstring.length() - 4);
sendMessage(player, "Heres a list of this players warps!: " + warpstring);
return true;
} else if(args[1].equals("offline")) {
Location loc = pony.getOfflineWarp();
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
} else if(args[1].equals("home")) {
Location loc = pony.getHomeWarp();
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
} else if(args[1].equals("back")) {
Location loc = pony.getBackWarp();
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
} else {
Location loc = pony.getNamedWarp(args[1]);
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
}
}
if(args.length < 1) {
sendMessage(player, notEnoughArgs);
return true;
}
if(cmd.getName().equals("gw")) {
WarpList global = warpHandler.get("global");
Location loc = global.getWarp(args[0]);
if(loc == null) {
sendMessage(player, "Uh oh, I couldnt find that warp!");
return true;
}
queueWarp(player, loc);
return true;
}
if(cmd.getName().equals("pw")) {
WarpList playerWarps = warpHandler.get(player.getName());
Location loc = playerWarps.getWarp(args[0]);
if(loc == null) {
sendMessage(player, "Uh oh, I couldnt find that warp!");
return true;
}
queueWarp(player, loc);
return true;
}
if(cmd.getName().equals("pwdel")) {
args[0] = args[0].toLowerCase();
Location w = warpHandler.get(player.getName()).getWarp(args[0]);
if(w == null || args[0].equalsIgnoreCase("other")) {
sendMessage(player, "Uh oh, I couldnt find that warp!");
return true;
}
Pony pony = Ponyville.getPony(player);
pony.removeNamedWarp(args[0]);
pony.save();
sendMessage(player, "Warp deleted!");
warpHandler.put(player.getName(), getPlayerWarps(player));
return true;
}
if(cmd.getName().equals("pwset")) {
args[0] = args[0].toLowerCase();
if(args[0].equals("other")) {
sendMessage(player, "Uh oh, sorry! thats a reserved name! please choose another warp name!");
return true;
}
Pony pony = Ponyville.getPony(player);
int count = 1;
for(String warp : pony.getAllNamedWarps().keySet()) {
if(!warp.equals(args[0])) {
count++;
}
}
if(count > warpCount) {
sendMessage(player, "You have too many warps! You need to delete one, or overwrite an existing one to set another warp!");
return true;
}
pony.setNamedWarp(args[0], player.getLocation());
pony.save();
sendMessage(player, "Wormhole opened! Warp " + args[0] + " set!");
warpHandler.put(player.getName(), getPlayerWarps(player));
return true;
}
if(cmd.getName().equals("gwset")) {
String name = args[0].toLowerCase();
FileConfiguration config = getNamedConfig("warps.yml");
config.set("warps." + name, getListFromLoc(player.getLocation()));
saveNamedConfig("warps.yml", config);
buildWarpList(config);
for(Player p : Bukkit.getOnlinePlayers()) {
sendMessage(p, "Wormhole opened! New global warp set: " + name + "!");
}
return true;
}
if(cmd.getName().equals("gwdel")) {
String name = args[0].toLowerCase();
WarpList global = warpHandler.get("global");
Location loc = global.getWarp(name);
if(loc == null) {
sendMessage(player, "Uh oh! I couldnt find that warp!");
return true;
}
FileConfiguration config = getNamedConfig("warps.yml");
config.set("warps." + name, null);
saveNamedConfig("warps.yml", config);
buildWarpList(config);
for(Player p : Bukkit.getOnlinePlayers()) {
sendMessage(p, "Wormhole closed! Global warp " + name + " deleted!");
}
return true;
}
if(cmd.getName().equals("tp")) {
Player target = getOnlinePlayer(args[0], player);
if(target == null) {
return true;
}
if(player.hasPermission("pppopp3.tpbypass")) {
player.teleport(target);
return true;
}
sendMessage(target, player.getDisplayName() + ChatColor.LIGHT_PURPLE + " has sent you a teleport request! type /tpa to accept, or type /tpd to deny it!");
sendMessage(player, "Yay! you've sent a teleport request to " + target.getDisplayName());
tpQueues.put(target.getName(), player.getName());
return true;
}
if(cmd.getName().equals("tphere")) {
Player target = getOnlinePlayer(args[0], player);
if(target == null) {
return true;
}
target.teleport(player);
return true;
}
return true;
}
private void queueWarp(Player player, Location loc){
if(player.hasPermission("pppopp3.tpbypass")) {
player.teleport(loc);
sendMessage(player, "Using the express admin wormhole!");
return;
}
try {
warpQueues.put(player.getName(), new QueuedWarp(player.getName(), loc, 7));
} catch(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendMessage(player, "Okay! setting up the wormhole... This process is delicate...");
}
@EventHandler
public void onJoin(JoinEvent event){
if(event.isJoining()) {
Player player = event.getPlayer();
if(!player.hasPlayedBefore()) {
player.teleport(spawns.get(Bukkit.getWorld("world")));
}
warpHandler.put(player.getName(), getPlayerWarps(player));
loadBack(player);
loadHome(player);
}
}
@EventHandler
public void onQuit(QuitEvent event){
Player player = event.getPlayer();
if(event.isQuitting()) {
warpHandler.remove(player.getName());
backs.remove(player.getName());
homes.remove(player.getName());
}
tpQueues.remove(player.getName());
}
@EventHandler (priority = EventPriority.MONITOR)
public void onDamage(EntityDamageEvent event){
if(event.getEntity() instanceof Player) {
Player player = (Player)event.getEntity();
if(warpQueues.containsKey(player.getName())) {
warpQueues.remove(player.getName());
sendMessage(player, "Oh no! Catastrophic failure! Warp aborted to avoid black holes!");
}
if(tpQueues.containsKey(player.getName())) {
tpQueues.remove(player.getName());
sendMessage(player, "Oh no! Catastrophic failure! Player teleport aborted to avoid black holes!");
}
}
}
@EventHandler
public void teleport(PlayerTeleportEvent event){
if(event.getCause() == TeleportCause.PLUGIN) {
event.getTo().getChunk().load();
Player player = event.getPlayer();
Pony pony = Ponyville.getPony(player);
Location back = event.getFrom();
pony.setBackWarp(back);
pony.save();
backs.put(player.getName(), back);
}
}
@EventHandler
public void onRespawn(PlayerRespawnEvent event){
Player player = event.getPlayer();
Location loc = homes.get(player.getName());
if(loc == null) {
Location spawn = spawns.get(Equestria.get().getParentWorld(player.getLocation().getWorld()));
event.setRespawnLocation(spawn);
return;
} else {
World overworld, parentOverworld;
overworld = Equestria.get().getParentWorld(loc.getWorld());
parentOverworld = Equestria.get().getParentWorld(player.getLocation().getWorld());
if(overworld != parentOverworld) {
event.setRespawnLocation(spawns.get(parentOverworld));
} else {
event.setRespawnLocation(loc);
}
return;
}
}
public static Location getWorldSpawn(){
return wh.spawns.get(Bukkit.getWorld("world"));
}
@EventHandler
public void onDeath(PlayerDeathEvent event){
Player player = event.getEntity();
Location loc = player.getLocation();
sendMessage(player, "Oh gosh! Are you okay? ..Shoot, silly me, of course youre not okay... Well, for future reference, heres your location: x: " + loc.getBlockX() + " y: " + loc.getBlockY() + " z: " + loc.getBlockZ() + "! Dont lose your stuff!!");
}
}
| true | true | public boolean handleCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equals("warpdebug")) {
for(String warpCategory : warpHandler.keySet()) {
System.out.print(warpCategory + ":");
WarpList wl = warpHandler.get(warpCategory);
for(String warp : wl.warps()) {
System.out.print(warp);
}
}
}
if(cmd.getName().equals("pwlist")) {
WarpList global = warpHandler.get("global");
if(global.size() > 0) {
String gWarps = ChatColor.RED + "Global Warps: ";
for(String warp : global.warps()) {
gWarps += ChatColor.RED + warp + ChatColor.WHITE + ", ";
}
gWarps = gWarps.substring(0, gWarps.length() - 4);
sendMessage(sender, "Heres a list of global warps!");
sender.sendMessage(gWarps);
}
if(sender instanceof Player) {
Player player = (Player)sender;
WarpList pWarps = warpHandler.get(player.getName());
if(pWarps.size() > 0) {
String pWarp = ChatColor.RED + "Private Warps: ";
for(String warp : pWarps.warps()) {
pWarp += ChatColor.RED + warp + ChatColor.WHITE + ", ";
}
pWarp = pWarp.substring(0, pWarp.length() - 4);
sendMessage(player, "Heres a list of your private warps!");
player.sendMessage(pWarp);
}
}
return true;
}
Player player;
if(sender instanceof Player) {
player = (Player)sender;
} else {
sendMessage(sender, notPlayer);
return true;
}
if(cmd.getName().equals("top")) {
Location loc = player.getLocation();
int y = loc.getWorld().getHighestBlockYAt(loc);
loc.setY(y);
player.teleport(loc);
return true;
}
if(cmd.getName().equals("spawn")) {
World w = player.getWorld();
if(args.length > 0) {
w = Bukkit.getWorld(args[0]);
}
w = Equestria.get().getParentWorld(w);
queueWarp(player, spawns.get(w));
return true;
}
if(cmd.getName().equals("setspawn")) {
World w = player.getWorld();
if(w.getEnvironment() != Environment.NORMAL) {
sendMessage(player, "The spawn is located in the overworld silly!");
return true;
}
Location l = player.getLocation();
ArrayList<String> loc = getListFromLoc(l);
sendMessage(player, "Spawn set!");
World parent = Equestria.get().getParentWorld(w);
spawns.put(parent, l);
FileConfiguration config = getNamedConfig("warps.yml");
config.set("spawns." + parent.getName(), loc);
saveNamedConfig("warps.yml", config);
return true;
}
if(cmd.getName().equals("tpa")) {
String target = tpQueues.get(player.getName());
if(target == null) {
sendMessage(player, "Uh oh! no teleport request!");
return true;
}
Player targetP;
targetP = Bukkit.getPlayerExact(target);
if(targetP == null) {
sendMessage(player, "Uh oh, no teleport request!");
return true;
}
tpQueues.remove(player.getName());
sendMessage(player, "Teleport request accepted!");
sendMessage(targetP, "Teleport request accepted!");
queueWarp(targetP, player.getLocation());
return true;
}
if(cmd.getName().equals("tpd")) {
String requester = tpQueues.get(player.getName());
if(requester == null) {
sendMessage(player, "Uh oh, no teleport request!");
return true;
}
Player targetP = Bukkit.getPlayerExact(requester);
if(targetP != null) {
sendMessage(targetP, "Teleport request denied from " + player.getDisplayName() + "!");
}
sendMessage(player, "Teleport request denied!");
tpQueues.remove(player.getName());
return true;
}
if(cmd.getName().equals("home")) {
Location home = homes.get(player.getName());
if(home == null) {
sendMessage(player, "Uh oh, you have no home set! Try setting a home with /sethome!");
return true;
}
queueWarp(player, home);
return true;
}
if(cmd.getName().equals("sethome")) {
Pony pony = Ponyville.getPony(player);
pony.setHomeWarp(player.getLocation());
pony.save();
homes.put(player.getName(), player.getLocation());
sendMessage(player, "Woo hoo! home set! Shall we throw a housewarming party?");
return true;
}
if(cmd.getName().equals("back")) {
Location back = backs.get(player.getName());
if(back != null) {
queueWarp(player, back);
return true;
} else {
sendMessage(player, "Hey, silly! You havnt warped anywhere yet!");
return true;
}
}
if(cmd.getName().equals("pwplayer")) {
if(args.length < 2) {
sendMessage(player, "Heres a list of pwplayer commands!");
sendMessage(player, "/pwplayer <player> list - This lists their warps!");
sendMessage(player, "/pwplayer <player> <warpname> - This teleports to one of their warps!");
sendMessage(player, "/pwplayer <player> offline - This teleports to the location they last logged off at!");
sendMessage(player, "/pwplayer <player> home - This teleports to their home location!");
sendMessage(player, "/pwplayer <player> back - This teleports to their back location!");
return true;
}
OfflinePlayer target = getOnlineOfflinePlayer(args[0], player);
if(target == null) {
return true;
}
Pony pony = Ponyville.getOfflinePony(target.getName());
if(args[1].equals("list")) {
ArrayList<String> warps = new ArrayList<String>();
warps.addAll(pony.getAllNamedWarps().keySet());
Collections.sort(warps);
if(warps.size() < 1) {
sendMessage(player, "That player doesnt have any warps... YET!");
return true;
}
String warpstring = "";
for(String warp : warps) {
warpstring += ChatColor.LIGHT_PURPLE + warp + ChatColor.WHITE + ", ";
}
warpstring = warpstring.substring(0, warpstring.length() - 4);
sendMessage(player, "Heres a list of this players warps!: " + warpstring);
return true;
} else if(args[1].equals("offline")) {
Location loc = pony.getOfflineWarp();
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
} else if(args[1].equals("home")) {
Location loc = pony.getHomeWarp();
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
} else if(args[1].equals("back")) {
Location loc = pony.getBackWarp();
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
} else {
Location loc = pony.getNamedWarp(args[1]);
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
}
}
if(args.length < 1) {
sendMessage(player, notEnoughArgs);
return true;
}
if(cmd.getName().equals("gw")) {
WarpList global = warpHandler.get("global");
Location loc = global.getWarp(args[0]);
if(loc == null) {
sendMessage(player, "Uh oh, I couldnt find that warp!");
return true;
}
queueWarp(player, loc);
return true;
}
if(cmd.getName().equals("pw")) {
WarpList playerWarps = warpHandler.get(player.getName());
Location loc = playerWarps.getWarp(args[0]);
if(loc == null) {
sendMessage(player, "Uh oh, I couldnt find that warp!");
return true;
}
queueWarp(player, loc);
return true;
}
if(cmd.getName().equals("pwdel")) {
args[0] = args[0].toLowerCase();
Location w = warpHandler.get(player.getName()).getWarp(args[0]);
if(w == null || args[0].equalsIgnoreCase("other")) {
sendMessage(player, "Uh oh, I couldnt find that warp!");
return true;
}
Pony pony = Ponyville.getPony(player);
pony.removeNamedWarp(args[0]);
pony.save();
sendMessage(player, "Warp deleted!");
warpHandler.put(player.getName(), getPlayerWarps(player));
return true;
}
if(cmd.getName().equals("pwset")) {
args[0] = args[0].toLowerCase();
if(args[0].equals("other")) {
sendMessage(player, "Uh oh, sorry! thats a reserved name! please choose another warp name!");
return true;
}
Pony pony = Ponyville.getPony(player);
int count = 1;
for(String warp : pony.getAllNamedWarps().keySet()) {
if(!warp.equals(args[0])) {
count++;
}
}
if(count > warpCount) {
sendMessage(player, "You have too many warps! You need to delete one, or overwrite an existing one to set another warp!");
return true;
}
pony.setNamedWarp(args[0], player.getLocation());
pony.save();
sendMessage(player, "Wormhole opened! Warp " + args[0] + " set!");
warpHandler.put(player.getName(), getPlayerWarps(player));
return true;
}
if(cmd.getName().equals("gwset")) {
String name = args[0].toLowerCase();
FileConfiguration config = getNamedConfig("warps.yml");
config.set("warps." + name, getListFromLoc(player.getLocation()));
saveNamedConfig("warps.yml", config);
buildWarpList(config);
for(Player p : Bukkit.getOnlinePlayers()) {
sendMessage(p, "Wormhole opened! New global warp set: " + name + "!");
}
return true;
}
if(cmd.getName().equals("gwdel")) {
String name = args[0].toLowerCase();
WarpList global = warpHandler.get("global");
Location loc = global.getWarp(name);
if(loc == null) {
sendMessage(player, "Uh oh! I couldnt find that warp!");
return true;
}
FileConfiguration config = getNamedConfig("warps.yml");
config.set("warps." + name, null);
saveNamedConfig("warps.yml", config);
buildWarpList(config);
for(Player p : Bukkit.getOnlinePlayers()) {
sendMessage(p, "Wormhole closed! Global warp " + name + " deleted!");
}
return true;
}
if(cmd.getName().equals("tp")) {
Player target = getOnlinePlayer(args[0], player);
if(target == null) {
return true;
}
if(player.hasPermission("pppopp3.tpbypass")) {
player.teleport(target);
return true;
}
sendMessage(target, player.getDisplayName() + ChatColor.LIGHT_PURPLE + " has sent you a teleport request! type /tpa to accept, or type /tpd to deny it!");
sendMessage(player, "Yay! you've sent a teleport request to " + target.getDisplayName());
tpQueues.put(target.getName(), player.getName());
return true;
}
if(cmd.getName().equals("tphere")) {
Player target = getOnlinePlayer(args[0], player);
if(target == null) {
return true;
}
target.teleport(player);
return true;
}
return true;
}
| public boolean handleCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equals("warpdebug")) {
for(String warpCategory : warpHandler.keySet()) {
System.out.print(warpCategory + ":");
WarpList wl = warpHandler.get(warpCategory);
for(String warp : wl.warps()) {
System.out.print(warp);
}
}
}
if(cmd.getName().equals("pwlist")) {
WarpList global = warpHandler.get("global");
if(global.size() > 0) {
String gWarps = ChatColor.RED + "Global Warps: ";
for(String warp : global.warps()) {
gWarps += ChatColor.RED + warp + ChatColor.WHITE + ", ";
}
gWarps = gWarps.substring(0, gWarps.length() - 4);
sendMessage(sender, "Heres a list of global warps!");
sender.sendMessage(gWarps);
}
if(sender instanceof Player) {
Player player = (Player)sender;
WarpList pWarps = warpHandler.get(player.getName());
if(pWarps.size() > 0) {
String pWarp = ChatColor.RED + "Private Warps: ";
for(String warp : pWarps.warps()) {
pWarp += ChatColor.RED + warp + ChatColor.WHITE + ", ";
}
pWarp = pWarp.substring(0, pWarp.length() - 4);
sendMessage(player, "Heres a list of your private warps!");
player.sendMessage(pWarp);
}
}
return true;
}
Player player;
if(sender instanceof Player) {
player = (Player)sender;
} else {
sendMessage(sender, notPlayer);
return true;
}
if(cmd.getName().equals("top")) {
Location loc = player.getLocation();
int y = loc.getWorld().getHighestBlockYAt(loc);
loc.setY(y);
player.teleport(loc);
return true;
}
if(cmd.getName().equals("spawn")) {
World w = player.getWorld();
if(args.length > 0) {
w = Bukkit.getWorld(args[0]);
}
w = Equestria.get().getParentWorld(w);
Location l = spawns.get(w);
if(l == null) {
sendMessage(player, "Spawn not found!");
return true;
}
queueWarp(player, spawns.get(w));
return true;
}
if(cmd.getName().equals("setspawn")) {
World w = player.getWorld();
if(w.getEnvironment() != Environment.NORMAL) {
sendMessage(player, "The spawn is located in the overworld silly!");
return true;
}
Location l = player.getLocation();
ArrayList<String> loc = getListFromLoc(l);
sendMessage(player, "Spawn set!");
World parent = Equestria.get().getParentWorld(w);
spawns.put(parent, l);
FileConfiguration config = getNamedConfig("warps.yml");
config.set("spawns." + parent.getName(), loc);
saveNamedConfig("warps.yml", config);
return true;
}
if(cmd.getName().equals("tpa")) {
String target = tpQueues.get(player.getName());
if(target == null) {
sendMessage(player, "Uh oh! no teleport request!");
return true;
}
Player targetP;
targetP = Bukkit.getPlayerExact(target);
if(targetP == null) {
sendMessage(player, "Uh oh, no teleport request!");
return true;
}
tpQueues.remove(player.getName());
sendMessage(player, "Teleport request accepted!");
sendMessage(targetP, "Teleport request accepted!");
queueWarp(targetP, player.getLocation());
return true;
}
if(cmd.getName().equals("tpd")) {
String requester = tpQueues.get(player.getName());
if(requester == null) {
sendMessage(player, "Uh oh, no teleport request!");
return true;
}
Player targetP = Bukkit.getPlayerExact(requester);
if(targetP != null) {
sendMessage(targetP, "Teleport request denied from " + player.getDisplayName() + "!");
}
sendMessage(player, "Teleport request denied!");
tpQueues.remove(player.getName());
return true;
}
if(cmd.getName().equals("home")) {
Location home = homes.get(player.getName());
if(home == null) {
sendMessage(player, "Uh oh, you have no home set! Try setting a home with /sethome!");
return true;
}
queueWarp(player, home);
return true;
}
if(cmd.getName().equals("sethome")) {
Pony pony = Ponyville.getPony(player);
pony.setHomeWarp(player.getLocation());
pony.save();
homes.put(player.getName(), player.getLocation());
sendMessage(player, "Woo hoo! home set! Shall we throw a housewarming party?");
return true;
}
if(cmd.getName().equals("back")) {
Location back = backs.get(player.getName());
if(back != null) {
queueWarp(player, back);
return true;
} else {
sendMessage(player, "Hey, silly! You havnt warped anywhere yet!");
return true;
}
}
if(cmd.getName().equals("pwplayer")) {
if(args.length < 2) {
sendMessage(player, "Heres a list of pwplayer commands!");
sendMessage(player, "/pwplayer <player> list - This lists their warps!");
sendMessage(player, "/pwplayer <player> <warpname> - This teleports to one of their warps!");
sendMessage(player, "/pwplayer <player> offline - This teleports to the location they last logged off at!");
sendMessage(player, "/pwplayer <player> home - This teleports to their home location!");
sendMessage(player, "/pwplayer <player> back - This teleports to their back location!");
return true;
}
OfflinePlayer target = getOnlineOfflinePlayer(args[0], player);
if(target == null) {
return true;
}
Pony pony = Ponyville.getOfflinePony(target.getName());
if(args[1].equals("list")) {
ArrayList<String> warps = new ArrayList<String>();
warps.addAll(pony.getAllNamedWarps().keySet());
Collections.sort(warps);
if(warps.size() < 1) {
sendMessage(player, "That player doesnt have any warps... YET!");
return true;
}
String warpstring = "";
for(String warp : warps) {
warpstring += ChatColor.LIGHT_PURPLE + warp + ChatColor.WHITE + ", ";
}
warpstring = warpstring.substring(0, warpstring.length() - 4);
sendMessage(player, "Heres a list of this players warps!: " + warpstring);
return true;
} else if(args[1].equals("offline")) {
Location loc = pony.getOfflineWarp();
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
} else if(args[1].equals("home")) {
Location loc = pony.getHomeWarp();
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
} else if(args[1].equals("back")) {
Location loc = pony.getBackWarp();
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
} else {
Location loc = pony.getNamedWarp(args[1]);
if(loc == null) {
sendMessage(player, "Uh oh, that warp isnt set!");
return true;
}
player.teleport(loc);
return true;
}
}
if(args.length < 1) {
sendMessage(player, notEnoughArgs);
return true;
}
if(cmd.getName().equals("gw")) {
WarpList global = warpHandler.get("global");
Location loc = global.getWarp(args[0]);
if(loc == null) {
sendMessage(player, "Uh oh, I couldnt find that warp!");
return true;
}
queueWarp(player, loc);
return true;
}
if(cmd.getName().equals("pw")) {
WarpList playerWarps = warpHandler.get(player.getName());
Location loc = playerWarps.getWarp(args[0]);
if(loc == null) {
sendMessage(player, "Uh oh, I couldnt find that warp!");
return true;
}
queueWarp(player, loc);
return true;
}
if(cmd.getName().equals("pwdel")) {
args[0] = args[0].toLowerCase();
Location w = warpHandler.get(player.getName()).getWarp(args[0]);
if(w == null || args[0].equalsIgnoreCase("other")) {
sendMessage(player, "Uh oh, I couldnt find that warp!");
return true;
}
Pony pony = Ponyville.getPony(player);
pony.removeNamedWarp(args[0]);
pony.save();
sendMessage(player, "Warp deleted!");
warpHandler.put(player.getName(), getPlayerWarps(player));
return true;
}
if(cmd.getName().equals("pwset")) {
args[0] = args[0].toLowerCase();
if(args[0].equals("other")) {
sendMessage(player, "Uh oh, sorry! thats a reserved name! please choose another warp name!");
return true;
}
Pony pony = Ponyville.getPony(player);
int count = 1;
for(String warp : pony.getAllNamedWarps().keySet()) {
if(!warp.equals(args[0])) {
count++;
}
}
if(count > warpCount) {
sendMessage(player, "You have too many warps! You need to delete one, or overwrite an existing one to set another warp!");
return true;
}
pony.setNamedWarp(args[0], player.getLocation());
pony.save();
sendMessage(player, "Wormhole opened! Warp " + args[0] + " set!");
warpHandler.put(player.getName(), getPlayerWarps(player));
return true;
}
if(cmd.getName().equals("gwset")) {
String name = args[0].toLowerCase();
FileConfiguration config = getNamedConfig("warps.yml");
config.set("warps." + name, getListFromLoc(player.getLocation()));
saveNamedConfig("warps.yml", config);
buildWarpList(config);
for(Player p : Bukkit.getOnlinePlayers()) {
sendMessage(p, "Wormhole opened! New global warp set: " + name + "!");
}
return true;
}
if(cmd.getName().equals("gwdel")) {
String name = args[0].toLowerCase();
WarpList global = warpHandler.get("global");
Location loc = global.getWarp(name);
if(loc == null) {
sendMessage(player, "Uh oh! I couldnt find that warp!");
return true;
}
FileConfiguration config = getNamedConfig("warps.yml");
config.set("warps." + name, null);
saveNamedConfig("warps.yml", config);
buildWarpList(config);
for(Player p : Bukkit.getOnlinePlayers()) {
sendMessage(p, "Wormhole closed! Global warp " + name + " deleted!");
}
return true;
}
if(cmd.getName().equals("tp")) {
Player target = getOnlinePlayer(args[0], player);
if(target == null) {
return true;
}
if(player.hasPermission("pppopp3.tpbypass")) {
player.teleport(target);
return true;
}
sendMessage(target, player.getDisplayName() + ChatColor.LIGHT_PURPLE + " has sent you a teleport request! type /tpa to accept, or type /tpd to deny it!");
sendMessage(player, "Yay! you've sent a teleport request to " + target.getDisplayName());
tpQueues.put(target.getName(), player.getName());
return true;
}
if(cmd.getName().equals("tphere")) {
Player target = getOnlinePlayer(args[0], player);
if(target == null) {
return true;
}
target.teleport(player);
return true;
}
return true;
}
|
diff --git a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/internal/adapter/DataAdapterUtil.java b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/internal/adapter/DataAdapterUtil.java
index 73cdaa028..a77719b4b 100644
--- a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/internal/adapter/DataAdapterUtil.java
+++ b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/internal/adapter/DataAdapterUtil.java
@@ -1,379 +1,376 @@
/*
*************************************************************************
* Copyright (c) 2006 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.data.adapter.internal.adapter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IColumnDefinition;
import org.eclipse.birt.data.engine.api.querydefn.BaseDataSetDesign;
import org.eclipse.birt.data.engine.api.querydefn.BaseDataSourceDesign;
import org.eclipse.birt.data.engine.api.querydefn.ColumnDefinition;
import org.eclipse.birt.report.data.adapter.api.AdapterException;
import org.eclipse.birt.report.data.adapter.i18n.ResourceConstants;
import org.eclipse.birt.report.model.api.ColumnHintHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSetParameterHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.FilterConditionHandle;
import org.eclipse.birt.report.model.api.JointDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSetParameterHandle;
import org.eclipse.birt.report.model.api.OdaResultSetColumnHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.metadata.IPropertyDefn;
/**
* Utility class for data adaptors
*/
class DataAdapterUtil
{
/**
* Adapts common base data source properties
*/
public static void adaptBaseDataSource( DataSourceHandle source, BaseDataSourceDesign dest )
{
dest.setBeforeOpenScript( source.getBeforeOpen( ) );
dest.setAfterOpenScript( source.getAfterOpen( ) );
dest.setBeforeCloseScript( source.getBeforeClose( ) );
dest.setAfterCloseScript( source.getAfterClose( ) );
}
/**
* Adapts base data set properties
*/
public static void adaptBaseDataSet( DataSetHandle modelDataSet,
BaseDataSetDesign dteDataSet ) throws BirtException
{
if ( ( !( modelDataSet instanceof JointDataSetHandle ) )
&& modelDataSet.getDataSource( ) == null )
{
throw new AdapterException( ResourceConstants.DATASOURCE_NULL_ERROR );
}
if ( !( modelDataSet instanceof JointDataSetHandle ) )
{
dteDataSet.setDataSource( modelDataSet.getDataSource( )
.getQualifiedName( ) );
dteDataSet.setBeforeOpenScript( modelDataSet.getBeforeOpen( ) );
dteDataSet.setAfterOpenScript( modelDataSet.getAfterOpen( ) );
dteDataSet.setOnFetchScript( modelDataSet.getOnFetch( ) );
dteDataSet.setBeforeCloseScript( modelDataSet.getBeforeClose( ) );
dteDataSet.setAfterCloseScript( modelDataSet.getAfterClose( ) );
}
populateParameter( modelDataSet, dteDataSet );
populateComputedColumn( modelDataSet, dteDataSet );
populateFilter( modelDataSet, dteDataSet );
dteDataSet.setRowFetchLimit( modelDataSet.getRowFetchLimit( ) );
mergeHints( modelDataSet, dteDataSet );
}
/**
*
* @param modelDataSet
* @param dteDataSet
*/
private static void populateParameter( DataSetHandle modelDataSet, BaseDataSetDesign dteDataSet )
{
//dataset parameters definition
HashMap paramBindingCandidates = new HashMap( );
Iterator elmtIter = modelDataSet.parametersIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
DataSetParameterHandle modelParam = ( DataSetParameterHandle ) elmtIter
.next( );
// collect input parameter default values as
// potential parameter binding if no explicit ones are
// defined for a parameter
if ( modelParam.isInput( ) )
{
String defaultValueExpr = null;
if ( modelParam instanceof OdaDataSetParameterHandle
&& ( (OdaDataSetParameterHandle) modelParam ).getParamName( ) != null )
{
defaultValueExpr = ExpressionUtil.createJSParameterExpression( ( ( (OdaDataSetParameterHandle) modelParam ).getParamName( ) ) );
}
else
defaultValueExpr = modelParam.getDefaultValue( );
- if ( defaultValueExpr != null )
- {
- dteDataSet.addParameter( new ParameterAdapter( modelParam ) );
- paramBindingCandidates.put( modelParam.getName( ),
- defaultValueExpr );
- }
+ dteDataSet.addParameter( new ParameterAdapter( modelParam ) );
+ paramBindingCandidates.put( modelParam.getName( ),
+ defaultValueExpr );
}
else
{
dteDataSet.addParameter( new ParameterAdapter( modelParam ) );
}
}
}
// input parameter bindings
elmtIter = modelDataSet.paramBindingsIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
ParamBindingHandle modelParamBinding = ( ParamBindingHandle ) elmtIter
.next( );
// replace default value of the same parameter, if defined
paramBindingCandidates.put( modelParamBinding.getParamName( ),
modelParamBinding.getExpression( ) );
}
}
// assign merged parameter bindings to the data set
if ( paramBindingCandidates.size( ) > 0 )
{
elmtIter = paramBindingCandidates.keySet( ).iterator( );
while ( elmtIter.hasNext( ) )
{
Object paramName = elmtIter.next( );
assert ( paramName != null && paramName instanceof String );
String expression = ( String ) paramBindingCandidates
.get( paramName );
dteDataSet.addInputParamBinding( new InputParamBindingAdapter(
( String ) paramName, expression ) );
}
}
}
/**
*
* @param modelDataSet
* @param dteDataSet
* @throws AdapterException
*/
private static void populateComputedColumn( DataSetHandle modelDataSet, BaseDataSetDesign dteDataSet ) throws AdapterException
{
// computed columns
Iterator elmtIter = modelDataSet.computedColumnsIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
ComputedColumnHandle modelCmptdColumn = ( ComputedColumnHandle ) elmtIter
.next( );
dteDataSet.addComputedColumn( new ComputedColumnAdapter( modelCmptdColumn ));
}
}
}
/**
*
* @param modelDataSet
* @param dteDataSet
*/
private static void populateFilter( DataSetHandle modelDataSet, BaseDataSetDesign dteDataSet )
{
// filter conditions
Iterator elmtIter = modelDataSet.filtersIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
FilterConditionHandle modelFilter = ( FilterConditionHandle ) elmtIter
.next( );
dteDataSet.addFilter( new FilterAdapter( modelFilter ) );
}
}
}
/**
*
* @param modelDataSet
* @param dteDataSet
*/
private static void mergeHints( DataSetHandle modelDataSet, BaseDataSetDesign dteDataSet )
{
// merge ResultSetHints and ColumnHints, the order is important.
// ResultSetHints will give each column a unique name, and
// column hints should base on the result of ResultSet hint.
// So in ResultSetHint list, the order of items should be
// ResultSetColumn and then ColumnHint.
// now merge model's result set column info into existing columnDefn
// with same column name, otherwise create new columnDefn
// based on the model's result set column
Iterator elmtIter;
if ( modelDataSet instanceof OdaDataSetHandle )
{
elmtIter = modelDataSet.resultSetIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
OdaResultSetColumnHandle modelColumn = (OdaResultSetColumnHandle) elmtIter.next( );
if ( !modelColumn.getColumnName( )
.equals( modelColumn.getNativeName( ) ) )
dteDataSet.addResultSetHint( new ColumnAdapter( (ResultSetColumnHandle) modelColumn ) );
}
}
}
elmtIter = modelDataSet.resultSetHintsIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
ResultSetColumnHandle modelColumn = (ResultSetColumnHandle) elmtIter.next( );
dteDataSet.addResultSetHint( new ColumnAdapter( modelColumn ) );
}
}
// merging result set column and column hints into DtE columnDefn;
// first create new columnDefn based on model's column hints
elmtIter = modelDataSet.columnHintsIterator( );
if ( elmtIter != null )
{
List columnDefns = dteDataSet.getResultSetHints( );
while ( elmtIter.hasNext( ) )
{
ColumnHintHandle modelColumnHint = ( ColumnHintHandle ) elmtIter
.next( );
ColumnDefinition existDefn = findColumnDefn( columnDefns,
modelColumnHint.getColumnName( ) );
if ( existDefn != null )
updateColumnDefn( existDefn, modelColumnHint );
else
dteDataSet
.addResultSetHint( new ColumnAdapter( modelColumnHint ) );
}
}
}
public static void updateColumnDefn( ColumnDefinition dteColumn,
ColumnHintHandle modelColumnHint )
{
assert dteColumn.getColumnName( ).equals(
modelColumnHint.getColumnName( ) );
dteColumn.setAlias( modelColumnHint.getAlias( ) );
String exportConstant = modelColumnHint.getExport( );
if ( exportConstant != null )
{
int exportHint = IColumnDefinition.DONOT_EXPORT; // default value
if ( exportConstant
.equals( DesignChoiceConstants.EXPORT_TYPE_IF_REALIZED ) )
exportHint = IColumnDefinition.EXPORT_IF_REALIZED;
else if ( exportConstant
.equals( DesignChoiceConstants.EXPORT_TYPE_ALWAYS ) )
exportHint = IColumnDefinition.ALWAYS_EXPORT;
else
assert exportConstant
.equals( DesignChoiceConstants.EXPORT_TYPE_NONE );
dteColumn.setExportHint( exportHint );
}
String searchConstant = modelColumnHint.getSearching( );
if ( searchConstant != null )
{
int searchHint = IColumnDefinition.NOT_SEARCHABLE;
if ( searchConstant
.equals( DesignChoiceConstants.SEARCH_TYPE_INDEXED ) )
searchHint = IColumnDefinition.SEARCHABLE_IF_INDEXED;
else if ( searchConstant
.equals( DesignChoiceConstants.SEARCH_TYPE_ANY ) )
searchHint = IColumnDefinition.ALWAYS_SEARCHABLE;
else
assert searchConstant
.equals( DesignChoiceConstants.SEARCH_TYPE_NONE );
dteColumn.setSearchHint( searchHint );
}
}
/**
* Find the DtE columnDefn from the given list of columnDefns that matches
* the given columnName.
*/
private static ColumnDefinition findColumnDefn( List columnDefns, String columnName )
{
assert columnName != null;
if ( columnDefns == null )
return null; // no list to find from
Iterator iter = columnDefns.iterator( );
if ( iter == null )
return null;
// iterate thru each columnDefn, and looks for a match of
// specified column name
while ( iter.hasNext( ) )
{
ColumnDefinition column = ( ColumnDefinition ) iter.next( );
if ( columnName.equals( column.getColumnName( ) ) )
return column;
}
return null;
}
/**
* Gets the data handle's static ROM extension properties name and value
* pairs in String values and returns them in a Map
*/
public static Map getExtensionProperties( ReportElementHandle dataHandle,
List driverPropList )
{
if ( driverPropList == null || driverPropList.isEmpty( ) )
return null; // nothing to add
Map properties = new HashMap( );
Iterator elmtIter = driverPropList.iterator( );
while ( elmtIter.hasNext( ) )
{
IPropertyDefn modelExtProp = ( IPropertyDefn ) elmtIter.next( );
// First get extension property's name
String propName = modelExtProp.getName( );
assert ( propName != null && propName.length( ) > 0 );
// Use property name to get property value
Object propValueObj = dataHandle.getProperty( modelExtProp
.getName( ) );
/*
* An ODA consumer does not distinguish whether a property value is
* not set or explicitly set to null. Its handling is pushed down to
* the underlying data provider.
*/
String propValue = ( propValueObj == null ) ? null : propValueObj
.toString( );
properties.put( propName, propValue );
}
return properties;
}
}
| true | true | private static void populateParameter( DataSetHandle modelDataSet, BaseDataSetDesign dteDataSet )
{
//dataset parameters definition
HashMap paramBindingCandidates = new HashMap( );
Iterator elmtIter = modelDataSet.parametersIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
DataSetParameterHandle modelParam = ( DataSetParameterHandle ) elmtIter
.next( );
// collect input parameter default values as
// potential parameter binding if no explicit ones are
// defined for a parameter
if ( modelParam.isInput( ) )
{
String defaultValueExpr = null;
if ( modelParam instanceof OdaDataSetParameterHandle
&& ( (OdaDataSetParameterHandle) modelParam ).getParamName( ) != null )
{
defaultValueExpr = ExpressionUtil.createJSParameterExpression( ( ( (OdaDataSetParameterHandle) modelParam ).getParamName( ) ) );
}
else
defaultValueExpr = modelParam.getDefaultValue( );
if ( defaultValueExpr != null )
{
dteDataSet.addParameter( new ParameterAdapter( modelParam ) );
paramBindingCandidates.put( modelParam.getName( ),
defaultValueExpr );
}
}
else
{
dteDataSet.addParameter( new ParameterAdapter( modelParam ) );
}
}
}
// input parameter bindings
elmtIter = modelDataSet.paramBindingsIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
ParamBindingHandle modelParamBinding = ( ParamBindingHandle ) elmtIter
.next( );
// replace default value of the same parameter, if defined
paramBindingCandidates.put( modelParamBinding.getParamName( ),
modelParamBinding.getExpression( ) );
}
}
// assign merged parameter bindings to the data set
if ( paramBindingCandidates.size( ) > 0 )
{
elmtIter = paramBindingCandidates.keySet( ).iterator( );
while ( elmtIter.hasNext( ) )
{
Object paramName = elmtIter.next( );
assert ( paramName != null && paramName instanceof String );
String expression = ( String ) paramBindingCandidates
.get( paramName );
dteDataSet.addInputParamBinding( new InputParamBindingAdapter(
( String ) paramName, expression ) );
}
}
}
| private static void populateParameter( DataSetHandle modelDataSet, BaseDataSetDesign dteDataSet )
{
//dataset parameters definition
HashMap paramBindingCandidates = new HashMap( );
Iterator elmtIter = modelDataSet.parametersIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
DataSetParameterHandle modelParam = ( DataSetParameterHandle ) elmtIter
.next( );
// collect input parameter default values as
// potential parameter binding if no explicit ones are
// defined for a parameter
if ( modelParam.isInput( ) )
{
String defaultValueExpr = null;
if ( modelParam instanceof OdaDataSetParameterHandle
&& ( (OdaDataSetParameterHandle) modelParam ).getParamName( ) != null )
{
defaultValueExpr = ExpressionUtil.createJSParameterExpression( ( ( (OdaDataSetParameterHandle) modelParam ).getParamName( ) ) );
}
else
defaultValueExpr = modelParam.getDefaultValue( );
dteDataSet.addParameter( new ParameterAdapter( modelParam ) );
paramBindingCandidates.put( modelParam.getName( ),
defaultValueExpr );
}
else
{
dteDataSet.addParameter( new ParameterAdapter( modelParam ) );
}
}
}
// input parameter bindings
elmtIter = modelDataSet.paramBindingsIterator( );
if ( elmtIter != null )
{
while ( elmtIter.hasNext( ) )
{
ParamBindingHandle modelParamBinding = ( ParamBindingHandle ) elmtIter
.next( );
// replace default value of the same parameter, if defined
paramBindingCandidates.put( modelParamBinding.getParamName( ),
modelParamBinding.getExpression( ) );
}
}
// assign merged parameter bindings to the data set
if ( paramBindingCandidates.size( ) > 0 )
{
elmtIter = paramBindingCandidates.keySet( ).iterator( );
while ( elmtIter.hasNext( ) )
{
Object paramName = elmtIter.next( );
assert ( paramName != null && paramName instanceof String );
String expression = ( String ) paramBindingCandidates
.get( paramName );
dteDataSet.addInputParamBinding( new InputParamBindingAdapter(
( String ) paramName, expression ) );
}
}
}
|
diff --git a/src/ua/luxoft/odessa/tetris/impl/strategies/ConeLStrategy.java b/src/ua/luxoft/odessa/tetris/impl/strategies/ConeLStrategy.java
index f7e61c3..c90eba9 100644
--- a/src/ua/luxoft/odessa/tetris/impl/strategies/ConeLStrategy.java
+++ b/src/ua/luxoft/odessa/tetris/impl/strategies/ConeLStrategy.java
@@ -1,105 +1,106 @@
package ua.luxoft.odessa.tetris.impl.strategies;
import ua.luxoft.odessa.tetris.api.IFigure.Coordinates;
import ua.luxoft.odessa.tetris.api.IFigureCheckStrategy;
import ua.luxoft.odessa.tetris.impl.Board;
/*
* Cone Left
*
* Presentations:
*
* down left up right
* - - - - - - - - - - - - - - - -
* * - - - * * * - - * * - - - - -
* * - - - * - - - - - * - - - * -
* * * - - - - - - - - * - * * * -
*
* */
public class ConeLStrategy implements IFigureCheckStrategy {
public static final int WIDTH = 4;
private OrientationLURD mOrientation;
public ConeLStrategy()
{
mOrientation = OrientationLURD.DOWN;
}
private Boolean checkSpace(int xPos, int yPos, Board board)
{
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++)
if (board.getMap(xPos + x, yPos + y + 1))
return false;
return true;
}
@Override
public void checkUp(Coordinates coordinates, Board board) {
switch (mOrientation)
{
case DOWN:
if (coordinates.x + 2 >= Board.WIDTH)
{
if (checkSpace(coordinates.x - 1, coordinates.y, board) == false)
return;
+ coordinates.x--;
}
else
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
case LEFT:
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
case UP:
if (coordinates.x < 0)
{
if (checkSpace(coordinates.x + 1, coordinates.y, board) == false)
return;
coordinates.x++;
}
else
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
case RIGHT:
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
}
mOrientation = mOrientation.next();
}
@Override
public Boolean[][] getPresentation() {
Boolean[][] presentation = new Boolean[WIDTH][WIDTH];
switch (mOrientation)
{
case DOWN:
for (int i = 0; i < 3; i++)
presentation[0][i+1] = true;
presentation[1][3] = true;
break;
case LEFT:
for (int i = 0; i < 3; i++)
presentation[i][1] = true;
presentation[0][2] = true;
break;
case UP:
for (int i = 0; i < 3; i++)
presentation[2][i+1] = true;
presentation[1][1] = true;
break;
case RIGHT:
for (int i = 0; i < 3; i++)
presentation[i][3] = true;
presentation[2][2] = true;
break;
}
return presentation;
}
}
| true | true | public void checkUp(Coordinates coordinates, Board board) {
switch (mOrientation)
{
case DOWN:
if (coordinates.x + 2 >= Board.WIDTH)
{
if (checkSpace(coordinates.x - 1, coordinates.y, board) == false)
return;
}
else
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
case LEFT:
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
case UP:
if (coordinates.x < 0)
{
if (checkSpace(coordinates.x + 1, coordinates.y, board) == false)
return;
coordinates.x++;
}
else
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
case RIGHT:
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
}
mOrientation = mOrientation.next();
}
| public void checkUp(Coordinates coordinates, Board board) {
switch (mOrientation)
{
case DOWN:
if (coordinates.x + 2 >= Board.WIDTH)
{
if (checkSpace(coordinates.x - 1, coordinates.y, board) == false)
return;
coordinates.x--;
}
else
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
case LEFT:
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
case UP:
if (coordinates.x < 0)
{
if (checkSpace(coordinates.x + 1, coordinates.y, board) == false)
return;
coordinates.x++;
}
else
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
case RIGHT:
if (checkSpace(coordinates.x, coordinates.y, board) == false)
return;
break;
}
mOrientation = mOrientation.next();
}
|
diff --git a/src/com/geeksville/location/parse/SeeYouCUP.java b/src/com/geeksville/location/parse/SeeYouCUP.java
index b6bc2a4..a984844 100644
--- a/src/com/geeksville/location/parse/SeeYouCUP.java
+++ b/src/com/geeksville/location/parse/SeeYouCUP.java
@@ -1,75 +1,71 @@
package com.geeksville.location.parse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.util.Log;
import com.geeksville.location.LocationUtils;
import com.geeksville.location.Waypoint;
import com.geeksville.location.WaypointDB;
public class SeeYouCUP extends Parse {
//as per specification at http://download.naviter.com/docs/cup_format.pdf
//"Lesce-Bled","LESCE",SI,4621.666N,01410.332E,505.0m,2,130,1140.0m,"123.50","Home airfield"
//http://stackoverflow.com/questions/1441556/parsing-csv-input-with-a-regex-in-java
//http://geekswithblogs.net/mwatson/archive/2004/09/04/10658.aspx
public SeeYouCUP(String fileContents, WaypointDB db) {
super(db, fileContents, "^(?:\"{0,1}([^\"]*)\"{0,1},)(?:\"{0,1}[^\"]*\"{0,1},)(?:[^,]*,)(?:([\\d]{2})([\\d]{2}).([\\d]{3})([NS]),)(?:([\\d]{3})([\\d]{2}).([\\d]{3})([EW]),)(?:([\\d\\.]*)(m|ft),)(\\d),(?:[^,]*,)(?:[^,]*,)(?:[^,]*,)(?:\"{0,1}([^\"]*)\"{0,1})$|-----Related\\sTasks-----");
}
@Override
public int Find() {
while (matcher.find())
{
try{
if (matcher.group().contains("-----Related Tasks-----"))
break;
String latDStr = matcher.group(2),
latMstr = matcher.group(3),
- latSstr = matcher.group(4),
+ latMDecimalStr = matcher.group(4),
latNS = matcher.group(5),
lonDStr = matcher.group(6),
lonMstr = matcher.group(7),
- lonSstr = matcher.group(8),
+ lonMDecimalStr = matcher.group(8),
lonEW = matcher.group(9),
altStr = matcher.group(10),
altUnits = matcher.group(11),
waypointStyle= matcher.group(12);
int wpStyle = Integer.parseInt(waypointStyle);
if(wpStyle>1 && wpStyle< 6)
type = Waypoint.Type.Landing;
- else
+ else
type = Waypoint.Type.Unknown;
name = matcher.group(1).trim();
description = matcher.group(13).trim();
float latM = 0, latS = 0, lonM = 0 , lonS = 0;
if (latMstr != null)
- latM = Float.parseFloat(latMstr);
- if (latSstr != null)
- latS = Float.parseFloat(latSstr);
+ latM = Float.parseFloat(latMstr + "." + latMDecimalStr);
if (lonMstr != null)
- latS = Float.parseFloat(lonMstr);
- if (lonSstr != null)
- lonS = Float.parseFloat(lonSstr);
+ lonM = Float.parseFloat(lonMstr + "." + lonMDecimalStr);
latitude = LocationUtils.DMSToDegrees(Integer.parseInt(latDStr), latM, latS, latNS.equals("N"));
longitude = LocationUtils.DMSToDegrees(Integer.parseInt(lonDStr), lonM, lonS, lonEW.equals("E"));
if (altUnits.toLowerCase() == "ft")
altitude = Double.parseDouble(altStr) ;
else
altitude = Double.parseDouble(altStr) / 3.2808399;
Save();
numFound ++;
}
catch(Exception ex)
{
Log.d(Tag, matcher.group());
}
}
return numFound;
}
}
| false | true | public int Find() {
while (matcher.find())
{
try{
if (matcher.group().contains("-----Related Tasks-----"))
break;
String latDStr = matcher.group(2),
latMstr = matcher.group(3),
latSstr = matcher.group(4),
latNS = matcher.group(5),
lonDStr = matcher.group(6),
lonMstr = matcher.group(7),
lonSstr = matcher.group(8),
lonEW = matcher.group(9),
altStr = matcher.group(10),
altUnits = matcher.group(11),
waypointStyle= matcher.group(12);
int wpStyle = Integer.parseInt(waypointStyle);
if(wpStyle>1 && wpStyle< 6)
type = Waypoint.Type.Landing;
else
type = Waypoint.Type.Unknown;
name = matcher.group(1).trim();
description = matcher.group(13).trim();
float latM = 0, latS = 0, lonM = 0 , lonS = 0;
if (latMstr != null)
latM = Float.parseFloat(latMstr);
if (latSstr != null)
latS = Float.parseFloat(latSstr);
if (lonMstr != null)
latS = Float.parseFloat(lonMstr);
if (lonSstr != null)
lonS = Float.parseFloat(lonSstr);
latitude = LocationUtils.DMSToDegrees(Integer.parseInt(latDStr), latM, latS, latNS.equals("N"));
longitude = LocationUtils.DMSToDegrees(Integer.parseInt(lonDStr), lonM, lonS, lonEW.equals("E"));
if (altUnits.toLowerCase() == "ft")
altitude = Double.parseDouble(altStr) ;
else
altitude = Double.parseDouble(altStr) / 3.2808399;
Save();
numFound ++;
}
catch(Exception ex)
{
Log.d(Tag, matcher.group());
}
}
return numFound;
}
| public int Find() {
while (matcher.find())
{
try{
if (matcher.group().contains("-----Related Tasks-----"))
break;
String latDStr = matcher.group(2),
latMstr = matcher.group(3),
latMDecimalStr = matcher.group(4),
latNS = matcher.group(5),
lonDStr = matcher.group(6),
lonMstr = matcher.group(7),
lonMDecimalStr = matcher.group(8),
lonEW = matcher.group(9),
altStr = matcher.group(10),
altUnits = matcher.group(11),
waypointStyle= matcher.group(12);
int wpStyle = Integer.parseInt(waypointStyle);
if(wpStyle>1 && wpStyle< 6)
type = Waypoint.Type.Landing;
else
type = Waypoint.Type.Unknown;
name = matcher.group(1).trim();
description = matcher.group(13).trim();
float latM = 0, latS = 0, lonM = 0 , lonS = 0;
if (latMstr != null)
latM = Float.parseFloat(latMstr + "." + latMDecimalStr);
if (lonMstr != null)
lonM = Float.parseFloat(lonMstr + "." + lonMDecimalStr);
latitude = LocationUtils.DMSToDegrees(Integer.parseInt(latDStr), latM, latS, latNS.equals("N"));
longitude = LocationUtils.DMSToDegrees(Integer.parseInt(lonDStr), lonM, lonS, lonEW.equals("E"));
if (altUnits.toLowerCase() == "ft")
altitude = Double.parseDouble(altStr) ;
else
altitude = Double.parseDouble(altStr) / 3.2808399;
Save();
numFound ++;
}
catch(Exception ex)
{
Log.d(Tag, matcher.group());
}
}
return numFound;
}
|
diff --git a/enunciate/maven-enunciate-plugin/src/main/java/org/codehaus/enunciate/ConfigMojo.java b/enunciate/maven-enunciate-plugin/src/main/java/org/codehaus/enunciate/ConfigMojo.java
index 3ea3863e..e3a0ed46 100644
--- a/enunciate/maven-enunciate-plugin/src/main/java/org/codehaus/enunciate/ConfigMojo.java
+++ b/enunciate/maven-enunciate-plugin/src/main/java/org/codehaus/enunciate/ConfigMojo.java
@@ -1,637 +1,640 @@
package org.codehaus.enunciate;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.maven.shared.filtering.MavenFileFilter;
import org.apache.maven.shared.filtering.MavenFilteringException;
import org.codehaus.enunciate.config.EnunciateConfiguration;
import org.codehaus.enunciate.main.Enunciate;
import org.codehaus.enunciate.modules.*;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* Goal which initializes an Enunciate build process.
*
* @goal config
* @phase validate
* @requiresDependencyResolution compile
*/
public class ConfigMojo extends AbstractMojo {
public static final String ENUNCIATE_PROPERTY = "urn:" + ConfigMojo.class.getName() + "#enunciate";
public static final String ENUNCIATE_STEPPER_PROPERTY = "urn:" + ConfigMojo.class.getName() + "#stepper";
/**
* @parameter expression="${plugin.artifacts}"
* @required
* @readonly
*/
private Collection<org.apache.maven.artifact.Artifact> pluginDepdendencies;
/**
* Project dependencies.
*
* @parameter expression="${project.artifacts}"
* @required
* @readonly
*/
private Collection<org.apache.maven.artifact.Artifact> projectDependencies;
/**
* Project artifacts.
*
* @parameter
*/
private Artifact[] artifacts;
/**
* The enunciate configuration file to use.
*
* @parameter
*/
private File configFile = null;
/**
* The output directory for the "generate" step.
*
* @parameter expression="${project.build.directory}/enunciate/generate"
*/
private File generateDir = null;
/**
* The output directory for the "compile" step.
*
* @parameter expression="${project.build.directory}/enunciate/compile"
*/
private File compileDir = null;
/**
* The output directory for the "build" step.
*
* @parameter expression="${project.build.directory}/enunciate/build"
*/
private File buildDir = null;
/**
* The output directory for the "package" step.
*
* @parameter expression="${project.build.directory}/enunciate/package"
*/
private File packageDir = null;
/**
* The directory where Enunciate puts scratch files.
*
* @parameter expression="${project.build.directory}/enunciate-scratch"
*/
private File scratchDir = null;
/**
* The directory for the generated WAR.
*
* @parameter expression="${project.build.directory}"
* @required
*/
private File outputDir = null;
/**
* Whether to add the GWT sources to the project compile sources.
*
* @parameter
*/
private boolean addGWTSources = true;
/**
* Whether to add the actionscript sources to the project compile sources.
*
* @parameter
*/
private boolean addActionscriptSources = true;
/**
* Whether to add the XFire client sources to the project test sources.
*
* @parameter
*/
private boolean addXFireClientSourcesToTestClasspath = false;
/**
* Whether to add the JAXWS client sources to the project test sources.
*
* @parameter
*/
private boolean addJAXWSClientSourcesToTestClasspath = false;
/**
* List of modules that are to be excluded as extensions to this project.
*
* @parameter
*/
private String[] excludeProjectExtensions;
/**
* The GWT home.
*
* @parameter
*/
private String gwtHome = null;
/**
* The Flex home.
*
* @parameter
*/
private String flexHome = null;
/**
* Whether to compile with debug information.
*
* @parameter
*/
private boolean compileDebug = true;
/**
* The exports.
*
* @parameter
*/
private Map<String, String> exports = new HashMap<String, String>();
/**
* The include patterns.
*/
private String[] includes;
/**
* The exclude patterns.
*/
private String[] excludes;
/**
* The id of the Enunciate artifact that is to be the primary artifact for the maven project.
*
* @parameter default-value="spring.war.file"
*/
private String warArtifactId = "spring.war.file";
/**
* The name of the generated WAR.
*
* @parameter expression="${project.build.finalName}"
* @required
*/
private String warArtifactName;
/**
* Classifier to add to the artifact generated. If given, the artifact will be an attachment instead.
*
* @parameter
*/
private String warArtifactClassifier = null;
/**
* The Maven project reference.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
protected MavenProject project;
/**
* Maven ProjectHelper
*
* @component
* @readonly
*/
private MavenProjectHelper projectHelper;
/**
* @parameter expression="${session}"
* @readonly
*/
private MavenSession session;
/**
* Maven file filter.
*
* @component role="org.apache.maven.shared.filtering.MavenFileFilter" role-hint="default"
* @readonly
*/
private MavenFileFilter configFilter;
/**
* List of source directories that are enunciate-added.
*/
private static final TreeSet<String> ENUNCIATE_ADDED = new TreeSet<String>();
public void execute() throws MojoExecutionException {
Set<File> sourceDirs = new HashSet<File>();
Collection<String> sourcePaths = (Collection<String>) project.getCompileSourceRoots();
for (String sourcePath : sourcePaths) {
File sourceDir = new File(sourcePath);
if (!isEnunciateAdded(sourceDir)) {
sourceDirs.add(sourceDir);
}
else {
getLog().info(sourceDir + " appears to be added to the source roots by Enunciate. Excluding from original source roots....");
}
}
MavenSpecificEnunciate enunciate = loadMavenSpecificEnunciate(sourceDirs);
EnunciateConfiguration config = createEnunciateConfiguration();
config.setLabel(project.getArtifactId());
if (this.configFile != null) {
try {
loadConfig(config, this.configFile);
}
catch (Exception e) {
throw new MojoExecutionException("Problem with enunciate config file " + this.configFile, e);
}
enunciate.setConfigFile(this.configFile);
}
else {
File defaultConfig = new File(project.getBasedir(), "enunciate.xml");
if (defaultConfig.exists()) {
getLog().info(defaultConfig.getAbsolutePath() + " exists, so it will be used.");
try {
loadConfig(config, defaultConfig);
}
catch (Exception e) {
throw new MojoExecutionException("Problem with enunciate config file " + defaultConfig, e);
}
enunciate.setConfigFile(defaultConfig);
}
}
if (this.includes != null) {
for (String include : this.includes) {
config.addApiIncludePattern(include);
}
}
if (this.excludes != null) {
for (String exclude : this.excludes) {
config.addApiExcludePattern(exclude);
}
}
enunciate.setConfig(config);
Set<org.apache.maven.artifact.Artifact> classpathEntries = new HashSet<org.apache.maven.artifact.Artifact>();
classpathEntries.addAll(this.projectDependencies);
Iterator<org.apache.maven.artifact.Artifact> it = classpathEntries.iterator();
while (it.hasNext()) {
org.apache.maven.artifact.Artifact artifact = it.next();
String artifactScope = artifact.getScope();
if (org.apache.maven.artifact.Artifact.SCOPE_TEST.equals(artifactScope)) {
//remove just the test-scope artifacts from the classpath.
it.remove();
}
}
StringBuffer classpath = new StringBuffer();
Iterator<org.apache.maven.artifact.Artifact> classpathIt = classpathEntries.iterator();
while (classpathIt.hasNext()) {
classpath.append(classpathIt.next().getFile().getAbsolutePath());
if (classpathIt.hasNext()) {
classpath.append(File.pathSeparatorChar);
}
}
enunciate.setRuntimeClasspath(classpath.toString());
classpathEntries.clear();
classpathEntries.addAll(this.pluginDepdendencies);
classpath = new StringBuffer();
classpathIt = classpathEntries.iterator();
while (classpathIt.hasNext()) {
classpath.append(classpathIt.next().getFile().getAbsolutePath());
if (classpathIt.hasNext()) {
classpath.append(File.pathSeparatorChar);
}
}
enunciate.setBuildClasspath(classpath.toString());
if (this.generateDir != null) {
enunciate.setGenerateDir(this.generateDir);
}
if (this.compileDir != null) {
enunciate.setCompileDir(this.compileDir);
}
if (this.buildDir != null) {
enunciate.setBuildDir(this.buildDir);
}
if (this.packageDir != null) {
enunciate.setPackageDir(this.packageDir);
}
if (this.scratchDir != null) {
enunciate.setScratchDir(this.scratchDir);
}
if (this.exports != null) {
for (String exportId : this.exports.keySet()) {
String filename = this.exports.get(exportId);
+ if (filename == null || "".equals(filename)) {
+ throw new MojoExecutionException("Invalid (empty or null) filename for export " + exportId + ".");
+ }
File exportFile = new File(filename);
if (!exportFile.isAbsolute()) {
exportFile = new File(this.outputDir, filename);
}
enunciate.addExport(exportId, exportFile);
}
}
enunciate.setCompileDebugInfo(this.compileDebug);
try {
enunciate.loadMavenConfiguration();
Enunciate.Stepper stepper = enunciate.getStepper();
getPluginContext().put(ENUNCIATE_STEPPER_PROPERTY, stepper);
getPluginContext().put(ENUNCIATE_PROPERTY, enunciate);
}
catch (Exception e) {
throw new MojoExecutionException("Error initializing Enunciate mechanism.", e);
}
}
/**
* Load the config, do filtering as needed.
*
* @param config The config to load into.
* @param configFile The config file.
*/
protected void loadConfig(EnunciateConfiguration config, File configFile) throws IOException, SAXException, MavenFilteringException {
if (this.configFilter == null) {
getLog().debug("No maven file filter was provided, so no filtering of the config file will be done.");
config.load(configFile);
}
else {
this.scratchDir.mkdirs();
File filteredConfig = File.createTempFile("enunciateConfig", ".xml", this.scratchDir);
getLog().debug("Filtering " + configFile + " to " + filteredConfig + "...");
this.configFilter.copyFile(configFile, filteredConfig, true, this.project, null, true, "utf-8", this.session);
config.load(filteredConfig);
}
}
/**
* Whether the given source directory is Enunciate-generated.
*
* @param sourceDir The source directory.
* @return Whether the given source directory is Enunciate-generated.Whether the given source directory is Enunciate-generated.
*/
protected boolean isEnunciateAdded(File sourceDir) {
return ENUNCIATE_ADDED.contains(sourceDir.getAbsolutePath());
}
/**
* Adds the specified source directory to the Maven project.
*
* @param dir The directory to add to the project.
*/
protected void addSourceDirToProject(File dir) {
String sourceDir = dir.getAbsolutePath();
ENUNCIATE_ADDED.add(sourceDir);
if (!project.getCompileSourceRoots().contains(sourceDir)) {
getLog().debug("Adding '" + sourceDir + "' to the compile source roots.");
project.addCompileSourceRoot(sourceDir);
}
}
/**
* Create an Enunciate configuration.
*
* @return The enunciate configuration.
*/
protected EnunciateConfiguration createEnunciateConfiguration() {
return new EnunciateConfiguration();
}
/**
* Loads a correct instance of the Maven-specific Enunciate mechanism.
*
* @param sourceDirs The directories where the source files exist.
* @return The maven-specific Enunciate mechanism.
*/
protected MavenSpecificEnunciate loadMavenSpecificEnunciate(Set<File> sourceDirs) {
return new MavenSpecificEnunciate(sourceDirs);
}
protected Set<String> getExcludedProjectExtensions() {
TreeSet<String> excluded = new TreeSet<String>();
if (excludeProjectExtensions != null) {
excluded.addAll(Arrays.asList(excludeProjectExtensions));
}
if (!addActionscriptSources) {
excluded.add("amf");
}
if (!addGWTSources) {
excluded.add("gwt");
}
if (!addJAXWSClientSourcesToTestClasspath) {
excluded.add("jaxws-client");
}
if (!addXFireClientSourcesToTestClasspath) {
excluded.add("xfire-client");
}
return excluded;
}
/**
* Enunciate mechanism that logs via the Maven logging mechanism.
*/
protected class MavenSpecificEnunciate extends Enunciate {
public MavenSpecificEnunciate(Collection<File> rootDirs) {
super();
ArrayList<String> sources = new ArrayList<String>();
for (File rootDir : rootDirs) {
sources.addAll(getJavaFiles(rootDir));
}
setSourceFiles(sources.toArray(new String[sources.size()]));
}
public void loadMavenConfiguration() throws IOException {
for (DeploymentModule module : getConfig().getAllModules()) {
if (!module.isDisabled()) {
if (gwtHome != null && (module instanceof GWTHomeAwareModule)) {
((GWTHomeAwareModule) module).setGwtHome(gwtHome);
}
else if (flexHome != null && (module instanceof FlexHomeAwareModule)) {
((FlexHomeAwareModule) module).setFlexHome(flexHome);
}
}
}
}
@Override
protected void initModules(Collection<DeploymentModule> modules) throws EnunciateException, IOException {
super.initModules(modules);
if (compileDir == null) {
//set an explicit compile dir if one doesn't exist because we're going to need to reference it to set the output directory for Maven.
setCompileDir(createTempDir());
}
for (DeploymentModule module : modules) {
if (!module.isDisabled()) {
if (module instanceof OutputDirectoryAware) {
String outputDir = project.getBuild().getOutputDirectory();
debug("Setting the output directory for module %s to %s...", module.getName(), outputDir);
((OutputDirectoryAware) module).setOutputDirectory(new File(outputDir));
}
if (project.getName() != null && !"".equals(project.getName().trim()) && module instanceof ProjectTitleAware) {
((ProjectTitleAware)module).setTitleConditionally(project.getName());
}
}
}
}
@Override
protected void doGenerate() throws IOException, EnunciateException {
super.doGenerate();
for (DeploymentModule module : getConfig().getAllModules()) {
if (!module.isDisabled() && (module instanceof ProjectExtensionModule) && !getExcludedProjectExtensions().contains(module.getName())) {
ProjectExtensionModule extensions = (ProjectExtensionModule) module;
for (File projectSource : extensions.getProjectSources()) {
addSourceDirToProject(projectSource);
}
for (File testSource : extensions.getProjectTestSources()) {
project.addTestCompileSourceRoot(testSource.getAbsolutePath());
}
for (File resourceDir : extensions.getProjectResourceDirectories()) {
Resource restResource = new Resource();
restResource.setDirectory(resourceDir.getAbsolutePath());
project.addResource(restResource);
}
for (File resourceDir : extensions.getProjectTestResourceDirectories()) {
Resource resource = new Resource();
resource.setDirectory(resourceDir.getAbsolutePath());
project.addTestResource(resource);
}
}
}
}
@Override
public void info(String message, Object... formatArgs) {
getLog().info(String.format(message, formatArgs));
}
@Override
public void debug(String message, Object... formatArgs) {
getLog().debug(String.format(message, formatArgs));
}
@Override
public void warn(String message, Object... formatArgs) {
getLog().warn(String.format(message, formatArgs));
}
@Override
public boolean isDebug() {
return getLog().isDebugEnabled();
}
@Override
public boolean isVerbose() {
return getLog().isInfoEnabled();
}
@Override
protected void doClose() throws EnunciateException, IOException {
super.doClose();
if (warArtifactId != null) {
org.codehaus.enunciate.main.Artifact warArtifact = null;
for (org.codehaus.enunciate.main.Artifact artifact : getArtifacts()) {
if (warArtifactId.equals(artifact.getId())) {
warArtifact = artifact;
break;
}
}
if (warArtifact != null) {
String classifier = warArtifactClassifier;
if (classifier == null) {
classifier = "";
}
else if (classifier.trim().length() > 0 && !classifier.startsWith("-")) {
classifier = "-" + classifier;
}
File warArtifactFile = new File(outputDir, warArtifactName + classifier + ".war");
warArtifact.exportTo(warArtifactFile, this);
project.getArtifact().setFile(warArtifactFile);
}
else {
getLog().debug("War artifact '" + warArtifactId + "' not found in the project...");
}
}
if (artifacts != null) {
for (Artifact projectArtifact : artifacts) {
if (projectArtifact.getEnunciateArtifactId() == null) {
getLog().warn("No enunciate export id specified. Skipping project artifact...");
continue;
}
org.codehaus.enunciate.main.Artifact artifact = null;
for (org.codehaus.enunciate.main.Artifact enunciateArtifact : getArtifacts()) {
if (projectArtifact.getEnunciateArtifactId().equals(enunciateArtifact.getId())) {
artifact = enunciateArtifact;
break;
}
}
if (artifact != null) {
File tempExportFile = createTempFile(project.getArtifactId() + "-" + projectArtifact.getClassifier(), projectArtifact.getArtifactType());
artifact.exportTo(tempExportFile, this);
projectHelper.attachArtifact(project, projectArtifact.getArtifactType(), projectArtifact.getClassifier(), tempExportFile);
}
else {
getLog().warn("Enunciate artifact '" + projectArtifact.getEnunciateArtifactId() + "' not found in the project...");
}
}
}
}
}
}
| true | true | public void execute() throws MojoExecutionException {
Set<File> sourceDirs = new HashSet<File>();
Collection<String> sourcePaths = (Collection<String>) project.getCompileSourceRoots();
for (String sourcePath : sourcePaths) {
File sourceDir = new File(sourcePath);
if (!isEnunciateAdded(sourceDir)) {
sourceDirs.add(sourceDir);
}
else {
getLog().info(sourceDir + " appears to be added to the source roots by Enunciate. Excluding from original source roots....");
}
}
MavenSpecificEnunciate enunciate = loadMavenSpecificEnunciate(sourceDirs);
EnunciateConfiguration config = createEnunciateConfiguration();
config.setLabel(project.getArtifactId());
if (this.configFile != null) {
try {
loadConfig(config, this.configFile);
}
catch (Exception e) {
throw new MojoExecutionException("Problem with enunciate config file " + this.configFile, e);
}
enunciate.setConfigFile(this.configFile);
}
else {
File defaultConfig = new File(project.getBasedir(), "enunciate.xml");
if (defaultConfig.exists()) {
getLog().info(defaultConfig.getAbsolutePath() + " exists, so it will be used.");
try {
loadConfig(config, defaultConfig);
}
catch (Exception e) {
throw new MojoExecutionException("Problem with enunciate config file " + defaultConfig, e);
}
enunciate.setConfigFile(defaultConfig);
}
}
if (this.includes != null) {
for (String include : this.includes) {
config.addApiIncludePattern(include);
}
}
if (this.excludes != null) {
for (String exclude : this.excludes) {
config.addApiExcludePattern(exclude);
}
}
enunciate.setConfig(config);
Set<org.apache.maven.artifact.Artifact> classpathEntries = new HashSet<org.apache.maven.artifact.Artifact>();
classpathEntries.addAll(this.projectDependencies);
Iterator<org.apache.maven.artifact.Artifact> it = classpathEntries.iterator();
while (it.hasNext()) {
org.apache.maven.artifact.Artifact artifact = it.next();
String artifactScope = artifact.getScope();
if (org.apache.maven.artifact.Artifact.SCOPE_TEST.equals(artifactScope)) {
//remove just the test-scope artifacts from the classpath.
it.remove();
}
}
StringBuffer classpath = new StringBuffer();
Iterator<org.apache.maven.artifact.Artifact> classpathIt = classpathEntries.iterator();
while (classpathIt.hasNext()) {
classpath.append(classpathIt.next().getFile().getAbsolutePath());
if (classpathIt.hasNext()) {
classpath.append(File.pathSeparatorChar);
}
}
enunciate.setRuntimeClasspath(classpath.toString());
classpathEntries.clear();
classpathEntries.addAll(this.pluginDepdendencies);
classpath = new StringBuffer();
classpathIt = classpathEntries.iterator();
while (classpathIt.hasNext()) {
classpath.append(classpathIt.next().getFile().getAbsolutePath());
if (classpathIt.hasNext()) {
classpath.append(File.pathSeparatorChar);
}
}
enunciate.setBuildClasspath(classpath.toString());
if (this.generateDir != null) {
enunciate.setGenerateDir(this.generateDir);
}
if (this.compileDir != null) {
enunciate.setCompileDir(this.compileDir);
}
if (this.buildDir != null) {
enunciate.setBuildDir(this.buildDir);
}
if (this.packageDir != null) {
enunciate.setPackageDir(this.packageDir);
}
if (this.scratchDir != null) {
enunciate.setScratchDir(this.scratchDir);
}
if (this.exports != null) {
for (String exportId : this.exports.keySet()) {
String filename = this.exports.get(exportId);
File exportFile = new File(filename);
if (!exportFile.isAbsolute()) {
exportFile = new File(this.outputDir, filename);
}
enunciate.addExport(exportId, exportFile);
}
}
enunciate.setCompileDebugInfo(this.compileDebug);
try {
enunciate.loadMavenConfiguration();
Enunciate.Stepper stepper = enunciate.getStepper();
getPluginContext().put(ENUNCIATE_STEPPER_PROPERTY, stepper);
getPluginContext().put(ENUNCIATE_PROPERTY, enunciate);
}
catch (Exception e) {
throw new MojoExecutionException("Error initializing Enunciate mechanism.", e);
}
}
| public void execute() throws MojoExecutionException {
Set<File> sourceDirs = new HashSet<File>();
Collection<String> sourcePaths = (Collection<String>) project.getCompileSourceRoots();
for (String sourcePath : sourcePaths) {
File sourceDir = new File(sourcePath);
if (!isEnunciateAdded(sourceDir)) {
sourceDirs.add(sourceDir);
}
else {
getLog().info(sourceDir + " appears to be added to the source roots by Enunciate. Excluding from original source roots....");
}
}
MavenSpecificEnunciate enunciate = loadMavenSpecificEnunciate(sourceDirs);
EnunciateConfiguration config = createEnunciateConfiguration();
config.setLabel(project.getArtifactId());
if (this.configFile != null) {
try {
loadConfig(config, this.configFile);
}
catch (Exception e) {
throw new MojoExecutionException("Problem with enunciate config file " + this.configFile, e);
}
enunciate.setConfigFile(this.configFile);
}
else {
File defaultConfig = new File(project.getBasedir(), "enunciate.xml");
if (defaultConfig.exists()) {
getLog().info(defaultConfig.getAbsolutePath() + " exists, so it will be used.");
try {
loadConfig(config, defaultConfig);
}
catch (Exception e) {
throw new MojoExecutionException("Problem with enunciate config file " + defaultConfig, e);
}
enunciate.setConfigFile(defaultConfig);
}
}
if (this.includes != null) {
for (String include : this.includes) {
config.addApiIncludePattern(include);
}
}
if (this.excludes != null) {
for (String exclude : this.excludes) {
config.addApiExcludePattern(exclude);
}
}
enunciate.setConfig(config);
Set<org.apache.maven.artifact.Artifact> classpathEntries = new HashSet<org.apache.maven.artifact.Artifact>();
classpathEntries.addAll(this.projectDependencies);
Iterator<org.apache.maven.artifact.Artifact> it = classpathEntries.iterator();
while (it.hasNext()) {
org.apache.maven.artifact.Artifact artifact = it.next();
String artifactScope = artifact.getScope();
if (org.apache.maven.artifact.Artifact.SCOPE_TEST.equals(artifactScope)) {
//remove just the test-scope artifacts from the classpath.
it.remove();
}
}
StringBuffer classpath = new StringBuffer();
Iterator<org.apache.maven.artifact.Artifact> classpathIt = classpathEntries.iterator();
while (classpathIt.hasNext()) {
classpath.append(classpathIt.next().getFile().getAbsolutePath());
if (classpathIt.hasNext()) {
classpath.append(File.pathSeparatorChar);
}
}
enunciate.setRuntimeClasspath(classpath.toString());
classpathEntries.clear();
classpathEntries.addAll(this.pluginDepdendencies);
classpath = new StringBuffer();
classpathIt = classpathEntries.iterator();
while (classpathIt.hasNext()) {
classpath.append(classpathIt.next().getFile().getAbsolutePath());
if (classpathIt.hasNext()) {
classpath.append(File.pathSeparatorChar);
}
}
enunciate.setBuildClasspath(classpath.toString());
if (this.generateDir != null) {
enunciate.setGenerateDir(this.generateDir);
}
if (this.compileDir != null) {
enunciate.setCompileDir(this.compileDir);
}
if (this.buildDir != null) {
enunciate.setBuildDir(this.buildDir);
}
if (this.packageDir != null) {
enunciate.setPackageDir(this.packageDir);
}
if (this.scratchDir != null) {
enunciate.setScratchDir(this.scratchDir);
}
if (this.exports != null) {
for (String exportId : this.exports.keySet()) {
String filename = this.exports.get(exportId);
if (filename == null || "".equals(filename)) {
throw new MojoExecutionException("Invalid (empty or null) filename for export " + exportId + ".");
}
File exportFile = new File(filename);
if (!exportFile.isAbsolute()) {
exportFile = new File(this.outputDir, filename);
}
enunciate.addExport(exportId, exportFile);
}
}
enunciate.setCompileDebugInfo(this.compileDebug);
try {
enunciate.loadMavenConfiguration();
Enunciate.Stepper stepper = enunciate.getStepper();
getPluginContext().put(ENUNCIATE_STEPPER_PROPERTY, stepper);
getPluginContext().put(ENUNCIATE_PROPERTY, enunciate);
}
catch (Exception e) {
throw new MojoExecutionException("Error initializing Enunciate mechanism.", e);
}
}
|
diff --git a/java/src/org/tom/weather/graph/SolarRadiationChart.java b/java/src/org/tom/weather/graph/SolarRadiationChart.java
index 3852d422..24d8c2bf 100644
--- a/java/src/org/tom/weather/graph/SolarRadiationChart.java
+++ b/java/src/org/tom/weather/graph/SolarRadiationChart.java
@@ -1,61 +1,61 @@
package org.tom.weather.graph;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.jdbc.JDBCXYDataset;
import org.jfree.data.xy.XYDataset;
public class SolarRadiationChart extends BaseChart {
private static final Logger LOGGER = Logger.getLogger(SolarRadiationChart.class);
public SolarRadiationChart(DataSource source, String filename, Timestamp start, Timestamp end) {
buildChart(source, filename, start, end);
}
private void buildChart(DataSource source, String filename, Timestamp start, Timestamp end) {
XYDataset data = readData(source, start, end);
// create the chart...
JFreeChart chart =
ChartFactory.createTimeSeriesChart("Solar Radiation",
"Date", "W/sq. m", data, // data
true, // include legend
true, false);
writeChart(chart, filename);
}
private XYDataset readData(DataSource source, Timestamp start, Timestamp end) {
JDBCXYDataset data = null;
try {
Connection con = source.getConnection();
data = new JDBCXYDataset(con);
String sql = "SELECT date - INTERVAL " + Grapher.OFFSET / 1000 + " second , solar_radiation FROM archive_records"
- + " where date >= '" + start + "' and date < '" + end + "' and solar_radiation != null order by date desc;";
+ + " where date >= '" + start + "' and date < '" + end + "' order by date desc;";
data.executeQuery(sql);
con.close();
}
catch (SQLException e) {
LOGGER.error(e);
}
catch (Exception e) {
LOGGER.error(e);
}
return data;
}
}
| true | true | private XYDataset readData(DataSource source, Timestamp start, Timestamp end) {
JDBCXYDataset data = null;
try {
Connection con = source.getConnection();
data = new JDBCXYDataset(con);
String sql = "SELECT date - INTERVAL " + Grapher.OFFSET / 1000 + " second , solar_radiation FROM archive_records"
+ " where date >= '" + start + "' and date < '" + end + "' and solar_radiation != null order by date desc;";
data.executeQuery(sql);
con.close();
}
catch (SQLException e) {
LOGGER.error(e);
}
catch (Exception e) {
LOGGER.error(e);
}
return data;
}
| private XYDataset readData(DataSource source, Timestamp start, Timestamp end) {
JDBCXYDataset data = null;
try {
Connection con = source.getConnection();
data = new JDBCXYDataset(con);
String sql = "SELECT date - INTERVAL " + Grapher.OFFSET / 1000 + " second , solar_radiation FROM archive_records"
+ " where date >= '" + start + "' and date < '" + end + "' order by date desc;";
data.executeQuery(sql);
con.close();
}
catch (SQLException e) {
LOGGER.error(e);
}
catch (Exception e) {
LOGGER.error(e);
}
return data;
}
|
diff --git a/main/src/com/google/android/apps/dashclock/calendar/CalendarExtension.java b/main/src/com/google/android/apps/dashclock/calendar/CalendarExtension.java
index 1f894f5..1f99f05 100644
--- a/main/src/com/google/android/apps/dashclock/calendar/CalendarExtension.java
+++ b/main/src/com/google/android/apps/dashclock/calendar/CalendarExtension.java
@@ -1,380 +1,383 @@
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.calendar;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import net.nurik.roman.dashclock.R;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.CalendarContract;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Pair;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
/**
* Calendar "upcoming appointment" extension.
*/
public class CalendarExtension extends DashClockExtension {
private static final String TAG = LogUtils.makeLogTag(CalendarExtension.class);
public static final String PREF_CUSTOM_VISIBILITY = "pref_calendar_custom_visibility";
public static final String PREF_SELECTED_CALENDARS = "pref_calendar_selected";
public static final String PREF_LOOK_AHEAD_HOURS = "pref_calendar_look_ahead_hours";
public static final String PREF_SHOW_ALL_DAY = "pref_calendar_show_all_day";
private static final String SQL_TAUTOLOGY = "1=1";
private static final long MINUTE_MILLIS = 60 * 1000;
private static final long HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DEFAULT_LOOK_AHEAD_HOURS = 6;
private int mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS;
static List<Pair<String, Boolean>> getAllCalendars(Context context) {
// Only return calendars that are marked as synced to device.
// (This is different from the display flag)
List<Pair<String, Boolean>> calendars = new ArrayList<Pair<String, Boolean>>();
try {
Cursor cursor = context.getContentResolver().query(
CalendarContract.Calendars.CONTENT_URI,
CalendarsQuery.PROJECTION,
CalendarContract.Calendars.SYNC_EVENTS + "=1",
null,
null);
if (cursor != null) {
while (cursor.moveToNext()) {
calendars.add(new Pair<String, Boolean>(
cursor.getString(CalendarsQuery.ID),
cursor.getInt(CalendarsQuery.VISIBLE) == 1));
}
cursor.close();
}
} catch (SecurityException e) {
LOGE(TAG, "Error querying calendar API", e);
return null;
}
return calendars;
}
private Set<String> getSelectedCalendars() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean customVisibility = sp.getBoolean(PREF_CUSTOM_VISIBILITY, false);
Set<String> selectedCalendars = sp.getStringSet(PREF_SELECTED_CALENDARS, null);
if (!customVisibility || selectedCalendars == null) {
final List<Pair<String, Boolean>> allCalendars = getAllCalendars(this);
// Build a set of all visible calendars in case we don't have a selection set in
// the preferences.
selectedCalendars = new HashSet<String>();
for (Pair<String, Boolean> pair : allCalendars) {
if (pair.second) {
selectedCalendars.add(pair.first);
}
}
}
return selectedCalendars;
}
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
if (!isReconnect) {
addWatchContentUris(new String[]{
CalendarContract.Events.CONTENT_URI.toString()
});
}
setUpdateWhenScreenOn(true);
}
@Override
protected void onUpdateData(int reason) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean showAllDay = sp.getBoolean(PREF_SHOW_ALL_DAY, false);
try {
mLookAheadHours = Integer.parseInt(sp.getString(PREF_LOOK_AHEAD_HOURS,
Integer.toString(mLookAheadHours)));
} catch (NumberFormatException e) {
mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS;
}
Cursor cursor = openEventsCursor(showAllDay);
if (cursor == null) {
LOGE(TAG, "Null events cursor, short-circuiting.");
return;
}
long currentTimestamp = getCurrentTimestamp();
long nextTimestamp = 0;
long timeUntilNextAppointent = 0;
boolean allDay = false;
int allDayPosition = -1;
while (cursor.moveToNext()) {
nextTimestamp = cursor.getLong(EventsQuery.BEGIN);
allDay = cursor.getInt(EventsQuery.ALL_DAY) != 0;
- if (showAllDay && allDay && allDayPosition < 0) {
- // Store the position of this all day event. If no regular events are found
- // and the user wanted to see all day events, then show this all day event.
- allDayPosition = cursor.getPosition();
+ if (allDay) {
+ if (showAllDay && allDayPosition < 0) {
+ // Store the position of this all day event. If no regular events are found
+ // and the user wanted to see all day events, then show this all day event.
+ allDayPosition = cursor.getPosition();
+ }
+ continue;
}
timeUntilNextAppointent = nextTimestamp - currentTimestamp;
if (timeUntilNextAppointent >= 0) {
break;
}
// Skip over events that are not ALL_DAY but span multiple days, including
// the next 6 hours. An example is an event that starts at 4pm yesterday
// day and ends 6pm tomorrow.
LOGD(TAG, "Skipping over event with start timestamp " + nextTimestamp + ". "
+ "Current timestamp " + currentTimestamp);
}
if (cursor.isAfterLast()) {
if (allDayPosition >= 0) {
// But wait, we have an all day event! Use it.
cursor.moveToPosition(allDayPosition);
allDay = true;
// For all day events (if the user wants to see them), convert the begin
// timestamp, which is the midnight UTC time, to local time. That is,
// nextTimestamp will now be midnight in local time since that's a more
// relevant representation of that day to the user.
nextTimestamp = cursor.getLong(EventsQuery.BEGIN)
- TimeZone.getDefault().getOffset(nextTimestamp);
timeUntilNextAppointent = nextTimestamp - currentTimestamp;
LOGD(TAG, "No regular events found but an all day event was found; showing it.");
} else {
LOGD(TAG, "No upcoming appointments found.");
cursor.close();
publishUpdate(new ExtensionData());
return;
}
}
Calendar nextEventCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
nextEventCalendar.setTimeInMillis(nextTimestamp);
int minutesUntilNextAppointment = (int) (timeUntilNextAppointent / MINUTE_MILLIS);
String untilString;
if (allDay) {
if (timeUntilNextAppointent <= 0) {
// All day event happening today (its start time is past today's midnight
// offset.
untilString = getString(R.string.today);
} else {
untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime());
}
} else if (minutesUntilNextAppointment < 60) {
untilString = getResources().getQuantityString(
R.plurals.calendar_template_mins,
minutesUntilNextAppointment,
minutesUntilNextAppointment);
} else {
int hours = Math.round(minutesUntilNextAppointment / 60f);
if (hours < 24) {
untilString = getResources().getQuantityString(
R.plurals.calendar_template_hours, hours, hours);
} else {
untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime());
}
}
String eventTitle = cursor.getString(EventsQuery.TITLE);
String eventLocation = cursor.getString(EventsQuery.EVENT_LOCATION);
long eventId = cursor.getLong(EventsQuery.EVENT_ID);
long eventBegin = cursor.getLong(EventsQuery.BEGIN);
long eventEnd = cursor.getLong(EventsQuery.END);
cursor.close();
String expandedTime = null;
StringBuilder expandedTimeFormat = new StringBuilder();
if (allDay) {
if (timeUntilNextAppointent <= 0) {
// All day event happening today (its start time is past today's midnight
// offset.
expandedTimeFormat.setLength(0);
expandedTime = getString(R.string.today);
} else {
expandedTimeFormat.append("EEEE, MMM dd");
}
} else {
if (nextTimestamp - currentTimestamp > 24 * HOUR_MILLIS) {
expandedTimeFormat.append("EEEE, ");
}
if (DateFormat.is24HourFormat(this)) {
expandedTimeFormat.append("HH:mm");
} else {
expandedTimeFormat.append("h:mm a");
}
}
if (expandedTimeFormat.length() > 0) {
expandedTime = new SimpleDateFormat(expandedTimeFormat.toString())
.format(nextEventCalendar.getTime());
}
String expandedBody = expandedTime;
if (!TextUtils.isEmpty(eventLocation)) {
expandedBody = getString(R.string.calendar_with_location_template,
expandedTime, eventLocation);
}
publishUpdate(new ExtensionData()
.visible(allDay || (timeUntilNextAppointent >= 0
&& timeUntilNextAppointent <= mLookAheadHours * HOUR_MILLIS))
.icon(R.drawable.ic_extension_calendar)
.status(untilString)
.expandedTitle(eventTitle)
.expandedBody(expandedBody)
.clickIntent(new Intent(Intent.ACTION_VIEW)
.setData(Uri.withAppendedPath(CalendarContract.Events.CONTENT_URI,
Long.toString(eventId)))
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, eventBegin)
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, eventEnd)));
}
private static long getCurrentTimestamp() {
return Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis();
}
private Cursor openEventsCursor(boolean showAllDay) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean customVisibility = sp.getBoolean(PREF_CUSTOM_VISIBILITY, false);
// Filter out all day events unless the user expressly requested to show all day events
String allDaySelection = SQL_TAUTOLOGY;
if (!showAllDay) {
allDaySelection = CalendarContract.Instances.ALL_DAY + "=0";
}
// Only filter on visible calendars if there isn't custom visibility
String visibleCalendarsSelection = SQL_TAUTOLOGY;
if (!customVisibility) {
allDaySelection = CalendarContract.Instances.VISIBLE + "!=0";
}
String calendarSelection = generateCalendarSelection();
Set<String> calendarSet = getSelectedCalendars();
String[] calendarsSelectionArgs = calendarSet.toArray(new String[calendarSet.size()]);
long now = getCurrentTimestamp();
try {
return getContentResolver().query(
CalendarContract.Instances.CONTENT_URI.buildUpon()
.appendPath(Long.toString(now))
.appendPath(Long.toString(now + mLookAheadHours * HOUR_MILLIS))
.build(),
EventsQuery.PROJECTION,
allDaySelection + " AND "
+ CalendarContract.Instances.SELF_ATTENDEE_STATUS + "!="
+ CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED + " AND "
+ "IFNULL(" + CalendarContract.Instances.STATUS + ",0)!="
+ CalendarContract.Instances.STATUS_CANCELED + " AND "
+ visibleCalendarsSelection + " AND ("
+ calendarSelection + ")",
calendarsSelectionArgs,
CalendarContract.Instances.BEGIN);
} catch (SecurityException e) {
LOGE(TAG, "Error querying calendar API", e);
return null;
}
}
private String generateCalendarSelection() {
Set<String> calendars = getSelectedCalendars();
int count = calendars.size();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
if (i != 0) {
sb.append(" OR ");
}
sb.append(CalendarContract.Events.CALENDAR_ID);
sb.append(" = ?");
}
if (sb.length() == 0) {
sb.append(SQL_TAUTOLOGY); // constant expression to prevent returning null
}
return sb.toString();
}
private interface EventsQuery {
String[] PROJECTION = {
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END,
CalendarContract.Instances.TITLE,
CalendarContract.Instances.EVENT_LOCATION,
CalendarContract.Instances.ALL_DAY,
};
int EVENT_ID = 0;
int BEGIN = 1;
int END = 2;
int TITLE = 3;
int EVENT_LOCATION = 4;
int ALL_DAY = 5;
}
private interface CalendarsQuery {
String[] PROJECTION = {
CalendarContract.Calendars._ID,
CalendarContract.Calendars.VISIBLE,
};
int ID = 0;
int VISIBLE = 1;
}
}
| true | true | protected void onUpdateData(int reason) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean showAllDay = sp.getBoolean(PREF_SHOW_ALL_DAY, false);
try {
mLookAheadHours = Integer.parseInt(sp.getString(PREF_LOOK_AHEAD_HOURS,
Integer.toString(mLookAheadHours)));
} catch (NumberFormatException e) {
mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS;
}
Cursor cursor = openEventsCursor(showAllDay);
if (cursor == null) {
LOGE(TAG, "Null events cursor, short-circuiting.");
return;
}
long currentTimestamp = getCurrentTimestamp();
long nextTimestamp = 0;
long timeUntilNextAppointent = 0;
boolean allDay = false;
int allDayPosition = -1;
while (cursor.moveToNext()) {
nextTimestamp = cursor.getLong(EventsQuery.BEGIN);
allDay = cursor.getInt(EventsQuery.ALL_DAY) != 0;
if (showAllDay && allDay && allDayPosition < 0) {
// Store the position of this all day event. If no regular events are found
// and the user wanted to see all day events, then show this all day event.
allDayPosition = cursor.getPosition();
}
timeUntilNextAppointent = nextTimestamp - currentTimestamp;
if (timeUntilNextAppointent >= 0) {
break;
}
// Skip over events that are not ALL_DAY but span multiple days, including
// the next 6 hours. An example is an event that starts at 4pm yesterday
// day and ends 6pm tomorrow.
LOGD(TAG, "Skipping over event with start timestamp " + nextTimestamp + ". "
+ "Current timestamp " + currentTimestamp);
}
if (cursor.isAfterLast()) {
if (allDayPosition >= 0) {
// But wait, we have an all day event! Use it.
cursor.moveToPosition(allDayPosition);
allDay = true;
// For all day events (if the user wants to see them), convert the begin
// timestamp, which is the midnight UTC time, to local time. That is,
// nextTimestamp will now be midnight in local time since that's a more
// relevant representation of that day to the user.
nextTimestamp = cursor.getLong(EventsQuery.BEGIN)
- TimeZone.getDefault().getOffset(nextTimestamp);
timeUntilNextAppointent = nextTimestamp - currentTimestamp;
LOGD(TAG, "No regular events found but an all day event was found; showing it.");
} else {
LOGD(TAG, "No upcoming appointments found.");
cursor.close();
publishUpdate(new ExtensionData());
return;
}
}
Calendar nextEventCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
nextEventCalendar.setTimeInMillis(nextTimestamp);
int minutesUntilNextAppointment = (int) (timeUntilNextAppointent / MINUTE_MILLIS);
String untilString;
if (allDay) {
if (timeUntilNextAppointent <= 0) {
// All day event happening today (its start time is past today's midnight
// offset.
untilString = getString(R.string.today);
} else {
untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime());
}
} else if (minutesUntilNextAppointment < 60) {
untilString = getResources().getQuantityString(
R.plurals.calendar_template_mins,
minutesUntilNextAppointment,
minutesUntilNextAppointment);
} else {
int hours = Math.round(minutesUntilNextAppointment / 60f);
if (hours < 24) {
untilString = getResources().getQuantityString(
R.plurals.calendar_template_hours, hours, hours);
} else {
untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime());
}
}
String eventTitle = cursor.getString(EventsQuery.TITLE);
String eventLocation = cursor.getString(EventsQuery.EVENT_LOCATION);
long eventId = cursor.getLong(EventsQuery.EVENT_ID);
long eventBegin = cursor.getLong(EventsQuery.BEGIN);
long eventEnd = cursor.getLong(EventsQuery.END);
cursor.close();
String expandedTime = null;
StringBuilder expandedTimeFormat = new StringBuilder();
if (allDay) {
if (timeUntilNextAppointent <= 0) {
// All day event happening today (its start time is past today's midnight
// offset.
expandedTimeFormat.setLength(0);
expandedTime = getString(R.string.today);
} else {
expandedTimeFormat.append("EEEE, MMM dd");
}
} else {
if (nextTimestamp - currentTimestamp > 24 * HOUR_MILLIS) {
expandedTimeFormat.append("EEEE, ");
}
if (DateFormat.is24HourFormat(this)) {
expandedTimeFormat.append("HH:mm");
} else {
expandedTimeFormat.append("h:mm a");
}
}
if (expandedTimeFormat.length() > 0) {
expandedTime = new SimpleDateFormat(expandedTimeFormat.toString())
.format(nextEventCalendar.getTime());
}
String expandedBody = expandedTime;
if (!TextUtils.isEmpty(eventLocation)) {
expandedBody = getString(R.string.calendar_with_location_template,
expandedTime, eventLocation);
}
publishUpdate(new ExtensionData()
.visible(allDay || (timeUntilNextAppointent >= 0
&& timeUntilNextAppointent <= mLookAheadHours * HOUR_MILLIS))
.icon(R.drawable.ic_extension_calendar)
.status(untilString)
.expandedTitle(eventTitle)
.expandedBody(expandedBody)
.clickIntent(new Intent(Intent.ACTION_VIEW)
.setData(Uri.withAppendedPath(CalendarContract.Events.CONTENT_URI,
Long.toString(eventId)))
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, eventBegin)
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, eventEnd)));
}
| protected void onUpdateData(int reason) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean showAllDay = sp.getBoolean(PREF_SHOW_ALL_DAY, false);
try {
mLookAheadHours = Integer.parseInt(sp.getString(PREF_LOOK_AHEAD_HOURS,
Integer.toString(mLookAheadHours)));
} catch (NumberFormatException e) {
mLookAheadHours = DEFAULT_LOOK_AHEAD_HOURS;
}
Cursor cursor = openEventsCursor(showAllDay);
if (cursor == null) {
LOGE(TAG, "Null events cursor, short-circuiting.");
return;
}
long currentTimestamp = getCurrentTimestamp();
long nextTimestamp = 0;
long timeUntilNextAppointent = 0;
boolean allDay = false;
int allDayPosition = -1;
while (cursor.moveToNext()) {
nextTimestamp = cursor.getLong(EventsQuery.BEGIN);
allDay = cursor.getInt(EventsQuery.ALL_DAY) != 0;
if (allDay) {
if (showAllDay && allDayPosition < 0) {
// Store the position of this all day event. If no regular events are found
// and the user wanted to see all day events, then show this all day event.
allDayPosition = cursor.getPosition();
}
continue;
}
timeUntilNextAppointent = nextTimestamp - currentTimestamp;
if (timeUntilNextAppointent >= 0) {
break;
}
// Skip over events that are not ALL_DAY but span multiple days, including
// the next 6 hours. An example is an event that starts at 4pm yesterday
// day and ends 6pm tomorrow.
LOGD(TAG, "Skipping over event with start timestamp " + nextTimestamp + ". "
+ "Current timestamp " + currentTimestamp);
}
if (cursor.isAfterLast()) {
if (allDayPosition >= 0) {
// But wait, we have an all day event! Use it.
cursor.moveToPosition(allDayPosition);
allDay = true;
// For all day events (if the user wants to see them), convert the begin
// timestamp, which is the midnight UTC time, to local time. That is,
// nextTimestamp will now be midnight in local time since that's a more
// relevant representation of that day to the user.
nextTimestamp = cursor.getLong(EventsQuery.BEGIN)
- TimeZone.getDefault().getOffset(nextTimestamp);
timeUntilNextAppointent = nextTimestamp - currentTimestamp;
LOGD(TAG, "No regular events found but an all day event was found; showing it.");
} else {
LOGD(TAG, "No upcoming appointments found.");
cursor.close();
publishUpdate(new ExtensionData());
return;
}
}
Calendar nextEventCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
nextEventCalendar.setTimeInMillis(nextTimestamp);
int minutesUntilNextAppointment = (int) (timeUntilNextAppointent / MINUTE_MILLIS);
String untilString;
if (allDay) {
if (timeUntilNextAppointent <= 0) {
// All day event happening today (its start time is past today's midnight
// offset.
untilString = getString(R.string.today);
} else {
untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime());
}
} else if (minutesUntilNextAppointment < 60) {
untilString = getResources().getQuantityString(
R.plurals.calendar_template_mins,
minutesUntilNextAppointment,
minutesUntilNextAppointment);
} else {
int hours = Math.round(minutesUntilNextAppointment / 60f);
if (hours < 24) {
untilString = getResources().getQuantityString(
R.plurals.calendar_template_hours, hours, hours);
} else {
untilString = new SimpleDateFormat("E").format(nextEventCalendar.getTime());
}
}
String eventTitle = cursor.getString(EventsQuery.TITLE);
String eventLocation = cursor.getString(EventsQuery.EVENT_LOCATION);
long eventId = cursor.getLong(EventsQuery.EVENT_ID);
long eventBegin = cursor.getLong(EventsQuery.BEGIN);
long eventEnd = cursor.getLong(EventsQuery.END);
cursor.close();
String expandedTime = null;
StringBuilder expandedTimeFormat = new StringBuilder();
if (allDay) {
if (timeUntilNextAppointent <= 0) {
// All day event happening today (its start time is past today's midnight
// offset.
expandedTimeFormat.setLength(0);
expandedTime = getString(R.string.today);
} else {
expandedTimeFormat.append("EEEE, MMM dd");
}
} else {
if (nextTimestamp - currentTimestamp > 24 * HOUR_MILLIS) {
expandedTimeFormat.append("EEEE, ");
}
if (DateFormat.is24HourFormat(this)) {
expandedTimeFormat.append("HH:mm");
} else {
expandedTimeFormat.append("h:mm a");
}
}
if (expandedTimeFormat.length() > 0) {
expandedTime = new SimpleDateFormat(expandedTimeFormat.toString())
.format(nextEventCalendar.getTime());
}
String expandedBody = expandedTime;
if (!TextUtils.isEmpty(eventLocation)) {
expandedBody = getString(R.string.calendar_with_location_template,
expandedTime, eventLocation);
}
publishUpdate(new ExtensionData()
.visible(allDay || (timeUntilNextAppointent >= 0
&& timeUntilNextAppointent <= mLookAheadHours * HOUR_MILLIS))
.icon(R.drawable.ic_extension_calendar)
.status(untilString)
.expandedTitle(eventTitle)
.expandedBody(expandedBody)
.clickIntent(new Intent(Intent.ACTION_VIEW)
.setData(Uri.withAppendedPath(CalendarContract.Events.CONTENT_URI,
Long.toString(eventId)))
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, eventBegin)
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, eventEnd)));
}
|
diff --git a/app/controllers/WeatherController.java b/app/controllers/WeatherController.java
index a7e699d..265b5e1 100644
--- a/app/controllers/WeatherController.java
+++ b/app/controllers/WeatherController.java
@@ -1,235 +1,236 @@
/**
*
*/
package controllers;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import play.Logger;
import play.libs.Json;
import play.libs.F.Callback;
import play.libs.F.Callback0;
import play.mvc.Controller;
import play.mvc.WebSocket;
import play.mvc.WebSocket.Out;
/**
* @author romanelm
*/
public class WeatherController extends Controller {
/**
* Hashmap that given an ID of a Display, returns
* an list of 2 websockets: one for the small view
* and one for the big one.
* Position 0: small
* Position 1: big
*/
public static HashMap<String, Sockets> sockets = new HashMap<String, Sockets>();
/**
* Hashmap that given an ID of a Display, returns
* how many request the application can still recieve
*/
public static HashMap<String,Integer> status = new HashMap<String, Integer>();
public static HashMap<String,ArrayList<String>> activeCities = new HashMap<String, ArrayList<String>>();
/**
* The number of maximum request must be multiplied
* by two because we have a SMALL and a BIG view
*/
public static Integer MAX_REQ = 3*2;
public static WebSocket<JsonNode> webSocket() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out) {
in.onMessage(new Callback<JsonNode>() {
public void invoke(JsonNode event) {
Logger.info("MESSAGE FOR WEATHER WS");
Logger.info(event.toString());
String messageKind = event.get("kind").asText();
String displayID = event.get("displayID").asText();
if(!sockets.containsKey(displayID)){
sockets.put(displayID, new Sockets(null, null));
status.put(displayID, MAX_REQ);
+ activeCities.put(displayID, new ArrayList<String>());
Logger.info("DisplayID " + displayID + " was added to the system.");
}
if(messageKind.equals("appReady")){
// Can be either small or big
String size = event.get("size").asText();
if(size.equals("small")){
sockets.get(displayID).small = out;
} else if(size.equals("big")) {
sockets.get(displayID).big = out;
}
Logger.info(
"\n ******* MESSAGE RECIEVED *******" +
"\n The "+ size + " view of \n" +
"weather app is now available on displayID: " + displayID +
"\n*********************************"
);
// TODO: look for defaults values
} else if(messageKind.equals("mobileRequest")){
Integer freeSpaces = status.get(displayID);
String location = event.get("preference").asText();
Logger.info("W FOR " + location);
if(freeSpaces>0 && !activeCities.get(displayID).contains(location)){
JsonNode forecast = findForecast(location);
ObjectNode result = Json.newObject();
result.put("original_request",location);
result.put("forecast",forecast);
Logger.info(result.toString());
Sockets displaySockets = sockets.get(displayID);
// Send the forecast to the two views of the application
displaySockets.small.write(result);
displaySockets.big.write(result);
Logger.info("SENT");
Logger.info(forecast.toString());
status.put(displayID, freeSpaces-2);
activeCities.get(displayID).add(location);
} else {
Logger.info("FULL OR DUPLICATE");
}
} else if(messageKind.equals("free")){
Integer freeSpaces = status.get(displayID);
activeCities.get(displayID).remove(event.get("location").asText());
status.put(displayID, freeSpaces+1);
} else {
Logger.info("WTF: " + event.toString());
}
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
Logger.info("\n ******* MESSAGE RECIEVED *******" +
"\n A weather tile on " + "FILL" +
"\n is now disconnected." +
"\n*********************************"
);
}
});
}
};
}
public static JsonNode findForecast(String location){
// Language
String lang = "it";
// Maximum number of city to find (by proximity)
String max = "5";
// AppID for http://developer.yahoo.com/
String appid = "QBulK6jV34F7ZJY2YP0RMtFHI7YJBE9pouDkGGBpKf9eSGzJBvDZq91dUzo60tp3XuFsjv7PvQHU";
try {
// Request for YAHOO WEATHER API
String request =
"http://where.yahooapis.com/v1/places.q('"+ URLEncoder.encode(location,"UTF-8") + "');" +
"start=0;count="+ max +"&" +
"lang=" + lang + "?" +
"format=json&" +
"appid=" + appid;
// Extract from the generated JSON the WOEID (if any) of the location
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory();
JsonParser jp = factory.createJsonParser(readUrl(request));
JsonNode actualObj = mapper.readTree(jp);
// Check if we found any city
if(actualObj.get("places").get("total").asInt() == 0){
Logger.info("City not found");
// TODO: city not found!
} else {
// Extract the woeid from the JSON
String woeid = actualObj.get("places").get("place").get(0).get("woeid").asText();
String unit = "c";
String request2 = "http://weather.yahooapis.com/forecastjson?w="
+ woeid + "&"
+ "u=" + unit
+ "&d=4";
jp = factory.createJsonParser(readUrl(request2));
return mapper.readTree(jp);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[2048];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
public static class Sockets {
public WebSocket.Out<JsonNode> small;
public WebSocket.Out<JsonNode> big;
public Sockets(Out<JsonNode> small, Out<JsonNode> big) {
this.small = small;
this.big = big;
}
}
}
| true | true | public static WebSocket<JsonNode> webSocket() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out) {
in.onMessage(new Callback<JsonNode>() {
public void invoke(JsonNode event) {
Logger.info("MESSAGE FOR WEATHER WS");
Logger.info(event.toString());
String messageKind = event.get("kind").asText();
String displayID = event.get("displayID").asText();
if(!sockets.containsKey(displayID)){
sockets.put(displayID, new Sockets(null, null));
status.put(displayID, MAX_REQ);
Logger.info("DisplayID " + displayID + " was added to the system.");
}
if(messageKind.equals("appReady")){
// Can be either small or big
String size = event.get("size").asText();
if(size.equals("small")){
sockets.get(displayID).small = out;
} else if(size.equals("big")) {
sockets.get(displayID).big = out;
}
Logger.info(
"\n ******* MESSAGE RECIEVED *******" +
"\n The "+ size + " view of \n" +
"weather app is now available on displayID: " + displayID +
"\n*********************************"
);
// TODO: look for defaults values
} else if(messageKind.equals("mobileRequest")){
Integer freeSpaces = status.get(displayID);
String location = event.get("preference").asText();
Logger.info("W FOR " + location);
if(freeSpaces>0 && !activeCities.get(displayID).contains(location)){
JsonNode forecast = findForecast(location);
ObjectNode result = Json.newObject();
result.put("original_request",location);
result.put("forecast",forecast);
Logger.info(result.toString());
Sockets displaySockets = sockets.get(displayID);
// Send the forecast to the two views of the application
displaySockets.small.write(result);
displaySockets.big.write(result);
Logger.info("SENT");
Logger.info(forecast.toString());
status.put(displayID, freeSpaces-2);
activeCities.get(displayID).add(location);
} else {
Logger.info("FULL OR DUPLICATE");
}
} else if(messageKind.equals("free")){
Integer freeSpaces = status.get(displayID);
activeCities.get(displayID).remove(event.get("location").asText());
status.put(displayID, freeSpaces+1);
} else {
Logger.info("WTF: " + event.toString());
}
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
Logger.info("\n ******* MESSAGE RECIEVED *******" +
"\n A weather tile on " + "FILL" +
"\n is now disconnected." +
"\n*********************************"
);
}
});
}
};
}
| public static WebSocket<JsonNode> webSocket() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out) {
in.onMessage(new Callback<JsonNode>() {
public void invoke(JsonNode event) {
Logger.info("MESSAGE FOR WEATHER WS");
Logger.info(event.toString());
String messageKind = event.get("kind").asText();
String displayID = event.get("displayID").asText();
if(!sockets.containsKey(displayID)){
sockets.put(displayID, new Sockets(null, null));
status.put(displayID, MAX_REQ);
activeCities.put(displayID, new ArrayList<String>());
Logger.info("DisplayID " + displayID + " was added to the system.");
}
if(messageKind.equals("appReady")){
// Can be either small or big
String size = event.get("size").asText();
if(size.equals("small")){
sockets.get(displayID).small = out;
} else if(size.equals("big")) {
sockets.get(displayID).big = out;
}
Logger.info(
"\n ******* MESSAGE RECIEVED *******" +
"\n The "+ size + " view of \n" +
"weather app is now available on displayID: " + displayID +
"\n*********************************"
);
// TODO: look for defaults values
} else if(messageKind.equals("mobileRequest")){
Integer freeSpaces = status.get(displayID);
String location = event.get("preference").asText();
Logger.info("W FOR " + location);
if(freeSpaces>0 && !activeCities.get(displayID).contains(location)){
JsonNode forecast = findForecast(location);
ObjectNode result = Json.newObject();
result.put("original_request",location);
result.put("forecast",forecast);
Logger.info(result.toString());
Sockets displaySockets = sockets.get(displayID);
// Send the forecast to the two views of the application
displaySockets.small.write(result);
displaySockets.big.write(result);
Logger.info("SENT");
Logger.info(forecast.toString());
status.put(displayID, freeSpaces-2);
activeCities.get(displayID).add(location);
} else {
Logger.info("FULL OR DUPLICATE");
}
} else if(messageKind.equals("free")){
Integer freeSpaces = status.get(displayID);
activeCities.get(displayID).remove(event.get("location").asText());
status.put(displayID, freeSpaces+1);
} else {
Logger.info("WTF: " + event.toString());
}
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
Logger.info("\n ******* MESSAGE RECIEVED *******" +
"\n A weather tile on " + "FILL" +
"\n is now disconnected." +
"\n*********************************"
);
}
});
}
};
}
|
diff --git a/src/com/iBank/Commands/BankRootCommand.java b/src/com/iBank/Commands/BankRootCommand.java
index 0b917de..e901542 100644
--- a/src/com/iBank/Commands/BankRootCommand.java
+++ b/src/com/iBank/Commands/BankRootCommand.java
@@ -1,51 +1,51 @@
package com.iBank.Commands;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.iBank.iBank;
import com.iBank.system.Bank;
import com.iBank.system.Configuration;
import com.iBank.system.Handler;
import com.iBank.system.MessageManager;
import com.iBank.utils.StringUtils;
/**
* /bank - Shows the accounts of the executor
* @author steffengy
* Can't be run from console
*/
public class BankRootCommand extends Handler{
/**
* Shows if in bank region if enabled
* Shows a list of all accounts the player owns and has access to
*/
@Override
public void handle(CommandSender sender, String[] arguments) {
if(!(sender instanceof Player)) {
MessageManager.send(sender, "&r&"+Configuration.StringEntry.ErrorNoPlayer.toString());
return;
}
if(iBank.GetRegionAt(((Player)sender).getLocation()) == "") {
MessageManager.send(sender, "&r&"+Configuration.StringEntry.ErrorNotRegion.toString());
return;
}
// Show list of accounts
List<String> owner = Bank.getAccountsByOwner(((Player)sender).getName());
List<String> user = Bank.getAccountsByUser(((Player)sender).getName());
- if(owner == null && user == null) {
+ if(owner.size() == 0 && user.size() == 0) {
MessageManager.send(sender, "&r&" + Configuration.StringEntry.GeneralNoAccounts.toString());
return;
}
MessageManager.send(sender, "&blue&Owner &y&User");
owner = owner == null ? new ArrayList<String>() : owner;
user = user == null ? new ArrayList<String>() : user;
MessageManager.send(sender, "&blue&"+StringUtils.join(owner, "&w&,&blue&"), "");
MessageManager.send(sender, "&y&"+StringUtils.join(user, "&w&,&y&"), "");
}
}
| true | true | public void handle(CommandSender sender, String[] arguments) {
if(!(sender instanceof Player)) {
MessageManager.send(sender, "&r&"+Configuration.StringEntry.ErrorNoPlayer.toString());
return;
}
if(iBank.GetRegionAt(((Player)sender).getLocation()) == "") {
MessageManager.send(sender, "&r&"+Configuration.StringEntry.ErrorNotRegion.toString());
return;
}
// Show list of accounts
List<String> owner = Bank.getAccountsByOwner(((Player)sender).getName());
List<String> user = Bank.getAccountsByUser(((Player)sender).getName());
if(owner == null && user == null) {
MessageManager.send(sender, "&r&" + Configuration.StringEntry.GeneralNoAccounts.toString());
return;
}
MessageManager.send(sender, "&blue&Owner &y&User");
owner = owner == null ? new ArrayList<String>() : owner;
user = user == null ? new ArrayList<String>() : user;
MessageManager.send(sender, "&blue&"+StringUtils.join(owner, "&w&,&blue&"), "");
MessageManager.send(sender, "&y&"+StringUtils.join(user, "&w&,&y&"), "");
}
| public void handle(CommandSender sender, String[] arguments) {
if(!(sender instanceof Player)) {
MessageManager.send(sender, "&r&"+Configuration.StringEntry.ErrorNoPlayer.toString());
return;
}
if(iBank.GetRegionAt(((Player)sender).getLocation()) == "") {
MessageManager.send(sender, "&r&"+Configuration.StringEntry.ErrorNotRegion.toString());
return;
}
// Show list of accounts
List<String> owner = Bank.getAccountsByOwner(((Player)sender).getName());
List<String> user = Bank.getAccountsByUser(((Player)sender).getName());
if(owner.size() == 0 && user.size() == 0) {
MessageManager.send(sender, "&r&" + Configuration.StringEntry.GeneralNoAccounts.toString());
return;
}
MessageManager.send(sender, "&blue&Owner &y&User");
owner = owner == null ? new ArrayList<String>() : owner;
user = user == null ? new ArrayList<String>() : user;
MessageManager.send(sender, "&blue&"+StringUtils.join(owner, "&w&,&blue&"), "");
MessageManager.send(sender, "&y&"+StringUtils.join(user, "&w&,&y&"), "");
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index 6b4d3f4a..d9017dab 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1244 +1,1239 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.os.Process;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = false;
static final String TAG = "Launcher.Model";
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private Loader mLoader = new Loader();
private boolean mBeforeFirstLoad = true;
private WeakReference<Callbacks> mCallbacks;
private AllAppsList mAllAppsList = new AllAppsList();
public interface Callbacks {
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindPackageAdded(ArrayList<ApplicationInfo> apps);
public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps);
public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps);
}
LauncherModel(LauncherApplication app) {
mApp = app;
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
int cellX, int cellY) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
- boolean update = false;
- boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
- update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
- remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
- update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
- if (update || modified != null) {
+ if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
- if (remove || removed != null) {
+ if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
if (itemType
!= LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info.title = c.getString(titleIndex);
}
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
if (DEBUG_LOADERS) {
Log.d(TAG, "cached app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
// We're adding this now, so clear out this so we don't re-send them.
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
| false | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
if (itemType
!= LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info.title = c.getString(titleIndex);
}
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
if (DEBUG_LOADERS) {
Log.d(TAG, "cached app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
// We're adding this now, so clear out this so we don't re-send them.
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with workspace");
}
LoaderThread.this.notify();
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "waiting to be done with workspace");
}
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "done waiting to be done with workspace");
}
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
if (DEBUG_LOADERS) {
Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
+ " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
mFolders.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
if (itemType
!= LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info.title = c.getString(titleIndex);
}
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
if (DEBUG_LOADERS) {
Log.d(TAG, "cached app icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
// We're adding this now, so clear out this so we don't re-send them.
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLoaderThread.mContext=" + mContext);
Log.d(TAG, "mLoader.mLoaderThread.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoader.mLoaderThread.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoader.mLoaderThread.mStopped=" + mStopped);
Log.d(TAG, "mLoader.mLoaderThread.mWorkspaceDoneBinding=" + mWorkspaceDoneBinding);
}
}
public void dumpState() {
Log.d(TAG, "mLoader.mLastWorkspaceSeq=" + mLoader.mLastWorkspaceSeq);
Log.d(TAG, "mLoader.mWorkspaceSeq=" + mLoader.mWorkspaceSeq);
Log.d(TAG, "mLoader.mLastAllAppsSeq=" + mLoader.mLastAllAppsSeq);
Log.d(TAG, "mLoader.mAllAppsSeq=" + mLoader.mAllAppsSeq);
Log.d(TAG, "mLoader.mItems size=" + mLoader.mItems.size());
if (mLoaderThread != null) {
mLoaderThread.dumpState();
} else {
Log.d(TAG, "mLoader.mLoaderThread=null");
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public void dumpState() {
Log.d(TAG, "mBeforeFirstLoad=" + mBeforeFirstLoad);
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
mLoader.dumpState();
}
}
|
diff --git a/deegree-datastores/deegree-featurestore/deegree-featurestore-sql/src/test/java/org/deegree/feature/persistence/sql/TOPPStatesTest.java b/deegree-datastores/deegree-featurestore/deegree-featurestore-sql/src/test/java/org/deegree/feature/persistence/sql/TOPPStatesTest.java
index 94e297b6ec..7f3e6b3761 100644
--- a/deegree-datastores/deegree-featurestore/deegree-featurestore-sql/src/test/java/org/deegree/feature/persistence/sql/TOPPStatesTest.java
+++ b/deegree-datastores/deegree-featurestore/deegree-featurestore-sql/src/test/java/org/deegree/feature/persistence/sql/TOPPStatesTest.java
@@ -1,315 +1,314 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2011 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.feature.persistence.sql;
import static junit.framework.Assert.assertEquals;
import static org.deegree.commons.tom.primitive.BaseType.DOUBLE;
import static org.deegree.commons.tom.primitive.BaseType.STRING;
import static org.deegree.feature.types.property.GeometryPropertyType.CoordinateDimension.DIM_2;
import static org.deegree.gml.GMLVersion.GML_2;
import static org.deegree.protocol.wfs.transaction.IDGenMode.GENERATE_NEW;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.namespace.QName;
import junit.framework.Assert;
import org.deegree.commons.config.DeegreeWorkspace;
import org.deegree.commons.config.ResourceInitException;
import org.deegree.commons.jdbc.ConnectionManager;
import org.deegree.commons.tom.primitive.PrimitiveValue;
import org.deegree.commons.utils.test.TestDBProperties;
import org.deegree.cs.coordinatesystems.ICRS;
import org.deegree.cs.exceptions.UnknownCRSException;
import org.deegree.cs.persistence.CRSManager;
import org.deegree.feature.Feature;
import org.deegree.feature.FeatureCollection;
import org.deegree.feature.persistence.FeatureStoreException;
import org.deegree.feature.persistence.FeatureStoreManager;
import org.deegree.feature.persistence.FeatureStoreTransaction;
import org.deegree.feature.persistence.query.Query;
import org.deegree.feature.persistence.sql.ddl.DDLCreator;
import org.deegree.feature.persistence.sql.mapper.AppSchemaMapper;
import org.deegree.feature.types.ApplicationSchema;
import org.deegree.feature.types.FeatureType;
import org.deegree.filter.Filter;
import org.deegree.filter.FilterEvaluationException;
import org.deegree.filter.OperatorFilter;
import org.deegree.filter.comparison.PropertyIsEqualTo;
import org.deegree.filter.expression.Literal;
import org.deegree.filter.expression.PropertyName;
import org.deegree.filter.spatial.BBOX;
import org.deegree.geometry.GeometryFactory;
import org.deegree.gml.GMLInputFactory;
import org.deegree.gml.GMLStreamReader;
import org.deegree.gml.feature.schema.ApplicationSchemaXSDDecoder;
import org.deegree.sqldialect.SQLDialect;
import org.deegree.sqldialect.SQLDialectManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Basic {@link SQLFeatureStore} test for table-based configurations.
*
* @author <a href="mailto:[email protected]">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
@RunWith(value = Parameterized.class)
public class TOPPStatesTest {
private static Logger LOG = LoggerFactory.getLogger( TOPPStatesTest.class );
private static final QName TOPP_STATES = QName.valueOf( "{http://www.openplans.org/topp}states" );
private static final QName STATE_NAME = QName.valueOf( "{http://www.openplans.org/topp}STATE_NAME" );
private static final QName STATE_FIPS = QName.valueOf( "{http://www.openplans.org/topp}STATE_FIPS" );
private static final QName SAMP_POP = QName.valueOf( "{http://www.openplans.org/topp}SAMP_POP" );
private final TestDBProperties settings;
private DeegreeWorkspace ws;
private SQLDialect dialect;
private SQLFeatureStore fs;
public TOPPStatesTest( TestDBProperties settings ) {
this.settings = settings;
}
@Before
public void setUp()
throws Throwable {
initWorkspace();
createDB();
createTables();
SQLFeatureStoreProvider provider = new SQLFeatureStoreProvider();
provider.init( ws );
fs = provider.create( TOPPStatesTest.class.getResource( "topp_states/topp_states.xml" ) );
fs.init( ws );
populateStore();
}
private void populateStore()
throws Throwable {
URL datasetURL = TOPPStatesTest.class.getResource( "topp_states/data/states.xml" );
GMLStreamReader gmlReader = GMLInputFactory.createGMLStreamReader( GML_2, datasetURL );
gmlReader.setApplicationSchema( fs.getSchema() );
FeatureCollection fc = gmlReader.readFeatureCollection();
Assert.assertEquals( 49, fc.size() );
gmlReader.close();
FeatureStoreTransaction ta = fs.acquireTransaction();
try {
List<String> fids = ta.performInsert( fc, GENERATE_NEW );
for ( String string : fids ) {
System.out.println( string );
}
// TODO
Assert.assertEquals( 98, fids.size() );
ta.commit();
} catch ( Throwable t ) {
ta.rollback();
throw t;
}
}
private void initWorkspace()
throws ResourceInitException {
// TODO
ws = DeegreeWorkspace.getInstance( "deegree-featurestore-sql-tests" );
ws.initManagers();
ws.getSubsystemManager( ConnectionManager.class ).startup( ws );
ws.getSubsystemManager( SQLDialectManager.class ).startup( ws );
ws.getSubsystemManager( FeatureStoreManager.class ).startup( ws );
ConnectionManager.addConnection( "admin", settings.getAdminUrl(), settings.getAdminUser(),
settings.getAdminPass(), 1, 10 );
ConnectionManager.addConnection( "deegree-test", settings.getUrl(), settings.getUser(), settings.getPass(), 1,
10 );
dialect = ws.getSubsystemManager( SQLDialectManager.class ).create( "admin" );
}
private void createDB()
throws SQLException {
Connection adminConn = ConnectionManager.getConnection( "admin" );
try {
dialect.createDB( adminConn, settings.getDbName() );
} finally {
adminConn.close();
}
}
private void createTables()
throws Exception {
// read application schema
URL schemaUrl = TOPPStatesTest.class.getResource( "topp_states/schema/states.xsd" );
ApplicationSchemaXSDDecoder decoder = new ApplicationSchemaXSDDecoder( null, null, schemaUrl.toString() );
ApplicationSchema appSchema = decoder.extractFeatureTypeSchema();
// map application schema
ICRS crs = CRSManager.getCRSRef( "EPSG:4326" );
GeometryStorageParams storageParams = new GeometryStorageParams( crs, dialect.getUndefinedSrid(), DIM_2 );
AppSchemaMapper mapper = new AppSchemaMapper( appSchema, false, true, storageParams,
dialect.getMaxTableNameLength(), false, false );
MappedApplicationSchema mappedSchema = mapper.getMappedSchema();
// create tables
- String[] ddl = DDLCreator.newInstance( mappedSchema, fs.getDialect() ).getDDL();
+ String[] ddl = DDLCreator.newInstance( mappedSchema, dialect ).getDDL();
Connection conn = ConnectionManager.getConnection( "deegree-test" );
Statement stmt = null;
try {
stmt = conn.createStatement();
for ( String sql : ddl ) {
- System.out.println( sql );
stmt.execute( sql );
}
} finally {
stmt.close();
conn.close();
}
}
@After
public void tearDown()
throws Exception {
Connection adminConn = ConnectionManager.getConnection( "admin" );
ConnectionManager.destroy( "deegree-test" );
try {
dialect.dropDB( adminConn, settings.getDbName() );
} finally {
adminConn.close();
}
ws.destroyAll();
fs.destroy();
}
@Test
public void testSchema() {
Assert.assertEquals( 1, fs.getSchema().getFeatureTypes().length );
FeatureType ft = fs.getSchema().getFeatureTypes()[0];
Assert.assertEquals( TOPP_STATES, ft.getName() );
Assert.assertEquals( 23, ft.getPropertyDeclarations().size() );
}
@Test
public void queryByStateName()
throws FeatureStoreException, FilterEvaluationException {
PropertyName propName = new PropertyName( STATE_NAME );
Literal literal = new Literal( "Illinois" );
PropertyIsEqualTo oper = new PropertyIsEqualTo( propName, literal, false );
Filter filter = new OperatorFilter( oper );
Query query = new Query( TOPP_STATES, filter, -1, -1, -1 );
FeatureCollection fc = fs.query( query ).toCollection();
Assert.assertEquals( 1, fc.size() );
Feature f = fc.iterator().next();
Assert.assertEquals( 23, ( f.getProperties().length ) );
assertEquals( "Illinois", getPropertyValue( f, STATE_NAME ).getAsText() );
assertEquals( STRING, getPropertyValue( f, STATE_NAME ).getType().getBaseType() );
assertEquals( "17", getPropertyValue( f, STATE_FIPS ).getAsText() );
assertEquals( STRING, getPropertyValue( f, STATE_FIPS ).getType().getBaseType() );
assertEquals( 1747776.0, ( (Double) getPropertyValue( f, SAMP_POP ).getValue() ), 0.001 );
assertEquals( DOUBLE, getPropertyValue( f, SAMP_POP ).getType().getBaseType() );
}
@Test
public void queryByBBOX()
throws FeatureStoreException, FilterEvaluationException, UnknownCRSException {
BBOX oper = new BBOX( new GeometryFactory().createEnvelope( -75.102613, 40.212597, -72.361859, 41.512517,
CRSManager.lookup( "EPSG:4326" ) ) );
Filter filter = new OperatorFilter( oper );
Query query = new Query( TOPP_STATES, filter, -1, -1, -1 );
FeatureCollection fc = fs.query( query ).toCollection();
Assert.assertEquals( 4, fc.size() );
Set<String> stateNames = new HashSet<String>();
for ( Feature f : fc ) {
stateNames.add( getPropertyValue( f, STATE_NAME ).getAsText() );
}
Assert.assertTrue( stateNames.contains( "New York" ) );
Assert.assertTrue( stateNames.contains( "Pennsylvania" ) );
Assert.assertTrue( stateNames.contains( "Connecticut" ) );
Assert.assertTrue( stateNames.contains( "New Jersey" ) );
}
private PrimitiveValue getPropertyValue( Feature f, QName propName ) {
return (PrimitiveValue) f.getProperty( propName ).getValue();
}
@Parameters
public static Collection<TestDBProperties[]> data()
throws IllegalArgumentException, IOException {
List<TestDBProperties[]> settings = new ArrayList<TestDBProperties[]>();
try {
for ( TestDBProperties testDBSettings : TestDBProperties.getAll() ) {
settings.add( new TestDBProperties[] { testDBSettings } );
}
} catch ( Throwable t ) {
LOG.error( "Access to test databases not configured properly: " + t.getMessage() );
}
return settings;
}
}
| false | true | private void createTables()
throws Exception {
// read application schema
URL schemaUrl = TOPPStatesTest.class.getResource( "topp_states/schema/states.xsd" );
ApplicationSchemaXSDDecoder decoder = new ApplicationSchemaXSDDecoder( null, null, schemaUrl.toString() );
ApplicationSchema appSchema = decoder.extractFeatureTypeSchema();
// map application schema
ICRS crs = CRSManager.getCRSRef( "EPSG:4326" );
GeometryStorageParams storageParams = new GeometryStorageParams( crs, dialect.getUndefinedSrid(), DIM_2 );
AppSchemaMapper mapper = new AppSchemaMapper( appSchema, false, true, storageParams,
dialect.getMaxTableNameLength(), false, false );
MappedApplicationSchema mappedSchema = mapper.getMappedSchema();
// create tables
String[] ddl = DDLCreator.newInstance( mappedSchema, fs.getDialect() ).getDDL();
Connection conn = ConnectionManager.getConnection( "deegree-test" );
Statement stmt = null;
try {
stmt = conn.createStatement();
for ( String sql : ddl ) {
System.out.println( sql );
stmt.execute( sql );
}
} finally {
stmt.close();
conn.close();
}
}
| private void createTables()
throws Exception {
// read application schema
URL schemaUrl = TOPPStatesTest.class.getResource( "topp_states/schema/states.xsd" );
ApplicationSchemaXSDDecoder decoder = new ApplicationSchemaXSDDecoder( null, null, schemaUrl.toString() );
ApplicationSchema appSchema = decoder.extractFeatureTypeSchema();
// map application schema
ICRS crs = CRSManager.getCRSRef( "EPSG:4326" );
GeometryStorageParams storageParams = new GeometryStorageParams( crs, dialect.getUndefinedSrid(), DIM_2 );
AppSchemaMapper mapper = new AppSchemaMapper( appSchema, false, true, storageParams,
dialect.getMaxTableNameLength(), false, false );
MappedApplicationSchema mappedSchema = mapper.getMappedSchema();
// create tables
String[] ddl = DDLCreator.newInstance( mappedSchema, dialect ).getDDL();
Connection conn = ConnectionManager.getConnection( "deegree-test" );
Statement stmt = null;
try {
stmt = conn.createStatement();
for ( String sql : ddl ) {
stmt.execute( sql );
}
} finally {
stmt.close();
conn.close();
}
}
|
diff --git a/core/src/com/google/zxing/pdf417/decoder/PDF417CodewordDecoder.java b/core/src/com/google/zxing/pdf417/decoder/PDF417CodewordDecoder.java
index 478f0e23..017f3f39 100644
--- a/core/src/com/google/zxing/pdf417/decoder/PDF417CodewordDecoder.java
+++ b/core/src/com/google/zxing/pdf417/decoder/PDF417CodewordDecoder.java
@@ -1,113 +1,117 @@
/*
* Copyright 2013 ZXing 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 com.google.zxing.pdf417.decoder;
import com.google.zxing.pdf417.PDF417Common;
/**
* @author Guenther Grau
* @author creatale GmbH ([email protected])
*/
final class PDF417CodewordDecoder {
private static final float[][] RATIOS_TABLE =
new float[PDF417Common.SYMBOL_TABLE.length][PDF417Common.BARS_IN_MODULE];
static {
// Pre-computes the symbol ratio table.
for (int i = 0; i < PDF417Common.SYMBOL_TABLE.length; i++) {
int currentSymbol = PDF417Common.SYMBOL_TABLE[i];
int currentBit = currentSymbol & 0x1;
for (int j = 0; j < PDF417Common.BARS_IN_MODULE; j++) {
float size = 0.0f;
while ((currentSymbol & 0x1) == currentBit) {
size += 1.0f;
currentSymbol >>= 1;
}
currentBit = currentSymbol & 0x1;
RATIOS_TABLE[i][PDF417Common.BARS_IN_MODULE - j - 1] = size / PDF417Common.MODULES_IN_CODEWORD;
}
}
}
private PDF417CodewordDecoder() {
}
static int getDecodedValue(int[] moduleBitCount) {
int decodedValue = getDecodedCodewordValue(sampleBitCounts(moduleBitCount));
if (decodedValue != -1) {
return decodedValue;
}
return getClosestDecodedValue(moduleBitCount);
}
private static int[] sampleBitCounts(int[] moduleBitCount) {
float bitCountSum = PDF417Common.getBitCountSum(moduleBitCount);
int[] result = new int[PDF417Common.BARS_IN_MODULE];
int bitCountIndex = 0;
int sumPreviousBits = 0;
for (int i = 0; i < PDF417Common.MODULES_IN_CODEWORD; i++) {
float sampleIndex =
bitCountSum / (2 * PDF417Common.MODULES_IN_CODEWORD) +
(i * bitCountSum) / PDF417Common.MODULES_IN_CODEWORD;
if (sumPreviousBits + moduleBitCount[bitCountIndex] <= sampleIndex) {
sumPreviousBits += moduleBitCount[bitCountIndex];
bitCountIndex++;
}
result[bitCountIndex]++;
}
return result;
}
private static int getDecodedCodewordValue(int[] moduleBitCount) {
int decodedValue = getBitValue(moduleBitCount);
return PDF417Common.getCodeword(decodedValue) == -1 ? -1 : decodedValue;
}
private static int getBitValue(int[] moduleBitCount) {
long result = 0;
for (int i = 0; i < moduleBitCount.length; i++) {
for (int bit = 0; bit < moduleBitCount[i]; bit++) {
result = (result << 1) | (i % 2 == 0 ? 1 : 0);
}
}
return (int) result;
}
private static int getClosestDecodedValue(int[] moduleBitCount) {
int bitCountSum = PDF417Common.getBitCountSum(moduleBitCount);
float[] bitCountRatios = new float[PDF417Common.BARS_IN_MODULE];
for (int i = 0; i < bitCountRatios.length; i++) {
bitCountRatios[i] = moduleBitCount[i] / (float) bitCountSum;
}
float bestMatchError = Float.MAX_VALUE;
int bestMatch = -1;
for (int j = 0; j < RATIOS_TABLE.length; j++) {
float error = 0.0f;
+ float[] ratioTableRow = RATIOS_TABLE[j];
for (int k = 0; k < PDF417Common.BARS_IN_MODULE; k++) {
- float diff = RATIOS_TABLE[j][k] - bitCountRatios[k];
+ float diff = ratioTableRow[k] - bitCountRatios[k];
error += diff * diff;
+ if (error >= bestMatchError) {
+ break;
+ }
}
if (error < bestMatchError) {
bestMatchError = error;
bestMatch = PDF417Common.SYMBOL_TABLE[j];
}
}
return bestMatch;
}
}
| false | true | private static int getClosestDecodedValue(int[] moduleBitCount) {
int bitCountSum = PDF417Common.getBitCountSum(moduleBitCount);
float[] bitCountRatios = new float[PDF417Common.BARS_IN_MODULE];
for (int i = 0; i < bitCountRatios.length; i++) {
bitCountRatios[i] = moduleBitCount[i] / (float) bitCountSum;
}
float bestMatchError = Float.MAX_VALUE;
int bestMatch = -1;
for (int j = 0; j < RATIOS_TABLE.length; j++) {
float error = 0.0f;
for (int k = 0; k < PDF417Common.BARS_IN_MODULE; k++) {
float diff = RATIOS_TABLE[j][k] - bitCountRatios[k];
error += diff * diff;
}
if (error < bestMatchError) {
bestMatchError = error;
bestMatch = PDF417Common.SYMBOL_TABLE[j];
}
}
return bestMatch;
}
| private static int getClosestDecodedValue(int[] moduleBitCount) {
int bitCountSum = PDF417Common.getBitCountSum(moduleBitCount);
float[] bitCountRatios = new float[PDF417Common.BARS_IN_MODULE];
for (int i = 0; i < bitCountRatios.length; i++) {
bitCountRatios[i] = moduleBitCount[i] / (float) bitCountSum;
}
float bestMatchError = Float.MAX_VALUE;
int bestMatch = -1;
for (int j = 0; j < RATIOS_TABLE.length; j++) {
float error = 0.0f;
float[] ratioTableRow = RATIOS_TABLE[j];
for (int k = 0; k < PDF417Common.BARS_IN_MODULE; k++) {
float diff = ratioTableRow[k] - bitCountRatios[k];
error += diff * diff;
if (error >= bestMatchError) {
break;
}
}
if (error < bestMatchError) {
bestMatchError = error;
bestMatch = PDF417Common.SYMBOL_TABLE[j];
}
}
return bestMatch;
}
|
diff --git a/components/bio-formats/src/loci/formats/in/MetamorphReader.java b/components/bio-formats/src/loci/formats/in/MetamorphReader.java
index d1c89f47a..dc4929ba3 100644
--- a/components/bio-formats/src/loci/formats/in/MetamorphReader.java
+++ b/components/bio-formats/src/loci/formats/in/MetamorphReader.java
@@ -1,1610 +1,1612 @@
//
// MetamorphReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormatSymbols;
import java.util.Arrays;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.xml.XMLTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import ome.xml.model.primitives.PositiveFloat;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.PhotoInterp;
import loci.formats.tiff.TiffIFDEntry;
import loci.formats.tiff.TiffParser;
import loci.formats.tiff.TiffRational;
import ome.xml.model.primitives.PositiveInteger;
/**
* Reader is the file format reader for Metamorph STK files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/MetamorphReader.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/MetamorphReader.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert melissa at glencoesoftware.com
* @author Curtis Rueden ctrueden at wisc.edu
* @author Sebastien Huart Sebastien dot Huart at curie.fr
*/
public class MetamorphReader extends BaseTiffReader {
// -- Constants --
/** Logger for this class. */
private static final Logger LOGGER =
LoggerFactory.getLogger(MetamorphReader.class);
public static final String SHORT_DATE_FORMAT = "yyyyMMdd HH:mm:ss";
public static final String MEDIUM_DATE_FORMAT = "yyyyMMdd HH:mm:ss.SSS";
public static final String LONG_DATE_FORMAT = "dd/MM/yyyy HH:mm:ss:SSS";
public static final String[] ND_SUFFIX = {"nd"};
public static final String[] STK_SUFFIX = {"stk", "tif", "tiff"};
// IFD tag numbers of important fields
private static final int METAMORPH_ID = 33628;
private static final int UIC1TAG = METAMORPH_ID;
private static final int UIC2TAG = 33629;
private static final int UIC3TAG = 33630;
private static final int UIC4TAG = 33631;
// -- Fields --
/** The TIFF's name */
private String imageName;
/** The TIFF's creation date */
private String imageCreationDate;
/** The TIFF's emWavelength */
private long[] emWavelength;
private double[] wave;
private String binning;
private double zoom, stepSize;
private Double exposureTime;
private Vector<String> waveNames;
private Vector<String> stageNames;
private long[] internalStamps;
private double[] zDistances, stageX, stageY;
private double zStart;
private Double sizeX = null, sizeY = null;
private double tempZ;
private boolean validZ;
private int mmPlanes; //number of metamorph planes
private MetamorphReader[][] stkReaders;
/** List of STK files in the dataset. */
private String[][] stks;
private String ndFilename;
private boolean canLookForND = true;
private boolean[] firstSeriesChannels;
// -- Constructor --
/** Constructs a new Metamorph reader. */
public MetamorphReader() {
super("Metamorph STK", new String[] {"stk", "nd", "tif", "tiff"});
domains = new String[] {FormatTools.LM_DOMAIN};
hasCompanionFiles = true;
suffixSufficient = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
Location location = new Location(name);
if (!location.exists()) {
return false;
}
if (checkSuffix(name, "nd")) return true;
if (open) {
location = location.getAbsoluteFile();
Location parent = location.getParentFile();
String[] list = parent.list(true);
for (String f : list) {
if (checkSuffix(f, "nd") && checkSuffix(name, suffixes)) {
return true;
}
}
}
return super.isThisType(name, open);
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
String software = ifd.getIFDTextValue(IFD.SOFTWARE);
boolean validSoftware = software != null &&
software.trim().toLowerCase().startsWith("metamorph");
return validSoftware || (ifd.containsKey(UIC1TAG) &&
ifd.containsKey(UIC3TAG) && ifd.containsKey(UIC4TAG));
}
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
return !checkSuffix(id, ND_SUFFIX);
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
if (checkSuffix(id, ND_SUFFIX)) return FormatTools.MUST_GROUP;
Location l = new Location(id).getAbsoluteFile();
String[] files = l.getParentFile().list();
for (String file : files) {
if (checkSuffix(file, ND_SUFFIX) &&
l.getName().startsWith(file.substring(0, file.lastIndexOf("."))))
{
return FormatTools.MUST_GROUP;
}
}
return FormatTools.CANNOT_GROUP;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
if (!noPixels && stks == null) return new String[] {currentId};
else if (stks == null) return new String[0];
Vector<String> v = new Vector<String>();
if (ndFilename != null) v.add(ndFilename);
if (!noPixels) {
for (String stk : stks[getSeries()]) {
if (stk != null && new Location(stk).exists()) {
v.add(stk);
}
}
}
return v.toArray(new String[v.size()]);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
if (stks == null) {
return super.openBytes(no, buf, x, y, w, h);
}
int[] coords = FormatTools.getZCTCoords(this, no % getSizeZ());
int ndx = no / getSizeZ();
if (stks[series].length == 1) ndx = 0;
String file = stks[series][ndx];
if (file == null) return buf;
// the original file is a .nd file, so we need to construct a new reader
// for the constituent STK files
stkReaders[series][ndx].setId(file);
int plane = stks[series].length == 1 ? no : coords[0];
stkReaders[series][ndx].openBytes(plane, buf, x, y, w, h);
stkReaders[series][ndx].close();
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (stkReaders != null) {
for (MetamorphReader[] s : stkReaders) {
if (s != null) {
for (MetamorphReader reader : s) {
if (reader != null) reader.close(fileOnly);
}
}
}
}
if (!fileOnly) {
imageName = imageCreationDate = null;
emWavelength = null;
stks = null;
mmPlanes = 0;
ndFilename = null;
wave = null;
binning = null;
zoom = stepSize = 0;
exposureTime = null;
waveNames = stageNames = null;
internalStamps = null;
zDistances = stageX = stageY = null;
firstSeriesChannels = null;
sizeX = sizeY = null;
tempZ = 0d;
validZ = false;
stkReaders = null;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (checkSuffix(id, ND_SUFFIX)) {
LOGGER.info("Initializing " + id);
// find an associated STK file
String stkFile = id.substring(0, id.lastIndexOf("."));
if (stkFile.indexOf(File.separator) != -1) {
stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1);
}
Location parent = new Location(id).getAbsoluteFile().getParentFile();
LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath());
String[] dirList = parent.list(true);
for (String f : dirList) {
int underscore = f.indexOf("_");
if (underscore < 0) underscore = f.indexOf(".");
if (underscore < 0) underscore = f.length();
String prefix = f.substring(0, underscore);
if ((f.equals(stkFile) || stkFile.startsWith(prefix)) &&
checkSuffix(f, STK_SUFFIX))
{
stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath();
break;
}
}
if (!checkSuffix(stkFile, STK_SUFFIX)) {
throw new FormatException("STK file not found in " +
parent.getAbsolutePath() + ".");
}
super.initFile(stkFile);
}
else super.initFile(id);
Location ndfile = null;
if (checkSuffix(id, ND_SUFFIX)) ndfile = new Location(id);
else if (canLookForND) {
// an STK file was passed to initFile
// let's check the parent directory for an .nd file
Location stk = new Location(id).getAbsoluteFile();
String stkName = stk.getName();
String stkPrefix = stkName;
if (stkPrefix.indexOf("_") >= 0) {
stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf("_") + 1);
}
Location parent = stk.getParentFile();
String[] list = parent.list(true);
for (String f : list) {
if (checkSuffix(f, ND_SUFFIX)) {
String prefix = f.substring(0, f.lastIndexOf("."));
if (prefix.indexOf("_") >= 0) {
prefix = prefix.substring(0, prefix.indexOf("_") + 1);
}
if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) {
ndfile = new Location(parent, f).getAbsoluteFile();
if (prefix.equals(stkPrefix)) {
break;
}
}
}
}
}
String creationTime = null;
if (ndfile != null && ndfile.exists() &&
(fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles()))
{
// parse key/value pairs from .nd file
int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT();
int nstages = 0;
String z = null, c = null, t = null;
Vector<Boolean> hasZ = new Vector<Boolean>();
waveNames = new Vector<String>();
stageNames = new Vector<String>();
boolean useWaveNames = true;
ndFilename = ndfile.getAbsolutePath();
String[] lines = DataTools.readFile(ndFilename).split("\n");
for (String line : lines) {
int comma = line.indexOf(",");
if (comma <= 0) continue;
String key = line.substring(1, comma - 1).trim();
String value = line.substring(comma + 1).trim();
addGlobalMeta(key, value);
if (key.equals("NZSteps")) z = value;
else if (key.equals("NWavelengths")) c = value;
else if (key.equals("NTimePoints")) t = value;
else if (key.startsWith("WaveDoZ")) {
hasZ.add(new Boolean(value.toLowerCase()));
}
else if (key.startsWith("WaveName")) {
waveNames.add(value.substring(1, value.length() - 1));
}
else if (key.startsWith("Stage")) {
stageNames.add(value);
}
else if (key.startsWith("StartTime")) {
creationTime = value;
}
else if (key.equals("ZStepSize")) {
char separator = new DecimalFormatSymbols().getDecimalSeparator();
value = value.replace('.', separator);
value = value.replace(',', separator);
stepSize = Double.parseDouble(value);
}
else if (key.equals("NStagePositions")) {
nstages = Integer.parseInt(value);
}
else if (key.equals("WaveInFileName")) {
useWaveNames = Boolean.parseBoolean(value);
}
}
// figure out how many files we need
if (z != null) zc = Integer.parseInt(z);
if (c != null) cc = Integer.parseInt(c);
if (t != null) tc = Integer.parseInt(t);
if (cc == 0) cc = 1;
int numFiles = cc * tc;
if (nstages > 0) numFiles *= nstages;
// determine series count
int seriesCount = nstages == 0 ? 1 : nstages;
firstSeriesChannels = new boolean[cc];
Arrays.fill(firstSeriesChannels, true);
boolean differentZs = false;
for (int i=0; i<cc; i++) {
boolean hasZ1 = i < hasZ.size() && hasZ.get(i).booleanValue();
boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) &&
hasZ.get(i - 1).booleanValue();
if (i > 0 && hasZ1 != hasZ2) {
if (!differentZs) seriesCount *= 2;
differentZs = true;
}
}
int channelsInFirstSeries = cc;
if (differentZs) {
channelsInFirstSeries = 0;
for (int i=0; i<cc; i++) {
if (hasZ.get(i).booleanValue()) channelsInFirstSeries++;
else firstSeriesChannels[i] = false;
}
}
stks = new String[seriesCount][];
if (seriesCount == 1) stks[0] = new String[numFiles];
else if (differentZs) {
int stages = nstages == 0 ? 1 : nstages;
for (int i=0; i<stages; i++) {
stks[i * 2] = new String[channelsInFirstSeries * tc];
stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc];
}
}
else {
for (int i=0; i<stks.length; i++) {
stks[i] = new String[numFiles / stks.length];
}
}
String prefix = ndfile.getPath();
prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1,
prefix.lastIndexOf("."));
// build list of STK files
int[] pt = new int[seriesCount];
for (int i=0; i<tc; i++) {
int ns = nstages == 0 ? 1 : nstages;
for (int s=0; s<ns; s++) {
for (int j=0; j<cc; j++) {
boolean validZ = j >= hasZ.size() || hasZ.get(j).booleanValue();
int seriesNdx = s * (seriesCount / ns);
- seriesNdx += (seriesCount == 1 || validZ) ? 0 : 1;
+ if (nstages == 0 && (!validZ || seriesCount > 1)) {
+ seriesNdx++;
+ }
stks[seriesNdx][pt[seriesNdx]] = prefix;
if (j < waveNames.size() && waveNames.get(j) != null) {
stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1);
if (useWaveNames) {
String waveName = waveNames.get(j);
// If there are underscores in the wavelength name, translate
// them to hyphens. (See #558)
waveName = waveName.replace('_', '-');
stks[seriesNdx][pt[seriesNdx]] += waveName;
}
}
if (nstages > 0) {
stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1);
}
if (tc > 1) {
stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK";
}
else stks[seriesNdx][pt[seriesNdx]] += ".STK";
pt[seriesNdx]++;
}
}
}
ndfile = ndfile.getAbsoluteFile();
// check that each STK file exists
for (int s=0; s<stks.length; s++) {
for (int f=0; f<stks[s].length; f++) {
Location l = new Location(ndfile.getParent(), stks[s][f]);
stks[s][f] = getRealSTKFile(l);
}
}
int q = 0;
int f = 0;
String file = stks[q][f];
while (file == null) {
if (f < stks[q].length - 1) f++;
else if (q < stks.length - 1) {
q++;
f = 0;
}
file = stks[q][f];
}
RandomAccessInputStream s = new RandomAccessInputStream(file);
TiffParser tp = new TiffParser(s);
IFD ifd = tp.getFirstIFD();
s.close();
core[0].sizeX = (int) ifd.getImageWidth();
core[0].sizeY = (int) ifd.getImageLength();
core[0].sizeZ = zc;
core[0].sizeC = cc;
core[0].sizeT = tc;
core[0].imageCount = zc * tc * cc;
core[0].dimensionOrder = "XYZCT";
if (stks != null && stks.length > 1) {
CoreMetadata[] newCore = new CoreMetadata[stks.length];
for (int i=0; i<stks.length; i++) {
newCore[i] = new CoreMetadata();
newCore[i].sizeX = getSizeX();
newCore[i].sizeY = getSizeY();
newCore[i].sizeZ = getSizeZ();
newCore[i].sizeC = getSizeC();
newCore[i].sizeT = getSizeT();
newCore[i].pixelType = getPixelType();
newCore[i].imageCount = getImageCount();
newCore[i].dimensionOrder = getDimensionOrder();
newCore[i].rgb = isRGB();
newCore[i].littleEndian = isLittleEndian();
newCore[i].interleaved = isInterleaved();
newCore[i].orderCertain = true;
}
if (stks.length > nstages) {
int ns = nstages == 0 ? 1 : nstages;
for (int j=0; j<ns; j++) {
newCore[j * 2].sizeC = stks[j * 2].length / getSizeT();
newCore[j * 2 + 1].sizeC =
stks[j * 2 + 1].length / newCore[j * 2 + 1].sizeT;
newCore[j * 2 + 1].sizeZ = 1;
newCore[j * 2].imageCount = newCore[j * 2].sizeC *
newCore[j * 2].sizeT * newCore[j * 2].sizeZ;
newCore[j * 2 + 1].imageCount =
newCore[j * 2 + 1].sizeC * newCore[j * 2 + 1].sizeT;
}
}
core = newCore;
}
}
if (stks == null) {
stkReaders = new MetamorphReader[1][1];
stkReaders[0][0] = new MetamorphReader();
stkReaders[0][0].setCanLookForND(false);
}
else {
stkReaders = new MetamorphReader[stks.length][];
for (int i=0; i<stks.length; i++) {
stkReaders[i] = new MetamorphReader[stks[i].length];
for (int j=0; j<stkReaders[i].length; j++) {
stkReaders[i][j] = new MetamorphReader();
stkReaders[i][j].setCanLookForND(false);
if (j > 0) {
stkReaders[i][j].setMetadataOptions(
new DefaultMetadataOptions(MetadataLevel.MINIMUM));
}
}
}
}
Vector<String> timestamps = null;
MetamorphHandler handler = null;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
handler = new MetamorphHandler(getSeriesMetadata());
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
store.setImageInstrumentRef(instrumentID, i);
if (i == 0) {
store.setDetectorID(detectorID, 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
}
String comment = getFirstComment(i);
if (comment != null && comment.startsWith("<MetaData>")) {
XMLTools.parseXML(comment, handler);
}
if (creationTime != null) {
String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT);
store.setImageAcquiredDate(date, 0);
}
else if (i > 0) MetadataTools.setDefaultCreationDate(store, id, i);
store.setImageName(makeImageName(i), i);
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
continue;
}
store.setImageDescription("", i);
store.setImagingEnvironmentTemperature(handler.getTemperature(), i);
if (sizeX == null) sizeX = handler.getPixelSizeX();
if (sizeY == null) sizeY = handler.getPixelSizeY();
if (sizeX > 0) {
store.setPixelsPhysicalSizeX(new PositiveFloat(sizeX), i);
}
if (sizeY > 0) {
store.setPixelsPhysicalSizeY(new PositiveFloat(sizeY), i);
}
if (zDistances != null) {
stepSize = zDistances[0];
}
if (stepSize > 0) {
store.setPixelsPhysicalSizeZ(new PositiveFloat(stepSize), i);
}
int waveIndex = 0;
for (int c=0; c<getEffectiveSizeC(); c++) {
if (firstSeriesChannels == null ||
(stageNames != null && stageNames.size() == getSeriesCount()))
{
waveIndex = c;
}
else if (firstSeriesChannels != null) {
int s = i % 2;
while (firstSeriesChannels[waveIndex] == (s == 1) &&
waveIndex < firstSeriesChannels.length)
{
waveIndex++;
}
}
if (waveNames != null && waveIndex < waveNames.size()) {
store.setChannelName(waveNames.get(waveIndex), i, c);
}
if (handler.getBinning() != null) binning = handler.getBinning();
if (binning != null) {
store.setDetectorSettingsBinning(getBinning(binning), i, c);
}
if (handler.getReadOutRate() != 0) {
store.setDetectorSettingsReadOutRate(handler.getReadOutRate(), i, c);
}
store.setDetectorSettingsID(detectorID, i, c);
if (wave != null && waveIndex < wave.length &&
(int) wave[waveIndex] >= 1)
{
store.setChannelLightSourceSettingsWavelength(
new PositiveInteger((int) wave[waveIndex]), i, c);
// link LightSource to Image
String lightSourceID = MetadataTools.createLSID("LightSource", i, c);
store.setLaserID(lightSourceID, i, c);
store.setChannelLightSourceSettingsID(lightSourceID, i, c);
store.setLaserType(getLaserType("Other"), i, c);
store.setLaserLaserMedium(getLaserMedium("Other"), i, c);
}
waveIndex++;
}
timestamps = handler.getTimestamps();
for (int t=0; t<timestamps.size(); t++) {
addSeriesMeta("timestamp " + t, DateTools.formatDate(timestamps.get(t),
MEDIUM_DATE_FORMAT));
}
long startDate = 0;
if (timestamps.size() > 0) {
startDate = DateTools.getTime(timestamps.get(0), MEDIUM_DATE_FORMAT);
}
Double positionX = new Double(handler.getStagePositionX());
Double positionY = new Double(handler.getStagePositionY());
Vector<Double> exposureTimes = handler.getExposures();
if (exposureTimes.size() == 0) {
for (int p=0; p<getImageCount(); p++) {
exposureTimes.add(exposureTime);
}
}
int lastFile = -1;
IFD lastIFD = null;
long[] lastOffsets = null;
double distance = zStart;
for (int p=0; p<getImageCount(); p++) {
int[] coords = getZCTCoords(p);
Double deltaT = new Double(0);
Double exposureTime = new Double(0);
Double xmlZPosition = null;
int fileIndex = getIndex(0, 0, coords[2]) / getSizeZ();
if (fileIndex >= 0) {
String file = stks == null ? currentId : stks[i][fileIndex];
if (file != null) {
RandomAccessInputStream stream = new RandomAccessInputStream(file);
TiffParser tp = new TiffParser(stream);
tp.checkHeader();
if (fileIndex != lastFile) {
lastFile = fileIndex;
lastOffsets = tp.getIFDOffsets();
}
lastIFD = tp.getIFD(lastOffsets[p % lastOffsets.length]);
stream.close();
comment = lastIFD.getComment();
if (comment != null) comment = comment.trim();
handler = new MetamorphHandler(getSeriesMetadata());
if (comment != null && comment.startsWith("<MetaData>")) {
XMLTools.parseXML(comment, handler);
}
timestamps = handler.getTimestamps();
exposureTimes = handler.getExposures();
Vector<Double> zPositions = handler.getZPositions();
if (zPositions != null && zPositions.size() > 0) {
xmlZPosition = zPositions.get(0);
}
}
}
int index = 0;
if (timestamps.size() > 0) {
if (coords[2] < timestamps.size()) index = coords[2];
String stamp = timestamps.get(index);
long ms = DateTools.getTime(stamp, MEDIUM_DATE_FORMAT);
deltaT = new Double((ms - startDate) / 1000.0);
}
else if (internalStamps != null && p < internalStamps.length) {
long delta = internalStamps[p] - internalStamps[0];
deltaT = new Double(delta / 1000.0);
if (coords[2] < exposureTimes.size()) index = coords[2];
}
if (index < exposureTimes.size()) {
exposureTime = exposureTimes.get(index);
}
store.setPlaneDeltaT(deltaT, i, p);
store.setPlaneExposureTime(exposureTime, i, p);
if (stageX != null && p < stageX.length) {
store.setPlanePositionX(stageX[p], i, p);
}
if (stageY != null && p < stageY.length) {
store.setPlanePositionY(stageY[p], i, p);
}
if (zDistances != null && p < zDistances.length) {
if (p > 0) {
if (zDistances[p] != 0d) distance += zDistances[p];
else distance += zDistances[0];
}
store.setPlanePositionZ(distance, i, p);
}
else if (xmlZPosition != null) {
store.setPlanePositionZ(xmlZPosition, i, p);
}
}
}
setSeries(0);
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
core[0].sizeZ = 1;
core[0].sizeT = 0;
int rgbChannels = getSizeC();
// Now that the base TIFF standard metadata has been parsed, we need to
// parse out the STK metadata from the UIC4TAG.
TiffIFDEntry uic1tagEntry = null;
TiffIFDEntry uic2tagEntry = null;
TiffIFDEntry uic4tagEntry = null;
try {
uic1tagEntry = tiffParser.getFirstIFDEntry(UIC1TAG);
uic2tagEntry = tiffParser.getFirstIFDEntry(UIC2TAG);
uic4tagEntry = tiffParser.getFirstIFDEntry(UIC4TAG);
}
catch (IllegalArgumentException exc) {
LOGGER.debug("Unknown tag", exc);
}
try {
if (uic4tagEntry != null) {
mmPlanes = uic4tagEntry.getValueCount();
}
if (uic2tagEntry != null) {
parseUIC2Tags(uic2tagEntry.getValueOffset());
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
if (uic4tagEntry != null) {
parseUIC4Tags(uic4tagEntry.getValueOffset());
}
if (uic1tagEntry != null) {
parseUIC1Tags(uic1tagEntry.getValueOffset(),
uic1tagEntry.getValueCount());
}
}
in.seek(uic4tagEntry.getValueOffset());
}
catch (NullPointerException exc) {
LOGGER.debug("", exc);
}
catch (IOException exc) {
LOGGER.debug("Failed to parse proprietary tags", exc);
}
try {
// copy ifds into a new array of Hashtables that will accommodate the
// additional image planes
IFD firstIFD = ifds.get(0);
long[] uic2 = firstIFD.getIFDLongArray(UIC2TAG);
if (uic2 == null) {
throw new FormatException("Invalid Metamorph file. Tag " + UIC2TAG +
" not found.");
}
core[0].imageCount = uic2.length;
Object entry = firstIFD.getIFDValue(UIC3TAG);
TiffRational[] uic3 = entry instanceof TiffRational[] ?
(TiffRational[]) entry : new TiffRational[] {(TiffRational) entry};
wave = new double[uic3.length];
Vector<Double> uniqueWavelengths = new Vector<Double>();
for (int i=0; i<uic3.length; i++) {
wave[i] = uic3[i].doubleValue();
addSeriesMeta("Wavelength [" + intFormatMax(i, mmPlanes) + "]",
wave[i]);
Double v = new Double(wave[i]);
if (!uniqueWavelengths.contains(v)) uniqueWavelengths.add(v);
}
if (getSizeC() == 1) {
core[0].sizeC = uniqueWavelengths.size();
}
IFDList tempIFDs = new IFDList();
long[] oldOffsets = firstIFD.getStripOffsets();
long[] stripByteCounts = firstIFD.getStripByteCounts();
int rowsPerStrip = (int) firstIFD.getRowsPerStrip()[0];
int stripsPerImage = getSizeY() / rowsPerStrip;
if (stripsPerImage * rowsPerStrip != getSizeY()) stripsPerImage++;
PhotoInterp check = firstIFD.getPhotometricInterpretation();
if (check == PhotoInterp.RGB_PALETTE) {
firstIFD.putIFDValue(IFD.PHOTOMETRIC_INTERPRETATION,
PhotoInterp.BLACK_IS_ZERO);
}
emWavelength = firstIFD.getIFDLongArray(UIC3TAG);
// for each image plane, construct an IFD hashtable
IFD temp;
for (int i=0; i<getImageCount(); i++) {
// copy data from the first IFD
temp = new IFD(firstIFD);
// now we need a StripOffsets entry - the original IFD doesn't have this
long[] newOffsets = new long[stripsPerImage];
if (stripsPerImage * (i + 1) <= oldOffsets.length) {
System.arraycopy(oldOffsets, stripsPerImage * i, newOffsets, 0,
stripsPerImage);
}
else {
System.arraycopy(oldOffsets, 0, newOffsets, 0, stripsPerImage);
long image = (stripByteCounts[0] / rowsPerStrip) * getSizeY();
for (int q=0; q<stripsPerImage; q++) {
newOffsets[q] += i * image;
}
}
temp.putIFDValue(IFD.STRIP_OFFSETS, newOffsets);
long[] newByteCounts = new long[stripsPerImage];
if (stripsPerImage * i < stripByteCounts.length) {
System.arraycopy(stripByteCounts, stripsPerImage * i, newByteCounts,
0, stripsPerImage);
}
else {
Arrays.fill(newByteCounts, stripByteCounts[0]);
}
temp.putIFDValue(IFD.STRIP_BYTE_COUNTS, newByteCounts);
tempIFDs.add(temp);
}
ifds = tempIFDs;
}
catch (IllegalArgumentException exc) {
LOGGER.debug("Unknown tag", exc);
}
catch (NullPointerException exc) {
LOGGER.debug("", exc);
}
catch (FormatException exc) {
LOGGER.debug("Failed to build list of IFDs", exc);
}
// parse (mangle) TIFF comment
String descr = ifds.get(0).getComment();
if (descr != null) {
String[] lines = descr.split("\n");
StringBuffer sb = new StringBuffer();
for (int i=0; i<lines.length; i++) {
String line = lines[i].trim();
int colon = line.indexOf(": ");
String descrValue = null;
if (colon < 0) {
// normal line (not a key/value pair)
if (line.length() > 0) {
// not a blank line
descrValue = line;
}
}
else {
if (i == 0) {
// first line could be mangled; make a reasonable guess
int dot = line.lastIndexOf(".", colon);
if (dot >= 0) {
descrValue = line.substring(0, dot + 1);
}
line = line.substring(dot + 1);
colon -= dot + 1;
}
// append value to description
if (descrValue != null) {
sb.append(descrValue);
if (!descrValue.endsWith(".")) sb.append(".");
sb.append(" ");
}
// add key/value pair embedded in comment as separate metadata
String key = line.substring(0, colon);
String value = line.substring(colon + 2);
addSeriesMeta(key, value);
if (key.equals("Exposure")) {
if (value.indexOf("=") != -1) {
value = value.substring(value.indexOf("=") + 1).trim();
}
if (value.indexOf(" ") != -1) {
value = value.substring(0, value.indexOf(" "));
}
try {
char separator = new DecimalFormatSymbols().getDecimalSeparator();
value = value.replace('.', separator);
value = value.replace(',', separator);
double exposure = Double.parseDouble(value);
exposureTime = new Double(exposure / 1000);
}
catch (NumberFormatException e) { }
}
else if (key.equals("Bit Depth")) {
if (value.indexOf("-") != -1) {
value = value.substring(0, value.indexOf("-"));
}
try {
core[0].bitsPerPixel = Integer.parseInt(value);
}
catch (NumberFormatException e) { }
}
}
}
// replace comment with trimmed version
descr = sb.toString().trim();
if (descr.equals("")) metadata.remove("Comment");
else addSeriesMeta("Comment", descr);
}
core[0].sizeT = getImageCount() / (getSizeZ() * (getSizeC() / rgbChannels));
if (getSizeT() * getSizeZ() * (getSizeC() / rgbChannels) !=
getImageCount())
{
core[0].sizeT = 1;
core[0].sizeZ = getImageCount() / (getSizeC() / rgbChannels);
}
// if '_t' is present in the file name, swap Z and T sizes
// this file was probably part of a larger dataset, but the .nd file is
// missing
String filename =
currentId.substring(currentId.lastIndexOf(File.separator) + 1);
if (filename.indexOf("_t") != -1 && getSizeT() > 1) {
int z = getSizeZ();
core[0].sizeZ = getSizeT();
core[0].sizeT = z;
}
if (getSizeZ() == 0) core[0].sizeZ = 1;
if (getSizeT() == 0) core[0].sizeT = 1;
if (getSizeZ() * getSizeT() * (isRGB() ? 1 : getSizeC()) != getImageCount())
{
core[0].sizeZ = getImageCount();
core[0].sizeT = 1;
if (!isRGB()) core[0].sizeC = 1;
}
}
// -- Helper methods --
/**
* Check that the given STK file exists. If it does, then return the
* absolute path. If it does not, then apply various formatting rules until
* an existing file is found.
*
* @return the absolute path of an STK file, or null if no STK file is found.
*/
private String getRealSTKFile(Location l) {
if (l.exists()) return l.getAbsolutePath();
String name = l.getName();
String parent = l.getParent();
if (name.indexOf("_") > 0) {
String prefix = name.substring(0, name.indexOf("_"));
String suffix = name.substring(name.indexOf("_"));
String basePrefix = new Location(currentId).getName();
int end = basePrefix.indexOf("_");
if (end < 0) end = basePrefix.indexOf(".");
basePrefix = basePrefix.substring(0, end);
if (!basePrefix.equals(prefix)) {
name = basePrefix + suffix;
Location p = new Location(parent, name);
if (p.exists()) return p.getAbsolutePath();
}
}
// '%' can be converted to '-'
if (name.indexOf("%") != -1) {
name = name.replaceAll("%", "-");
l = new Location(parent, name);
if (!l.exists()) {
// try replacing extension
name = name.substring(0, name.lastIndexOf(".")) + ".TIF";
l = new Location(parent, name);
if (!l.exists()) {
name = name.substring(0, name.lastIndexOf(".")) + ".tif";
l = new Location(parent, name);
return l.exists() ? l.getAbsolutePath() : null;
}
}
}
if (!l.exists()) {
// try replacing extension
name = name.substring(0, name.lastIndexOf(".")) + ".TIF";
l = new Location(parent, name);
if (!l.exists()) {
name = name.substring(0, name.lastIndexOf(".")) + ".tif";
l = new Location(parent, name);
if (!l.exists()) {
name = name.substring(0, name.lastIndexOf(".")) + ".stk";
l = new Location(parent, name);
return l.exists() ? l.getAbsolutePath() : null;
}
}
}
return l.getAbsolutePath();
}
/**
* Returns the TIFF comment from the first IFD of the first STK file in the
* given series.
*/
private String getFirstComment(int i) throws IOException {
if (stks != null && stks[i][0] != null) {
RandomAccessInputStream stream = new RandomAccessInputStream(stks[i][0]);
TiffParser tp = new TiffParser(stream);
String comment = tp.getComment();
stream.close();
return comment;
}
return ifds.get(0).getComment();
}
/** Create an appropriate name for the given series. */
private String makeImageName(int i) {
String name = "";
if (stageNames != null && stageNames.size() > 0) {
int stagePosition = i / (getSeriesCount() / stageNames.size());
name += "Stage " + stageNames.get(stagePosition) + "; ";
}
if (firstSeriesChannels != null) {
for (int c=0; c<firstSeriesChannels.length; c++) {
if (firstSeriesChannels[c] == ((i % 2) == 0) && c < waveNames.size()) {
name += waveNames.get(c) + "/";
}
}
if (name.length() > 0) {
name = name.substring(0, name.length() - 1);
}
}
return name;
}
/**
* Populates metadata fields with some contained in MetaMorph UIC2 Tag.
* (for each plane: 6 integers:
* zdistance numerator, zdistance denominator,
* creation date, creation time, modif date, modif time)
* @param uic2offset offset to UIC2 (33629) tag entries
*
* not a regular tiff tag (6*N entries, N being the tagCount)
* @throws IOException
*/
void parseUIC2Tags(long uic2offset) throws IOException {
long saveLoc = in.getFilePointer();
in.seek(uic2offset);
/*number of days since the 1st of January 4713 B.C*/
String cDate;
/*milliseconds since 0:00*/
String cTime;
/*z step, distance separating previous slice from current one*/
String iAsString;
zDistances = new double[mmPlanes];
internalStamps = new long[mmPlanes];
for (int i=0; i<mmPlanes; i++) {
iAsString = intFormatMax(i, mmPlanes);
if (in.getFilePointer() + 8 > in.length()) break;
zDistances[i] = readRational(in).doubleValue();
addSeriesMeta("zDistance[" + iAsString + "]", zDistances[i]);
if (zDistances[i] != 0.0) core[0].sizeZ++;
cDate = decodeDate(in.readInt());
cTime = decodeTime(in.readInt());
internalStamps[i] = DateTools.getTime(cDate + " " + cTime,
LONG_DATE_FORMAT);
addSeriesMeta("creationDate[" + iAsString + "]", cDate);
addSeriesMeta("creationTime[" + iAsString + "]", cTime);
// modification date and time are skipped as they all seem equal to 0...?
in.skip(8);
}
if (getSizeZ() == 0) core[0].sizeZ = 1;
in.seek(saveLoc);
}
/**
* UIC4 metadata parser
*
* UIC4 Table contains per-plane blocks of metadata
* stage X/Y positions,
* camera chip offsets,
* stage labels...
* @param long uic4offset: offset of UIC4 table (not tiff-compliant)
* @throws IOException
*/
private void parseUIC4Tags(long uic4offset) throws IOException {
long saveLoc = in.getFilePointer();
in.seek(uic4offset);
if (in.getFilePointer() + 2 >= in.length()) return;
tempZ = 0d;
validZ = false;
short id = in.readShort();
while (id != 0) {
switch (id) {
case 28:
readStagePositions();
break;
case 29:
readRationals(
new String[] {"cameraXChipOffset", "cameraYChipOffset"});
break;
case 37:
readStageLabels();
break;
case 40:
readRationals(new String[] {"UIC4 absoluteZ"});
break;
case 41:
readAbsoluteZValid();
break;
case 46:
in.skipBytes(mmPlanes * 8); // TODO
break;
default:
in.skipBytes(4);
}
id = in.readShort();
}
in.seek(saveLoc);
if (validZ) zStart = tempZ;
}
private void readStagePositions() throws IOException {
stageX = new double[mmPlanes];
stageY = new double[mmPlanes];
String pos;
for (int i=0; i<mmPlanes; i++) {
pos = intFormatMax(i, mmPlanes);
stageX[i] = readRational(in).doubleValue();
stageY[i] = readRational(in).doubleValue();
addSeriesMeta("stageX[" + pos + "]", stageX[i]);
addSeriesMeta("stageY[" + pos + "]", stageY[i]);
addGlobalMeta("X position for position #" + (getSeries() + 1), stageX[i]);
addGlobalMeta("Y position for position #" + (getSeries() + 1), stageY[i]);
}
}
private void readRationals(String[] labels) throws IOException {
String pos;
for (int i=0; i<mmPlanes; i++) {
pos = intFormatMax(i, mmPlanes);
for (int q=0; q<labels.length; q++) {
double v = readRational(in).doubleValue();
if (labels[q].endsWith("absoluteZ") && i == 0) {
tempZ = v;
}
addSeriesMeta(labels[q] + "[" + pos + "]", v);
}
}
}
void readStageLabels() throws IOException {
int strlen;
String iAsString;
for (int i=0; i<mmPlanes; i++) {
iAsString = intFormatMax(i, mmPlanes);
strlen = in.readInt();
addSeriesMeta("stageLabel[" + iAsString + "]", in.readString(strlen));
}
}
void readAbsoluteZValid() throws IOException {
for (int i=0; i<mmPlanes; i++) {
int valid = in.readInt();
addSeriesMeta("absoluteZValid[" + intFormatMax(i, mmPlanes) + "]", valid);
if (i == 0) {
validZ = valid == 1;
}
}
}
/**
* UIC1 entry parser
* @throws IOException
* @param long uic1offset : offset as found in the tiff tag 33628 (UIC1Tag)
* @param int uic1count : number of entries in UIC1 table (not tiff-compliant)
*/
private void parseUIC1Tags(long uic1offset, int uic1count) throws IOException
{
// Loop through and parse out each field. A field whose
// code is "0" represents the end of the fields so we'll stop
// when we reach that; much like a NULL terminated C string.
long saveLoc = in.getFilePointer();
in.seek(uic1offset);
int currentID;
long valOrOffset;
// variable declarations, because switch is dumb
int num, denom;
String thedate, thetime;
long lastOffset;
tempZ = 0d;
validZ = false;
for (int i=0; i<uic1count; i++) {
if (in.getFilePointer() >= in.length()) break;
currentID = in.readInt();
valOrOffset = in.readInt() & 0xffffffffL;
lastOffset = in.getFilePointer();
String key = getKey(currentID);
Object value = String.valueOf(valOrOffset);
switch (currentID) {
case 3:
value = valOrOffset != 0 ? "on" : "off";
break;
case 4:
case 5:
case 21:
case 22:
case 23:
case 24:
case 38:
case 39:
value = readRational(in, valOrOffset);
break;
case 6:
case 25:
in.seek(valOrOffset);
num = in.readInt();
if (num + in.getFilePointer() >= in.length()) {
num = (int) (in.length() - in.getFilePointer() - 1);
}
value = in.readString(num);
break;
case 7:
in.seek(valOrOffset);
num = in.readInt();
imageName = in.readString(num);
value = imageName;
break;
case 8:
if (valOrOffset == 1) value = "inside";
else if (valOrOffset == 2) value = "outside";
else value = "off";
break;
case 17: // oh how we hate you Julian format...
in.seek(valOrOffset);
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
imageCreationDate = thedate + " " + thetime;
value = imageCreationDate;
break;
case 16:
in.seek(valOrOffset);
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
value = thedate + " " + thetime;
break;
case 26:
in.seek(valOrOffset);
int standardLUT = in.readInt();
switch (standardLUT) {
case 0:
value = "monochrome";
break;
case 1:
value = "pseudocolor";
break;
case 2:
value = "Red";
break;
case 3:
value = "Green";
break;
case 4:
value = "Blue";
break;
case 5:
value = "user-defined";
break;
default:
value = "monochrome";
}
break;
case 34:
value = String.valueOf(in.readInt());
break;
case 46:
in.seek(valOrOffset);
int xBin = in.readInt();
int yBin = in.readInt();
binning = xBin + "x" + yBin;
value = binning;
break;
case 40:
if (valOrOffset != 0) {
in.seek(valOrOffset);
readRationals(new String[] {"UIC1 absoluteZ"});
}
break;
case 41:
if (valOrOffset != 0) {
in.seek(valOrOffset);
readAbsoluteZValid();
}
break;
case 49:
in.seek(valOrOffset);
readPlaneData();
break;
}
addSeriesMeta(key, value);
in.seek(lastOffset);
if ("Zoom".equals(key) && value != null) {
zoom = Double.parseDouble(value.toString());
}
if ("XCalibration".equals(key) && value != null) {
if (value instanceof TiffRational) {
sizeX = ((TiffRational) value).doubleValue();
}
else sizeX = new Double(value.toString());
}
if ("YCalibration".equals(key) && value != null) {
if (value instanceof TiffRational) {
sizeY = ((TiffRational) value).doubleValue();
}
else sizeY = new Double(value.toString());
}
}
in.seek(saveLoc);
if (validZ) zStart = tempZ;
}
// -- Utility methods --
/** Converts a Julian date value into a human-readable string. */
public static String decodeDate(int julian) {
long a, b, c, d, e, alpha, z;
short day, month, year;
// code reused from the Metamorph data specification
z = julian + 1;
if (z < 2299161L) a = z;
else {
alpha = (long) ((z - 1867216.25) / 36524.25);
a = z + 1 + alpha - alpha / 4;
}
b = (a > 1721423L ? a + 1524 : a + 1158);
c = (long) ((b - 122.1) / 365.25);
d = (long) (365.25 * c);
e = (long) ((b - d) / 30.6001);
day = (short) (b - d - (long) (30.6001 * e));
month = (short) ((e < 13.5) ? e - 1 : e - 13);
year = (short) ((month > 2.5) ? (c - 4716) : c - 4715);
return intFormat(day, 2) + "/" + intFormat(month, 2) + "/" + year;
}
/** Converts a time value in milliseconds into a human-readable string. */
public static String decodeTime(int millis) {
Calendar time = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
time.setTimeInMillis(millis);
String hours = intFormat(time.get(Calendar.HOUR_OF_DAY), 2);
String minutes = intFormat(time.get(Calendar.MINUTE), 2);
String seconds = intFormat(time.get(Calendar.SECOND), 2);
String ms = intFormat(time.get(Calendar.MILLISECOND), 3);
return hours + ":" + minutes + ":" + seconds + ":" + ms;
}
/** Formats an integer value with leading 0s if needed. */
public static String intFormat(int myint, int digits) {
return String.format("%0" + digits + "d", myint);
}
/**
* Formats an integer with leading 0 using maximum sequence number.
*
* @param myint integer to format
* @param maxint max of "myint"
* @return String
*/
public static String intFormatMax(int myint, int maxint) {
return intFormat(myint, String.valueOf(maxint).length());
}
private TiffRational readRational(RandomAccessInputStream s)
throws IOException
{
return readRational(s, s.getFilePointer());
}
private TiffRational readRational(RandomAccessInputStream s, long offset)
throws IOException
{
s.seek(offset);
int num = s.readInt();
int denom = s.readInt();
return new TiffRational(num, denom);
}
private void setCanLookForND(boolean v) {
FormatTools.assertId(currentId, false, 1);
canLookForND = v;
}
private void readPlaneData() throws IOException {
in.skipBytes(4);
int keyLength = in.read();
String key = in.readString(keyLength);
in.skipBytes(4);
int type = in.read();
int index = 0;
switch (type) {
case 1:
in.skipBytes(1);
while (getGlobalMeta("Channel #" + index + " " + key) != null) {
index++;
}
addGlobalMeta("Channel #" + index + " " + key, in.readDouble());
break;
case 2:
int valueLength = in.read();
String value = in.readString(valueLength);
if (valueLength == 0) {
in.skipBytes(4);
valueLength = in.read();
value = in.readString(valueLength);
}
while (getGlobalMeta("Channel #" + index + " " + key) != null) {
index++;
}
addGlobalMeta("Channel #" + index + " " + key, value);
if (key.equals("_IllumSetting_")) {
if (waveNames == null) waveNames = new Vector<String>();
waveNames.add(value);
}
break;
}
}
private String getKey(int id) {
switch (id) {
case 0: return "AutoScale";
case 1: return "MinScale";
case 2: return "MaxScale";
case 3: return "Spatial Calibration";
case 4: return "XCalibration";
case 5: return "YCalibration";
case 6: return "CalibrationUnits";
case 7: return "Name";
case 8: return "ThreshState";
case 9: return "ThreshStateRed";
// there is no 10
case 11: return "ThreshStateGreen";
case 12: return "ThreshStateBlue";
case 13: return "ThreshStateLo";
case 14: return "ThreshStateHi";
case 15: return "Zoom";
case 16: return "DateTime";
case 17: return "LastSavedTime";
case 18: return "currentBuffer";
case 19: return "grayFit";
case 20: return "grayPointCount";
case 21: return "grayX";
case 22: return "grayY";
case 23: return "grayMin";
case 24: return "grayMax";
case 25: return "grayUnitName";
case 26: return "StandardLUT";
case 27: return "Wavelength";
case 28: return "StagePosition";
case 29: return "CameraChipOffset";
case 30: return "OverlayMask";
case 31: return "OverlayCompress";
case 32: return "Overlay";
case 33: return "SpecialOverlayMask";
case 34: return "SpecialOverlayCompress";
case 35: return "SpecialOverlay";
case 36: return "ImageProperty";
case 38: return "AutoScaleLoInfo";
case 39: return "AutoScaleHiInfo";
case 40: return "AbsoluteZ";
case 41: return "AbsoluteZValid";
case 42: return "Gamma";
case 43: return "GammaRed";
case 44: return "GammaGreen";
case 45: return "GammaBlue";
case 46: return "CameraBin";
case 47: return "NewLUT";
case 48: return "ImagePropertyEx";
case 49: return "PlaneProperty";
case 50: return "UserLutTable";
case 51: return "RedAutoScaleInfo";
case 52: return "RedAutoScaleLoInfo";
case 53: return "RedAutoScaleHiInfo";
case 54: return "RedMinScaleInfo";
case 55: return "RedMaxScaleInfo";
case 56: return "GreenAutoScaleInfo";
case 57: return "GreenAutoScaleLoInfo";
case 58: return "GreenAutoScaleHiInfo";
case 59: return "GreenMinScaleInfo";
case 60: return "GreenMaxScaleInfo";
case 61: return "BlueAutoScaleInfo";
case 62: return "BlueAutoScaleLoInfo";
case 63: return "BlueAutoScaleHiInfo";
case 64: return "BlueMinScaleInfo";
case 65: return "BlueMaxScaleInfo";
case 66: return "OverlayPlaneColor";
}
return null;
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
if (checkSuffix(id, ND_SUFFIX)) {
LOGGER.info("Initializing " + id);
// find an associated STK file
String stkFile = id.substring(0, id.lastIndexOf("."));
if (stkFile.indexOf(File.separator) != -1) {
stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1);
}
Location parent = new Location(id).getAbsoluteFile().getParentFile();
LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath());
String[] dirList = parent.list(true);
for (String f : dirList) {
int underscore = f.indexOf("_");
if (underscore < 0) underscore = f.indexOf(".");
if (underscore < 0) underscore = f.length();
String prefix = f.substring(0, underscore);
if ((f.equals(stkFile) || stkFile.startsWith(prefix)) &&
checkSuffix(f, STK_SUFFIX))
{
stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath();
break;
}
}
if (!checkSuffix(stkFile, STK_SUFFIX)) {
throw new FormatException("STK file not found in " +
parent.getAbsolutePath() + ".");
}
super.initFile(stkFile);
}
else super.initFile(id);
Location ndfile = null;
if (checkSuffix(id, ND_SUFFIX)) ndfile = new Location(id);
else if (canLookForND) {
// an STK file was passed to initFile
// let's check the parent directory for an .nd file
Location stk = new Location(id).getAbsoluteFile();
String stkName = stk.getName();
String stkPrefix = stkName;
if (stkPrefix.indexOf("_") >= 0) {
stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf("_") + 1);
}
Location parent = stk.getParentFile();
String[] list = parent.list(true);
for (String f : list) {
if (checkSuffix(f, ND_SUFFIX)) {
String prefix = f.substring(0, f.lastIndexOf("."));
if (prefix.indexOf("_") >= 0) {
prefix = prefix.substring(0, prefix.indexOf("_") + 1);
}
if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) {
ndfile = new Location(parent, f).getAbsoluteFile();
if (prefix.equals(stkPrefix)) {
break;
}
}
}
}
}
String creationTime = null;
if (ndfile != null && ndfile.exists() &&
(fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles()))
{
// parse key/value pairs from .nd file
int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT();
int nstages = 0;
String z = null, c = null, t = null;
Vector<Boolean> hasZ = new Vector<Boolean>();
waveNames = new Vector<String>();
stageNames = new Vector<String>();
boolean useWaveNames = true;
ndFilename = ndfile.getAbsolutePath();
String[] lines = DataTools.readFile(ndFilename).split("\n");
for (String line : lines) {
int comma = line.indexOf(",");
if (comma <= 0) continue;
String key = line.substring(1, comma - 1).trim();
String value = line.substring(comma + 1).trim();
addGlobalMeta(key, value);
if (key.equals("NZSteps")) z = value;
else if (key.equals("NWavelengths")) c = value;
else if (key.equals("NTimePoints")) t = value;
else if (key.startsWith("WaveDoZ")) {
hasZ.add(new Boolean(value.toLowerCase()));
}
else if (key.startsWith("WaveName")) {
waveNames.add(value.substring(1, value.length() - 1));
}
else if (key.startsWith("Stage")) {
stageNames.add(value);
}
else if (key.startsWith("StartTime")) {
creationTime = value;
}
else if (key.equals("ZStepSize")) {
char separator = new DecimalFormatSymbols().getDecimalSeparator();
value = value.replace('.', separator);
value = value.replace(',', separator);
stepSize = Double.parseDouble(value);
}
else if (key.equals("NStagePositions")) {
nstages = Integer.parseInt(value);
}
else if (key.equals("WaveInFileName")) {
useWaveNames = Boolean.parseBoolean(value);
}
}
// figure out how many files we need
if (z != null) zc = Integer.parseInt(z);
if (c != null) cc = Integer.parseInt(c);
if (t != null) tc = Integer.parseInt(t);
if (cc == 0) cc = 1;
int numFiles = cc * tc;
if (nstages > 0) numFiles *= nstages;
// determine series count
int seriesCount = nstages == 0 ? 1 : nstages;
firstSeriesChannels = new boolean[cc];
Arrays.fill(firstSeriesChannels, true);
boolean differentZs = false;
for (int i=0; i<cc; i++) {
boolean hasZ1 = i < hasZ.size() && hasZ.get(i).booleanValue();
boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) &&
hasZ.get(i - 1).booleanValue();
if (i > 0 && hasZ1 != hasZ2) {
if (!differentZs) seriesCount *= 2;
differentZs = true;
}
}
int channelsInFirstSeries = cc;
if (differentZs) {
channelsInFirstSeries = 0;
for (int i=0; i<cc; i++) {
if (hasZ.get(i).booleanValue()) channelsInFirstSeries++;
else firstSeriesChannels[i] = false;
}
}
stks = new String[seriesCount][];
if (seriesCount == 1) stks[0] = new String[numFiles];
else if (differentZs) {
int stages = nstages == 0 ? 1 : nstages;
for (int i=0; i<stages; i++) {
stks[i * 2] = new String[channelsInFirstSeries * tc];
stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc];
}
}
else {
for (int i=0; i<stks.length; i++) {
stks[i] = new String[numFiles / stks.length];
}
}
String prefix = ndfile.getPath();
prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1,
prefix.lastIndexOf("."));
// build list of STK files
int[] pt = new int[seriesCount];
for (int i=0; i<tc; i++) {
int ns = nstages == 0 ? 1 : nstages;
for (int s=0; s<ns; s++) {
for (int j=0; j<cc; j++) {
boolean validZ = j >= hasZ.size() || hasZ.get(j).booleanValue();
int seriesNdx = s * (seriesCount / ns);
seriesNdx += (seriesCount == 1 || validZ) ? 0 : 1;
stks[seriesNdx][pt[seriesNdx]] = prefix;
if (j < waveNames.size() && waveNames.get(j) != null) {
stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1);
if (useWaveNames) {
String waveName = waveNames.get(j);
// If there are underscores in the wavelength name, translate
// them to hyphens. (See #558)
waveName = waveName.replace('_', '-');
stks[seriesNdx][pt[seriesNdx]] += waveName;
}
}
if (nstages > 0) {
stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1);
}
if (tc > 1) {
stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK";
}
else stks[seriesNdx][pt[seriesNdx]] += ".STK";
pt[seriesNdx]++;
}
}
}
ndfile = ndfile.getAbsoluteFile();
// check that each STK file exists
for (int s=0; s<stks.length; s++) {
for (int f=0; f<stks[s].length; f++) {
Location l = new Location(ndfile.getParent(), stks[s][f]);
stks[s][f] = getRealSTKFile(l);
}
}
int q = 0;
int f = 0;
String file = stks[q][f];
while (file == null) {
if (f < stks[q].length - 1) f++;
else if (q < stks.length - 1) {
q++;
f = 0;
}
file = stks[q][f];
}
RandomAccessInputStream s = new RandomAccessInputStream(file);
TiffParser tp = new TiffParser(s);
IFD ifd = tp.getFirstIFD();
s.close();
core[0].sizeX = (int) ifd.getImageWidth();
core[0].sizeY = (int) ifd.getImageLength();
core[0].sizeZ = zc;
core[0].sizeC = cc;
core[0].sizeT = tc;
core[0].imageCount = zc * tc * cc;
core[0].dimensionOrder = "XYZCT";
if (stks != null && stks.length > 1) {
CoreMetadata[] newCore = new CoreMetadata[stks.length];
for (int i=0; i<stks.length; i++) {
newCore[i] = new CoreMetadata();
newCore[i].sizeX = getSizeX();
newCore[i].sizeY = getSizeY();
newCore[i].sizeZ = getSizeZ();
newCore[i].sizeC = getSizeC();
newCore[i].sizeT = getSizeT();
newCore[i].pixelType = getPixelType();
newCore[i].imageCount = getImageCount();
newCore[i].dimensionOrder = getDimensionOrder();
newCore[i].rgb = isRGB();
newCore[i].littleEndian = isLittleEndian();
newCore[i].interleaved = isInterleaved();
newCore[i].orderCertain = true;
}
if (stks.length > nstages) {
int ns = nstages == 0 ? 1 : nstages;
for (int j=0; j<ns; j++) {
newCore[j * 2].sizeC = stks[j * 2].length / getSizeT();
newCore[j * 2 + 1].sizeC =
stks[j * 2 + 1].length / newCore[j * 2 + 1].sizeT;
newCore[j * 2 + 1].sizeZ = 1;
newCore[j * 2].imageCount = newCore[j * 2].sizeC *
newCore[j * 2].sizeT * newCore[j * 2].sizeZ;
newCore[j * 2 + 1].imageCount =
newCore[j * 2 + 1].sizeC * newCore[j * 2 + 1].sizeT;
}
}
core = newCore;
}
}
if (stks == null) {
stkReaders = new MetamorphReader[1][1];
stkReaders[0][0] = new MetamorphReader();
stkReaders[0][0].setCanLookForND(false);
}
else {
stkReaders = new MetamorphReader[stks.length][];
for (int i=0; i<stks.length; i++) {
stkReaders[i] = new MetamorphReader[stks[i].length];
for (int j=0; j<stkReaders[i].length; j++) {
stkReaders[i][j] = new MetamorphReader();
stkReaders[i][j].setCanLookForND(false);
if (j > 0) {
stkReaders[i][j].setMetadataOptions(
new DefaultMetadataOptions(MetadataLevel.MINIMUM));
}
}
}
}
Vector<String> timestamps = null;
MetamorphHandler handler = null;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
handler = new MetamorphHandler(getSeriesMetadata());
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
store.setImageInstrumentRef(instrumentID, i);
if (i == 0) {
store.setDetectorID(detectorID, 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
}
String comment = getFirstComment(i);
if (comment != null && comment.startsWith("<MetaData>")) {
XMLTools.parseXML(comment, handler);
}
if (creationTime != null) {
String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT);
store.setImageAcquiredDate(date, 0);
}
else if (i > 0) MetadataTools.setDefaultCreationDate(store, id, i);
store.setImageName(makeImageName(i), i);
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
continue;
}
store.setImageDescription("", i);
store.setImagingEnvironmentTemperature(handler.getTemperature(), i);
if (sizeX == null) sizeX = handler.getPixelSizeX();
if (sizeY == null) sizeY = handler.getPixelSizeY();
if (sizeX > 0) {
store.setPixelsPhysicalSizeX(new PositiveFloat(sizeX), i);
}
if (sizeY > 0) {
store.setPixelsPhysicalSizeY(new PositiveFloat(sizeY), i);
}
if (zDistances != null) {
stepSize = zDistances[0];
}
if (stepSize > 0) {
store.setPixelsPhysicalSizeZ(new PositiveFloat(stepSize), i);
}
int waveIndex = 0;
for (int c=0; c<getEffectiveSizeC(); c++) {
if (firstSeriesChannels == null ||
(stageNames != null && stageNames.size() == getSeriesCount()))
{
waveIndex = c;
}
else if (firstSeriesChannels != null) {
int s = i % 2;
while (firstSeriesChannels[waveIndex] == (s == 1) &&
waveIndex < firstSeriesChannels.length)
{
waveIndex++;
}
}
if (waveNames != null && waveIndex < waveNames.size()) {
store.setChannelName(waveNames.get(waveIndex), i, c);
}
if (handler.getBinning() != null) binning = handler.getBinning();
if (binning != null) {
store.setDetectorSettingsBinning(getBinning(binning), i, c);
}
if (handler.getReadOutRate() != 0) {
store.setDetectorSettingsReadOutRate(handler.getReadOutRate(), i, c);
}
store.setDetectorSettingsID(detectorID, i, c);
if (wave != null && waveIndex < wave.length &&
(int) wave[waveIndex] >= 1)
{
store.setChannelLightSourceSettingsWavelength(
new PositiveInteger((int) wave[waveIndex]), i, c);
// link LightSource to Image
String lightSourceID = MetadataTools.createLSID("LightSource", i, c);
store.setLaserID(lightSourceID, i, c);
store.setChannelLightSourceSettingsID(lightSourceID, i, c);
store.setLaserType(getLaserType("Other"), i, c);
store.setLaserLaserMedium(getLaserMedium("Other"), i, c);
}
waveIndex++;
}
timestamps = handler.getTimestamps();
for (int t=0; t<timestamps.size(); t++) {
addSeriesMeta("timestamp " + t, DateTools.formatDate(timestamps.get(t),
MEDIUM_DATE_FORMAT));
}
long startDate = 0;
if (timestamps.size() > 0) {
startDate = DateTools.getTime(timestamps.get(0), MEDIUM_DATE_FORMAT);
}
Double positionX = new Double(handler.getStagePositionX());
Double positionY = new Double(handler.getStagePositionY());
Vector<Double> exposureTimes = handler.getExposures();
if (exposureTimes.size() == 0) {
for (int p=0; p<getImageCount(); p++) {
exposureTimes.add(exposureTime);
}
}
int lastFile = -1;
IFD lastIFD = null;
long[] lastOffsets = null;
double distance = zStart;
for (int p=0; p<getImageCount(); p++) {
int[] coords = getZCTCoords(p);
Double deltaT = new Double(0);
Double exposureTime = new Double(0);
Double xmlZPosition = null;
int fileIndex = getIndex(0, 0, coords[2]) / getSizeZ();
if (fileIndex >= 0) {
String file = stks == null ? currentId : stks[i][fileIndex];
if (file != null) {
RandomAccessInputStream stream = new RandomAccessInputStream(file);
TiffParser tp = new TiffParser(stream);
tp.checkHeader();
if (fileIndex != lastFile) {
lastFile = fileIndex;
lastOffsets = tp.getIFDOffsets();
}
lastIFD = tp.getIFD(lastOffsets[p % lastOffsets.length]);
stream.close();
comment = lastIFD.getComment();
if (comment != null) comment = comment.trim();
handler = new MetamorphHandler(getSeriesMetadata());
if (comment != null && comment.startsWith("<MetaData>")) {
XMLTools.parseXML(comment, handler);
}
timestamps = handler.getTimestamps();
exposureTimes = handler.getExposures();
Vector<Double> zPositions = handler.getZPositions();
if (zPositions != null && zPositions.size() > 0) {
xmlZPosition = zPositions.get(0);
}
}
}
int index = 0;
if (timestamps.size() > 0) {
if (coords[2] < timestamps.size()) index = coords[2];
String stamp = timestamps.get(index);
long ms = DateTools.getTime(stamp, MEDIUM_DATE_FORMAT);
deltaT = new Double((ms - startDate) / 1000.0);
}
else if (internalStamps != null && p < internalStamps.length) {
long delta = internalStamps[p] - internalStamps[0];
deltaT = new Double(delta / 1000.0);
if (coords[2] < exposureTimes.size()) index = coords[2];
}
if (index < exposureTimes.size()) {
exposureTime = exposureTimes.get(index);
}
store.setPlaneDeltaT(deltaT, i, p);
store.setPlaneExposureTime(exposureTime, i, p);
if (stageX != null && p < stageX.length) {
store.setPlanePositionX(stageX[p], i, p);
}
if (stageY != null && p < stageY.length) {
store.setPlanePositionY(stageY[p], i, p);
}
if (zDistances != null && p < zDistances.length) {
if (p > 0) {
if (zDistances[p] != 0d) distance += zDistances[p];
else distance += zDistances[0];
}
store.setPlanePositionZ(distance, i, p);
}
else if (xmlZPosition != null) {
store.setPlanePositionZ(xmlZPosition, i, p);
}
}
}
setSeries(0);
}
| protected void initFile(String id) throws FormatException, IOException {
if (checkSuffix(id, ND_SUFFIX)) {
LOGGER.info("Initializing " + id);
// find an associated STK file
String stkFile = id.substring(0, id.lastIndexOf("."));
if (stkFile.indexOf(File.separator) != -1) {
stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1);
}
Location parent = new Location(id).getAbsoluteFile().getParentFile();
LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath());
String[] dirList = parent.list(true);
for (String f : dirList) {
int underscore = f.indexOf("_");
if (underscore < 0) underscore = f.indexOf(".");
if (underscore < 0) underscore = f.length();
String prefix = f.substring(0, underscore);
if ((f.equals(stkFile) || stkFile.startsWith(prefix)) &&
checkSuffix(f, STK_SUFFIX))
{
stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath();
break;
}
}
if (!checkSuffix(stkFile, STK_SUFFIX)) {
throw new FormatException("STK file not found in " +
parent.getAbsolutePath() + ".");
}
super.initFile(stkFile);
}
else super.initFile(id);
Location ndfile = null;
if (checkSuffix(id, ND_SUFFIX)) ndfile = new Location(id);
else if (canLookForND) {
// an STK file was passed to initFile
// let's check the parent directory for an .nd file
Location stk = new Location(id).getAbsoluteFile();
String stkName = stk.getName();
String stkPrefix = stkName;
if (stkPrefix.indexOf("_") >= 0) {
stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf("_") + 1);
}
Location parent = stk.getParentFile();
String[] list = parent.list(true);
for (String f : list) {
if (checkSuffix(f, ND_SUFFIX)) {
String prefix = f.substring(0, f.lastIndexOf("."));
if (prefix.indexOf("_") >= 0) {
prefix = prefix.substring(0, prefix.indexOf("_") + 1);
}
if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) {
ndfile = new Location(parent, f).getAbsoluteFile();
if (prefix.equals(stkPrefix)) {
break;
}
}
}
}
}
String creationTime = null;
if (ndfile != null && ndfile.exists() &&
(fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles()))
{
// parse key/value pairs from .nd file
int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT();
int nstages = 0;
String z = null, c = null, t = null;
Vector<Boolean> hasZ = new Vector<Boolean>();
waveNames = new Vector<String>();
stageNames = new Vector<String>();
boolean useWaveNames = true;
ndFilename = ndfile.getAbsolutePath();
String[] lines = DataTools.readFile(ndFilename).split("\n");
for (String line : lines) {
int comma = line.indexOf(",");
if (comma <= 0) continue;
String key = line.substring(1, comma - 1).trim();
String value = line.substring(comma + 1).trim();
addGlobalMeta(key, value);
if (key.equals("NZSteps")) z = value;
else if (key.equals("NWavelengths")) c = value;
else if (key.equals("NTimePoints")) t = value;
else if (key.startsWith("WaveDoZ")) {
hasZ.add(new Boolean(value.toLowerCase()));
}
else if (key.startsWith("WaveName")) {
waveNames.add(value.substring(1, value.length() - 1));
}
else if (key.startsWith("Stage")) {
stageNames.add(value);
}
else if (key.startsWith("StartTime")) {
creationTime = value;
}
else if (key.equals("ZStepSize")) {
char separator = new DecimalFormatSymbols().getDecimalSeparator();
value = value.replace('.', separator);
value = value.replace(',', separator);
stepSize = Double.parseDouble(value);
}
else if (key.equals("NStagePositions")) {
nstages = Integer.parseInt(value);
}
else if (key.equals("WaveInFileName")) {
useWaveNames = Boolean.parseBoolean(value);
}
}
// figure out how many files we need
if (z != null) zc = Integer.parseInt(z);
if (c != null) cc = Integer.parseInt(c);
if (t != null) tc = Integer.parseInt(t);
if (cc == 0) cc = 1;
int numFiles = cc * tc;
if (nstages > 0) numFiles *= nstages;
// determine series count
int seriesCount = nstages == 0 ? 1 : nstages;
firstSeriesChannels = new boolean[cc];
Arrays.fill(firstSeriesChannels, true);
boolean differentZs = false;
for (int i=0; i<cc; i++) {
boolean hasZ1 = i < hasZ.size() && hasZ.get(i).booleanValue();
boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) &&
hasZ.get(i - 1).booleanValue();
if (i > 0 && hasZ1 != hasZ2) {
if (!differentZs) seriesCount *= 2;
differentZs = true;
}
}
int channelsInFirstSeries = cc;
if (differentZs) {
channelsInFirstSeries = 0;
for (int i=0; i<cc; i++) {
if (hasZ.get(i).booleanValue()) channelsInFirstSeries++;
else firstSeriesChannels[i] = false;
}
}
stks = new String[seriesCount][];
if (seriesCount == 1) stks[0] = new String[numFiles];
else if (differentZs) {
int stages = nstages == 0 ? 1 : nstages;
for (int i=0; i<stages; i++) {
stks[i * 2] = new String[channelsInFirstSeries * tc];
stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc];
}
}
else {
for (int i=0; i<stks.length; i++) {
stks[i] = new String[numFiles / stks.length];
}
}
String prefix = ndfile.getPath();
prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1,
prefix.lastIndexOf("."));
// build list of STK files
int[] pt = new int[seriesCount];
for (int i=0; i<tc; i++) {
int ns = nstages == 0 ? 1 : nstages;
for (int s=0; s<ns; s++) {
for (int j=0; j<cc; j++) {
boolean validZ = j >= hasZ.size() || hasZ.get(j).booleanValue();
int seriesNdx = s * (seriesCount / ns);
if (nstages == 0 && (!validZ || seriesCount > 1)) {
seriesNdx++;
}
stks[seriesNdx][pt[seriesNdx]] = prefix;
if (j < waveNames.size() && waveNames.get(j) != null) {
stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1);
if (useWaveNames) {
String waveName = waveNames.get(j);
// If there are underscores in the wavelength name, translate
// them to hyphens. (See #558)
waveName = waveName.replace('_', '-');
stks[seriesNdx][pt[seriesNdx]] += waveName;
}
}
if (nstages > 0) {
stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1);
}
if (tc > 1) {
stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK";
}
else stks[seriesNdx][pt[seriesNdx]] += ".STK";
pt[seriesNdx]++;
}
}
}
ndfile = ndfile.getAbsoluteFile();
// check that each STK file exists
for (int s=0; s<stks.length; s++) {
for (int f=0; f<stks[s].length; f++) {
Location l = new Location(ndfile.getParent(), stks[s][f]);
stks[s][f] = getRealSTKFile(l);
}
}
int q = 0;
int f = 0;
String file = stks[q][f];
while (file == null) {
if (f < stks[q].length - 1) f++;
else if (q < stks.length - 1) {
q++;
f = 0;
}
file = stks[q][f];
}
RandomAccessInputStream s = new RandomAccessInputStream(file);
TiffParser tp = new TiffParser(s);
IFD ifd = tp.getFirstIFD();
s.close();
core[0].sizeX = (int) ifd.getImageWidth();
core[0].sizeY = (int) ifd.getImageLength();
core[0].sizeZ = zc;
core[0].sizeC = cc;
core[0].sizeT = tc;
core[0].imageCount = zc * tc * cc;
core[0].dimensionOrder = "XYZCT";
if (stks != null && stks.length > 1) {
CoreMetadata[] newCore = new CoreMetadata[stks.length];
for (int i=0; i<stks.length; i++) {
newCore[i] = new CoreMetadata();
newCore[i].sizeX = getSizeX();
newCore[i].sizeY = getSizeY();
newCore[i].sizeZ = getSizeZ();
newCore[i].sizeC = getSizeC();
newCore[i].sizeT = getSizeT();
newCore[i].pixelType = getPixelType();
newCore[i].imageCount = getImageCount();
newCore[i].dimensionOrder = getDimensionOrder();
newCore[i].rgb = isRGB();
newCore[i].littleEndian = isLittleEndian();
newCore[i].interleaved = isInterleaved();
newCore[i].orderCertain = true;
}
if (stks.length > nstages) {
int ns = nstages == 0 ? 1 : nstages;
for (int j=0; j<ns; j++) {
newCore[j * 2].sizeC = stks[j * 2].length / getSizeT();
newCore[j * 2 + 1].sizeC =
stks[j * 2 + 1].length / newCore[j * 2 + 1].sizeT;
newCore[j * 2 + 1].sizeZ = 1;
newCore[j * 2].imageCount = newCore[j * 2].sizeC *
newCore[j * 2].sizeT * newCore[j * 2].sizeZ;
newCore[j * 2 + 1].imageCount =
newCore[j * 2 + 1].sizeC * newCore[j * 2 + 1].sizeT;
}
}
core = newCore;
}
}
if (stks == null) {
stkReaders = new MetamorphReader[1][1];
stkReaders[0][0] = new MetamorphReader();
stkReaders[0][0].setCanLookForND(false);
}
else {
stkReaders = new MetamorphReader[stks.length][];
for (int i=0; i<stks.length; i++) {
stkReaders[i] = new MetamorphReader[stks[i].length];
for (int j=0; j<stkReaders[i].length; j++) {
stkReaders[i][j] = new MetamorphReader();
stkReaders[i][j].setCanLookForND(false);
if (j > 0) {
stkReaders[i][j].setMetadataOptions(
new DefaultMetadataOptions(MetadataLevel.MINIMUM));
}
}
}
}
Vector<String> timestamps = null;
MetamorphHandler handler = null;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
handler = new MetamorphHandler(getSeriesMetadata());
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
store.setImageInstrumentRef(instrumentID, i);
if (i == 0) {
store.setDetectorID(detectorID, 0, 0);
store.setDetectorType(getDetectorType("Other"), 0, 0);
}
String comment = getFirstComment(i);
if (comment != null && comment.startsWith("<MetaData>")) {
XMLTools.parseXML(comment, handler);
}
if (creationTime != null) {
String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT);
store.setImageAcquiredDate(date, 0);
}
else if (i > 0) MetadataTools.setDefaultCreationDate(store, id, i);
store.setImageName(makeImageName(i), i);
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
continue;
}
store.setImageDescription("", i);
store.setImagingEnvironmentTemperature(handler.getTemperature(), i);
if (sizeX == null) sizeX = handler.getPixelSizeX();
if (sizeY == null) sizeY = handler.getPixelSizeY();
if (sizeX > 0) {
store.setPixelsPhysicalSizeX(new PositiveFloat(sizeX), i);
}
if (sizeY > 0) {
store.setPixelsPhysicalSizeY(new PositiveFloat(sizeY), i);
}
if (zDistances != null) {
stepSize = zDistances[0];
}
if (stepSize > 0) {
store.setPixelsPhysicalSizeZ(new PositiveFloat(stepSize), i);
}
int waveIndex = 0;
for (int c=0; c<getEffectiveSizeC(); c++) {
if (firstSeriesChannels == null ||
(stageNames != null && stageNames.size() == getSeriesCount()))
{
waveIndex = c;
}
else if (firstSeriesChannels != null) {
int s = i % 2;
while (firstSeriesChannels[waveIndex] == (s == 1) &&
waveIndex < firstSeriesChannels.length)
{
waveIndex++;
}
}
if (waveNames != null && waveIndex < waveNames.size()) {
store.setChannelName(waveNames.get(waveIndex), i, c);
}
if (handler.getBinning() != null) binning = handler.getBinning();
if (binning != null) {
store.setDetectorSettingsBinning(getBinning(binning), i, c);
}
if (handler.getReadOutRate() != 0) {
store.setDetectorSettingsReadOutRate(handler.getReadOutRate(), i, c);
}
store.setDetectorSettingsID(detectorID, i, c);
if (wave != null && waveIndex < wave.length &&
(int) wave[waveIndex] >= 1)
{
store.setChannelLightSourceSettingsWavelength(
new PositiveInteger((int) wave[waveIndex]), i, c);
// link LightSource to Image
String lightSourceID = MetadataTools.createLSID("LightSource", i, c);
store.setLaserID(lightSourceID, i, c);
store.setChannelLightSourceSettingsID(lightSourceID, i, c);
store.setLaserType(getLaserType("Other"), i, c);
store.setLaserLaserMedium(getLaserMedium("Other"), i, c);
}
waveIndex++;
}
timestamps = handler.getTimestamps();
for (int t=0; t<timestamps.size(); t++) {
addSeriesMeta("timestamp " + t, DateTools.formatDate(timestamps.get(t),
MEDIUM_DATE_FORMAT));
}
long startDate = 0;
if (timestamps.size() > 0) {
startDate = DateTools.getTime(timestamps.get(0), MEDIUM_DATE_FORMAT);
}
Double positionX = new Double(handler.getStagePositionX());
Double positionY = new Double(handler.getStagePositionY());
Vector<Double> exposureTimes = handler.getExposures();
if (exposureTimes.size() == 0) {
for (int p=0; p<getImageCount(); p++) {
exposureTimes.add(exposureTime);
}
}
int lastFile = -1;
IFD lastIFD = null;
long[] lastOffsets = null;
double distance = zStart;
for (int p=0; p<getImageCount(); p++) {
int[] coords = getZCTCoords(p);
Double deltaT = new Double(0);
Double exposureTime = new Double(0);
Double xmlZPosition = null;
int fileIndex = getIndex(0, 0, coords[2]) / getSizeZ();
if (fileIndex >= 0) {
String file = stks == null ? currentId : stks[i][fileIndex];
if (file != null) {
RandomAccessInputStream stream = new RandomAccessInputStream(file);
TiffParser tp = new TiffParser(stream);
tp.checkHeader();
if (fileIndex != lastFile) {
lastFile = fileIndex;
lastOffsets = tp.getIFDOffsets();
}
lastIFD = tp.getIFD(lastOffsets[p % lastOffsets.length]);
stream.close();
comment = lastIFD.getComment();
if (comment != null) comment = comment.trim();
handler = new MetamorphHandler(getSeriesMetadata());
if (comment != null && comment.startsWith("<MetaData>")) {
XMLTools.parseXML(comment, handler);
}
timestamps = handler.getTimestamps();
exposureTimes = handler.getExposures();
Vector<Double> zPositions = handler.getZPositions();
if (zPositions != null && zPositions.size() > 0) {
xmlZPosition = zPositions.get(0);
}
}
}
int index = 0;
if (timestamps.size() > 0) {
if (coords[2] < timestamps.size()) index = coords[2];
String stamp = timestamps.get(index);
long ms = DateTools.getTime(stamp, MEDIUM_DATE_FORMAT);
deltaT = new Double((ms - startDate) / 1000.0);
}
else if (internalStamps != null && p < internalStamps.length) {
long delta = internalStamps[p] - internalStamps[0];
deltaT = new Double(delta / 1000.0);
if (coords[2] < exposureTimes.size()) index = coords[2];
}
if (index < exposureTimes.size()) {
exposureTime = exposureTimes.get(index);
}
store.setPlaneDeltaT(deltaT, i, p);
store.setPlaneExposureTime(exposureTime, i, p);
if (stageX != null && p < stageX.length) {
store.setPlanePositionX(stageX[p], i, p);
}
if (stageY != null && p < stageY.length) {
store.setPlanePositionY(stageY[p], i, p);
}
if (zDistances != null && p < zDistances.length) {
if (p > 0) {
if (zDistances[p] != 0d) distance += zDistances[p];
else distance += zDistances[0];
}
store.setPlanePositionZ(distance, i, p);
}
else if (xmlZPosition != null) {
store.setPlanePositionZ(xmlZPosition, i, p);
}
}
}
setSeries(0);
}
|
diff --git a/src/UltraCommand.java b/src/UltraCommand.java
index 59691a2..71f3366 100644
--- a/src/UltraCommand.java
+++ b/src/UltraCommand.java
@@ -1,354 +1,353 @@
package com.kierdavis.ultracommand;
import com.kierdavis.flex.FlexCommandExecutor;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import org.mcstats.Metrics;
public class UltraCommand extends JavaPlugin {
private File commandsFile;
private FileConfiguration commandsConfig;
private BukkitTask saveCommandsTask;
private boolean dirty;
public void onEnable() {
commandsFile = new File(getDataFolder(), "commands.yml");
loadCustomCommands();
getServer().getPluginManager().registerEvents(new PlayerListener(this), this);
FlexCommandExecutor cmdExec = FlexCommandExecutor.getInstance();
cmdExec.addHandler(this, new AddCommandHandler(this));
cmdExec.addHandler(this, new ListCommandHandler(this));
cmdExec.addHandler(this, new MiscCommandHandler(this));
cmdExec.addHandler(this, new RemoveCommandHandler(this));
cmdExec.alias("ultracommand", "uc");
dirty = false;
saveCommandsTask = new SaveCommandsTask(this).runTaskTimer(this, 20 * 60, 20 * 60); // Check every minute.
// Start Metrics
try {
Metrics metrics = new Metrics(this);
metrics.start();
}
catch (IOException e) {
getLogger().severe("Failed to submit stats to Metrics: " + e.toString());
}
}
public void onDisable() {
saveCommandsTask.cancel();
saveCustomCommands();
}
public void loadCustomCommands() {
if (!commandsFile.exists()) {
createCommandsFile();
}
commandsConfig = YamlConfiguration.loadConfiguration(commandsFile);
getLogger().info("Loaded " + commandsFile.toString());
}
public void saveCustomCommands() {
try {
commandsConfig.save(commandsFile);
dirty = false;
getLogger().info("Saved " + commandsFile.toString());
}
catch (IOException e) {
getLogger().severe("Could not save " + commandsFile.toString() + ": " + e.toString());
}
}
public Set<String> getCustomCommands() {
return getCommandsSection().getKeys(false);
}
public CustomCommandContext getCustomCommandContext(String name, Player player, String[] args) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
CustomCommandContext cmd = new CustomCommandContext(getLogger(), player, args);
List<String> l;
l = commandSection.getStringList("text");
if (l != null && l.size() > 0) cmd.setText(l);
l = commandSection.getStringList("chat");
if (l != null && l.size() > 0) cmd.setText(l);
l = commandSection.getStringList("playerCommands");
if (l != null && l.size() > 0) cmd.setPlayerCommands(l);
l = commandSection.getStringList("consoleCommands");
if (l != null && l.size() > 0) cmd.setConsoleCommands(l);
String usage = commandSection.getString("usage");
if (usage != null && usage.length() > 0) cmd.setUsage(usage);
return cmd;
}
public boolean addCustomCommand(String name) {
ConfigurationSection commandsSection = getCommandsSection();
name = name.toLowerCase();
if (commandsSection.contains(name)) {
return false;
}
ConfigurationSection commandSection = commandsSection.createSection(name);
//commandSection.set("text", new ArrayList<String>());
//commandSection.set("chat", new ArrayList<String>());
//commandSection.set("playerCommands", new ArrayList<String>());
//commandSection.set("consoleCommands", new ArrayList<String>());
dirty = true;
return true;
}
public boolean hasCustomCommand(String name) {
return getCommandSection(name) != null;
}
public boolean removeCustomCommand(String name) {
ConfigurationSection commandsSection = getCommandsSection();
name = name.toLowerCase();
if (!commandsSection.contains(name)) {
return false;
}
commandsSection.set(name, null);
dirty = true;
return true;
}
public boolean addText(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
List<String> l = commandSection.getStringList("text");
l.add(s);
commandSection.set("text", l);
dirty = true;
return true;
}
public boolean addChat(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
List<String> l = commandSection.getStringList("chat");
l.add(s);
commandSection.set("chat", l);
dirty = true;
return true;
}
public boolean addPlayerCommand(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
List<String> l = commandSection.getStringList("playerCommands");
l.add(s);
commandSection.set("playerCommands", l);
dirty = true;
return true;
}
public boolean addConsoleCommand(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
List<String> l = commandSection.getStringList("consoleCommands");
l.add(s);
commandSection.set("consoleCommands", l);
dirty = true;
return true;
}
public boolean setUsage(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("usage", s);
dirty = true;
return true;
}
public List<String> getText(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getStringList("text");
}
public List<String> getChat(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getStringList("chat");
}
public List<String> getPlayerCommands(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getStringList("playerCommands");
}
public List<String> getConsoleCommands(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getStringList("consoleCommands");
}
public String getUsage(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getString("usage");
}
public boolean clearText(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("text", new ArrayList<String>());
dirty = true;
return true;
}
public boolean clearChat(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("chat", new ArrayList<String>());
dirty = true;
return true;
}
public boolean clearPlayerCommands(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("playerCommands", new ArrayList<String>());
dirty = true;
return true;
}
public boolean clearConsoleCommands(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("consoleCommands", new ArrayList<String>());
dirty = true;
return true;
}
private ConfigurationSection getCommandsSection() {
ConfigurationSection commandsSection = commandsConfig.getConfigurationSection("commands");
if (commandsSection == null) {
commandsSection = commandsConfig.createSection("commands");
}
return commandsSection;
}
private ConfigurationSection getCommandSection(String name) {
return getCommandsSection().getConfigurationSection(name.toLowerCase());
}
private void createCommandsFile() {
File parent = commandsFile.getParentFile();
try {
if (!parent.exists()) {
parent.mkdirs();
}
if (!commandsFile.exists()) {
boolean b = commandsFile.createNewFile();
if (b) {
getLogger().info("Created " + commandsFile.toString());
}
}
}
catch (IOException e) {
getLogger().warning("Could not create " + commandsFile.toString() + ": " + e.toString());
}
}
public boolean isDirty() {
return dirty;
}
public boolean doCommand(Player player, String[] parts) {
CustomCommandContext ccc = null;
String cmdName = "";
StringBuilder b = new StringBuilder();
- b.append(parts[0]);
for (int i = 0; i < parts.length; i++) {
String thisCmdName = b.toString().replaceAll(" ", "_");
CustomCommandContext thisCCC = getCustomCommandContext(cmdName, player, Arrays.copyOfRange(parts, i+1, parts.length));
if (thisCCC != null) {
cmdName = thisCmdName;
ccc = thisCCC;
}
getLogger().info(ccc.toString());
getLogger().info(thisCCC.toString());
getLogger().info(cmdName.toString());
getLogger().info(thisCmdName.toString());
if (i > 0) b.append(" ");
b.append(parts[i]);
}
if (ccc != null) {
String perm = "ultracommand.commands." + cmdName;
if (!player.hasPermission(perm) && !player.hasPermission("ultracommand.commands.*")) {
player.sendMessage(ChatColor.YELLOW + "You don't have permission for this command (" + perm + ")");
return true;
}
getLogger().info(player.getName() + " issued custom command: /" + b.toString());
ccc.execute();
return true;
}
return false;
}
}
| true | true | public boolean doCommand(Player player, String[] parts) {
CustomCommandContext ccc = null;
String cmdName = "";
StringBuilder b = new StringBuilder();
b.append(parts[0]);
for (int i = 0; i < parts.length; i++) {
String thisCmdName = b.toString().replaceAll(" ", "_");
CustomCommandContext thisCCC = getCustomCommandContext(cmdName, player, Arrays.copyOfRange(parts, i+1, parts.length));
if (thisCCC != null) {
cmdName = thisCmdName;
ccc = thisCCC;
}
getLogger().info(ccc.toString());
getLogger().info(thisCCC.toString());
getLogger().info(cmdName.toString());
getLogger().info(thisCmdName.toString());
if (i > 0) b.append(" ");
b.append(parts[i]);
}
if (ccc != null) {
String perm = "ultracommand.commands." + cmdName;
if (!player.hasPermission(perm) && !player.hasPermission("ultracommand.commands.*")) {
player.sendMessage(ChatColor.YELLOW + "You don't have permission for this command (" + perm + ")");
return true;
}
getLogger().info(player.getName() + " issued custom command: /" + b.toString());
ccc.execute();
return true;
}
return false;
}
| public boolean doCommand(Player player, String[] parts) {
CustomCommandContext ccc = null;
String cmdName = "";
StringBuilder b = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
String thisCmdName = b.toString().replaceAll(" ", "_");
CustomCommandContext thisCCC = getCustomCommandContext(cmdName, player, Arrays.copyOfRange(parts, i+1, parts.length));
if (thisCCC != null) {
cmdName = thisCmdName;
ccc = thisCCC;
}
getLogger().info(ccc.toString());
getLogger().info(thisCCC.toString());
getLogger().info(cmdName.toString());
getLogger().info(thisCmdName.toString());
if (i > 0) b.append(" ");
b.append(parts[i]);
}
if (ccc != null) {
String perm = "ultracommand.commands." + cmdName;
if (!player.hasPermission(perm) && !player.hasPermission("ultracommand.commands.*")) {
player.sendMessage(ChatColor.YELLOW + "You don't have permission for this command (" + perm + ")");
return true;
}
getLogger().info(player.getName() + " issued custom command: /" + b.toString());
ccc.execute();
return true;
}
return false;
}
|
diff --git a/src/fniki/wiki/HtmlResultFactory.java b/src/fniki/wiki/HtmlResultFactory.java
index 33a9c34..8b69ffd 100644
--- a/src/fniki/wiki/HtmlResultFactory.java
+++ b/src/fniki/wiki/HtmlResultFactory.java
@@ -1,111 +1,116 @@
/* Make ChildContainerResults for HTML.
*
* Copyright (C) 2010, 2011 Darrell Karbott
*
* This library 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.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
* General Public License for more details.
*
* You should have received a copy of the GNU 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
*
* Author: djk@isFiaD04zgAgnrEC5XJt1i4IE7AkNPqhBG5bONi6Yks
*
* This file was developed as component of
* "fniki" (a wiki implementation running over Freenet).
*/
package fniki.wiki;
import java.io.IOException;
import java.io.InputStream;
import wormarc.IOUtil;
import static ys.wikiparser.Utils.*;
// INTENT: Encapsulate the hacks we need to do handle the fact that the Freenet plugin
// only wants the html body, not the full document.
public class HtmlResultFactory {
private final static String ENCODING = "UTF-8";
public static ChildContainerResult makeResult(String utf8Title,
String utf8Body,
boolean includeOuterHtml,
int refreshSeconds)
throws ServerErrorException {
try {
return new StaticResult(ENCODING, "text/html", utf8Title, refreshSeconds,
makeData(utf8Title, utf8Body, refreshSeconds, includeOuterHtml));
} catch (IOException ioe) {
throw new ServerErrorException("HtmlResultFactory.makeResult failed. Bad data?");
}
}
public static ChildContainerResult makeResult(String utf8Title,
String utf8Body,
boolean includeOuterHtml)
throws ServerErrorException {
return makeResult(utf8Title, utf8Body, includeOuterHtml, 0);
}
public static byte[] makeData(String utf8Title,
String utf8Body,
int refreshSeconds,
boolean includeOuterHtml)
throws IOException {
if (!includeOuterHtml) {
return utf8Body.getBytes(ENCODING);
}
StringBuilder buffer = new StringBuilder();
buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
buffer.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
buffer.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
- buffer.append("<head><title>\n");
+ buffer.append("<head>\n");
+ // The freenet content filter rips out the <?xml > line above.
+ // We need to do this to get correct utf-8 charater handling
+ // when running stand alone.
+ buffer.append("<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\" />\n");
+ buffer.append("<title>\n");
buffer.append(escapeHTML(utf8Title));
buffer.append("</title>\n");
// CAREFUL: MUST audit .css files built into .jar to make sure they are safe.
// Load .css snippet from jar. Names can only have 1 '/' and must be globally unique.
String css = getStaticCss();
buffer.append("<style>\n");
buffer.append(css);
buffer.append("</style>\n");
if (refreshSeconds > 0) {
buffer.append("<meta http-equiv=\"refresh\" content=\"");
buffer.append(refreshSeconds);
buffer.append("\" />\n");
}
buffer.append("</head>\n");
buffer.append("<body>\n");
// Road. Meet rubber. Rubber. Meet road.
buffer.append(utf8Body);
buffer.append("</body></html>\n");
return buffer.toString().getBytes(ENCODING);
}
// MUST exist and not be empty.
private static String getStaticCss() throws IOException {
// Seems fast enough. If people complain we can cache the value.
InputStream resourceStream =
HtmlResultFactory.class.getResourceAsStream("/standalone_jfniki.css");
if (resourceStream == null) {
throw new IOException("Not in Jar!");
}
return IOUtil.readUtf8StringAndClose(resourceStream);
}
}
| true | true | public static byte[] makeData(String utf8Title,
String utf8Body,
int refreshSeconds,
boolean includeOuterHtml)
throws IOException {
if (!includeOuterHtml) {
return utf8Body.getBytes(ENCODING);
}
StringBuilder buffer = new StringBuilder();
buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
buffer.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
buffer.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
buffer.append("<head><title>\n");
buffer.append(escapeHTML(utf8Title));
buffer.append("</title>\n");
// CAREFUL: MUST audit .css files built into .jar to make sure they are safe.
// Load .css snippet from jar. Names can only have 1 '/' and must be globally unique.
String css = getStaticCss();
buffer.append("<style>\n");
buffer.append(css);
buffer.append("</style>\n");
if (refreshSeconds > 0) {
buffer.append("<meta http-equiv=\"refresh\" content=\"");
buffer.append(refreshSeconds);
buffer.append("\" />\n");
}
buffer.append("</head>\n");
buffer.append("<body>\n");
// Road. Meet rubber. Rubber. Meet road.
buffer.append(utf8Body);
buffer.append("</body></html>\n");
return buffer.toString().getBytes(ENCODING);
}
| public static byte[] makeData(String utf8Title,
String utf8Body,
int refreshSeconds,
boolean includeOuterHtml)
throws IOException {
if (!includeOuterHtml) {
return utf8Body.getBytes(ENCODING);
}
StringBuilder buffer = new StringBuilder();
buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
buffer.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" " +
"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
buffer.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
buffer.append("<head>\n");
// The freenet content filter rips out the <?xml > line above.
// We need to do this to get correct utf-8 charater handling
// when running stand alone.
buffer.append("<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\" />\n");
buffer.append("<title>\n");
buffer.append(escapeHTML(utf8Title));
buffer.append("</title>\n");
// CAREFUL: MUST audit .css files built into .jar to make sure they are safe.
// Load .css snippet from jar. Names can only have 1 '/' and must be globally unique.
String css = getStaticCss();
buffer.append("<style>\n");
buffer.append(css);
buffer.append("</style>\n");
if (refreshSeconds > 0) {
buffer.append("<meta http-equiv=\"refresh\" content=\"");
buffer.append(refreshSeconds);
buffer.append("\" />\n");
}
buffer.append("</head>\n");
buffer.append("<body>\n");
// Road. Meet rubber. Rubber. Meet road.
buffer.append(utf8Body);
buffer.append("</body></html>\n");
return buffer.toString().getBytes(ENCODING);
}
|
diff --git a/Essentials/src/com/earth2me/essentials/api/Economy.java b/Essentials/src/com/earth2me/essentials/api/Economy.java
index fcab616b..ddafacd5 100644
--- a/Essentials/src/com/earth2me/essentials/api/Economy.java
+++ b/Essentials/src/com/earth2me/essentials/api/Economy.java
@@ -1,292 +1,293 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.EssentialsConf;
import com.earth2me.essentials.IEssentials;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.entity.Player;
/**
* Instead of using this api directly, we recommend to use the register plugin:
* http://bit.ly/RegisterMethod
*/
public final class Economy
{
private Economy()
{
}
private static final Logger logger = Logger.getLogger("Minecraft");
private static IEssentials ess;
/**
* @param aEss the ess to set
*/
public static void setEss(IEssentials aEss)
{
ess = aEss;
}
private static void createNPCFile(String name)
{
File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs();
}
EssentialsConf npcConfig = new EssentialsConf(new File(folder, Util.sanitizeFileName(name) + ".yml"));
npcConfig.load();
npcConfig.setProperty("npc", true);
npcConfig.setProperty("money", ess.getSettings().getStartingBalance());
npcConfig.save();
}
private static void deleteNPC(String name)
{
File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs();
}
File config = new File(folder, Util.sanitizeFileName(name) + ".yml");
EssentialsConf npcConfig = new EssentialsConf(config);
npcConfig.load();
if (npcConfig.hasProperty("npc") && npcConfig.getBoolean("npc", false))
{
if (!config.delete())
{
logger.log(Level.WARNING, Util.format("deleteFileError", config));
}
+ ess.getAllUsers().remove(name.toLowerCase());
}
}
private static User getUserByName(String name)
{
User user;
Player player = ess.getServer().getPlayer(name);
if (player != null)
{
user = ess.getUser(player);
}
else
{
user = ess.getOfflineUser(name);
}
return user;
}
/**
* Returns the balance of a user
* @param name Name of the user
* @return balance
* @throws UserDoesNotExistException
*/
public static double getMoney(String name) throws UserDoesNotExistException
{
User user = getUserByName(name);
if (user == null)
{
throw new UserDoesNotExistException(name);
}
return user.getMoney();
}
/**
* Sets the balance of a user
* @param name Name of the user
* @param balance The balance you want to set
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException
{
User user = getUserByName(name);
if (user == null)
{
throw new UserDoesNotExistException(name);
}
if (balance < 0.0 && !user.isAuthorized("essentials.eco.loan"))
{
throw new NoLoanPermittedException();
}
user.setMoney(balance);
}
/**
* Adds money to the balance of a user
* @param name Name of the user
* @param amount The money you want to add
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException
{
double result = getMoney(name) + amount;
setMoney(name, result);
}
/**
* Substracts money from the balance of a user
* @param name Name of the user
* @param amount The money you want to substract
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException
{
double result = getMoney(name) - amount;
setMoney(name, result);
}
/**
* Divides the balance of a user by a value
* @param name Name of the user
* @param value The balance is divided by this value
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void divide(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException
{
double result = getMoney(name) / value;
setMoney(name, result);
}
/**
* Multiplies the balance of a user by a value
* @param name Name of the user
* @param value The balance is multiplied by this value
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void multiply(String name, double value) throws UserDoesNotExistException, NoLoanPermittedException
{
double result = getMoney(name) * value;
setMoney(name, result);
}
/**
* Resets the balance of a user to the starting balance
* @param name Name of the user
* @throws UserDoesNotExistException If a user by that name does not exists
* @throws NoLoanPermittedException If the user is not allowed to have a negative balance
*/
public static void resetBalance(String name) throws UserDoesNotExistException, NoLoanPermittedException
{
setMoney(name, ess.getSettings().getStartingBalance());
}
/**
* @param name Name of the user
* @param amount The amount of money the user should have
* @return true, if the user has more or an equal amount of money
* @throws UserDoesNotExistException If a user by that name does not exists
*/
public static boolean hasEnough(String name, double amount) throws UserDoesNotExistException
{
return amount <= getMoney(name);
}
/**
* @param name Name of the user
* @param amount The amount of money the user should have
* @return true, if the user has more money
* @throws UserDoesNotExistException If a user by that name does not exists
*/
public static boolean hasMore(String name, double amount) throws UserDoesNotExistException
{
return amount < getMoney(name);
}
/**
* @param name Name of the user
* @param amount The amount of money the user should not have
* @return true, if the user has less money
* @throws UserDoesNotExistException If a user by that name does not exists
*/
public static boolean hasLess(String name, double amount) throws UserDoesNotExistException
{
return amount > getMoney(name);
}
/**
* Test if the user has a negative balance
* @param name Name of the user
* @return true, if the user has a negative balance
* @throws UserDoesNotExistException If a user by that name does not exists
*/
public static boolean isNegative(String name) throws UserDoesNotExistException
{
return getMoney(name) < 0.0;
}
/**
* Formats the amount of money like all other Essentials functions.
* Example: $100000 or $12345.67
* @param amount The amount of money
* @return Formatted money
*/
public static String format(double amount)
{
return Util.formatCurrency(amount, ess);
}
/**
* Test if a player exists to avoid the UserDoesNotExistException
* @param name Name of the user
* @return true, if the user exists
*/
public static boolean playerExists(String name)
{
return getUserByName(name) != null;
}
/**
* Test if a player is a npc
* @param name Name of the player
* @return true, if it's a npc
* @throws UserDoesNotExistException
*/
public static boolean isNPC(String name) throws UserDoesNotExistException
{
User user = getUserByName(name);
if (user == null)
{
throw new UserDoesNotExistException(name);
}
return user.isNPC();
}
/**
* Creates dummy files for a npc, if there is no player yet with that name.
* @param name Name of the player
* @return true, if a new npc was created
*/
public static boolean createNPC(String name)
{
User user = getUserByName(name);
if (user == null)
{
createNPCFile(name);
return true;
}
return false;
}
/**
* Deletes a user, if it is marked as npc.
* @param name Name of the player
* @throws UserDoesNotExistException
*/
public static void removeNPC(String name) throws UserDoesNotExistException
{
User user = getUserByName(name);
if (user == null)
{
throw new UserDoesNotExistException(name);
}
deleteNPC(name);
}
}
| true | true | private static void deleteNPC(String name)
{
File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs();
}
File config = new File(folder, Util.sanitizeFileName(name) + ".yml");
EssentialsConf npcConfig = new EssentialsConf(config);
npcConfig.load();
if (npcConfig.hasProperty("npc") && npcConfig.getBoolean("npc", false))
{
if (!config.delete())
{
logger.log(Level.WARNING, Util.format("deleteFileError", config));
}
}
}
| private static void deleteNPC(String name)
{
File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs();
}
File config = new File(folder, Util.sanitizeFileName(name) + ".yml");
EssentialsConf npcConfig = new EssentialsConf(config);
npcConfig.load();
if (npcConfig.hasProperty("npc") && npcConfig.getBoolean("npc", false))
{
if (!config.delete())
{
logger.log(Level.WARNING, Util.format("deleteFileError", config));
}
ess.getAllUsers().remove(name.toLowerCase());
}
}
|
diff --git a/BofSA/src/au/edu/csu/bofsa/InGameStateST.java b/BofSA/src/au/edu/csu/bofsa/InGameStateST.java
index 431790d..377498b 100644
--- a/BofSA/src/au/edu/csu/bofsa/InGameStateST.java
+++ b/BofSA/src/au/edu/csu/bofsa/InGameStateST.java
@@ -1,458 +1,459 @@
/**
* The MIT License
*
* Copyright 2011 Andrew James <[email protected]>.
*
* 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 au.edu.csu.bofsa;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.GameState;
import org.newdawn.slick.state.StateBasedGame;
import au.edu.csu.bofsa.Behaviours.CreepFactoryBehaviour;
import au.edu.csu.bofsa.Behaviours.TowerFactoryBehaviour;
import au.edu.csu.bofsa.Events.Event;
import au.edu.csu.bofsa.Events.EventSink;
import au.edu.csu.bofsa.Signals.Signal;
/**
* @author ephphatha
*
*/
public class InGameStateST implements Comparable<Object>, CreepManager, EventSink, GameState, Runnable {
private int stateID;
protected GameLevelST map;
protected List<Tower> towers;
protected Queue<Creep> newCreeps;
protected List<Creep> creeps;
protected Queue<Creep> deadCreeps;
protected List<Tower> towerBallast;
protected List<Creep> creepBallast;
protected Logger logger;
protected Logger dummyLogger;
protected Logger.Mode logMode;
protected int numTowers;
protected Signal<CopyableDimension> tileSize;
protected Signal<CopyableList<Pipe<CopyableVector2f>>> creepPositions;
protected Thread updateThread;
private float elapsed;
@SuppressWarnings("unused")
private InGameStateST() {
this(0, Logger.Mode.BASIC, 0);
}
public InGameStateST(int id, Logger.Mode logMode, int numTowers) {
this.stateID = id;
this.numTowers = numTowers;
this.towers = new CopyOnWriteArrayList<Tower>();
this.towerBallast = new LinkedList<Tower>();
this.creeps = new LinkedList<Creep>();
this.creepBallast = new LinkedList<Creep>();
this.deadCreeps = new ConcurrentLinkedQueue<Creep>();
this.newCreeps = new ConcurrentLinkedQueue<Creep>();
this.creepPositions = new Signal<CopyableList<Pipe<CopyableVector2f>>>(new CopyableList<Pipe<CopyableVector2f>>());
this.tileSize = new Signal<CopyableDimension>(new CopyableDimension(1,1));
this.logger = new Logger();
this.logMode = logMode;
}
@Override
public int getID() {
return this.stateID;
}
@Override
public void init(GameContainer container, StateBasedGame game)
throws SlickException {
}
@Override
public void enter(GameContainer container, StateBasedGame game)
throws SlickException {
try {
this.map = new GameLevelST("test");
} catch (SlickException e) {
e.printStackTrace();
}
this.elapsed = 0;
this.updateThread = new Thread(this);
{
CopyablePoint dummy = new CopyablePoint(0,0);
Tower t = null;
for (int i = 0; i < this.map.getHeight() * this.map.getWidth(); ++i) {
t = new Tower(dummy);
TowerFactoryBehaviour.createTower(dummy, this.creepPositions, t, this.tileSize, this);
this.towerBallast.add(t);
}
}
Signal<CopyableList<Pipe<CopyableVector2f>>> tempSignal = new Signal<CopyableList<Pipe<CopyableVector2f>>>(new CopyableList<Pipe<CopyableVector2f>>());
{
CopyableVector2f dummy = new CopyableVector2f(1,1);
Queue<CheckPoint> cps = new LinkedList<CheckPoint>();
cps.add(new CheckPoint(0, dummy));
Creep c = null;
for (int i = 0; i < 1024; ++i) {
c = new Creep();
CreepFactoryBehaviour.spawnCreep(dummy, cps, c, c, this.tileSize, this, tempSignal);
this.creepBallast.add(c);
}
}
{
CopyablePoint dummy = new CopyablePoint(0,0);
Tower t = null;
for (int i = 0; i < this.numTowers; ++i) {
- TowerFactoryBehaviour.createTower(dummy, this.creepPositions, t, this.tileSize, null);
+ t = new Tower(dummy);
+ TowerFactoryBehaviour.createTower(dummy, this.creepPositions, t, this.tileSize, this);
this.towers.add(t);
}
}
this.logger.setLogMode(this.logMode);
this.dummyLogger = new Logger();
this.dummyLogger.setLogMode(this.logMode);
if (this.getClass() == InGameStateST.class) {
this.logger.startLogging("SINGLETHREAD");
this.updateThread.start();
}
}
@Override
public void leave(GameContainer container, StateBasedGame game)
throws SlickException {
this.updateThread.interrupt();
try {
this.updateThread.join();
} catch (InterruptedException e) {
//Goggles
}
this.dummyLogger = null;
this.logger.stopLogging();
this.map = null;
this.towerBallast.clear();
this.creepBallast.clear();
this.towers.clear();
this.creeps.clear();
this.deadCreeps.clear();
this.newCreeps.clear();
}
@Override
public void render(GameContainer container, StateBasedGame game, Graphics g)
throws SlickException {
for (int i = 0; i < this.towerBallast.size(); ++i) {
this.towerBallast.get(i).draw(g);
}
for (int i = 0; i < this.creepBallast.size(); ++i) {
this.creepBallast.get(i).draw(g);
}
if (this.map != null) {
this.tileSize.write(new CopyableDimension(container.getWidth() / this.map.getWidth(), container.getHeight() / this.map.getHeight()));
this.map.render(container, g);
}
}
@Override
public void update(GameContainer container, StateBasedGame game, int delta)
throws SlickException {
Input input = container.getInput();
Vector2f relativeInput = new Vector2f((float) input.getMouseX() / (float) container.getWidth(),
(float) input.getMouseY() / (float) container.getHeight());
if (input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
CopyablePoint towerPos = new CopyablePoint((int) Math.floor(relativeInput.x * this.map.getWidth()),
(int) Math.floor(relativeInput.y * this.map.getHeight()));
Tower t = this.map.spawnTower(towerPos, this.creepPositions, this.tileSize, this);
if (t != null) {
this.towers.add(t);
}
}
this.elapsed += delta/1000.0f;
if (input.isKeyPressed(Input.KEY_ESCAPE) || this.elapsed >= 70.0f) {
game.enterState(BofSA.States.MAINMENU.ordinal());
}
}
public void update(final float delta) {
// Game logic
while (!this.newCreeps.isEmpty()) {
Creep c = this.newCreeps.poll();
this.creeps.add(c);
}
this.map.update(this, delta);
this.dummyLogger.taskRun("Spawn");
for (final Tower t : this.towers) {
t.update(delta);
dummyLogger.taskRun("Attack");
dummyLogger.taskRun("Render");
}
for (final Creep c : this.creeps) {
c.update(this, delta);
dummyLogger.taskRun("Move");
dummyLogger.taskRun("Velocity");
dummyLogger.taskRun("Collision");
dummyLogger.taskRun("Waypoint");
dummyLogger.taskRun("Health");
dummyLogger.taskRun("Render");
}
while (!this.deadCreeps.isEmpty()) {
Creep c = this.deadCreeps.poll();
this.creeps.remove(c);
}
this.logger.taskRun("Update");
}
@Override
public void run() {
long last = System.nanoTime();
while (!Thread.currentThread().isInterrupted()) {
long current = System.nanoTime();
this.update((current - last) / 1E9f);
last = current;
}
}
@Override
public void onDeath(Creep c) {
this.deadCreeps.add(c);
}
@Override
public void onSpawn(Creep c) {
this.newCreeps.add(c);
}
@Override
public void spawnCreep(
CopyableVector2f position,
Queue<CheckPoint> checkpoints) {
Creep c = new Creep();
CreepFactoryBehaviour.spawnCreep(
position,
checkpoints,
c,
c,
tileSize,
this,
this.creepPositions);
this.onSpawn(c);
}
@Override
public void handleEvent(Event event) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(int button, int x, int y, int clickCount) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(int oldx, int oldy, int newx, int newy) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(int oldx, int oldy, int newx, int newy) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(int button, int x, int y) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(int button, int x, int y) {
// TODO Auto-generated method stub
}
@Override
public void mouseWheelMoved(int change) {
// TODO Auto-generated method stub
}
@Override
public void inputEnded() {
// TODO Auto-generated method stub
}
@Override
public void inputStarted() {
// TODO Auto-generated method stub
}
@Override
public boolean isAcceptingInput() {
// TODO Auto-generated method stub
return false;
}
@Override
public void setInput(Input input) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(int key, char c) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(int key, char c) {
// TODO Auto-generated method stub
}
@Override
public void controllerButtonPressed(int controller, int button) {
// TODO Auto-generated method stub
}
@Override
public void controllerButtonReleased(int controller, int button) {
// TODO Auto-generated method stub
}
@Override
public void controllerDownPressed(int controller) {
// TODO Auto-generated method stub
}
@Override
public void controllerDownReleased(int controller) {
// TODO Auto-generated method stub
}
@Override
public void controllerLeftPressed(int controller) {
// TODO Auto-generated method stub
}
@Override
public void controllerLeftReleased(int controller) {
// TODO Auto-generated method stub
}
@Override
public void controllerRightPressed(int controller) {
// TODO Auto-generated method stub
}
@Override
public void controllerRightReleased(int controller) {
// TODO Auto-generated method stub
}
@Override
public void controllerUpPressed(int controller) {
// TODO Auto-generated method stub
}
@Override
public void controllerUpReleased(int controller) {
// TODO Auto-generated method stub
}
@Override
public int compareTo(Object o) {
return this.hashCode() - o.hashCode();
}
}
| true | true | public void enter(GameContainer container, StateBasedGame game)
throws SlickException {
try {
this.map = new GameLevelST("test");
} catch (SlickException e) {
e.printStackTrace();
}
this.elapsed = 0;
this.updateThread = new Thread(this);
{
CopyablePoint dummy = new CopyablePoint(0,0);
Tower t = null;
for (int i = 0; i < this.map.getHeight() * this.map.getWidth(); ++i) {
t = new Tower(dummy);
TowerFactoryBehaviour.createTower(dummy, this.creepPositions, t, this.tileSize, this);
this.towerBallast.add(t);
}
}
Signal<CopyableList<Pipe<CopyableVector2f>>> tempSignal = new Signal<CopyableList<Pipe<CopyableVector2f>>>(new CopyableList<Pipe<CopyableVector2f>>());
{
CopyableVector2f dummy = new CopyableVector2f(1,1);
Queue<CheckPoint> cps = new LinkedList<CheckPoint>();
cps.add(new CheckPoint(0, dummy));
Creep c = null;
for (int i = 0; i < 1024; ++i) {
c = new Creep();
CreepFactoryBehaviour.spawnCreep(dummy, cps, c, c, this.tileSize, this, tempSignal);
this.creepBallast.add(c);
}
}
{
CopyablePoint dummy = new CopyablePoint(0,0);
Tower t = null;
for (int i = 0; i < this.numTowers; ++i) {
TowerFactoryBehaviour.createTower(dummy, this.creepPositions, t, this.tileSize, null);
this.towers.add(t);
}
}
this.logger.setLogMode(this.logMode);
this.dummyLogger = new Logger();
this.dummyLogger.setLogMode(this.logMode);
if (this.getClass() == InGameStateST.class) {
this.logger.startLogging("SINGLETHREAD");
this.updateThread.start();
}
}
| public void enter(GameContainer container, StateBasedGame game)
throws SlickException {
try {
this.map = new GameLevelST("test");
} catch (SlickException e) {
e.printStackTrace();
}
this.elapsed = 0;
this.updateThread = new Thread(this);
{
CopyablePoint dummy = new CopyablePoint(0,0);
Tower t = null;
for (int i = 0; i < this.map.getHeight() * this.map.getWidth(); ++i) {
t = new Tower(dummy);
TowerFactoryBehaviour.createTower(dummy, this.creepPositions, t, this.tileSize, this);
this.towerBallast.add(t);
}
}
Signal<CopyableList<Pipe<CopyableVector2f>>> tempSignal = new Signal<CopyableList<Pipe<CopyableVector2f>>>(new CopyableList<Pipe<CopyableVector2f>>());
{
CopyableVector2f dummy = new CopyableVector2f(1,1);
Queue<CheckPoint> cps = new LinkedList<CheckPoint>();
cps.add(new CheckPoint(0, dummy));
Creep c = null;
for (int i = 0; i < 1024; ++i) {
c = new Creep();
CreepFactoryBehaviour.spawnCreep(dummy, cps, c, c, this.tileSize, this, tempSignal);
this.creepBallast.add(c);
}
}
{
CopyablePoint dummy = new CopyablePoint(0,0);
Tower t = null;
for (int i = 0; i < this.numTowers; ++i) {
t = new Tower(dummy);
TowerFactoryBehaviour.createTower(dummy, this.creepPositions, t, this.tileSize, this);
this.towers.add(t);
}
}
this.logger.setLogMode(this.logMode);
this.dummyLogger = new Logger();
this.dummyLogger.setLogMode(this.logMode);
if (this.getClass() == InGameStateST.class) {
this.logger.startLogging("SINGLETHREAD");
this.updateThread.start();
}
}
|
diff --git a/osl-slql-console/src/test/java/org/openspotlight/graph/query/console/command/ExampleRemoteServerWithData.java b/osl-slql-console/src/test/java/org/openspotlight/graph/query/console/command/ExampleRemoteServerWithData.java
index fc3f64c98..44a508b63 100644
--- a/osl-slql-console/src/test/java/org/openspotlight/graph/query/console/command/ExampleRemoteServerWithData.java
+++ b/osl-slql-console/src/test/java/org/openspotlight/graph/query/console/command/ExampleRemoteServerWithData.java
@@ -1,325 +1,325 @@
/*
* OpenSpotLight - Open Source IT Governance Platform
*
* Copyright (c) 2009, CARAVELATECH CONSULTORIA E TECNOLOGIA EM INFORMATICA LTDA
* or third-party contributors as indicated by the @author tags or express
* copyright attribution statements applied by the authors. All third-party
* contributions are distributed under license by CARAVELATECH CONSULTORIA E
* TECNOLOGIA EM INFORMATICA LTDA.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
***********************************************************************
* OpenSpotLight - Plataforma de Governança de TI de Código Aberto
*
* Direitos Autorais Reservados (c) 2009, CARAVELATECH CONSULTORIA E TECNOLOGIA
* EM INFORMATICA LTDA ou como contribuidores terceiros indicados pela etiqueta
* @author ou por expressa atribuição de direito autoral declarada e atribuída pelo autor.
* Todas as contribuições de terceiros estão distribuídas sob licença da
* CARAVELATECH CONSULTORIA E TECNOLOGIA EM INFORMATICA LTDA.
*
* Este programa é software livre; você pode redistribuí-lo e/ou modificá-lo sob os
* termos da Licença Pública Geral Menor do GNU conforme publicada pela Free Software
* Foundation.
*
* Este programa é distribuído na expectativa de que seja útil, porém, SEM NENHUMA
* GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU ADEQUAÇÃO A UMA
* FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor do GNU para mais detalhes.
*
* Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto com este
* programa; se não, escreva para:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.openspotlight.graph.query.console.command;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.openspotlight.common.exception.SLException;
import org.openspotlight.common.util.Files;
import org.openspotlight.graph.*;
import org.openspotlight.graph.annotation.SLVisibility.VisibilityLevel;
import org.openspotlight.graph.guice.SLGraphModule;
import org.openspotlight.graph.query.console.GraphConnection;
import org.openspotlight.graph.query.console.test.domain.*;
import org.openspotlight.graph.server.RemoteGraphSessionServer;
import org.openspotlight.jcr.provider.DefaultJcrDescriptor;
import org.openspotlight.persist.guice.SimplePersistModule;
import org.openspotlight.remote.server.UserAuthenticator;
import org.openspotlight.security.SecurityFactory;
import org.openspotlight.security.idm.AuthenticatedUser;
import org.openspotlight.security.idm.User;
import org.openspotlight.security.idm.auth.IdentityException;
import org.openspotlight.storage.STStorageSession;
import org.openspotlight.storage.redis.guice.JRedisStorageModule;
import org.openspotlight.storage.redis.util.ExampleRedisConfig;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import static org.openspotlight.common.util.ClassPathResource.getResourceFromClassPath;
import static org.openspotlight.storage.STRepositoryPath.repositoryPath;
public class ExampleRemoteServerWithData {
private static SLGraph graph;
private static class ExampleDataSupport {
/**
* Adds the class implements interface links.
*
* @param root the root
* @param clazz the clazz
* @param javaClass the java class
* @param session the session
*/
private void addClassImplementsInterfaceLinks(final SLGraphSession session,
final SLNode root,
final Class<?> clazz,
final JavaClass javaClass) {
final Class<?>[] iFaces = clazz.getInterfaces();
for (final Class<?> iFace : iFaces) {
final Package iFacePack = iFace.getPackage();
final JavaPackage javaPackage = root.addNode(JavaPackage.class, iFacePack.getName());
javaPackage.setCaption(iFacePack.getName());
final JavaInterface javaInterface = javaPackage.addNode(JavaInterface.class, iFace.getName());
javaInterface.setCaption(iFace.getName());
session.addLink(ClassImplementsInterface.class, javaClass, javaInterface, false);
}
}
/**
* Adds the java class contains java class method.
*
* @param clazz the clazz
* @param javaClass the java class
* @param session the session
*/
private void addJavaClassContainsJavaClassMethod(final SLGraphSession session,
final Class<?> clazz,
final JavaClass javaClass) {
final Method[] methods = clazz.getDeclaredMethods();
for (final Method method : methods) {
final JavaTypeMethod javaTypeMethod = javaClass.addNode(JavaTypeMethod.class, method.getName());
javaTypeMethod.setCaption(method.getName());
session.addLink(TypeContainsMethod.class, javaClass, javaTypeMethod, false);
}
}
/**
* Adds the java class hirarchy links.
*
* @param root the root
* @param clazz the clazz
* @param javaClass the java class
* @param session the session
*/
private void addJavaClassHirarchyLinks(final SLGraphSession session,
final SLNode root,
final Class<?> clazz,
final JavaClass javaClass) {
final Class<?> superClass = clazz.getSuperclass();
if (superClass != null) {
final Package classPack = clazz.getPackage();
final JavaPackage javaPackage = root.addNode(JavaPackage.class, classPack.getName());
javaPackage.setCaption(classPack.getName());
final JavaClass superJavaClass = javaPackage.addNode(JavaClass.class, superClass.getName());
session.addLink(PackageContainsType.class, javaPackage, superJavaClass, false);
session.addLink(JavaClassHierarchy.class, javaClass, superJavaClass, false);
this.addJavaClassHirarchyLinks(session, root, superClass, superJavaClass);
}
}
/**
* Adds the java interface contains java method.
*
* @param iFace the i face
* @param javaInterface the java interface
* @param session the session
*/
private void addJavaInterfaceContainsJavaMethod(final SLGraphSession session,
final Class<?> iFace,
final JavaInterface javaInterface) {
final Method[] methods = iFace.getDeclaredMethods();
for (final Method method : methods) {
final JavaTypeMethod javaTypeMethod = javaInterface.addNode(JavaTypeMethod.class, method.getName());
javaTypeMethod.setCaption(method.getName());
session.addLink(TypeContainsMethod.class, javaInterface, javaTypeMethod, false);
}
}
/**
* Adds the java interface hirarchy links.
*
* @param root the root
* @param iFace the i face
* @param javaInterface the java interface
* @param session the session
*/
private void addJavaInterfaceHirarchyLinks(final SLGraphSession session,
final SLNode root,
final Class<?> iFace,
final JavaInterface javaInterface) {
final Class<?>[] superIFaces = iFace.getInterfaces();
for (final Class<?> superIFace : superIFaces) {
final Package iFacePack = iFace.getPackage();
final JavaPackage javaPackage = root.addNode(JavaPackage.class, iFacePack.getName());
javaPackage.setCaption(iFacePack.getName());
final JavaInterface superJavaInterface = javaPackage.addNode(JavaInterface.class, superIFace.getName());
session.addLink(PackageContainsType.class, javaPackage, superJavaInterface, false);
superJavaInterface.setCaption(superIFace.getName());
session.addLink(JavaInterfaceHierarchy.class, javaInterface, superJavaInterface, false);
this.addJavaInterfaceHirarchyLinks(session, root, superIFace, superJavaInterface);
}
}
/**
* Load classes.
*
* @param fileName the file name
* @return the collection< class<?>>
* @throws SLException the SL exception
* @throws IOException Signals that an I/O exception has occurred.
* @throws ClassNotFoundException the class not found exception
*/
private Collection<Class<?>> loadClasses(final String fileName) throws SLException, IOException, ClassNotFoundException {
final Collection<Class<?>> classes = new ArrayList<Class<?>>();
final String packagePath = GraphConnection.class.getPackage().getName().replace('.', '/');
final String filePath = packagePath + '/' + fileName;
final InputStream inputStream = getResourceFromClassPath(filePath);
final Collection<String> names = Files.readLines(inputStream);
inputStream.close();
for (final String name : names) {
final String className = "java.util.".concat(name).trim();
final Class<?> clazz = Class.forName(className);
classes.add(clazz);
}
return classes;
}
/**
* Gets the populated graph. This method is temporary and used just for testing purpose!
*
* @return the populated graph
* @throws SLException the SL exception
* @throws IOException Signals that an I/O exception has occurred.
* @throws ClassNotFoundException the class not found exception
*/
public void populateGraph() throws SLException, IOException, ClassNotFoundException, IdentityException {
Injector injector = Guice.createInjector(new JRedisStorageModule(STStorageSession.STFlushMode.AUTO,
ExampleRedisConfig.EXAMPLE.getMappedServerConfig(),
- repositoryPath("repository")),
+ repositoryPath(SLConsts.DEFAULT_REPOSITORY_NAME)),
new SimplePersistModule(), new SLGraphModule(DefaultJcrDescriptor.TEMP_DESCRIPTOR));
graph = injector.getInstance(SLGraph.class);
final SecurityFactory securityFactory = injector.getInstance(SecurityFactory.class);
final User simpleUser = securityFactory.createUser("testUser");
AuthenticatedUser user = securityFactory.createIdentityManager(DefaultJcrDescriptor.TEMP_DESCRIPTOR).authenticate(simpleUser, "password");
final SLGraphSession session = graph.openSession(user, SLConsts.DEFAULT_REPOSITORY_NAME);
final Collection<Class<?>> iFaces = this.loadClasses("java-util-interfaces.txt");
final Collection<Class<?>> classes = this.loadClasses("java-util-classes.txt");
SLContext context = null;
- if (session.getContext("queryTest") == null) {
+// if (session.getContext("queryTest") == null) {
context = session.createContext("queryTest");
SLNode root = context.getRootNode();
final Package pack = java.util.Date.class.getPackage();
final JavaPackage utilJavaPackage = root.addNode(JavaPackage.class, pack.getName());
utilJavaPackage.setCaption(pack.getName());
int count = 0;
final float floatValue = 0.3F;
for (final Class<?> iFace : iFaces) {
final JavaInterface javaInterface = utilJavaPackage.addNode(JavaInterface.class, iFace.getName());
session.addLink(PackageContainsType.class, utilJavaPackage, javaInterface, false);
javaInterface.setCaption(iFace.getName());
javaInterface.setProperty(Integer.class, VisibilityLevel.PUBLIC, "intValue", count);
javaInterface.setProperty(Float.class, VisibilityLevel.PUBLIC, "decValue", new Float(count + floatValue));
javaInterface.setProperty(Boolean.class, VisibilityLevel.PUBLIC, "boolValue", new Boolean(true));
this.addJavaInterfaceHirarchyLinks(session, root, iFace, javaInterface);
this.addJavaInterfaceContainsJavaMethod(session, iFace, javaInterface);
count++;
}
count = 0;
for (final Class<?> clazz : classes) {
// context = session.createContext("queryTest2");
root = context.getRootNode();
final JavaClass javaClass = utilJavaPackage.addNode(JavaClass.class, clazz.getName());
session.addLink(PackageContainsType.class, utilJavaPackage, javaClass, false);
javaClass.setCaption(clazz.getName());
javaClass.setProperty(Integer.class, VisibilityLevel.PUBLIC, "intValue", count);
javaClass.setProperty(Float.class, VisibilityLevel.PUBLIC, "decValue", new Float(count + floatValue));
javaClass.setProperty(Boolean.class, VisibilityLevel.PUBLIC, "boolValue", new Boolean(false));
this.addJavaClassHirarchyLinks(session, root, clazz, javaClass);
this.addClassImplementsInterfaceLinks(session, root, clazz, javaClass);
this.addJavaClassContainsJavaClassMethod(session, clazz, javaClass);
count++;
}
session.save();
- }
+// }
session.close();
}
}
public static void main(final String... args) throws Exception {
RemoteGraphSessionServer server = null;
try {
server = populateSomeDataAndStartTheServer();
while (true) {
Thread.sleep(5000);
}
} finally {
if (server != null) {
server.shutdown();
}
}
}
public static RemoteGraphSessionServer populateSomeDataAndStartTheServer() throws Exception {
new ExampleDataSupport().populateGraph();
return new RemoteGraphSessionServer(new UserAuthenticator() {
public boolean canConnect(final String userName,
final String password,
final String clientHost) {
return true;
}
public boolean equals(final Object o) {
return this.getClass().equals(o.getClass());
}
}, 7070, 60 * 1000 * 10L, DefaultJcrDescriptor.TEMP_DESCRIPTOR, graph);
}
}
| false | true | public void populateGraph() throws SLException, IOException, ClassNotFoundException, IdentityException {
Injector injector = Guice.createInjector(new JRedisStorageModule(STStorageSession.STFlushMode.AUTO,
ExampleRedisConfig.EXAMPLE.getMappedServerConfig(),
repositoryPath("repository")),
new SimplePersistModule(), new SLGraphModule(DefaultJcrDescriptor.TEMP_DESCRIPTOR));
graph = injector.getInstance(SLGraph.class);
final SecurityFactory securityFactory = injector.getInstance(SecurityFactory.class);
final User simpleUser = securityFactory.createUser("testUser");
AuthenticatedUser user = securityFactory.createIdentityManager(DefaultJcrDescriptor.TEMP_DESCRIPTOR).authenticate(simpleUser, "password");
final SLGraphSession session = graph.openSession(user, SLConsts.DEFAULT_REPOSITORY_NAME);
final Collection<Class<?>> iFaces = this.loadClasses("java-util-interfaces.txt");
final Collection<Class<?>> classes = this.loadClasses("java-util-classes.txt");
SLContext context = null;
if (session.getContext("queryTest") == null) {
context = session.createContext("queryTest");
SLNode root = context.getRootNode();
final Package pack = java.util.Date.class.getPackage();
final JavaPackage utilJavaPackage = root.addNode(JavaPackage.class, pack.getName());
utilJavaPackage.setCaption(pack.getName());
int count = 0;
final float floatValue = 0.3F;
for (final Class<?> iFace : iFaces) {
final JavaInterface javaInterface = utilJavaPackage.addNode(JavaInterface.class, iFace.getName());
session.addLink(PackageContainsType.class, utilJavaPackage, javaInterface, false);
javaInterface.setCaption(iFace.getName());
javaInterface.setProperty(Integer.class, VisibilityLevel.PUBLIC, "intValue", count);
javaInterface.setProperty(Float.class, VisibilityLevel.PUBLIC, "decValue", new Float(count + floatValue));
javaInterface.setProperty(Boolean.class, VisibilityLevel.PUBLIC, "boolValue", new Boolean(true));
this.addJavaInterfaceHirarchyLinks(session, root, iFace, javaInterface);
this.addJavaInterfaceContainsJavaMethod(session, iFace, javaInterface);
count++;
}
count = 0;
for (final Class<?> clazz : classes) {
// context = session.createContext("queryTest2");
root = context.getRootNode();
final JavaClass javaClass = utilJavaPackage.addNode(JavaClass.class, clazz.getName());
session.addLink(PackageContainsType.class, utilJavaPackage, javaClass, false);
javaClass.setCaption(clazz.getName());
javaClass.setProperty(Integer.class, VisibilityLevel.PUBLIC, "intValue", count);
javaClass.setProperty(Float.class, VisibilityLevel.PUBLIC, "decValue", new Float(count + floatValue));
javaClass.setProperty(Boolean.class, VisibilityLevel.PUBLIC, "boolValue", new Boolean(false));
this.addJavaClassHirarchyLinks(session, root, clazz, javaClass);
this.addClassImplementsInterfaceLinks(session, root, clazz, javaClass);
this.addJavaClassContainsJavaClassMethod(session, clazz, javaClass);
count++;
}
session.save();
}
session.close();
}
| public void populateGraph() throws SLException, IOException, ClassNotFoundException, IdentityException {
Injector injector = Guice.createInjector(new JRedisStorageModule(STStorageSession.STFlushMode.AUTO,
ExampleRedisConfig.EXAMPLE.getMappedServerConfig(),
repositoryPath(SLConsts.DEFAULT_REPOSITORY_NAME)),
new SimplePersistModule(), new SLGraphModule(DefaultJcrDescriptor.TEMP_DESCRIPTOR));
graph = injector.getInstance(SLGraph.class);
final SecurityFactory securityFactory = injector.getInstance(SecurityFactory.class);
final User simpleUser = securityFactory.createUser("testUser");
AuthenticatedUser user = securityFactory.createIdentityManager(DefaultJcrDescriptor.TEMP_DESCRIPTOR).authenticate(simpleUser, "password");
final SLGraphSession session = graph.openSession(user, SLConsts.DEFAULT_REPOSITORY_NAME);
final Collection<Class<?>> iFaces = this.loadClasses("java-util-interfaces.txt");
final Collection<Class<?>> classes = this.loadClasses("java-util-classes.txt");
SLContext context = null;
// if (session.getContext("queryTest") == null) {
context = session.createContext("queryTest");
SLNode root = context.getRootNode();
final Package pack = java.util.Date.class.getPackage();
final JavaPackage utilJavaPackage = root.addNode(JavaPackage.class, pack.getName());
utilJavaPackage.setCaption(pack.getName());
int count = 0;
final float floatValue = 0.3F;
for (final Class<?> iFace : iFaces) {
final JavaInterface javaInterface = utilJavaPackage.addNode(JavaInterface.class, iFace.getName());
session.addLink(PackageContainsType.class, utilJavaPackage, javaInterface, false);
javaInterface.setCaption(iFace.getName());
javaInterface.setProperty(Integer.class, VisibilityLevel.PUBLIC, "intValue", count);
javaInterface.setProperty(Float.class, VisibilityLevel.PUBLIC, "decValue", new Float(count + floatValue));
javaInterface.setProperty(Boolean.class, VisibilityLevel.PUBLIC, "boolValue", new Boolean(true));
this.addJavaInterfaceHirarchyLinks(session, root, iFace, javaInterface);
this.addJavaInterfaceContainsJavaMethod(session, iFace, javaInterface);
count++;
}
count = 0;
for (final Class<?> clazz : classes) {
// context = session.createContext("queryTest2");
root = context.getRootNode();
final JavaClass javaClass = utilJavaPackage.addNode(JavaClass.class, clazz.getName());
session.addLink(PackageContainsType.class, utilJavaPackage, javaClass, false);
javaClass.setCaption(clazz.getName());
javaClass.setProperty(Integer.class, VisibilityLevel.PUBLIC, "intValue", count);
javaClass.setProperty(Float.class, VisibilityLevel.PUBLIC, "decValue", new Float(count + floatValue));
javaClass.setProperty(Boolean.class, VisibilityLevel.PUBLIC, "boolValue", new Boolean(false));
this.addJavaClassHirarchyLinks(session, root, clazz, javaClass);
this.addClassImplementsInterfaceLinks(session, root, clazz, javaClass);
this.addJavaClassContainsJavaClassMethod(session, clazz, javaClass);
count++;
}
session.save();
// }
session.close();
}
|
diff --git a/src/main/java/org/atlasapi/remotesite/space/TheSpacePlaylistProcessor.java b/src/main/java/org/atlasapi/remotesite/space/TheSpacePlaylistProcessor.java
index 37c8e37ac..ea94792f4 100644
--- a/src/main/java/org/atlasapi/remotesite/space/TheSpacePlaylistProcessor.java
+++ b/src/main/java/org/atlasapi/remotesite/space/TheSpacePlaylistProcessor.java
@@ -1,142 +1,142 @@
package org.atlasapi.remotesite.space;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.metabroadcast.common.http.SimpleHttpClient;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.atlasapi.media.entity.ChildRef;
import org.atlasapi.media.entity.Container;
import org.atlasapi.media.entity.Content;
import org.atlasapi.media.entity.ContentGroup;
import org.atlasapi.media.entity.Item;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.persistence.content.ContentGroupResolver;
import org.atlasapi.persistence.content.ContentGroupWriter;
import org.atlasapi.persistence.content.ContentResolver;
import org.atlasapi.persistence.content.ContentWriter;
import org.atlasapi.persistence.content.ResolvedContent;
import org.atlasapi.persistence.logging.AdapterLog;
import org.atlasapi.persistence.logging.AdapterLogEntry;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
/**
*/
public class TheSpacePlaylistProcessor {
private final String BASE_CANONICAL_URI = "http://thespace.org/items/";
private final Function<Content, ChildRef> CONTENT_TO_CHILD_REF = new ContentToChildRef();
//
private final SimpleHttpClient client;
private final AdapterLog log;
private final ContentResolver contentResolver;
private final ContentWriter contentWriter;
private final ContentGroupResolver groupResolver;
private final ContentGroupWriter groupWriter;
public TheSpacePlaylistProcessor(SimpleHttpClient client, AdapterLog log, ContentResolver contentResolver, ContentWriter contentWriter, ContentGroupResolver groupResolver, ContentGroupWriter groupWriter) {
this.client = client;
this.log = log;
this.contentResolver = contentResolver;
this.contentWriter = contentWriter;
this.groupResolver = groupResolver;
this.groupWriter = groupWriter;
}
public void process(JsonNode item) throws Exception {
ObjectMapper mapper = new ObjectMapper();
//
String pid = item.get("pid").asText();
//
ContentGroup playlist = (ContentGroup) groupResolver.findByCanonicalUris(ImmutableSet.of(getCanonicalUri(pid))).getFirstValue().valueOrNull();
if (playlist == null) {
playlist = new ContentGroup(getCanonicalUri(pid));
playlist.setType(ContentGroup.Type.PLAYLIST);
}
makePlaylist(playlist, item, mapper);
}
private void makePlaylist(ContentGroup playlist, JsonNode node, ObjectMapper mapper) throws Exception {
try {
JsonNode pid = node.get("pid");
playlist.setCanonicalUri(getCanonicalUri(pid.asText()));
playlist.setPublisher(Publisher.THESPACE);
JsonNode long_synopsis = node.get("long_synopsis");
JsonNode medium_synopsis = node.get("medium_synopsis");
JsonNode short_synopsis = node.get("short_synopsis");
String synopsis = null;
if (long_synopsis != null) {
synopsis = long_synopsis.asText();
} else if (medium_synopsis != null) {
synopsis = medium_synopsis.asText();
} else if (short_synopsis != null) {
synopsis = short_synopsis.asText();
}
playlist.setDescription(synopsis);
JsonNode image = node.get("image");
if (image != null) {
JsonNode smallImage = image.get("depiction_320");
if (smallImage != null) {
playlist.setThumbnail(smallImage.asText());
}
JsonNode bigImage = image.get("depiction_640");
if (bigImage != null) {
playlist.setImage(bigImage.asText());
}
}
Iterable<Content> contents = getContents(node);
playlist.setContents(Iterables.transform(contents, CONTENT_TO_CHILD_REF));
groupWriter.createOrUpdate(playlist);
for (Content content : contents) {
if (!content.getContentGroupRefs().contains(playlist.contentGroupRef())) {
content.addContentGroup(playlist.contentGroupRef());
- if (contents instanceof Item) {
+ if (content instanceof Item) {
contentWriter.createOrUpdate((Item) contents);
- } else if (contents instanceof Container) {
+ } else if (content instanceof Container) {
contentWriter.createOrUpdate((Container) contents);
} else {
throw new IllegalStateException("Unexpected content type: " + contents.getClass().getName());
}
}
}
} catch (Exception ex) {
log.record(new AdapterLogEntry(AdapterLogEntry.Severity.WARN).withDescription("Failed ingesting playlist: " + playlist.getCanonicalUri()).withSource(getClass()));
throw ex;
}
}
private Iterable<Content> getContents(JsonNode node) throws Exception {
List<Content> result = new LinkedList<Content>();
Iterator<JsonNode> contents = node.get("children").getElements();
while (contents.hasNext()) {
JsonNode content = contents.next();
String cPid = content.get("pid").asText();
ResolvedContent episode = contentResolver.findByCanonicalUris(ImmutableList.of(getCanonicalUri(cPid)));
if (!episode.isEmpty()) {
result.add((Content) episode.getFirstValue().requireValue());
}
}
return result;
}
private String getCanonicalUri(String pid) {
return BASE_CANONICAL_URI + pid;
}
private class ContentToChildRef implements Function<Content, ChildRef> {
@Override
public ChildRef apply(Content input) {
return input.childRef();
}
}
}
| false | true | private void makePlaylist(ContentGroup playlist, JsonNode node, ObjectMapper mapper) throws Exception {
try {
JsonNode pid = node.get("pid");
playlist.setCanonicalUri(getCanonicalUri(pid.asText()));
playlist.setPublisher(Publisher.THESPACE);
JsonNode long_synopsis = node.get("long_synopsis");
JsonNode medium_synopsis = node.get("medium_synopsis");
JsonNode short_synopsis = node.get("short_synopsis");
String synopsis = null;
if (long_synopsis != null) {
synopsis = long_synopsis.asText();
} else if (medium_synopsis != null) {
synopsis = medium_synopsis.asText();
} else if (short_synopsis != null) {
synopsis = short_synopsis.asText();
}
playlist.setDescription(synopsis);
JsonNode image = node.get("image");
if (image != null) {
JsonNode smallImage = image.get("depiction_320");
if (smallImage != null) {
playlist.setThumbnail(smallImage.asText());
}
JsonNode bigImage = image.get("depiction_640");
if (bigImage != null) {
playlist.setImage(bigImage.asText());
}
}
Iterable<Content> contents = getContents(node);
playlist.setContents(Iterables.transform(contents, CONTENT_TO_CHILD_REF));
groupWriter.createOrUpdate(playlist);
for (Content content : contents) {
if (!content.getContentGroupRefs().contains(playlist.contentGroupRef())) {
content.addContentGroup(playlist.contentGroupRef());
if (contents instanceof Item) {
contentWriter.createOrUpdate((Item) contents);
} else if (contents instanceof Container) {
contentWriter.createOrUpdate((Container) contents);
} else {
throw new IllegalStateException("Unexpected content type: " + contents.getClass().getName());
}
}
}
} catch (Exception ex) {
log.record(new AdapterLogEntry(AdapterLogEntry.Severity.WARN).withDescription("Failed ingesting playlist: " + playlist.getCanonicalUri()).withSource(getClass()));
throw ex;
}
}
| private void makePlaylist(ContentGroup playlist, JsonNode node, ObjectMapper mapper) throws Exception {
try {
JsonNode pid = node.get("pid");
playlist.setCanonicalUri(getCanonicalUri(pid.asText()));
playlist.setPublisher(Publisher.THESPACE);
JsonNode long_synopsis = node.get("long_synopsis");
JsonNode medium_synopsis = node.get("medium_synopsis");
JsonNode short_synopsis = node.get("short_synopsis");
String synopsis = null;
if (long_synopsis != null) {
synopsis = long_synopsis.asText();
} else if (medium_synopsis != null) {
synopsis = medium_synopsis.asText();
} else if (short_synopsis != null) {
synopsis = short_synopsis.asText();
}
playlist.setDescription(synopsis);
JsonNode image = node.get("image");
if (image != null) {
JsonNode smallImage = image.get("depiction_320");
if (smallImage != null) {
playlist.setThumbnail(smallImage.asText());
}
JsonNode bigImage = image.get("depiction_640");
if (bigImage != null) {
playlist.setImage(bigImage.asText());
}
}
Iterable<Content> contents = getContents(node);
playlist.setContents(Iterables.transform(contents, CONTENT_TO_CHILD_REF));
groupWriter.createOrUpdate(playlist);
for (Content content : contents) {
if (!content.getContentGroupRefs().contains(playlist.contentGroupRef())) {
content.addContentGroup(playlist.contentGroupRef());
if (content instanceof Item) {
contentWriter.createOrUpdate((Item) contents);
} else if (content instanceof Container) {
contentWriter.createOrUpdate((Container) contents);
} else {
throw new IllegalStateException("Unexpected content type: " + contents.getClass().getName());
}
}
}
} catch (Exception ex) {
log.record(new AdapterLogEntry(AdapterLogEntry.Severity.WARN).withDescription("Failed ingesting playlist: " + playlist.getCanonicalUri()).withSource(getClass()));
throw ex;
}
}
|
diff --git a/plexus-notification/src/test/java/org/codehaus/plexus/notification/NotificationDispatcherTest.java b/plexus-notification/src/test/java/org/codehaus/plexus/notification/NotificationDispatcherTest.java
index 47caa4c6..67d8d776 100644
--- a/plexus-notification/src/test/java/org/codehaus/plexus/notification/NotificationDispatcherTest.java
+++ b/plexus-notification/src/test/java/org/codehaus/plexus/notification/NotificationDispatcherTest.java
@@ -1,111 +1,111 @@
package org.codehaus.plexus.notification;
/*
* The MIT License
*
* Copyright (c) 2004, The Codehaus
*
* 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.
*/
import java.util.HashMap;
import java.util.Map;
import org.codehaus.plexus.PlexusTestCase;
import org.codehaus.plexus.notification.notifier.EenyNotifier;
import org.codehaus.plexus.notification.notifier.MeenyNotifier;
import org.codehaus.plexus.notification.notifier.Message;
import org.codehaus.plexus.notification.notifier.MinyNotifier;
import org.codehaus.plexus.notification.notifier.MoNotifier;
import org.codehaus.plexus.notification.notifier.manager.NotifierManager;
/**
* @author <a href="mailto:[email protected]">Trygve Laugstøl</a>
* @version $Id$
*/
public class NotificationDispatcherTest
extends PlexusTestCase
{
public void testBasic()
throws Exception
{
NotificationDispatcher notificationDispatcher = (NotificationDispatcher) lookup( NotificationDispatcher.ROLE );
NotifierManager notifierManager = (NotifierManager) lookup( NotifierManager.ROLE );
EenyNotifier eenyNotifier = (EenyNotifier) notifierManager.getNotifier( "eeny" );
MeenyNotifier meenyNotifier = (MeenyNotifier) notifierManager.getNotifier( "meeny" );
MinyNotifier minyNotifier = (MinyNotifier) notifierManager.getNotifier( "miny" );
MoNotifier moNotifier = (MoNotifier) notifierManager.getNotifier( "mo" );
// ----------------------------------------------------------------------
// Send message
// ----------------------------------------------------------------------
String messageId = "buildComplete";
Map context = new HashMap();
notificationDispatcher.sendNotification( messageId, context );
// ----------------------------------------------------------------------
// Assert
// ----------------------------------------------------------------------
assertEquals( 1, eenyNotifier.messages.size() );
assertEquals( 3, ( (Message) eenyNotifier.messages.get( 0 ) ).getRecipients().size() );
assertEquals( new String[]{ "brett", "jason", "trygve" },
(String[]) ( (Message) eenyNotifier.messages.get( 0 ) ).getRecipients().toArray( new String[ 3 ] ) );
assertEquals( 1, meenyNotifier.messages.size() );
assertEquals( 3, ( (Message) meenyNotifier.messages.get( 0 ) ).getRecipients().size() );
assertEquals( new String[]{ "bob", "brett", "jt" },
(String[]) ( (Message) meenyNotifier.messages.get( 0 ) ).getRecipients().toArray( new String[ 3 ] ) );
assertEquals( 1, minyNotifier.messages.size() );
assertEquals( 3, ( (Message) minyNotifier.messages.get( 0 ) ).getRecipients().size() );
assertEquals( new String[]{ "brett", "dan", "topping" },
(String[]) ( (Message) minyNotifier.messages.get( 0 ) ).getRecipients().toArray( new String[ 3 ] ) );
- assertEquals( 0, moNotifier.messages.size() );
+ assertEquals( 1, moNotifier.messages.size() );
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
private void assertEquals( String[] expected, String[] actual )
{
assertEquals( "Error in array length.", expected.length, actual.length );
for ( int i = 0; i < expected.length; i++ )
{
assertEquals( "Error in element #" + i, expected[ i ], actual[ i ] );
}
}
}
| true | true | public void testBasic()
throws Exception
{
NotificationDispatcher notificationDispatcher = (NotificationDispatcher) lookup( NotificationDispatcher.ROLE );
NotifierManager notifierManager = (NotifierManager) lookup( NotifierManager.ROLE );
EenyNotifier eenyNotifier = (EenyNotifier) notifierManager.getNotifier( "eeny" );
MeenyNotifier meenyNotifier = (MeenyNotifier) notifierManager.getNotifier( "meeny" );
MinyNotifier minyNotifier = (MinyNotifier) notifierManager.getNotifier( "miny" );
MoNotifier moNotifier = (MoNotifier) notifierManager.getNotifier( "mo" );
// ----------------------------------------------------------------------
// Send message
// ----------------------------------------------------------------------
String messageId = "buildComplete";
Map context = new HashMap();
notificationDispatcher.sendNotification( messageId, context );
// ----------------------------------------------------------------------
// Assert
// ----------------------------------------------------------------------
assertEquals( 1, eenyNotifier.messages.size() );
assertEquals( 3, ( (Message) eenyNotifier.messages.get( 0 ) ).getRecipients().size() );
assertEquals( new String[]{ "brett", "jason", "trygve" },
(String[]) ( (Message) eenyNotifier.messages.get( 0 ) ).getRecipients().toArray( new String[ 3 ] ) );
assertEquals( 1, meenyNotifier.messages.size() );
assertEquals( 3, ( (Message) meenyNotifier.messages.get( 0 ) ).getRecipients().size() );
assertEquals( new String[]{ "bob", "brett", "jt" },
(String[]) ( (Message) meenyNotifier.messages.get( 0 ) ).getRecipients().toArray( new String[ 3 ] ) );
assertEquals( 1, minyNotifier.messages.size() );
assertEquals( 3, ( (Message) minyNotifier.messages.get( 0 ) ).getRecipients().size() );
assertEquals( new String[]{ "brett", "dan", "topping" },
(String[]) ( (Message) minyNotifier.messages.get( 0 ) ).getRecipients().toArray( new String[ 3 ] ) );
assertEquals( 0, moNotifier.messages.size() );
}
| public void testBasic()
throws Exception
{
NotificationDispatcher notificationDispatcher = (NotificationDispatcher) lookup( NotificationDispatcher.ROLE );
NotifierManager notifierManager = (NotifierManager) lookup( NotifierManager.ROLE );
EenyNotifier eenyNotifier = (EenyNotifier) notifierManager.getNotifier( "eeny" );
MeenyNotifier meenyNotifier = (MeenyNotifier) notifierManager.getNotifier( "meeny" );
MinyNotifier minyNotifier = (MinyNotifier) notifierManager.getNotifier( "miny" );
MoNotifier moNotifier = (MoNotifier) notifierManager.getNotifier( "mo" );
// ----------------------------------------------------------------------
// Send message
// ----------------------------------------------------------------------
String messageId = "buildComplete";
Map context = new HashMap();
notificationDispatcher.sendNotification( messageId, context );
// ----------------------------------------------------------------------
// Assert
// ----------------------------------------------------------------------
assertEquals( 1, eenyNotifier.messages.size() );
assertEquals( 3, ( (Message) eenyNotifier.messages.get( 0 ) ).getRecipients().size() );
assertEquals( new String[]{ "brett", "jason", "trygve" },
(String[]) ( (Message) eenyNotifier.messages.get( 0 ) ).getRecipients().toArray( new String[ 3 ] ) );
assertEquals( 1, meenyNotifier.messages.size() );
assertEquals( 3, ( (Message) meenyNotifier.messages.get( 0 ) ).getRecipients().size() );
assertEquals( new String[]{ "bob", "brett", "jt" },
(String[]) ( (Message) meenyNotifier.messages.get( 0 ) ).getRecipients().toArray( new String[ 3 ] ) );
assertEquals( 1, minyNotifier.messages.size() );
assertEquals( 3, ( (Message) minyNotifier.messages.get( 0 ) ).getRecipients().size() );
assertEquals( new String[]{ "brett", "dan", "topping" },
(String[]) ( (Message) minyNotifier.messages.get( 0 ) ).getRecipients().toArray( new String[ 3 ] ) );
assertEquals( 1, moNotifier.messages.size() );
}
|
diff --git a/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java b/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java
index 3ff512b..ae383a8 100644
--- a/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java
+++ b/src/org/pentaho/agilebi/modeler/util/MultiTableModelerSource.java
@@ -1,253 +1,254 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2011 Pentaho Corporation.. All rights reserved.
*
* @author Ezequiel Cuellar
*/
package org.pentaho.agilebi.modeler.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.pentaho.agilebi.modeler.BaseModelerWorkspaceHelper;
import org.pentaho.agilebi.modeler.ModelerException;
import org.pentaho.agilebi.modeler.ModelerWorkspace;
import org.pentaho.agilebi.modeler.models.JoinRelationshipModel;
import org.pentaho.agilebi.modeler.models.JoinTableModel;
import org.pentaho.agilebi.modeler.models.SchemaModel;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.metadata.automodel.SchemaTable;
import org.pentaho.metadata.model.Domain;
import org.pentaho.metadata.model.LogicalColumn;
import org.pentaho.metadata.model.LogicalModel;
import org.pentaho.metadata.model.LogicalRelationship;
import org.pentaho.metadata.model.LogicalTable;
import org.pentaho.metadata.model.concept.types.LocalizedString;
import org.pentaho.metadata.model.concept.types.RelationshipType;
import org.pentaho.metadata.model.olap.OlapCube;
import org.pentaho.pms.core.exception.PentahoMetadataException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MultiTableModelerSource implements ISpoonModelerSource {
private ModelGenerator generator;
private DatabaseMeta databaseMeta;
private SchemaModel schemaModel;
private List<String> selectedTables;
private String datasourceName;
public static final String SOURCE_TYPE = MultiTableModelerSource.class.getSimpleName();
private static Logger logger = LoggerFactory.getLogger(MultiTableModelerSource.class);
public MultiTableModelerSource(DatabaseMeta databaseMeta, SchemaModel schemaModel, String datasourceName, List<String> selectedTables) {
this.datasourceName = datasourceName;
this.databaseMeta = databaseMeta;
this.schemaModel = schemaModel;
this.selectedTables = selectedTables;
this.generator = new ModelGenerator();
}
@Override
public Domain generateDomain(boolean doOlap) throws ModelerException {
Domain domain = null;
try {
// Generate domain based on the table names.
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
Set<String> usedTables = new HashSet<String>();
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
if(selectedTables.size() == 1){ // special single table story BISERVER-5806
schemas.add(new SchemaTable("", selectedTables.get(0)));
} else {
for(JoinRelationshipModel joinModel : schemaModel.getJoins()) {
String fromTable = joinModel.getLeftKeyFieldModel().getParentTable().getName();
String toTable = joinModel.getRightKeyFieldModel().getParentTable().getName();
if(!usedTables.contains(fromTable)){
schemas.add(new SchemaTable("", fromTable));
usedTables.add(fromTable);
}
if(!usedTables.contains(toTable)){
schemas.add(new SchemaTable("", toTable));
usedTables.add(toTable);
}
}
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setDomain(domain);
LogicalModel logicalModel = domain.getLogicalModels().get(0);
+ logicalModel.setProperty("AGILE_BI_GENERATED_SCHEMA", "TRUE");
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName)); // TODO do this with messages
workspace.setModelName(datasourceName);
helper.autoModelMultiTableRelational(workspace);
if(doOlap) {
helper.autoModelFlat(workspace);
}
helper.populateDomain(workspace);
for(LogicalTable businessTable : logicalModel.getLogicalTables()) {
businessTable.setName(new LocalizedString(locale, businessTable.getPhysicalTable().getName(locale)));
}
//Create olap tables
//BaseModelerWorkspaceHelper.duplicateLogicalTablesForDualModelingMode(logicalModel);
// Create and add LogicalRelationships to the LogicalModel from the
// domain.
generateLogicalRelationships(logicalModel, false);
if(doOlap) {
generateLogicalRelationships(logicalModel, true);
LogicalTable factTable = findFactTable(schemaModel.getFactTable(), logicalModel);
if(factTable == null) {
throw new IllegalStateException("Fact table not found");
}
List<OlapCube> cubes = (List) logicalModel.getProperty("olap_cubes");
OlapCube cube = cubes.get(0);
cube.setLogicalTable(factTable);
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
throw new ModelerException(e.getLocalizedMessage());
}
return domain;
}
private LogicalTable findFactTable(JoinTableModel table, LogicalModel logicalModel) {
LogicalTable factTable = null;
for (LogicalTable lTable : logicalModel.getLogicalTables()) {
if(lTable.getId().endsWith(BaseModelerWorkspaceHelper.OLAP_SUFFIX)) {
if(lTable.getPhysicalTable().getProperty("target_table").equals(table.getName())) {
lTable.getPhysicalTable().setProperty("FACT_TABLE", true);
factTable = lTable;
break;
}
}
}
return factTable;
}
private void generateLogicalRelationships(LogicalModel logicalModel, boolean doOlap) throws IllegalStateException {
for(JoinRelationshipModel joinModel : schemaModel.getJoins()) {
String lTable = joinModel.getLeftKeyFieldModel().getParentTable().getName();
String rTable = joinModel.getRightKeyFieldModel().getParentTable().getName();
LogicalTable fromTable = null;
LogicalColumn fromColumn = null;
LogicalTable toTable = null;
LogicalColumn toColumn = null;
for (LogicalTable logicalTable : logicalModel.getLogicalTables()) {
if(doOlap && !logicalTable.getId().endsWith(BaseModelerWorkspaceHelper.OLAP_SUFFIX)) {
continue;
} else if(!doOlap && logicalTable.getId().endsWith(BaseModelerWorkspaceHelper.OLAP_SUFFIX)) {
continue;
}
if (logicalTable.getPhysicalTable().getProperty("target_table").equals(lTable)) {
fromTable = logicalTable;
for (LogicalColumn logicalColumn : fromTable.getLogicalColumns()) {
if (logicalColumn.getPhysicalColumn().getProperty("target_column").equals(joinModel.getLeftKeyFieldModel().getName())) {
fromColumn = logicalColumn;
}
}
}
if (logicalTable.getPhysicalTable().getProperty("target_table").equals(rTable)) {
toTable = logicalTable;
for (LogicalColumn logicalColumn : toTable.getLogicalColumns()) {
if (logicalColumn.getPhysicalColumn().getProperty("target_column").equals(joinModel.getRightKeyFieldModel().getName())) {
toColumn = logicalColumn;
}
}
}
}
if(fromTable == null || fromColumn == null || toTable == null || toColumn == null) {
throw new IllegalStateException("Invalid Relationship");
}
LogicalRelationship logicalRelationship = new LogicalRelationship();
logicalRelationship.setRelationshipType(RelationshipType._1_1);
logicalRelationship.setFromTable(fromTable);
logicalRelationship.setFromColumn(fromColumn);
logicalRelationship.setToTable(toTable);
logicalRelationship.setToColumn(toColumn);
logicalModel.addLogicalRelationship(logicalRelationship);
}
}
@Override
public String getDatabaseName() {
String name = null;
if (this.databaseMeta != null) {
name = this.databaseMeta.getDatabaseName();
}
return name;
}
@Override
public void initialize(Domain domain) throws ModelerException {
}
@Override
public void serializeIntoDomain(Domain d) {
LogicalModel lm = d.getLogicalModels().get(0);
lm.setProperty("source_type", SOURCE_TYPE);
}
@Override
public String getSchemaName() {
return null;
}
@Override
public String getTableName() {
return null;
}
@Override
public DatabaseMeta getDatabaseMeta() {
return this.databaseMeta;
}
public Domain generateDomain() throws ModelerException {
return generateDomain(false);
}
}
| true | true | public Domain generateDomain(boolean doOlap) throws ModelerException {
Domain domain = null;
try {
// Generate domain based on the table names.
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
Set<String> usedTables = new HashSet<String>();
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
if(selectedTables.size() == 1){ // special single table story BISERVER-5806
schemas.add(new SchemaTable("", selectedTables.get(0)));
} else {
for(JoinRelationshipModel joinModel : schemaModel.getJoins()) {
String fromTable = joinModel.getLeftKeyFieldModel().getParentTable().getName();
String toTable = joinModel.getRightKeyFieldModel().getParentTable().getName();
if(!usedTables.contains(fromTable)){
schemas.add(new SchemaTable("", fromTable));
usedTables.add(fromTable);
}
if(!usedTables.contains(toTable)){
schemas.add(new SchemaTable("", toTable));
usedTables.add(toTable);
}
}
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setDomain(domain);
LogicalModel logicalModel = domain.getLogicalModels().get(0);
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName)); // TODO do this with messages
workspace.setModelName(datasourceName);
helper.autoModelMultiTableRelational(workspace);
if(doOlap) {
helper.autoModelFlat(workspace);
}
helper.populateDomain(workspace);
for(LogicalTable businessTable : logicalModel.getLogicalTables()) {
businessTable.setName(new LocalizedString(locale, businessTable.getPhysicalTable().getName(locale)));
}
//Create olap tables
//BaseModelerWorkspaceHelper.duplicateLogicalTablesForDualModelingMode(logicalModel);
// Create and add LogicalRelationships to the LogicalModel from the
// domain.
generateLogicalRelationships(logicalModel, false);
if(doOlap) {
generateLogicalRelationships(logicalModel, true);
LogicalTable factTable = findFactTable(schemaModel.getFactTable(), logicalModel);
if(factTable == null) {
throw new IllegalStateException("Fact table not found");
}
List<OlapCube> cubes = (List) logicalModel.getProperty("olap_cubes");
OlapCube cube = cubes.get(0);
cube.setLogicalTable(factTable);
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
throw new ModelerException(e.getLocalizedMessage());
}
return domain;
}
| public Domain generateDomain(boolean doOlap) throws ModelerException {
Domain domain = null;
try {
// Generate domain based on the table names.
String locale = LocalizedString.DEFAULT_LOCALE;
this.generator.setLocale(locale);
this.generator.setDatabaseMeta(databaseMeta);
this.generator.setModelName(datasourceName);
Set<String> usedTables = new HashSet<String>();
List<SchemaTable> schemas = new ArrayList<SchemaTable>();
if(selectedTables.size() == 1){ // special single table story BISERVER-5806
schemas.add(new SchemaTable("", selectedTables.get(0)));
} else {
for(JoinRelationshipModel joinModel : schemaModel.getJoins()) {
String fromTable = joinModel.getLeftKeyFieldModel().getParentTable().getName();
String toTable = joinModel.getRightKeyFieldModel().getParentTable().getName();
if(!usedTables.contains(fromTable)){
schemas.add(new SchemaTable("", fromTable));
usedTables.add(fromTable);
}
if(!usedTables.contains(toTable)){
schemas.add(new SchemaTable("", toTable));
usedTables.add(toTable);
}
}
}
SchemaTable tableNames[] = new SchemaTable[schemas.size()];
tableNames = schemas.toArray(tableNames);
this.generator.setTableNames(tableNames);
domain = this.generator.generateDomain();
domain.setId(datasourceName);
ModelerWorkspaceHelper helper = new ModelerWorkspaceHelper(locale);
ModelerWorkspace workspace = new ModelerWorkspace(helper);
workspace.setDomain(domain);
LogicalModel logicalModel = domain.getLogicalModels().get(0);
logicalModel.setProperty("AGILE_BI_GENERATED_SCHEMA", "TRUE");
logicalModel.setName(new LocalizedString(locale, datasourceName));
logicalModel.setDescription(new LocalizedString(locale, "This is the data model for "
+ datasourceName)); // TODO do this with messages
workspace.setModelName(datasourceName);
helper.autoModelMultiTableRelational(workspace);
if(doOlap) {
helper.autoModelFlat(workspace);
}
helper.populateDomain(workspace);
for(LogicalTable businessTable : logicalModel.getLogicalTables()) {
businessTable.setName(new LocalizedString(locale, businessTable.getPhysicalTable().getName(locale)));
}
//Create olap tables
//BaseModelerWorkspaceHelper.duplicateLogicalTablesForDualModelingMode(logicalModel);
// Create and add LogicalRelationships to the LogicalModel from the
// domain.
generateLogicalRelationships(logicalModel, false);
if(doOlap) {
generateLogicalRelationships(logicalModel, true);
LogicalTable factTable = findFactTable(schemaModel.getFactTable(), logicalModel);
if(factTable == null) {
throw new IllegalStateException("Fact table not found");
}
List<OlapCube> cubes = (List) logicalModel.getProperty("olap_cubes");
OlapCube cube = cubes.get(0);
cube.setLogicalTable(factTable);
}
} catch (Exception e) {
e.printStackTrace();
logger.info(e.getLocalizedMessage());
throw new ModelerException(e.getLocalizedMessage());
}
return domain;
}
|
diff --git a/src/main/java/org/tcgframework/JoinGameService.java b/src/main/java/org/tcgframework/JoinGameService.java
index 604b940..a1cf9f3 100644
--- a/src/main/java/org/tcgframework/JoinGameService.java
+++ b/src/main/java/org/tcgframework/JoinGameService.java
@@ -1,99 +1,99 @@
package org.tcgframework;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import javax.inject.Inject;
import org.cometd.annotation.Listener;
import org.cometd.annotation.Service;
import org.cometd.annotation.Session;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.tcgframework.resource.DominionGameState;
import org.tcgframework.resource.GameState;
@Service
public class JoinGameService {
//Instance Variables
HashMap<String, Object> users = new HashMap<String, Object>();
HashSet<String> usernames = new HashSet<String>();
HashMap<String, DominionGameState> games = new HashMap<String, DominionGameState>();
int gameID = 1;
@Session
private ServerSession session;
@Inject
private BayeuxServer bayeux;
//whenever a user joins the room
@Listener("/broadcast/waiting")
public void addUser(ServerSession session, ServerMessage message){
//add the owner
if (users.isEmpty()){
users.put("OWNER", message.getData().toString());
}
//add user to map -- assume username not in set
if(usernames.add(message.getData().toString())){
users.put("USERS", usernames);
}
//broadcast list to all users who are waiting
this.bayeux.createIfAbsent("/broadcast/waiting");
ServerChannel broadcastChannel = this.bayeux.getChannel("/broadcast/waiting");
broadcastChannel.publish(this.session, users , null);
System.out.println("Broadcasted List of Users");
}
//whenever owner starts a game
@Listener("/broadcast/startgame")
public void startGame(ServerSession session, ServerMessage message){
//add a new game to games
games.put("/game/"+ this.gameID, new DominionGameState(this.gameID, (HashSet<String>) usernames.clone()));
//broadcast to all users that a new game started
this.bayeux.createIfAbsent("/broadcast/waiting");
ServerChannel broadcastChannel = this.bayeux.getChannel("/broadcast/waiting");
broadcastChannel.publish(this.session, this.gameID, "start");
//empty out the users list
users.clear();
usernames.clear();
this.gameID++;
System.out.println("Game has started, Users have been cleared");
}
//GAME LISTENERS
@Listener("/game/*")
public void gameHandler(ServerSession sender, ServerMessage message){
System.out.println("caught a message");
DominionGameState state = games.get(message.getChannel());
if (message.getData().toString().equals("iam_ready")){
System.out.println("Channel: " + message.getChannel());
- sender.deliver(this.session, message.getChannel(), state.players, null);
+ sender.deliver(this.session, message.getChannel(), state, "gamestate");
} else if (message.getData().toString().equals("phase_change")){
//progress phase
state.nextPhase();
//send gamestate
ServerChannel broadcastChannel = this.bayeux.getChannel(message.getChannel());
broadcastChannel.publish(this.session, state, "gamestate");
} else if (message.getData().toString().equals("do_card")){
}
}
}
| true | true | public void gameHandler(ServerSession sender, ServerMessage message){
System.out.println("caught a message");
DominionGameState state = games.get(message.getChannel());
if (message.getData().toString().equals("iam_ready")){
System.out.println("Channel: " + message.getChannel());
sender.deliver(this.session, message.getChannel(), state.players, null);
} else if (message.getData().toString().equals("phase_change")){
//progress phase
state.nextPhase();
//send gamestate
ServerChannel broadcastChannel = this.bayeux.getChannel(message.getChannel());
broadcastChannel.publish(this.session, state, "gamestate");
} else if (message.getData().toString().equals("do_card")){
}
}
| public void gameHandler(ServerSession sender, ServerMessage message){
System.out.println("caught a message");
DominionGameState state = games.get(message.getChannel());
if (message.getData().toString().equals("iam_ready")){
System.out.println("Channel: " + message.getChannel());
sender.deliver(this.session, message.getChannel(), state, "gamestate");
} else if (message.getData().toString().equals("phase_change")){
//progress phase
state.nextPhase();
//send gamestate
ServerChannel broadcastChannel = this.bayeux.getChannel(message.getChannel());
broadcastChannel.publish(this.session, state, "gamestate");
} else if (message.getData().toString().equals("do_card")){
}
}
|
diff --git a/src/main/java/ohtu/radioaine/controller/TestDBController.java b/src/main/java/ohtu/radioaine/controller/TestDBController.java
index 851931b..27b2f2a 100644
--- a/src/main/java/ohtu/radioaine/controller/TestDBController.java
+++ b/src/main/java/ohtu/radioaine/controller/TestDBController.java
@@ -1,85 +1,88 @@
package ohtu.radioaine.controller;
import ohtu.radioaine.domain.Batch;
import ohtu.radioaine.domain.Event;
import ohtu.radioaine.domain.Substance;
import ohtu.radioaine.service.BatchService;
import ohtu.radioaine.service.EventService;
import ohtu.radioaine.service.SubstanceService;
import ohtu.radioaine.tools.EventHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* Creates a test database
*
* @author Radioaine
*
*/
@Controller
public class TestDBController {
@Autowired
private SubstanceService substanceService;
@Autowired
private BatchService batchService;
@Autowired
private EventService eventService;
private String[][] substances = {{"Angiocis 20.12mg 5 inj.plo", "10", "12", "true", "false", "Lääkefirma Jamppa", "Magnum Medical Finland Oy", "0"},
{"Bridatec kittipakkaus 5 inj.plo", "3", "4", "false", "true", "Lääkefirma Perttilä", "Oy GE Healthcare Bio-Sciences Ab", "0"},
{"Ceretec Exametazine Agent kittipakkaus 5 inj.plo", "3", "4", "false", "true", "Lääkefirma Perttilä", "Oy GE Healthcare Bio-Sciences Ab", "0"},
{"Geneerinen generaattori", "3", "4", "true", "false", "Lääkefirma Perttilä", "Oy GE Healthcare Bio-Sciences Ab", "1"},
{"Suolaliuos plo", "3", "4", "true", "false", "Lääkefirma Perttilä", "Oy GE Healthcare Bio-Sciences Ab", "2"}};
private String[][] batches = {{"123445EE", "8", "30", "0", "Jeejeee paljon huomautettavaa"},
{"99AADD22", "3", "10", "1", "puolet rikki"},{"AAD175", "3", "10", "2", "1 lainassa"}};
@RequestMapping("generateTestDB")
public String createDB() {
createSubstances();
createBatches();
return "redirect:/storage";
}
private void createSubstances() {
for (int i = 0; i < substances.length; i++) {
Substance substance = new Substance();
substance.setName(substances[i][0]);
substance.setAlertLimit1(Integer.parseInt(substances[i][1]));
substance.setAlertLimit2(Integer.parseInt(substances[i][2]));
substance.setHasBeenOrdered(Boolean.parseBoolean(substances[i][3]));
substance.setNeedsColdStorage(Boolean.parseBoolean(substances[i][4]));
substance.setManufacturer(substances[i][5]);
substance.setSupplier(substances[i][6]);
substance.setType(Integer.parseInt(substances[i][7]));
substanceService.createOrUpdate(substance);
}
}
private void createBatches() {
for (int i = 0; i < batches.length; i++) {
Batch batch = new Batch();
batch.setBatchNumber(batches[i][0]);
batch.setAmount(Integer.parseInt(batches[i][1]));
int[][] storageLocations = new int[10][2];
storageLocations[0][0] = 1;
storageLocations[0][1] = Integer.parseInt(batches[i][1]);
batch.setStorageLocations(storageLocations);
batch.setSubstanceVolume(Integer.parseInt(batches[i][2]));
batch.setQualityCheck(Integer.parseInt(batches[i][3]));
batch.setNote(batches[i][4]);
Substance substance = (Substance) substanceService.read(1);
substance.setTotalAmount(substance.getTotalAmount() + batch.getAmount());
substanceService.createOrUpdate(substance);
batch.setSubstance(substance);
+ batch.setManufacturer(substance.getManufacturer());
+ batch.setSupplier(substance.getSupplier());
+ batch.setSignature("testi db");
batch = batchService.createOrUpdate(batch);
Event event = EventHandler.newBatchEvent(batch);
eventService.createOrUpdate(event);
}
}
}
| true | true | private void createBatches() {
for (int i = 0; i < batches.length; i++) {
Batch batch = new Batch();
batch.setBatchNumber(batches[i][0]);
batch.setAmount(Integer.parseInt(batches[i][1]));
int[][] storageLocations = new int[10][2];
storageLocations[0][0] = 1;
storageLocations[0][1] = Integer.parseInt(batches[i][1]);
batch.setStorageLocations(storageLocations);
batch.setSubstanceVolume(Integer.parseInt(batches[i][2]));
batch.setQualityCheck(Integer.parseInt(batches[i][3]));
batch.setNote(batches[i][4]);
Substance substance = (Substance) substanceService.read(1);
substance.setTotalAmount(substance.getTotalAmount() + batch.getAmount());
substanceService.createOrUpdate(substance);
batch.setSubstance(substance);
batch = batchService.createOrUpdate(batch);
Event event = EventHandler.newBatchEvent(batch);
eventService.createOrUpdate(event);
}
}
| private void createBatches() {
for (int i = 0; i < batches.length; i++) {
Batch batch = new Batch();
batch.setBatchNumber(batches[i][0]);
batch.setAmount(Integer.parseInt(batches[i][1]));
int[][] storageLocations = new int[10][2];
storageLocations[0][0] = 1;
storageLocations[0][1] = Integer.parseInt(batches[i][1]);
batch.setStorageLocations(storageLocations);
batch.setSubstanceVolume(Integer.parseInt(batches[i][2]));
batch.setQualityCheck(Integer.parseInt(batches[i][3]));
batch.setNote(batches[i][4]);
Substance substance = (Substance) substanceService.read(1);
substance.setTotalAmount(substance.getTotalAmount() + batch.getAmount());
substanceService.createOrUpdate(substance);
batch.setSubstance(substance);
batch.setManufacturer(substance.getManufacturer());
batch.setSupplier(substance.getSupplier());
batch.setSignature("testi db");
batch = batchService.createOrUpdate(batch);
Event event = EventHandler.newBatchEvent(batch);
eventService.createOrUpdate(event);
}
}
|
diff --git a/src/main/java/com/jayway/lab/numberclassification/NumberClassifier.java b/src/main/java/com/jayway/lab/numberclassification/NumberClassifier.java
index 0b687c4..4fec3ca 100644
--- a/src/main/java/com/jayway/lab/numberclassification/NumberClassifier.java
+++ b/src/main/java/com/jayway/lab/numberclassification/NumberClassifier.java
@@ -1,60 +1,60 @@
package com.jayway.lab.numberclassification;
import static com.jayway.lab.numberclassification.Classification.*;
import static java.util.stream.IntStream.range;
public class NumberClassifier {
/**
* Number classification has the following rules:
*
* <ol>
* <li># must be greater than 0</li>
* <li>If <code>(sum of all factors of a #) == 2#</code> the number is considered <tt>perfect</tt>.</li>
* <li>If <code>(sum of all factors of a #) > 2#</code> the number is considered <tt>abundant</tt>.</li>
* <li>If <code>(sum of all factors of a #) < 2#</code> the number is considered <tt>deficient</tt>.</li>
* </ol
*<p>
* For example consider 6:<br>
* <code>1+2+3+6 = 12 = 2*6 => <tt>perfect</tt>
* </p>
* <p>and 28:<br>
* <code>1+2+4+7+14+28 = 56 = 2*28 => <tt>perfect</tt>
* </p>
* <p>17:<br>
* <code>1+2+4+7+14+28 = 56 = 2*28 => <tt>perfect</tt>
* </p>
* <p>12:<br>
* <code>1+2+4+6+12 = 25 > 2*12 => <tt>abundant</tt>
* </p>
* <p>15:<br>
* <code>1+3+5+15 = 23 < 2*15 => <tt>deficient</tt>
* </p>
*
* More info:<br>
* <a href="http://en.wikipedia.org/wiki/Perfect_number">Perfect Numbers</a><br>
* <a href="http://en.wikipedia.org/wiki/Abundant_number">Abundant Numbers</a><br>
* <a href="http://en.wikipedia.org/wiki/Deficient_number">Deficient Numbers</a><br>
*
* @param number
* @return
*/
public Classification classify(int number) {
if(number <= 0) throw new IllegalArgumentException("Number must be greater than 0");
// We use "number+1" in range since numbers are not inclusive in the range method.
- final int sumOfFactors = range(1, number + 1).filter(potentialFactory -> number % potentialFactory == 0).sum();
+ final int sumOfFactors = range(1, number + 1).filter(potentialFactor -> number % potentialFactor == 0).sum();
final int numberTimesTwo = 2 * number;
final Classification classification;
if(sumOfFactors == numberTimesTwo) {
classification = PERFECT;
} else if (sumOfFactors > numberTimesTwo) {
classification = ABUNDANT;
} else {
classification = DEFICIENT;
}
return classification;
}
}
| true | true | public Classification classify(int number) {
if(number <= 0) throw new IllegalArgumentException("Number must be greater than 0");
// We use "number+1" in range since numbers are not inclusive in the range method.
final int sumOfFactors = range(1, number + 1).filter(potentialFactory -> number % potentialFactory == 0).sum();
final int numberTimesTwo = 2 * number;
final Classification classification;
if(sumOfFactors == numberTimesTwo) {
classification = PERFECT;
} else if (sumOfFactors > numberTimesTwo) {
classification = ABUNDANT;
} else {
classification = DEFICIENT;
}
return classification;
}
| public Classification classify(int number) {
if(number <= 0) throw new IllegalArgumentException("Number must be greater than 0");
// We use "number+1" in range since numbers are not inclusive in the range method.
final int sumOfFactors = range(1, number + 1).filter(potentialFactor -> number % potentialFactor == 0).sum();
final int numberTimesTwo = 2 * number;
final Classification classification;
if(sumOfFactors == numberTimesTwo) {
classification = PERFECT;
} else if (sumOfFactors > numberTimesTwo) {
classification = ABUNDANT;
} else {
classification = DEFICIENT;
}
return classification;
}
|
diff --git a/performance/plugins/org.eclipse.dltk.tests.performance/src/org/eclipse/dltk/tests/performance/TclFullSourceWorkspaceTests.java b/performance/plugins/org.eclipse.dltk.tests.performance/src/org/eclipse/dltk/tests/performance/TclFullSourceWorkspaceTests.java
index 64904da..9302f58 100644
--- a/performance/plugins/org.eclipse.dltk.tests.performance/src/org/eclipse/dltk/tests/performance/TclFullSourceWorkspaceTests.java
+++ b/performance/plugins/org.eclipse.dltk.tests.performance/src/org/eclipse/dltk/tests/performance/TclFullSourceWorkspaceTests.java
@@ -1,28 +1,29 @@
/*******************************************************************************
* Copyright (c) 2008 xored software, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* xored software, Inc. - initial API and Implementation (Andrei Sobolev)
*******************************************************************************/
package org.eclipse.dltk.tests.performance;
import org.eclipse.dltk.core.tests.FullSourceWorkspaceTests;
public abstract class TclFullSourceWorkspaceTests extends
FullSourceWorkspaceTests {
public TclFullSourceWorkspaceTests(String name) {
super(name);
AllPerformanceTests.init();
}
public String getFullWorkspaceZip() {
// return getPluginDirectoryPath(Activator.PLUGIN_ID + ".data")
// + File.separator + "bigFile.zip";
- return "/home/dltk/data/bigFile.zip";
+ String property = System.getProperty("BUILD_HOME", "/home/dltk");
+ return property + "/data/bigFile.zip";
}
}
| true | true | public String getFullWorkspaceZip() {
// return getPluginDirectoryPath(Activator.PLUGIN_ID + ".data")
// + File.separator + "bigFile.zip";
return "/home/dltk/data/bigFile.zip";
}
| public String getFullWorkspaceZip() {
// return getPluginDirectoryPath(Activator.PLUGIN_ID + ".data")
// + File.separator + "bigFile.zip";
String property = System.getProperty("BUILD_HOME", "/home/dltk");
return property + "/data/bigFile.zip";
}
|
diff --git a/solr/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java b/solr/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java
index 4ec455bbd..48425034b 100644
--- a/solr/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java
+++ b/solr/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java
@@ -1,430 +1,433 @@
/**
* 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.solr.handler;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.CharReader;
import org.apache.lucene.analysis.CharStream;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.*;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.index.Payload;
import org.apache.lucene.util.Attribute;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.AttributeReflector;
import org.apache.lucene.util.SorterTemplate;
import org.apache.solr.analysis.CharFilterFactory;
import org.apache.solr.analysis.TokenFilterFactory;
import org.apache.solr.analysis.TokenizerChain;
import org.apache.solr.analysis.TokenizerFactory;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.common.SolrException;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.FieldType;
import org.apache.solr.util.ByteUtils;
import org.apache.noggit.CharArr;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
/**
* A base class for all analysis request handlers.
*
* @version $Id$
* @since solr 1.4
*/
public abstract class AnalysisRequestHandlerBase extends RequestHandlerBase {
public static final Set<BytesRef> EMPTY_BYTES_SET = Collections.emptySet();
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
rsp.add("analysis", doAnalysis(req));
}
/**
* Performs the analysis based on the given solr request and returns the analysis result as a named list.
*
* @param req The solr request.
*
* @return The analysis result as a named list.
*
* @throws Exception When analysis fails.
*/
protected abstract NamedList doAnalysis(SolrQueryRequest req) throws Exception;
/**
* Analyzes the given value using the given Analyzer.
*
* @param value Value to analyze
* @param context The {@link AnalysisContext analysis context}.
*
* @return NamedList containing the tokens produced by analyzing the given value
*/
protected NamedList<? extends Object> analyzeValue(String value, AnalysisContext context) {
Analyzer analyzer = context.getAnalyzer();
if (!TokenizerChain.class.isInstance(analyzer)) {
TokenStream tokenStream = null;
try {
tokenStream = analyzer.reusableTokenStream(context.getFieldName(), new StringReader(value));
tokenStream.reset();
} catch (IOException e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
}
NamedList<List<NamedList>> namedList = new NamedList<List<NamedList>>();
namedList.add(tokenStream.getClass().getName(), convertTokensToNamedLists(analyzeTokenStream(tokenStream), context));
return namedList;
}
TokenizerChain tokenizerChain = (TokenizerChain) analyzer;
CharFilterFactory[] cfiltfacs = tokenizerChain.getCharFilterFactories();
TokenizerFactory tfac = tokenizerChain.getTokenizerFactory();
TokenFilterFactory[] filtfacs = tokenizerChain.getTokenFilterFactories();
NamedList<Object> namedList = new NamedList<Object>();
if( cfiltfacs != null ){
String source = value;
for(CharFilterFactory cfiltfac : cfiltfacs ){
CharStream reader = CharReader.get(new StringReader(source));
reader = cfiltfac.create(reader);
source = writeCharStream(namedList, reader);
}
}
TokenStream tokenStream = tfac.create(tokenizerChain.charStream(new StringReader(value)));
List<AttributeSource> tokens = analyzeTokenStream(tokenStream);
namedList.add(tokenStream.getClass().getName(), convertTokensToNamedLists(tokens, context));
ListBasedTokenStream listBasedTokenStream = new ListBasedTokenStream(tokens);
for (TokenFilterFactory tokenFilterFactory : filtfacs) {
tokenStream = tokenFilterFactory.create(listBasedTokenStream);
List<AttributeSource> tokenList = analyzeTokenStream(tokenStream);
namedList.add(tokenStream.getClass().getName(), convertTokensToNamedLists(tokenList, context));
listBasedTokenStream = new ListBasedTokenStream(tokenList);
}
return namedList;
}
/**
* Analyzes the given text using the given analyzer and returns the produced tokens.
*
* @param query The query to analyze.
* @param analyzer The analyzer to use.
*/
protected Set<BytesRef> getQueryTokenSet(String query, Analyzer analyzer) {
final Set<BytesRef> tokens = new HashSet<BytesRef>();
final TokenStream tokenStream = analyzer.tokenStream("", new StringReader(query));
final TermToBytesRefAttribute bytesAtt = tokenStream.getAttribute(TermToBytesRefAttribute.class);
try {
tokenStream.reset();
while (tokenStream.incrementToken()) {
final BytesRef bytes = new BytesRef();
bytesAtt.toBytesRef(bytes);
tokens.add(bytes);
}
} catch (IOException ioe) {
throw new RuntimeException("Error occured while iterating over tokenstream", ioe);
}
return tokens;
}
/**
* Analyzes the given TokenStream, collecting the Tokens it produces.
*
* @param tokenStream TokenStream to analyze
*
* @return List of tokens produced from the TokenStream
*/
private List<AttributeSource> analyzeTokenStream(TokenStream tokenStream) {
List<AttributeSource> tokens = new ArrayList<AttributeSource>();
// for backwards compatibility, add all "common" attributes
tokenStream.addAttribute(PositionIncrementAttribute.class);
tokenStream.addAttribute(OffsetAttribute.class);
tokenStream.addAttribute(TypeAttribute.class);
final BytesRef bytes = new BytesRef();
try {
tokenStream.reset();
while (tokenStream.incrementToken()) {
tokens.add(tokenStream.cloneAttributes());
}
} catch (IOException ioe) {
throw new RuntimeException("Error occured while iterating over tokenstream", ioe);
}
return tokens;
}
// a static mapping of the reflected attribute keys to the names used in Solr 1.4
static Map<String,String> ATTRIBUTE_MAPPING = Collections.unmodifiableMap(new HashMap<String,String>() {{
put(OffsetAttribute.class.getName() + "#startOffset", "start");
put(OffsetAttribute.class.getName() + "#endOffset", "end");
put(TypeAttribute.class.getName() + "#type", "type");
}});
/**
* Converts the list of Tokens to a list of NamedLists representing the tokens.
*
* @param tokens Tokens to convert
* @param context The analysis context
*
* @return List of NamedLists containing the relevant information taken from the tokens
*/
private List<NamedList> convertTokensToNamedLists(final List<AttributeSource> tokens, AnalysisContext context) {
final List<NamedList> tokensNamedLists = new ArrayList<NamedList>();
final int[] positions = new int[tokens.size()];
int position = 0;
for (int i = 0, c = tokens.size(); i < c; i++) {
AttributeSource token = tokens.get(i);
position += token.addAttribute(PositionIncrementAttribute.class).getPositionIncrement();
positions[i] = position;
}
// sort the tokens by absoulte position
new SorterTemplate() {
@Override
protected void swap(int i, int j) {
+ final int p = positions[i];
+ positions[i] = positions[j];
+ positions[j] = p;
Collections.swap(tokens, i, j);
}
@Override
protected int compare(int i, int j) {
return positions[i] - positions[j];
}
@Override
protected void setPivot(int i) {
pivot = positions[i];
}
@Override
protected int comparePivot(int j) {
return pivot - positions[j];
}
private int pivot;
}.mergeSort(0, tokens.size() - 1);
FieldType fieldType = context.getFieldType();
final BytesRef rawBytes = new BytesRef();
final CharArr textBuf = new CharArr();
for (int i = 0, c = tokens.size(); i < c; i++) {
AttributeSource token = tokens.get(i);
final NamedList<Object> tokenNamedList = new SimpleOrderedMap<Object>();
token.getAttribute(TermToBytesRefAttribute.class).toBytesRef(rawBytes);
textBuf.reset();
fieldType.indexedToReadable(rawBytes, textBuf);
final String text = textBuf.toString();
tokenNamedList.add("text", text);
if (token.hasAttribute(CharTermAttribute.class)) {
final String rawText = token.getAttribute(CharTermAttribute.class).toString();
if (!rawText.equals(text)) {
tokenNamedList.add("raw_text", rawText);
}
}
tokenNamedList.add("raw_bytes", rawBytes.toString());
if (context.getTermsToMatch().contains(rawBytes)) {
tokenNamedList.add("match", true);
}
tokenNamedList.add("position", positions[i]);
token.reflectWith(new AttributeReflector() {
public void reflect(Class<? extends Attribute> attClass, String key, Object value) {
// leave out position and bytes term
if (TermToBytesRefAttribute.class.isAssignableFrom(attClass))
return;
if (CharTermAttribute.class.isAssignableFrom(attClass))
return;
if (PositionIncrementAttribute.class.isAssignableFrom(attClass))
return;
String k = attClass.getName() + '#' + key;
// map keys for "standard attributes":
if (ATTRIBUTE_MAPPING.containsKey(k)) {
k = ATTRIBUTE_MAPPING.get(k);
}
if (value instanceof Payload) {
final Payload p = (Payload) value;
value = new BytesRef(p.getData()).toString();
}
tokenNamedList.add(k, value);
}
});
tokensNamedLists.add(tokenNamedList);
}
return tokensNamedLists;
}
private String writeCharStream(NamedList<Object> out, CharStream input ){
final int BUFFER_SIZE = 1024;
char[] buf = new char[BUFFER_SIZE];
int len = 0;
StringBuilder sb = new StringBuilder();
do {
try {
len = input.read( buf, 0, BUFFER_SIZE );
} catch (IOException e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
}
if( len > 0 )
sb.append(buf, 0, len);
} while( len == BUFFER_SIZE );
out.add( input.getClass().getName(), sb.toString());
return sb.toString();
}
// ================================================= Inner classes =================================================
/**
* TokenStream that iterates over a list of pre-existing Tokens
*/
// TODO refactor to support custom attributes
protected final static class ListBasedTokenStream extends TokenStream {
private final List<AttributeSource> tokens;
private Iterator<AttributeSource> tokenIterator;
/**
* Creates a new ListBasedTokenStream which uses the given tokens as its token source.
*
* @param tokens Source of tokens to be used
*/
ListBasedTokenStream(List<AttributeSource> tokens) {
this.tokens = tokens;
tokenIterator = tokens.iterator();
}
@Override
public boolean incrementToken() throws IOException {
if (tokenIterator.hasNext()) {
AttributeSource next = tokenIterator.next();
Iterator<Class<? extends Attribute>> atts = next.getAttributeClassesIterator();
while (atts.hasNext()) // make sure all att impls in the token exist here
addAttribute(atts.next());
next.copyTo(this);
return true;
} else {
return false;
}
}
@Override
public void reset() throws IOException {
super.reset();
tokenIterator = tokens.iterator();
}
}
/**
* Serves as the context of an analysis process. This context contains the following constructs
*/
protected static class AnalysisContext {
private final String fieldName;
private final FieldType fieldType;
private final Analyzer analyzer;
private final Set<BytesRef> termsToMatch;
/**
* Constructs a new AnalysisContext with a given field tpe, analyzer and
* termsToMatch. By default the field name in this context will be
* {@code null}. During the analysis processs, The produced tokens will
* be compaired to the terms in the {@code termsToMatch} set. When found,
* these tokens will be marked as a match.
*
* @param fieldType The type of the field the analysis is performed on.
* @param analyzer The analyzer to be used.
* @param termsToMatch Holds all the terms that should match during the
* analysis process.
*/
public AnalysisContext(FieldType fieldType, Analyzer analyzer, Set<BytesRef> termsToMatch) {
this(null, fieldType, analyzer, termsToMatch);
}
/**
* Constructs an AnalysisContext with a given field name, field type
* and analyzer. By default this context will hold no terms to match
*
* @param fieldName The name of the field the analysis is performed on
* (may be {@code null}).
* @param fieldType The type of the field the analysis is performed on.
* @param analyzer The analyzer to be used during the analysis process.
*
*/
public AnalysisContext(String fieldName, FieldType fieldType, Analyzer analyzer) {
this(fieldName, fieldType, analyzer, EMPTY_BYTES_SET);
}
/**
* Constructs a new AnalysisContext with a given field tpe, analyzer and
* termsToMatch. During the analysis processs, The produced tokens will be
* compaired to the termes in the {@code termsToMatch} set. When found,
* these tokens will be marked as a match.
*
* @param fieldName The name of the field the analysis is performed on
* (may be {@code null}).
* @param fieldType The type of the field the analysis is performed on.
* @param analyzer The analyzer to be used.
* @param termsToMatch Holds all the terms that should match during the
* analysis process.
*/
public AnalysisContext(String fieldName, FieldType fieldType, Analyzer analyzer, Set<BytesRef> termsToMatch) {
this.fieldName = fieldName;
this.fieldType = fieldType;
this.analyzer = analyzer;
this.termsToMatch = termsToMatch;
}
public String getFieldName() {
return fieldName;
}
public FieldType getFieldType() {
return fieldType;
}
public Analyzer getAnalyzer() {
return analyzer;
}
public Set<BytesRef> getTermsToMatch() {
return termsToMatch;
}
}
}
| true | true | private List<NamedList> convertTokensToNamedLists(final List<AttributeSource> tokens, AnalysisContext context) {
final List<NamedList> tokensNamedLists = new ArrayList<NamedList>();
final int[] positions = new int[tokens.size()];
int position = 0;
for (int i = 0, c = tokens.size(); i < c; i++) {
AttributeSource token = tokens.get(i);
position += token.addAttribute(PositionIncrementAttribute.class).getPositionIncrement();
positions[i] = position;
}
// sort the tokens by absoulte position
new SorterTemplate() {
@Override
protected void swap(int i, int j) {
Collections.swap(tokens, i, j);
}
@Override
protected int compare(int i, int j) {
return positions[i] - positions[j];
}
@Override
protected void setPivot(int i) {
pivot = positions[i];
}
@Override
protected int comparePivot(int j) {
return pivot - positions[j];
}
private int pivot;
}.mergeSort(0, tokens.size() - 1);
FieldType fieldType = context.getFieldType();
final BytesRef rawBytes = new BytesRef();
final CharArr textBuf = new CharArr();
for (int i = 0, c = tokens.size(); i < c; i++) {
AttributeSource token = tokens.get(i);
final NamedList<Object> tokenNamedList = new SimpleOrderedMap<Object>();
token.getAttribute(TermToBytesRefAttribute.class).toBytesRef(rawBytes);
textBuf.reset();
fieldType.indexedToReadable(rawBytes, textBuf);
final String text = textBuf.toString();
tokenNamedList.add("text", text);
if (token.hasAttribute(CharTermAttribute.class)) {
final String rawText = token.getAttribute(CharTermAttribute.class).toString();
if (!rawText.equals(text)) {
tokenNamedList.add("raw_text", rawText);
}
}
tokenNamedList.add("raw_bytes", rawBytes.toString());
if (context.getTermsToMatch().contains(rawBytes)) {
tokenNamedList.add("match", true);
}
tokenNamedList.add("position", positions[i]);
token.reflectWith(new AttributeReflector() {
public void reflect(Class<? extends Attribute> attClass, String key, Object value) {
// leave out position and bytes term
if (TermToBytesRefAttribute.class.isAssignableFrom(attClass))
return;
if (CharTermAttribute.class.isAssignableFrom(attClass))
return;
if (PositionIncrementAttribute.class.isAssignableFrom(attClass))
return;
String k = attClass.getName() + '#' + key;
// map keys for "standard attributes":
if (ATTRIBUTE_MAPPING.containsKey(k)) {
k = ATTRIBUTE_MAPPING.get(k);
}
if (value instanceof Payload) {
final Payload p = (Payload) value;
value = new BytesRef(p.getData()).toString();
}
tokenNamedList.add(k, value);
}
});
tokensNamedLists.add(tokenNamedList);
}
return tokensNamedLists;
}
| private List<NamedList> convertTokensToNamedLists(final List<AttributeSource> tokens, AnalysisContext context) {
final List<NamedList> tokensNamedLists = new ArrayList<NamedList>();
final int[] positions = new int[tokens.size()];
int position = 0;
for (int i = 0, c = tokens.size(); i < c; i++) {
AttributeSource token = tokens.get(i);
position += token.addAttribute(PositionIncrementAttribute.class).getPositionIncrement();
positions[i] = position;
}
// sort the tokens by absoulte position
new SorterTemplate() {
@Override
protected void swap(int i, int j) {
final int p = positions[i];
positions[i] = positions[j];
positions[j] = p;
Collections.swap(tokens, i, j);
}
@Override
protected int compare(int i, int j) {
return positions[i] - positions[j];
}
@Override
protected void setPivot(int i) {
pivot = positions[i];
}
@Override
protected int comparePivot(int j) {
return pivot - positions[j];
}
private int pivot;
}.mergeSort(0, tokens.size() - 1);
FieldType fieldType = context.getFieldType();
final BytesRef rawBytes = new BytesRef();
final CharArr textBuf = new CharArr();
for (int i = 0, c = tokens.size(); i < c; i++) {
AttributeSource token = tokens.get(i);
final NamedList<Object> tokenNamedList = new SimpleOrderedMap<Object>();
token.getAttribute(TermToBytesRefAttribute.class).toBytesRef(rawBytes);
textBuf.reset();
fieldType.indexedToReadable(rawBytes, textBuf);
final String text = textBuf.toString();
tokenNamedList.add("text", text);
if (token.hasAttribute(CharTermAttribute.class)) {
final String rawText = token.getAttribute(CharTermAttribute.class).toString();
if (!rawText.equals(text)) {
tokenNamedList.add("raw_text", rawText);
}
}
tokenNamedList.add("raw_bytes", rawBytes.toString());
if (context.getTermsToMatch().contains(rawBytes)) {
tokenNamedList.add("match", true);
}
tokenNamedList.add("position", positions[i]);
token.reflectWith(new AttributeReflector() {
public void reflect(Class<? extends Attribute> attClass, String key, Object value) {
// leave out position and bytes term
if (TermToBytesRefAttribute.class.isAssignableFrom(attClass))
return;
if (CharTermAttribute.class.isAssignableFrom(attClass))
return;
if (PositionIncrementAttribute.class.isAssignableFrom(attClass))
return;
String k = attClass.getName() + '#' + key;
// map keys for "standard attributes":
if (ATTRIBUTE_MAPPING.containsKey(k)) {
k = ATTRIBUTE_MAPPING.get(k);
}
if (value instanceof Payload) {
final Payload p = (Payload) value;
value = new BytesRef(p.getData()).toString();
}
tokenNamedList.add(k, value);
}
});
tokensNamedLists.add(tokenNamedList);
}
return tokensNamedLists;
}
|
diff --git a/src/net/skyebook/OSMReader.java b/src/net/skyebook/OSMReader.java
index f824a6a..17a1d98 100644
--- a/src/net/skyebook/OSMReader.java
+++ b/src/net/skyebook/OSMReader.java
@@ -1,157 +1,159 @@
/**
*
*/
package net.skyebook;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import edu.poly.bxmc.betaville.jme.map.GPSCoordinate;
import edu.poly.bxmc.betaville.osm.Node;
/**
* @author Skye Book
*
*/
public class OSMReader {
private long totalBytesRead = 0;
private BufferedReader br;
// line prefixes
private static final String nodePrefix = "<node";
private static final String wayPrefix = "<way";
private static final String relationPrefix = "<relation";
private static final String tagPrefix = "<tag";
private static final String nodeReferencePrefix = "<nd";
// line suffixes
private static final String nodeSuffix = "</node";
private static final String waySuffix = "</way";
private static final String relationSuffix = "</relation";
private static final String tagSuffix = "</tag";
private static final String nodeReferenceSuffix = "</nd";
private boolean relationsHaveBeenProcessed = false;
private boolean waysHaveBeenProcessed = false;
public void read() throws FileNotFoundException, IOException{
GZIPInputStream is = new GZIPInputStream(new FileInputStream("/Users/skyebook/Downloads/new-york.osm.gz"));
br = new BufferedReader(new InputStreamReader(is));
long start = System.currentTimeMillis();
while(br.ready()){
readLine(br.readLine());
}
System.out.println("Read Took " + (System.currentTimeMillis()-start));
}
public void readPlain() throws FileNotFoundException, IOException{
FileInputStream fis= new FileInputStream("/Users/skyebook/Downloads/new-york.osm.xml");
br = new BufferedReader(new InputStreamReader(fis));
long start = System.currentTimeMillis();
while(br.ready()){
readLine(br.readLine());
}
System.out.println("Read Took " + (System.currentTimeMillis()-start));
}
public void readLine(String line) throws IOException{
totalBytesRead+=line.length();
// what type of element is this?
if(line.contains(nodePrefix)){
Node node = new Node();
double lat = -1;
double lon = -1;
// get the information
String[] attributes = line.split("=\"");
for(int i=0; i<attributes.length; i++){
String attr=attributes[i];
- if(attr.endsWith("id")){
+ if(attr.endsWith(" id")){
+ //System.out.println(attributes[i]);
+ //System.out.println(attributes[i+1]);
node.setId(Long.parseLong(getNextAttributeValue(attributes[i+1])));
}
- else if(attr.endsWith("lat")){
+ else if(attr.endsWith(" lat")){
lat = Double.parseDouble(getNextAttributeValue(attributes[i+1]));
if(lon!=-1){
node.setLocation(new GPSCoordinate(0, lat, lon));
}
}
- else if(attr.endsWith("lon")){
+ else if(attr.endsWith(" lon")){
lon = Double.parseDouble(getNextAttributeValue(attributes[i+1]));
if(lat!=-1){
node.setLocation(new GPSCoordinate(0, lat, lon));
}
}
- else if(attr.endsWith("user")){
+ else if(attr.endsWith(" user")){
// Will implement this later if the need arises
}
- else if(attr.endsWith("uid")){
+ else if(attr.endsWith(" uid")){
// Will implement this later if the need arises
}
- else if(attr.endsWith("visible")){
+ else if(attr.endsWith(" visible")){
// Will implement this later if the need arises
}
- else if(attr.endsWith("version")){
+ else if(attr.endsWith(" version")){
// Will implement this later if the need arises
}
- else if(attr.endsWith("changeset")){
+ else if(attr.endsWith(" changeset")){
// Will implement this later if the need arises
}
- else if(attr.endsWith("timestamp")){
+ else if(attr.endsWith(" timestamp")){
// Will implement this later if the need arises
}
}
- //System.out.println(node.getId()+" "+node.getLocation().toString());
+ System.out.println(node.getId()+" "+node.getLocation().toString());
// move forward until the node is complete
if(!isLineSelfContained(line)){
String subLine = "";
while(br.ready() && !subLine.contains(nodeSuffix)){
subLine = br.readLine();
//System.out.println("Subline caught: " + subLine);
}
}
}
else if(line.contains(wayPrefix)){
}
else if(line.contains(relationPrefix)){
}
else if(line.contains(tagPrefix)){
}
else if(line.contains(nodeReferencePrefix)){
}
}
private String getNextAttributeValue(String nextToken){
return nextToken.substring(0, nextToken.indexOf("\""));
}
/**
* Checks if the XML element starts and ends on the same line
* @param line The content of the line to check
* @return True if the element ends on the same line as it begins, otherwise false
*/
private boolean isLineSelfContained(String line){
return line.endsWith("/>");
}
private long getTotalBytesRead(){
return totalBytesRead;
}
public static void main(String[] args) throws FileNotFoundException, IOException{
OSMReader reader = new OSMReader();
reader.read();
//reader.readPlain();
System.out.println(reader.getTotalBytesRead() + " bytes read");
}
}
| false | true | public void readLine(String line) throws IOException{
totalBytesRead+=line.length();
// what type of element is this?
if(line.contains(nodePrefix)){
Node node = new Node();
double lat = -1;
double lon = -1;
// get the information
String[] attributes = line.split("=\"");
for(int i=0; i<attributes.length; i++){
String attr=attributes[i];
if(attr.endsWith("id")){
node.setId(Long.parseLong(getNextAttributeValue(attributes[i+1])));
}
else if(attr.endsWith("lat")){
lat = Double.parseDouble(getNextAttributeValue(attributes[i+1]));
if(lon!=-1){
node.setLocation(new GPSCoordinate(0, lat, lon));
}
}
else if(attr.endsWith("lon")){
lon = Double.parseDouble(getNextAttributeValue(attributes[i+1]));
if(lat!=-1){
node.setLocation(new GPSCoordinate(0, lat, lon));
}
}
else if(attr.endsWith("user")){
// Will implement this later if the need arises
}
else if(attr.endsWith("uid")){
// Will implement this later if the need arises
}
else if(attr.endsWith("visible")){
// Will implement this later if the need arises
}
else if(attr.endsWith("version")){
// Will implement this later if the need arises
}
else if(attr.endsWith("changeset")){
// Will implement this later if the need arises
}
else if(attr.endsWith("timestamp")){
// Will implement this later if the need arises
}
}
//System.out.println(node.getId()+" "+node.getLocation().toString());
// move forward until the node is complete
if(!isLineSelfContained(line)){
String subLine = "";
while(br.ready() && !subLine.contains(nodeSuffix)){
subLine = br.readLine();
//System.out.println("Subline caught: " + subLine);
}
}
}
else if(line.contains(wayPrefix)){
}
else if(line.contains(relationPrefix)){
}
else if(line.contains(tagPrefix)){
}
else if(line.contains(nodeReferencePrefix)){
}
}
| public void readLine(String line) throws IOException{
totalBytesRead+=line.length();
// what type of element is this?
if(line.contains(nodePrefix)){
Node node = new Node();
double lat = -1;
double lon = -1;
// get the information
String[] attributes = line.split("=\"");
for(int i=0; i<attributes.length; i++){
String attr=attributes[i];
if(attr.endsWith(" id")){
//System.out.println(attributes[i]);
//System.out.println(attributes[i+1]);
node.setId(Long.parseLong(getNextAttributeValue(attributes[i+1])));
}
else if(attr.endsWith(" lat")){
lat = Double.parseDouble(getNextAttributeValue(attributes[i+1]));
if(lon!=-1){
node.setLocation(new GPSCoordinate(0, lat, lon));
}
}
else if(attr.endsWith(" lon")){
lon = Double.parseDouble(getNextAttributeValue(attributes[i+1]));
if(lat!=-1){
node.setLocation(new GPSCoordinate(0, lat, lon));
}
}
else if(attr.endsWith(" user")){
// Will implement this later if the need arises
}
else if(attr.endsWith(" uid")){
// Will implement this later if the need arises
}
else if(attr.endsWith(" visible")){
// Will implement this later if the need arises
}
else if(attr.endsWith(" version")){
// Will implement this later if the need arises
}
else if(attr.endsWith(" changeset")){
// Will implement this later if the need arises
}
else if(attr.endsWith(" timestamp")){
// Will implement this later if the need arises
}
}
System.out.println(node.getId()+" "+node.getLocation().toString());
// move forward until the node is complete
if(!isLineSelfContained(line)){
String subLine = "";
while(br.ready() && !subLine.contains(nodeSuffix)){
subLine = br.readLine();
//System.out.println("Subline caught: " + subLine);
}
}
}
else if(line.contains(wayPrefix)){
}
else if(line.contains(relationPrefix)){
}
else if(line.contains(tagPrefix)){
}
else if(line.contains(nodeReferencePrefix)){
}
}
|
diff --git a/flexmojos-testing/flexmojos-test-harness/src/test/java/org/sonatype/flexmojos/tests/concept/TrustTest.java b/flexmojos-testing/flexmojos-test-harness/src/test/java/org/sonatype/flexmojos/tests/concept/TrustTest.java
index 7bbb32b31..a792f7bc2 100644
--- a/flexmojos-testing/flexmojos-test-harness/src/test/java/org/sonatype/flexmojos/tests/concept/TrustTest.java
+++ b/flexmojos-testing/flexmojos-test-harness/src/test/java/org/sonatype/flexmojos/tests/concept/TrustTest.java
@@ -1,58 +1,57 @@
/**
* Flexmojos is a set of maven goals to allow maven users to compile, optimize and test Flex SWF, Flex SWC, Air SWF and Air SWC.
* Copyright (C) 2008-2012 Marvin Froeder <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sonatype.flexmojos.tests.concept;
import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.io.FileReader;
import org.codehaus.plexus.util.IOUtil;
import org.sonatype.flexmojos.truster.FlashPlayerTruster;
import org.testng.annotations.Test;
public class TrustTest
extends AbstractConceptTest
{
@Test
public void testTrust()
throws Exception
{
File fpTrustFolder = container.lookup( FlashPlayerTruster.class ).getTrustDir();
if ( !fpTrustFolder.isDirectory() )
{
fpTrustFolder.mkdirs();
}
File mavenCfg = new File( fpTrustFolder, "maven.cfg" );
if ( mavenCfg.exists() )
{
mavenCfg.delete();
}
- standardConceptTester( "flashplayertrust" );
+ String basedir = standardConceptTester( "flashplayertrust" ).getBasedir();
String cfg = IOUtil.toString( new FileReader( mavenCfg ) );
- assertTrue( "flexmojos should write trust localtion", cfg.contains( "file1.swf" ) );
- assertTrue( "flexmojos should write trust localtion", cfg.contains( "something_else.zip" ) );
+ assertTrue( "flexmojos should write trust localtion", cfg.contains( basedir ) );
}
}
| false | true | public void testTrust()
throws Exception
{
File fpTrustFolder = container.lookup( FlashPlayerTruster.class ).getTrustDir();
if ( !fpTrustFolder.isDirectory() )
{
fpTrustFolder.mkdirs();
}
File mavenCfg = new File( fpTrustFolder, "maven.cfg" );
if ( mavenCfg.exists() )
{
mavenCfg.delete();
}
standardConceptTester( "flashplayertrust" );
String cfg = IOUtil.toString( new FileReader( mavenCfg ) );
assertTrue( "flexmojos should write trust localtion", cfg.contains( "file1.swf" ) );
assertTrue( "flexmojos should write trust localtion", cfg.contains( "something_else.zip" ) );
}
| public void testTrust()
throws Exception
{
File fpTrustFolder = container.lookup( FlashPlayerTruster.class ).getTrustDir();
if ( !fpTrustFolder.isDirectory() )
{
fpTrustFolder.mkdirs();
}
File mavenCfg = new File( fpTrustFolder, "maven.cfg" );
if ( mavenCfg.exists() )
{
mavenCfg.delete();
}
String basedir = standardConceptTester( "flashplayertrust" ).getBasedir();
String cfg = IOUtil.toString( new FileReader( mavenCfg ) );
assertTrue( "flexmojos should write trust localtion", cfg.contains( basedir ) );
}
|
diff --git a/src/com/android/email/Email.java b/src/com/android/email/Email.java
index 46069ed5..1ef55cf2 100644
--- a/src/com/android/email/Email.java
+++ b/src/com/android/email/Email.java
@@ -1,280 +1,278 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.util.Log;
import com.android.email.activity.MessageCompose;
import com.android.email.activity.ShortcutPicker;
import com.android.email.service.AttachmentDownloadService;
import com.android.email.service.MailService;
import com.android.email.widget.WidgetConfiguration;
import com.android.emailcommon.Logging;
import com.android.emailcommon.TempDirectory;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.service.EmailServiceProxy;
import com.android.emailcommon.utility.EmailAsyncTask;
import com.android.emailcommon.utility.Utility;
public class Email extends Application {
/**
* If this is enabled there will be additional logging information sent to
* Log.d, including protocol dumps.
*
* This should only be used for logs that are useful for debbuging user problems,
* not for internal/development logs.
*
* This can be enabled by typing "debug" in the AccountFolderList activity.
* Changing the value to 'true' here will likely have no effect at all!
*
* TODO: rename this to sUserDebug, and rename LOGD below to DEBUG.
*/
public static boolean DEBUG;
// Exchange debugging flags (passed to Exchange, when available, via EmailServiceProxy)
public static boolean DEBUG_EXCHANGE;
public static boolean DEBUG_EXCHANGE_VERBOSE;
public static boolean DEBUG_EXCHANGE_FILE;
/**
* If true, inhibit hardware graphics acceleration in UI (for a/b testing)
*/
public static boolean sDebugInhibitGraphicsAcceleration = false;
/**
* Specifies how many messages will be shown in a folder by default. This number is set
* on each new folder and can be incremented with "Load more messages..." by the
* VISIBLE_LIMIT_INCREMENT
*/
public static final int VISIBLE_LIMIT_DEFAULT = 25;
/**
* Number of additional messages to load when a user selects "Load more messages..."
*/
public static final int VISIBLE_LIMIT_INCREMENT = 25;
/**
* This is used to force stacked UI to return to the "welcome" screen any time we change
* the accounts list (e.g. deleting accounts in the Account Manager preferences.)
*/
private static boolean sAccountsChangedNotification = false;
private static String sMessageDecodeErrorString;
private static Thread sUiThread;
/**
* Asynchronous version of {@link #setServicesEnabledSync(Context)}. Use when calling from
* UI thread (or lifecycle entry points.)
*
* @param context
*/
public static void setServicesEnabledAsync(final Context context) {
EmailAsyncTask.runAsyncParallel(new Runnable() {
@Override
public void run() {
setServicesEnabledSync(context);
}
});
}
/**
* Called throughout the application when the number of accounts has changed. This method
* enables or disables the Compose activity, the boot receiver and the service based on
* whether any accounts are configured.
*
* Blocking call - do not call from UI/lifecycle threads.
*
* @param context
* @return true if there are any accounts configured.
*/
public static boolean setServicesEnabledSync(Context context) {
Cursor c = null;
try {
c = context.getContentResolver().query(
Account.CONTENT_URI,
Account.ID_PROJECTION,
null, null, null);
boolean enable = c.getCount() > 0;
setServicesEnabled(context, enable);
return enable;
} finally {
if (c != null) {
c.close();
}
}
}
private static void setServicesEnabled(Context context, boolean enabled) {
PackageManager pm = context.getPackageManager();
if (!enabled && pm.getComponentEnabledSetting(
new ComponentName(context, MailService.class)) ==
PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
/*
* If no accounts now exist but the service is still enabled we're about to disable it
* so we'll reschedule to kill off any existing alarms.
*/
MailService.actionReschedule(context);
}
pm.setComponentEnabledSetting(
new ComponentName(context, MessageCompose.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context, ShortcutPicker.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context, MailService.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context, AttachmentDownloadService.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
if (enabled && pm.getComponentEnabledSetting(
new ComponentName(context, MailService.class)) ==
PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
/*
* And now if accounts do exist then we've just enabled the service and we want to
* schedule alarms for the new accounts.
*/
MailService.actionReschedule(context);
}
- // Note - the Email widget is always enabled as it will show a warning if no accounts are
- // configured. In previous releases, this was disabled if no accounts were set, so we
- // need to unconditionally enable it here.
pm.setComponentEnabledSetting(
new ComponentName(context, WidgetConfiguration.class),
- PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
+ enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
+ PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
// Start/stop the various services depending on whether there are any accounts
startOrStopService(enabled, context, new Intent(context, AttachmentDownloadService.class));
NotificationController.getInstance(context).watchForMessages(enabled);
}
/**
* Starts or stops the service as necessary.
* @param enabled If {@code true}, the service will be started. Otherwise, it will be stopped.
* @param context The context to manage the service with.
* @param intent The intent of the service to be managed.
*/
private static void startOrStopService(boolean enabled, Context context, Intent intent) {
if (enabled) {
context.startService(intent);
} else {
context.stopService(intent);
}
}
@Override
public void onCreate() {
super.onCreate();
sUiThread = Thread.currentThread();
Preferences prefs = Preferences.getPreferences(this);
DEBUG = prefs.getEnableDebugLogging();
sDebugInhibitGraphicsAcceleration = prefs.getInhibitGraphicsAcceleration();
enableStrictMode(prefs.getEnableStrictMode());
TempDirectory.setTempDirectory(this);
// Tie MailRefreshManager to the Controller.
RefreshManager.getInstance(this);
// Reset all accounts to default visible window
Controller.getInstance(this).resetVisibleLimits();
// Enable logging in the EAS service, so it starts up as early as possible.
updateLoggingFlags(this);
// Get a helper string used deep inside message decoders (which don't have context)
sMessageDecodeErrorString = getString(R.string.message_decode_error);
// Make sure all required services are running when the app is started (can prevent
// issues after an adb sync/install)
setServicesEnabledAsync(this);
}
/**
* Load enabled debug flags from the preferences and update the EAS debug flag.
*/
public static void updateLoggingFlags(Context context) {
Preferences prefs = Preferences.getPreferences(context);
int debugLogging = prefs.getEnableDebugLogging() ? EmailServiceProxy.DEBUG_BIT : 0;
int verboseLogging =
prefs.getEnableExchangeLogging() ? EmailServiceProxy.DEBUG_VERBOSE_BIT : 0;
int fileLogging =
prefs.getEnableExchangeFileLogging() ? EmailServiceProxy.DEBUG_FILE_BIT : 0;
int enableStrictMode =
prefs.getEnableStrictMode() ? EmailServiceProxy.DEBUG_ENABLE_STRICT_MODE : 0;
int debugBits = debugLogging | verboseLogging | fileLogging | enableStrictMode;
Controller.getInstance(context).serviceLogging(debugBits);
}
/**
* Internal, utility method for logging.
* The calls to log() must be guarded with "if (Email.LOGD)" for performance reasons.
*/
public static void log(String message) {
Log.d(Logging.LOG_TAG, message);
}
/**
* Called by the accounts reconciler to notify that accounts have changed, or by "Welcome"
* to clear the flag.
* @param setFlag true to set the notification flag, false to clear it
*/
public static synchronized void setNotifyUiAccountsChanged(boolean setFlag) {
sAccountsChangedNotification = setFlag;
}
/**
* Called from activity onResume() functions to check for an accounts-changed condition, at
* which point they should finish() and jump to the Welcome activity.
*/
public static synchronized boolean getNotifyUiAccountsChanged() {
return sAccountsChangedNotification;
}
public static void warnIfUiThread() {
if (Thread.currentThread().equals(sUiThread)) {
Log.w(Logging.LOG_TAG, "Method called on the UI thread", new Exception("STACK TRACE"));
}
}
/**
* Retrieve a simple string that can be used when message decoders encounter bad data.
* This is provided here because the protocol decoders typically don't have mContext.
*/
public static String getMessageDecodeErrorString() {
return sMessageDecodeErrorString != null ? sMessageDecodeErrorString : "";
}
public static void enableStrictMode(boolean enabled) {
Utility.enableStrictMode(enabled);
}
}
| false | true | private static void setServicesEnabled(Context context, boolean enabled) {
PackageManager pm = context.getPackageManager();
if (!enabled && pm.getComponentEnabledSetting(
new ComponentName(context, MailService.class)) ==
PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
/*
* If no accounts now exist but the service is still enabled we're about to disable it
* so we'll reschedule to kill off any existing alarms.
*/
MailService.actionReschedule(context);
}
pm.setComponentEnabledSetting(
new ComponentName(context, MessageCompose.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context, ShortcutPicker.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context, MailService.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context, AttachmentDownloadService.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
if (enabled && pm.getComponentEnabledSetting(
new ComponentName(context, MailService.class)) ==
PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
/*
* And now if accounts do exist then we've just enabled the service and we want to
* schedule alarms for the new accounts.
*/
MailService.actionReschedule(context);
}
// Note - the Email widget is always enabled as it will show a warning if no accounts are
// configured. In previous releases, this was disabled if no accounts were set, so we
// need to unconditionally enable it here.
pm.setComponentEnabledSetting(
new ComponentName(context, WidgetConfiguration.class),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
// Start/stop the various services depending on whether there are any accounts
startOrStopService(enabled, context, new Intent(context, AttachmentDownloadService.class));
NotificationController.getInstance(context).watchForMessages(enabled);
}
| private static void setServicesEnabled(Context context, boolean enabled) {
PackageManager pm = context.getPackageManager();
if (!enabled && pm.getComponentEnabledSetting(
new ComponentName(context, MailService.class)) ==
PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
/*
* If no accounts now exist but the service is still enabled we're about to disable it
* so we'll reschedule to kill off any existing alarms.
*/
MailService.actionReschedule(context);
}
pm.setComponentEnabledSetting(
new ComponentName(context, MessageCompose.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context, ShortcutPicker.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context, MailService.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context, AttachmentDownloadService.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
if (enabled && pm.getComponentEnabledSetting(
new ComponentName(context, MailService.class)) ==
PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
/*
* And now if accounts do exist then we've just enabled the service and we want to
* schedule alarms for the new accounts.
*/
MailService.actionReschedule(context);
}
pm.setComponentEnabledSetting(
new ComponentName(context, WidgetConfiguration.class),
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
// Start/stop the various services depending on whether there are any accounts
startOrStopService(enabled, context, new Intent(context, AttachmentDownloadService.class));
NotificationController.getInstance(context).watchForMessages(enabled);
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index c19ac4a0..1a097b52 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1854 +1,1858 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Parcelable;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import com.android.launcher.R;
import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = false;
static final String TAG = "Launcher.Model";
private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
private final boolean mAppsCanBeOnExternalStorage;
private int mBatchSize; // 0 is all apps at once
private int mAllAppsLoadDelay; // milliseconds between batches
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private LoaderTask mLoaderTask;
private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
static {
sWorkerThread.start();
}
private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
// We start off with everything not loaded. After that, we assume that
// our monitoring of the package manager provides all updates and we never
// need to do a requery. These are only ever touched from the loader thread.
private boolean mWorkspaceLoaded;
private boolean mAllAppsLoaded;
private WeakReference<Callbacks> mCallbacks;
// < only access in worker thread >
private AllAppsList mAllAppsList;
// sItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
// LauncherModel to their ids
static final HashMap<Long, ItemInfo> sItemsIdMap = new HashMap<Long, ItemInfo>();
// sItems is passed to bindItems, which expects a list of all folders and shortcuts created by
// LauncherModel that are directly on the home screen (however, no widgets or shortcuts
// within folders).
static final ArrayList<ItemInfo> sWorkspaceItems = new ArrayList<ItemInfo>();
// sAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
static final ArrayList<LauncherAppWidgetInfo> sAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
// sFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
static final HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
// </ only access in worker thread >
private IconCache mIconCache;
private Bitmap mDefaultIcon;
private static int mCellCountX;
private static int mCellCountY;
public interface Callbacks {
public boolean setLoadOnResume();
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent);
public void bindPackagesUpdated();
public boolean isAllAppsVisible();
}
LauncherModel(LauncherApplication app, IconCache iconCache) {
mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
mApp = app;
mAllAppsList = new AllAppsList(iconCache);
mIconCache = iconCache;
mDefaultIcon = Utilities.createIconBitmap(
mIconCache.getFullResDefaultActivityIcon(), app);
mAllAppsLoadDelay = app.getResources().getInteger(R.integer.config_allAppsBatchLoadDelay);
mBatchSize = app.getResources().getInteger(R.integer.config_allAppsBatchSize);
}
public Bitmap getFallbackIcon() {
return Bitmap.createBitmap(mDefaultIcon);
}
public static void unbindWorkspaceItems() {
for (ItemInfo item: sWorkspaceItems) {
item.unbind();
}
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, cellX);
values.put(LauncherSettings.Favorites.CELLY, cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
sWorker.post(new Runnable() {
public void run() {
cr.update(uri, values, null, null);
ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " +
"doesn't match original");
}
// Items are added/removed from the corresponding FolderInfo elsewhere, such
// as in Workspace.onDrop. Here, we just add/remove them from the list of items
// that are on the desktop, as appropriate
if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
if (!sWorkspaceItems.contains(modelItem)) {
sWorkspaceItems.add(modelItem);
}
} else {
sWorkspaceItems.remove(modelItem);
}
}
});
}
/**
* Resize an item in the DB to a new <spanX, spanY, cellX, cellY>
*/
static void resizeItemInDatabase(Context context, final ItemInfo item, final int cellX,
final int cellY, final int spanX, final int spanY) {
item.spanX = spanX;
item.spanY = spanY;
item.cellX = cellX;
item.cellY = cellY;
final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.SPANX, spanX);
values.put(LauncherSettings.Favorites.SPANY, spanY);
values.put(LauncherSettings.Favorites.CELLX, cellX);
values.put(LauncherSettings.Favorites.CELLY, cellY);
sWorker.post(new Runnable() {
public void run() {
cr.update(uri, values, null, null);
ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " +
"doesn't match original");
}
}
});
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screen = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, long container,
int screen, int cellX, int cellY, final boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Launcher l = (Launcher) context;
LauncherApplication app = (LauncherApplication) l.getApplication();
item.id = app.getLauncherProvider().generateNewId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, cellX, cellY);
sWorker.post(new Runnable() {
public void run() {
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
sItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.put(item.id, (FolderInfo) item);
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
});
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
int cellId, int screen, int localCellX, int localCellY, int spanX, int spanY) {
return ((cellId & 0xFF) << 24)
| (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, final ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
sWorker.post(new Runnable() {
public void run() {
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false),
values, null, null);
final ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " +
"doesn't match original");
}
}
});
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
sWorker.post(new Runnable() {
public void run() {
cr.delete(uriToDelete, null, null);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.remove(item.id);
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sItemsIdMap.remove(item.id);
}
});
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
sWorker.post(new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
sItemsIdMap.remove(info.id);
sFolders.remove(info.id);
sWorkspaceItems.remove(info);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
for (ItemInfo childInfo : info.contents) {
sItemsIdMap.remove(childInfo.id);
}
}
});
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps.
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything
// next time.
mAllAppsLoaded = false;
startLoaderFromBackground();
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(mApp, false);
}
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldTask.stopLocked();
}
mLoaderTask = new LoaderTask(context, isLaunching);
sWorker.post(mLoaderTask);
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
private void loadAndBindWorkspace() {
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
// Bind the workspace
bindWorkspace();
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
public void run() {
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
loadAndBindAllApps();
}
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
loadAndBindWorkspace();
}
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
return true;
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (occupied[item.screen][x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + item.screen + ":"
+ x + "," + y
+ ") occupied by "
+ occupied[item.screen][x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
occupied[item.screen][x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
sWorkspaceItems.clear();
sAppWidgets.clear();
sFolders.clear();
sItemsIdMap.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
final ItemInfo occupied[][][] =
new ItemInfo[Launcher.SCREEN_COUNT][mCellCountX][mCellCountY];
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
sWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sFolders, container);
folderInfo.add(info);
break;
}
sItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
updateSavedIcon(context, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
sWorkspaceItems.add(folderInfo);
break;
}
sItemsIdMap.put(folderInfo.id, folderInfo);
sFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
Log.e(TAG, "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied[s][x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = sWorkspaceItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(sWorkspaceItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(sFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
N = sAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllAppsByBatch();
if (mStopped) {
return;
}
mAllAppsLoaded = true;
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAllAppsByBatch() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
if (i == 0) {
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp;
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mAllAppsList.updatePackage(context, packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mAllAppsList.removePackage(packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsAdded(addedFinal);
}
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
if (removed != null) {
final boolean permanent = mOp != OP_UNAVAILABLE;
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsRemoved(removedFinal, permanent);
}
}
});
}
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated();
}
}
});
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
if (labelCache != null && labelCache.containsKey(resolveInfo)) {
info.title = labelCache.get(resolveInfo);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(resolveInfo, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data,
int screen, int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
boolean needSave;
byte[] data = c.getBlob(iconIndex);
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
- return sCollator.compare(a.title.toString(), b.title.toString());
+ int result = sCollator.compare(a.title.toString(), b.title.toString());
+ if (result == 0) {
+ result = a.componentName.compareTo(b.componentName);
+ }
+ return result;
}
};
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
= new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return sCollator.compare(a.label.toString(), b.label.toString());
}
};
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| true | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screen = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, long container,
int screen, int cellX, int cellY, final boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Launcher l = (Launcher) context;
LauncherApplication app = (LauncherApplication) l.getApplication();
item.id = app.getLauncherProvider().generateNewId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, cellX, cellY);
sWorker.post(new Runnable() {
public void run() {
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
sItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.put(item.id, (FolderInfo) item);
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
});
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
int cellId, int screen, int localCellX, int localCellY, int spanX, int spanY) {
return ((cellId & 0xFF) << 24)
| (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, final ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
sWorker.post(new Runnable() {
public void run() {
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false),
values, null, null);
final ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " +
"doesn't match original");
}
}
});
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
sWorker.post(new Runnable() {
public void run() {
cr.delete(uriToDelete, null, null);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.remove(item.id);
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sItemsIdMap.remove(item.id);
}
});
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
sWorker.post(new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
sItemsIdMap.remove(info.id);
sFolders.remove(info.id);
sWorkspaceItems.remove(info);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
for (ItemInfo childInfo : info.contents) {
sItemsIdMap.remove(childInfo.id);
}
}
});
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps.
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything
// next time.
mAllAppsLoaded = false;
startLoaderFromBackground();
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(mApp, false);
}
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldTask.stopLocked();
}
mLoaderTask = new LoaderTask(context, isLaunching);
sWorker.post(mLoaderTask);
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
private void loadAndBindWorkspace() {
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
// Bind the workspace
bindWorkspace();
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
public void run() {
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
loadAndBindAllApps();
}
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
loadAndBindWorkspace();
}
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
return true;
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (occupied[item.screen][x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + item.screen + ":"
+ x + "," + y
+ ") occupied by "
+ occupied[item.screen][x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
occupied[item.screen][x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
sWorkspaceItems.clear();
sAppWidgets.clear();
sFolders.clear();
sItemsIdMap.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
final ItemInfo occupied[][][] =
new ItemInfo[Launcher.SCREEN_COUNT][mCellCountX][mCellCountY];
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
sWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sFolders, container);
folderInfo.add(info);
break;
}
sItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
updateSavedIcon(context, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
sWorkspaceItems.add(folderInfo);
break;
}
sItemsIdMap.put(folderInfo.id, folderInfo);
sFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
Log.e(TAG, "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied[s][x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = sWorkspaceItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(sWorkspaceItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(sFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
N = sAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllAppsByBatch();
if (mStopped) {
return;
}
mAllAppsLoaded = true;
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAllAppsByBatch() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
if (i == 0) {
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp;
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mAllAppsList.updatePackage(context, packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mAllAppsList.removePackage(packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsAdded(addedFinal);
}
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
if (removed != null) {
final boolean permanent = mOp != OP_UNAVAILABLE;
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsRemoved(removedFinal, permanent);
}
}
});
}
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated();
}
}
});
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
if (labelCache != null && labelCache.containsKey(resolveInfo)) {
info.title = labelCache.get(resolveInfo);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(resolveInfo, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data,
int screen, int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
boolean needSave;
byte[] data = c.getBlob(iconIndex);
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
= new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return sCollator.compare(a.label.toString(), b.label.toString());
}
};
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screen = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, long container,
int screen, int cellX, int cellY, final boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Launcher l = (Launcher) context;
LauncherApplication app = (LauncherApplication) l.getApplication();
item.id = app.getLauncherProvider().generateNewId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, cellX, cellY);
sWorker.post(new Runnable() {
public void run() {
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
sItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.put(item.id, (FolderInfo) item);
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
});
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
int cellId, int screen, int localCellX, int localCellY, int spanX, int spanY) {
return ((cellId & 0xFF) << 24)
| (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, final ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
sWorker.post(new Runnable() {
public void run() {
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false),
values, null, null);
final ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
throw new RuntimeException("Error: ItemInfo passed to moveItemInDatabase " +
"doesn't match original");
}
}
});
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
sWorker.post(new Runnable() {
public void run() {
cr.delete(uriToDelete, null, null);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.remove(item.id);
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sItemsIdMap.remove(item.id);
}
});
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
sWorker.post(new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
sItemsIdMap.remove(info.id);
sFolders.remove(info.id);
sWorkspaceItems.remove(info);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
for (ItemInfo childInfo : info.contents) {
sItemsIdMap.remove(childInfo.id);
}
}
});
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps.
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything
// next time.
mAllAppsLoaded = false;
startLoaderFromBackground();
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(mApp, false);
}
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldTask.stopLocked();
}
mLoaderTask = new LoaderTask(context, isLaunching);
sWorker.post(mLoaderTask);
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
private void loadAndBindWorkspace() {
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
// Bind the workspace
bindWorkspace();
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
public void run() {
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
loadAndBindAllApps();
}
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
loadAndBindWorkspace();
}
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
return true;
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (occupied[item.screen][x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + item.screen + ":"
+ x + "," + y
+ ") occupied by "
+ occupied[item.screen][x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
occupied[item.screen][x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
sWorkspaceItems.clear();
sAppWidgets.clear();
sFolders.clear();
sItemsIdMap.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
final ItemInfo occupied[][][] =
new ItemInfo[Launcher.SCREEN_COUNT][mCellCountX][mCellCountY];
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
sWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sFolders, container);
folderInfo.add(info);
break;
}
sItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
updateSavedIcon(context, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
sWorkspaceItems.add(folderInfo);
break;
}
sItemsIdMap.put(folderInfo.id, folderInfo);
sFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
Log.e(TAG, "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied[s][x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = sWorkspaceItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(sWorkspaceItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(sFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
N = sAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllAppsByBatch();
if (mStopped) {
return;
}
mAllAppsLoaded = true;
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAllAppsByBatch() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
if (i == 0) {
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp;
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mAllAppsList.updatePackage(context, packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mAllAppsList.removePackage(packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsAdded(addedFinal);
}
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
if (removed != null) {
final boolean permanent = mOp != OP_UNAVAILABLE;
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsRemoved(removedFinal, permanent);
}
}
});
}
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated();
}
}
});
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
if (labelCache != null && labelCache.containsKey(resolveInfo)) {
info.title = labelCache.get(resolveInfo);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(resolveInfo, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data,
int screen, int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
void updateSavedIcon(Context context, ShortcutInfo info, Cursor c, int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
boolean needSave;
byte[] data = c.getBlob(iconIndex);
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = sCollator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
= new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return sCollator.compare(a.label.toString(), b.label.toString());
}
};
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
|
diff --git a/src/org/joval/plugin/adapter/independent/BaseFileAdapter.java b/src/org/joval/plugin/adapter/independent/BaseFileAdapter.java
index d96bd17c..96c308e9 100755
--- a/src/org/joval/plugin/adapter/independent/BaseFileAdapter.java
+++ b/src/org/joval/plugin/adapter/independent/BaseFileAdapter.java
@@ -1,736 +1,739 @@
// Copyright (C) 2011 jOVAL.org. All rights reserved.
// This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt
package org.joval.plugin.adapter.independent;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.xml.bind.JAXBElement;
import oval.schemas.common.MessageLevelEnumeration;
import oval.schemas.common.MessageType;
import oval.schemas.common.OperationEnumeration;
import oval.schemas.definitions.core.EntityObjectStringType;
import oval.schemas.definitions.core.ObjectType;
import oval.schemas.systemcharacteristics.core.EntityItemAnySimpleType;
import oval.schemas.systemcharacteristics.core.EntityItemIntType;
import oval.schemas.systemcharacteristics.core.EntityItemStringType;
import oval.schemas.systemcharacteristics.core.EntityItemVersionType;
import oval.schemas.systemcharacteristics.core.FlagEnumeration;
import oval.schemas.systemcharacteristics.core.ItemType;
import oval.schemas.systemcharacteristics.core.StatusEnumeration;
/* DAS: TBD -- adding view information to the base objects.
import oval.schemas.systemcharacteristics.independent.EntityItemWindowsViewType;
import oval.schemas.systemcharacteristics.windows.EntityItemWindowsViewType;
*/
import org.joval.intf.io.IFile;
import org.joval.intf.io.IFilesystem;
import org.joval.intf.plugin.IAdapter;
import org.joval.intf.plugin.IRequestContext;
import org.joval.intf.system.ISession;
import org.joval.intf.util.tree.INode;
import org.joval.intf.windows.system.IWindowsSession;
import org.joval.oval.OvalException;
import org.joval.oval.ResolveException;
import org.joval.util.JOVALMsg;
import org.joval.util.JOVALSystem;
import org.joval.util.Version;
/**
* Base class for IFile-based IAdapters. Subclasses need only implement getObjectClass, createFileItem, convertFilename
* and getItems methods. The base class handles searches and caching of search results.
*
* @author David A. Solin
* @version %I% %G%
*/
public abstract class BaseFileAdapter implements IAdapter {
protected ISession session;
protected Hashtable<String, Collection<String>> pathMap;
protected BaseFileAdapter(ISession session) {
this.session = session;
pathMap = new Hashtable<String, Collection<String>>();
}
// Implement IAdapter
public boolean connect() {
return true;
}
public void disconnect() {
}
public Collection<JAXBElement<? extends ItemType>> getItems(IRequestContext rc) throws OvalException {
ObjectType obj = rc.getObject();
String id = obj.getId();
if (!obj.getClass().getName().equals(getObjectClass().getName())) {
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_INSTANCE,
getObjectClass().getName(), obj.getClass().getName()));
}
//
// Get the appropriate IFilesystem
//
ReflectedFileObject fObj = new ReflectedFileObject(obj);
ReflectedFileBehaviors behaviors = null;
if (fObj.isSetBehaviors()) {
behaviors = fObj.getBehaviors();
}
IFilesystem fs = null;
int winView = 0;
if (session instanceof IWindowsSession) {
if (behaviors != null) {
if ("32_bit".equals(behaviors.getWindowsView())) {
fs = ((IWindowsSession)session).getFilesystem(IWindowsSession.View._32BIT);
winView = 32;
}
}
if (winView == 0 && ((IWindowsSession)session).supports(IWindowsSession.View._64BIT)) {
winView = 64;
}
}
if (fs == null) {
fs = session.getFilesystem();
}
Collection<JAXBElement<? extends ItemType>> items = new Vector<JAXBElement<? extends ItemType>>();
Collection<String> paths = getPathList(rc, fs, behaviors);
for (String path : paths) {
IFile f = null;
try {
ReflectedFileItem fItem = new ReflectedFileItem();
f = fs.getFile(path);
if (!f.exists()) {
throw new NoSuchElementException(path);
}
String dirPath = null;
boolean isDirectory = f.isDirectory();
if (isDirectory) {
dirPath = path;
} else {
dirPath = path.substring(0, path.lastIndexOf(fs.getDelimiter()));
}
if (fObj.isSetFilepath()) {
if (isDirectory) {
//
// Object is looking for files, so skip over this directory
//
continue;
} else {
EntityItemStringType filepathType = JOVALSystem.factories.sc.core.createEntityItemStringType();
filepathType.setValue(f.getLocalName());
EntityItemStringType pathType = JOVALSystem.factories.sc.core.createEntityItemStringType();
pathType.setValue(getPath(f));
EntityItemStringType filenameType = JOVALSystem.factories.sc.core.createEntityItemStringType();
filenameType.setValue(f.getName());
fItem.setFilepath(filepathType);
fItem.setPath(pathType);
fItem.setFilename(filenameType);
}
} else if (fObj.isSetFilename() && fObj.getFilename() != null) {
if (isDirectory) {
//
// Object is looking for files, so skip over this directory
//
continue;
} else {
EntityItemStringType filepathType = JOVALSystem.factories.sc.core.createEntityItemStringType();
filepathType.setValue(f.getLocalName());
EntityItemStringType pathType = JOVALSystem.factories.sc.core.createEntityItemStringType();
pathType.setValue(getPath(f));
EntityItemStringType filenameType = JOVALSystem.factories.sc.core.createEntityItemStringType();
filenameType.setValue(f.getName());
fItem.setFilepath(filepathType);
fItem.setPath(pathType);
fItem.setFilename(filenameType);
}
} else if (fObj.isSetPath()) {
EntityItemStringType pathType = JOVALSystem.factories.sc.core.createEntityItemStringType();
pathType.setValue(dirPath);
fItem.setPath(pathType);
if (!isDirectory) {
EntityItemStringType filenameType = JOVALSystem.factories.sc.core.createEntityItemStringType();
filenameType.setValue(f.getName());
fItem.setFilename(filenameType);
EntityItemStringType filepathType = JOVALSystem.factories.sc.core.createEntityItemStringType();
filepathType.setValue(getPath(f));
fItem.setFilepath(filepathType);
}
} else {
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_TEXTFILECONTENT_SPEC, id));
}
switch(winView) {
case 32:
fItem.setWindowsView("32_bit");
break;
case 64:
fItem.setWindowsView("64_bit");
break;
}
items.addAll(getItems(fItem.it, f, rc));
} catch (NoSuchElementException e) {
// skip it
} catch (IllegalAccessException e) {
JOVALSystem.getLogger().warn(JOVALMsg.ERROR_REFLECTION, e.getMessage());
} catch (IllegalArgumentException e) {
JOVALSystem.getLogger().warn(JOVALMsg.ERROR_REFLECTION, e.getMessage());
} catch (InvocationTargetException e) {
JOVALSystem.getLogger().warn(JOVALMsg.ERROR_REFLECTION, e.getMessage());
} catch (IOException e) {
MessageType msg = JOVALSystem.factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
if (f == null) {
msg.setValue(e.getMessage());
} else {
msg.setValue(JOVALSystem.getMessage(JOVALMsg.ERROR_IO, path, e.getMessage()));
}
rc.addMessage(msg);
}
}
return items;
}
// Protected
/**
* Return either an EntityItemStringType or a JAXBElement<EntityItemStringType>, as appropriate for the relevant ItemType.
*/
protected abstract Object convertFilename(EntityItemStringType filename);
/**
* Create and return an instance of the appropriate ItemType.
*/
protected abstract ItemType createFileItem();
/**
* Return a list of items to associate with the given ObjectType, based on information gathered from the IFile.
*
* @arg it the base ItemType containing filepath, path and filename information already populated
*/
protected abstract Collection<JAXBElement<? extends ItemType>>
getItems(ItemType it, IFile f, IRequestContext rc) throws IOException, OvalException;
// Internal
/**
* Get a list of String paths for this object. This accommodates searches (from pattern match operations),
* singletons (from equals operations) and handles recursive searches specified by FileBehaviors.
*/
final Collection<String> getPathList(IRequestContext rc, IFilesystem fs, ReflectedFileBehaviors fb) throws OvalException {
ObjectType obj = rc.getObject();
Collection<String> list = pathMap.get(obj.getId());
if (list != null) {
return list;
}
list = new Vector<String>();
try {
ReflectedFileObject fObj = new ReflectedFileObject(obj);
boolean patternMatch = false;
if (fObj.isSetFilepath()) {
Collection<String> filepaths = new Vector<String>();
EntityObjectStringType filepath = fObj.getFilepath();
if (filepath.isSetVarRef()) {
filepaths.addAll(rc.resolve(filepath.getVarRef()));
} else {
filepaths.add((String)filepath.getValue());
}
OperationEnumeration op = filepath.getOperation();
switch(op) {
case EQUALS:
list.addAll(filepaths);
break;
case PATTERN_MATCH:
patternMatch = true;
for (String value : filepaths) {
list.addAll(fs.search(Pattern.compile(value), false));
}
break;
default:
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op));
}
} else if (fObj.isSetPath()) {
//
// First, collect all possible matching paths (i.e., dirs)
//
Collection<String> paths = new Vector<String>();
EntityObjectStringType path = fObj.getPath();
if (path.isSetVarRef()) {
paths.addAll(rc.resolve(path.getVarRef()));
} else if (path.isSetValue()) {
paths.add((String)path.getValue());
}
OperationEnumeration op = path.getOperation();
switch(op) {
case EQUALS:
list.addAll(paths);
break;
case PATTERN_MATCH:
patternMatch = true;
for (String value : paths) {
for (String s : fs.search(Pattern.compile(value), false)) {
list.add(s);
}
}
break;
default:
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op));
}
if (fb != null) {
list = getDirs(list, fb.getDepth(), fb.getRecurseDirection(), fb.getRecurse(), fs);
} else if (patternMatch) {
//
// Wildcard pattern matches are really supposed to be recursive searches, unfortunately
//
Collection<String> newList = new Vector<String>();
for (String value : list) {
if (((String)path.getValue()).indexOf(".*") != -1 ||
((String)path.getValue()).indexOf(".+") != -1) {
Collection<String> l = new Vector<String>();
l.add(value);
newList.addAll(getDirs(l, -1, "down", "directories", fs));
}
}
for (String value : newList) {
if (!list.contains(value)) {
list.add(value);
}
}
}
if (fObj.isSetFilename()) {
EntityObjectStringType filename = fObj.getFilename();
if (filename == null) {
// False positive for isSetFilename -- happens with nil
} else {
Collection<String> fnames = new Vector<String>();
if (filename.isSetVarRef()) {
fnames.addAll(rc.resolve(filename.getVarRef()));
} else {
fnames.add((String)filename.getValue());
}
Collection<String> files = new Vector<String>();
for (String pathString : list) {
if (!pathString.endsWith(fs.getDelimiter())) {
pathString = pathString + fs.getDelimiter();
}
for (String fname : fnames) {
try {
switch(filename.getOperation()) {
case PATTERN_MATCH: {
IFile f = fs.getFile(pathString);
if (f.exists() && f.isDirectory() && f.hasChildren()) {
for (INode child : f.getChildren(Pattern.compile(fname))) {
files.add(child.getPath());
}
}
break;
}
case EQUALS:
files.add(pathString + fname);
break;
case NOT_EQUAL: {
IFile f = fs.getFile(pathString);
if (f.exists() && f.isDirectory() && f.hasChildren()) {
for (INode child : f.getChildren(Pattern.compile(fname))) {
files.add(child.getPath());
}
}
break;
}
default:
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION,
filename.getOperation()));
}
} catch (UnsupportedOperationException e) {
// ignore -- not a directory
} catch (IllegalArgumentException e) {
JOVALSystem.getLogger().warn(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
+ } catch (IOException e) {
+ MessageType msg = JOVALSystem.factories.common.createMessageType();
+ msg.setLevel(MessageLevelEnumeration.ERROR);
+ msg.setValue(e.getMessage());
+ rc.addMessage(msg);
}
}
}
list = files;
}
}
} else {
throw new OvalException("ERROR_BAD_FILEOBJECT" + obj.getId());
}
} catch (PatternSyntaxException e) {
JOVALSystem.getLogger().error(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
- } catch (IOException e) {
- JOVALSystem.getLogger().warn(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (NoSuchElementException e) {
JOVALSystem.getLogger().trace(JOVALMsg.STATUS_NOT_FOUND, e.getMessage(), obj.getId());
} catch (ResolveException e) {
MessageType msg = JOVALSystem.factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(e.getMessage());
rc.addMessage(msg);
}
pathMap.put(obj.getId(), list);
return list;
}
/**
* Finds directories recursively based on FileBahaviors.
*/
private Collection<String> getDirs(Collection<String> list, int depth, String direction, String recurse, IFilesystem fs) {
if ("none".equals(direction) || depth == 0) {
return list;
} else {
Collection<String> results = new Vector<String>();
for (String path : list) {
if (!path.endsWith(fs.getDelimiter())) {
path = path + fs.getDelimiter();
}
JOVALSystem.getLogger().trace(JOVALMsg.STATUS_FS_RECURSE, path);
try {
IFile f = (IFile)fs.lookup(path);
if (f == null) {
// skip permission denied (or other access error)
} else if (!f.exists()) {
// skip non-existent files
} else if (recurse != null && recurse.indexOf("symlinks") == -1 && f.isLink()) {
// skip the symlink
} else if (recurse != null && recurse.indexOf("directories") == -1 && f.isDirectory()) {
// skip the directory
} else if (f.isDirectory()) {
results.add(f.getLocalName());
if ("up".equals(direction)) {
int ptr = 0;
ptr = path.lastIndexOf(fs.getDelimiter(), path.lastIndexOf(fs.getDelimiter())-1);
if (ptr != -1) {
Vector<String> v = new Vector<String>();
v.add(path.substring(0, ptr));
results.addAll(getDirs(v, --depth, direction, recurse, fs));
}
} else { // recurse down
Vector<String> v = new Vector<String>();
for (INode child : f.getChildren()) {
v.add(child.getPath());
}
results.addAll(getDirs(v, --depth, direction, recurse, fs));
}
}
} catch (UnsupportedOperationException e) {
// ignore -- not a directory
} catch (NoSuchElementException e) {
// dir path doesn't exist.
} catch (FileNotFoundException e) {
// link is not a link to a directory
} catch (IOException e) {
JOVALSystem.getLogger().warn(JOVALMsg.ERROR_IO, path, e.getMessage());
JOVALSystem.getLogger().debug(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
}
}
//
// Eliminate any duplicates, and remove any trailing slashes
//
HashSet<String> deduped = new HashSet<String>();
for (String s : results) {
if (!deduped.contains(s)) {
deduped.add(s);
}
}
return deduped;
}
}
private String getPath(IFile f) {
String name = f.getName();
String path = f.getLocalName();
int len = path.length();
if (len > 1) {
return path.substring(0, len - name.length() - 1);
} else {
return path;
}
}
/**
* A reflection proxy for:
* oval.schemas.definitions.independent.Textfilecontent54Object
* oval.schemas.definitions.independent.TextfilecontentObject
* oval.schemas.definitions.unix.FileObject
* oval.schemas.definitions.windows.FileObject
*/
class ReflectedFileObject {
ObjectType obj;
String id = null;
EntityObjectStringType filepath = null, path = null, filename = null;
ReflectedFileBehaviors behaviors = null;
ReflectedFileObject(ObjectType obj) {
this.obj = obj;
try {
Method getId = obj.getClass().getMethod("getId");
Object o = getId.invoke(obj);
if (o != null) {
id = (String)o;
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}
try {
Method getFilepath = obj.getClass().getMethod("getFilepath");
Object o = getFilepath.invoke(obj);
if (o != null) {
filepath = (EntityObjectStringType)o;
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}
try {
Method getFilename = obj.getClass().getMethod("getFilename");
Object o = getFilename.invoke(obj);
if (o != null) {
if (o instanceof JAXBElement) {
o = ((JAXBElement)o).getValue();
}
filename = (EntityObjectStringType)o;
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}
try {
Method getPath = obj.getClass().getMethod("getPath");
Object o = getPath.invoke(obj);
if (o != null) {
path = (EntityObjectStringType)o;
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}
try {
Method getBehaviors = obj.getClass().getMethod("getBehaviors");
Object o = getBehaviors.invoke(obj);
if (o != null) {
behaviors = new ReflectedFileBehaviors(o);
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}
}
String getId() {
return id;
}
boolean isSetFilepath() {
return filepath != null;
}
EntityObjectStringType getFilepath() {
return filepath;
}
boolean isSetFilename() {
return filename != null;
}
EntityObjectStringType getFilename() {
return filename;
}
boolean isSetPath() {
return path != null;
}
EntityObjectStringType getPath() {
return path;
}
boolean isSetBehaviors() {
return behaviors != null;
}
ReflectedFileBehaviors getBehaviors() {
return behaviors;
}
}
/**
* A reflection proxy for:
* oval.schemas.definitions.independent.FileBehaviors
* oval.schemas.definitions.unix.FileBehaviors
* oval.schemas.definitions.windows.FileBehaviors
*/
class ReflectedFileBehaviors {
BigInteger maxDepth = new BigInteger("-1");
String recurseDirection = "none";
String recurse = "symlinks and directories";
String recurseFS = "all";
String windowsView = "64_bit";
ReflectedFileBehaviors(Object obj)
throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (obj != null) {
Method getMaxDepth = obj.getClass().getMethod("getMaxDepth");
maxDepth = (BigInteger)getMaxDepth.invoke(obj);
Method getRecurseDirection = obj.getClass().getMethod("getRecurseDirection");
recurseDirection = (String)getRecurseDirection.invoke(obj);
try {
//
// Not applicable to Unix FileBehaviors
//
Method getWindowsView = obj.getClass().getMethod("getWindowsView");
windowsView = (String)getWindowsView.invoke(obj);
} catch (NoSuchMethodException e) {
recurse = null;
}
try {
//
// Not applicable to Windows FileBehaviors
//
Method getRecurse = obj.getClass().getMethod("getRecurse");
recurse = (String)getRecurse.invoke(obj);
} catch (NoSuchMethodException e) {
recurse = null;
}
Method getRecurseFileSystem = obj.getClass().getMethod("getRecurseFileSystem");
recurseFS = (String)getRecurseFileSystem.invoke(obj);
if (!"all".equals(recurseFS)) {
JOVALSystem.getLogger().error(JOVALMsg.ERROR_UNSUPPORTED_BEHAVIOR, recurseFS);
}
}
if ("none".equals(recurseDirection)) {
maxDepth = BigInteger.ZERO;
}
}
String getRecurse() {
return recurse;
}
String getRecurseDirection() {
return recurseDirection;
}
int getDepth() {
return Integer.parseInt(maxDepth.toString());
}
String getRecurseFileSystem() {
return recurseFS;
}
String getWindowsView() {
return windowsView;
}
}
/**
* A reflection proxy for:
* oval.schemas.systemcharacteristics.independent.TextfilecontentItem
* oval.schemas.systemcharacteristics.unix.FileItem
* oval.schemas.systemcharacteristics.windows.FileItem
*/
class ReflectedFileItem {
ItemType it;
Method setFilepath, setFilename, setPath, setStatus, setWindowsView;
ReflectedFileItem() {
it = createFileItem();
Method[] methods = it.getClass().getMethods();
for (int i=0; i < methods.length; i++) {
String name = methods[i].getName();
if ("setFilepath".equals(name)) {
setFilepath = methods[i];
} else if ("setFilename".equals(name)) {
setFilename = methods[i];
} else if ("setPath".equals(name)) {
setPath = methods[i];
} else if ("setStatus".equals(name)) {
setStatus = methods[i];
} else if ("setWindowsView".equals(name)) {
setWindowsView = methods[i];
}
}
}
void setWindowsView(String view) {
try {
if (setWindowsView != null) {
Class[] types = setWindowsView.getParameterTypes();
if (types.length == 1) {
Class type = types[0];
Object instance = Class.forName(type.getName());
@SuppressWarnings("unchecked")
Method setValue = type.getMethod("setValue", Object.class);
setValue.invoke(instance, view);
setWindowsView.invoke(it, instance);
}
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
} catch (ClassNotFoundException e) {
}
}
void setFilename(EntityItemStringType filename)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
setFilename.invoke(it, convertFilename(filename));
}
void setFilepath(EntityItemStringType filepath)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
setFilepath.invoke(it, filepath);
}
void setPath(EntityItemStringType path)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
setPath.invoke(it, path);
}
void setStatus(StatusEnumeration status)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
setStatus.invoke(it, status);
}
}
}
| false | true | final Collection<String> getPathList(IRequestContext rc, IFilesystem fs, ReflectedFileBehaviors fb) throws OvalException {
ObjectType obj = rc.getObject();
Collection<String> list = pathMap.get(obj.getId());
if (list != null) {
return list;
}
list = new Vector<String>();
try {
ReflectedFileObject fObj = new ReflectedFileObject(obj);
boolean patternMatch = false;
if (fObj.isSetFilepath()) {
Collection<String> filepaths = new Vector<String>();
EntityObjectStringType filepath = fObj.getFilepath();
if (filepath.isSetVarRef()) {
filepaths.addAll(rc.resolve(filepath.getVarRef()));
} else {
filepaths.add((String)filepath.getValue());
}
OperationEnumeration op = filepath.getOperation();
switch(op) {
case EQUALS:
list.addAll(filepaths);
break;
case PATTERN_MATCH:
patternMatch = true;
for (String value : filepaths) {
list.addAll(fs.search(Pattern.compile(value), false));
}
break;
default:
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op));
}
} else if (fObj.isSetPath()) {
//
// First, collect all possible matching paths (i.e., dirs)
//
Collection<String> paths = new Vector<String>();
EntityObjectStringType path = fObj.getPath();
if (path.isSetVarRef()) {
paths.addAll(rc.resolve(path.getVarRef()));
} else if (path.isSetValue()) {
paths.add((String)path.getValue());
}
OperationEnumeration op = path.getOperation();
switch(op) {
case EQUALS:
list.addAll(paths);
break;
case PATTERN_MATCH:
patternMatch = true;
for (String value : paths) {
for (String s : fs.search(Pattern.compile(value), false)) {
list.add(s);
}
}
break;
default:
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op));
}
if (fb != null) {
list = getDirs(list, fb.getDepth(), fb.getRecurseDirection(), fb.getRecurse(), fs);
} else if (patternMatch) {
//
// Wildcard pattern matches are really supposed to be recursive searches, unfortunately
//
Collection<String> newList = new Vector<String>();
for (String value : list) {
if (((String)path.getValue()).indexOf(".*") != -1 ||
((String)path.getValue()).indexOf(".+") != -1) {
Collection<String> l = new Vector<String>();
l.add(value);
newList.addAll(getDirs(l, -1, "down", "directories", fs));
}
}
for (String value : newList) {
if (!list.contains(value)) {
list.add(value);
}
}
}
if (fObj.isSetFilename()) {
EntityObjectStringType filename = fObj.getFilename();
if (filename == null) {
// False positive for isSetFilename -- happens with nil
} else {
Collection<String> fnames = new Vector<String>();
if (filename.isSetVarRef()) {
fnames.addAll(rc.resolve(filename.getVarRef()));
} else {
fnames.add((String)filename.getValue());
}
Collection<String> files = new Vector<String>();
for (String pathString : list) {
if (!pathString.endsWith(fs.getDelimiter())) {
pathString = pathString + fs.getDelimiter();
}
for (String fname : fnames) {
try {
switch(filename.getOperation()) {
case PATTERN_MATCH: {
IFile f = fs.getFile(pathString);
if (f.exists() && f.isDirectory() && f.hasChildren()) {
for (INode child : f.getChildren(Pattern.compile(fname))) {
files.add(child.getPath());
}
}
break;
}
case EQUALS:
files.add(pathString + fname);
break;
case NOT_EQUAL: {
IFile f = fs.getFile(pathString);
if (f.exists() && f.isDirectory() && f.hasChildren()) {
for (INode child : f.getChildren(Pattern.compile(fname))) {
files.add(child.getPath());
}
}
break;
}
default:
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION,
filename.getOperation()));
}
} catch (UnsupportedOperationException e) {
// ignore -- not a directory
} catch (IllegalArgumentException e) {
JOVALSystem.getLogger().warn(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
}
}
}
list = files;
}
}
} else {
throw new OvalException("ERROR_BAD_FILEOBJECT" + obj.getId());
}
} catch (PatternSyntaxException e) {
JOVALSystem.getLogger().error(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (IOException e) {
JOVALSystem.getLogger().warn(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (NoSuchElementException e) {
JOVALSystem.getLogger().trace(JOVALMsg.STATUS_NOT_FOUND, e.getMessage(), obj.getId());
} catch (ResolveException e) {
MessageType msg = JOVALSystem.factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(e.getMessage());
rc.addMessage(msg);
}
pathMap.put(obj.getId(), list);
return list;
}
| final Collection<String> getPathList(IRequestContext rc, IFilesystem fs, ReflectedFileBehaviors fb) throws OvalException {
ObjectType obj = rc.getObject();
Collection<String> list = pathMap.get(obj.getId());
if (list != null) {
return list;
}
list = new Vector<String>();
try {
ReflectedFileObject fObj = new ReflectedFileObject(obj);
boolean patternMatch = false;
if (fObj.isSetFilepath()) {
Collection<String> filepaths = new Vector<String>();
EntityObjectStringType filepath = fObj.getFilepath();
if (filepath.isSetVarRef()) {
filepaths.addAll(rc.resolve(filepath.getVarRef()));
} else {
filepaths.add((String)filepath.getValue());
}
OperationEnumeration op = filepath.getOperation();
switch(op) {
case EQUALS:
list.addAll(filepaths);
break;
case PATTERN_MATCH:
patternMatch = true;
for (String value : filepaths) {
list.addAll(fs.search(Pattern.compile(value), false));
}
break;
default:
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op));
}
} else if (fObj.isSetPath()) {
//
// First, collect all possible matching paths (i.e., dirs)
//
Collection<String> paths = new Vector<String>();
EntityObjectStringType path = fObj.getPath();
if (path.isSetVarRef()) {
paths.addAll(rc.resolve(path.getVarRef()));
} else if (path.isSetValue()) {
paths.add((String)path.getValue());
}
OperationEnumeration op = path.getOperation();
switch(op) {
case EQUALS:
list.addAll(paths);
break;
case PATTERN_MATCH:
patternMatch = true;
for (String value : paths) {
for (String s : fs.search(Pattern.compile(value), false)) {
list.add(s);
}
}
break;
default:
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, op));
}
if (fb != null) {
list = getDirs(list, fb.getDepth(), fb.getRecurseDirection(), fb.getRecurse(), fs);
} else if (patternMatch) {
//
// Wildcard pattern matches are really supposed to be recursive searches, unfortunately
//
Collection<String> newList = new Vector<String>();
for (String value : list) {
if (((String)path.getValue()).indexOf(".*") != -1 ||
((String)path.getValue()).indexOf(".+") != -1) {
Collection<String> l = new Vector<String>();
l.add(value);
newList.addAll(getDirs(l, -1, "down", "directories", fs));
}
}
for (String value : newList) {
if (!list.contains(value)) {
list.add(value);
}
}
}
if (fObj.isSetFilename()) {
EntityObjectStringType filename = fObj.getFilename();
if (filename == null) {
// False positive for isSetFilename -- happens with nil
} else {
Collection<String> fnames = new Vector<String>();
if (filename.isSetVarRef()) {
fnames.addAll(rc.resolve(filename.getVarRef()));
} else {
fnames.add((String)filename.getValue());
}
Collection<String> files = new Vector<String>();
for (String pathString : list) {
if (!pathString.endsWith(fs.getDelimiter())) {
pathString = pathString + fs.getDelimiter();
}
for (String fname : fnames) {
try {
switch(filename.getOperation()) {
case PATTERN_MATCH: {
IFile f = fs.getFile(pathString);
if (f.exists() && f.isDirectory() && f.hasChildren()) {
for (INode child : f.getChildren(Pattern.compile(fname))) {
files.add(child.getPath());
}
}
break;
}
case EQUALS:
files.add(pathString + fname);
break;
case NOT_EQUAL: {
IFile f = fs.getFile(pathString);
if (f.exists() && f.isDirectory() && f.hasChildren()) {
for (INode child : f.getChildren(Pattern.compile(fname))) {
files.add(child.getPath());
}
}
break;
}
default:
throw new OvalException(JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION,
filename.getOperation()));
}
} catch (UnsupportedOperationException e) {
// ignore -- not a directory
} catch (IllegalArgumentException e) {
JOVALSystem.getLogger().warn(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (IOException e) {
MessageType msg = JOVALSystem.factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(e.getMessage());
rc.addMessage(msg);
}
}
}
list = files;
}
}
} else {
throw new OvalException("ERROR_BAD_FILEOBJECT" + obj.getId());
}
} catch (PatternSyntaxException e) {
JOVALSystem.getLogger().error(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (NoSuchElementException e) {
JOVALSystem.getLogger().trace(JOVALMsg.STATUS_NOT_FOUND, e.getMessage(), obj.getId());
} catch (ResolveException e) {
MessageType msg = JOVALSystem.factories.common.createMessageType();
msg.setLevel(MessageLevelEnumeration.ERROR);
msg.setValue(e.getMessage());
rc.addMessage(msg);
}
pathMap.put(obj.getId(), list);
return list;
}
|
diff --git a/src/nl/tdegroot/games/nemesis/level/Level.java b/src/nl/tdegroot/games/nemesis/level/Level.java
index 0a87663..79078e1 100644
--- a/src/nl/tdegroot/games/nemesis/level/Level.java
+++ b/src/nl/tdegroot/games/nemesis/level/Level.java
@@ -1,65 +1,65 @@
package nl.tdegroot.games.nemesis.level;
import nl.tdegroot.games.nemesis.Camera;
import nl.tdegroot.games.nemesis.entity.Entity;
import org.lwjgl.opengl.Display;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.tiled.TiledMap;
import java.util.ArrayList;
import java.util.List;
public class Level {
private TiledMap map;
private final int tileSize;
private List<Entity> entities = new ArrayList<Entity>();
public Level(String path) throws SlickException {
map = new TiledMap(path);
tileSize = map.getTileWidth() & map.getTileHeight();
if (tileSize == 0) {
throw new SlickException("Tilewidth and Tileheight are not equal!");
}
}
public void update() {
for (int i = 0; i < entities.size(); i++) {
entities.get(i).update();
}
}
public void render(Graphics g, Camera camera) {
int x = (int) - (camera.getX() % tileSize) - tileSize;
int y = (int) - (camera.getY() % tileSize) - tileSize;
- int sx = (int) camera.getX() / tileSize;
- int sy = (int) camera.getY() / tileSize;
+ int sx = (int) (camera.getX() / tileSize) -1;
+ int sy = (int) (camera.getY() / tileSize) -1;
int sectionWidth = (Display.getWidth() / tileSize) + 3;
- int sectionHeight = (Display.getHeight() / tileSize) + 3;
+ int sectionHeight = (Display.getHeight() / tileSize) + 4;
map.render(x, y, sx, sy, sectionWidth, sectionHeight);
for (int i = 0; i < entities.size(); i++) {
entities.get(i).render(g, camera);
}
}
public void addEntity(Entity e) {
entities.add(e);
}
public TiledMap getMap() {
return map;
}
public float getPixelWidth() {
return map.getWidth() * map.getTileWidth();
}
public float getPixelHeight() {
return map.getHeight() * map.getTileHeight();
}
}
| false | true | public void render(Graphics g, Camera camera) {
int x = (int) - (camera.getX() % tileSize) - tileSize;
int y = (int) - (camera.getY() % tileSize) - tileSize;
int sx = (int) camera.getX() / tileSize;
int sy = (int) camera.getY() / tileSize;
int sectionWidth = (Display.getWidth() / tileSize) + 3;
int sectionHeight = (Display.getHeight() / tileSize) + 3;
map.render(x, y, sx, sy, sectionWidth, sectionHeight);
for (int i = 0; i < entities.size(); i++) {
entities.get(i).render(g, camera);
}
}
| public void render(Graphics g, Camera camera) {
int x = (int) - (camera.getX() % tileSize) - tileSize;
int y = (int) - (camera.getY() % tileSize) - tileSize;
int sx = (int) (camera.getX() / tileSize) -1;
int sy = (int) (camera.getY() / tileSize) -1;
int sectionWidth = (Display.getWidth() / tileSize) + 3;
int sectionHeight = (Display.getHeight() / tileSize) + 4;
map.render(x, y, sx, sy, sectionWidth, sectionHeight);
for (int i = 0; i < entities.size(); i++) {
entities.get(i).render(g, camera);
}
}
|
diff --git a/DroidPlanner/src/com/droidplanner/fragments/EditorListFragment.java b/DroidPlanner/src/com/droidplanner/fragments/EditorListFragment.java
index 4616a888..fda84a71 100644
--- a/DroidPlanner/src/com/droidplanner/fragments/EditorListFragment.java
+++ b/DroidPlanner/src/com/droidplanner/fragments/EditorListFragment.java
@@ -1,132 +1,132 @@
package com.droidplanner.fragments;
import it.sephiroth.android.library.widget.AdapterView;
import it.sephiroth.android.library.widget.AdapterView.OnItemClickListener;
import it.sephiroth.android.library.widget.AdapterView.OnItemLongClickListener;
import it.sephiroth.android.library.widget.AdapterView.OnItemSelectedListener;
import it.sephiroth.android.library.widget.HListView;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.droidplanner.DroidPlannerApp;
import com.droidplanner.R;
import com.droidplanner.activitys.helpers.OnEditorInteraction;
import com.droidplanner.drone.DroneInterfaces.OnWaypointChangedListner;
import com.droidplanner.drone.variables.mission.Mission;
import com.droidplanner.drone.variables.mission.MissionItem;
import com.droidplanner.widgets.adapterViews.MissionItemView;
public class EditorListFragment extends Fragment implements OnWaypointChangedListner, OnItemLongClickListener, OnItemClickListener, OnItemSelectedListener{
public HListView list;
private Mission mission;
private MissionItemView adapter;
private OnEditorInteraction editorListner;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.fragment_mission, container,
+ View view = inflater.inflate(R.layout.fragment_mission_list, container,
false);
list = (HListView) view.findViewById(R.id.listView1);
mission = ((DroidPlannerApp) getActivity().getApplication()).drone.mission;
mission.addOnMissionUpdateListner(this);
adapter = new MissionItemView(this.getActivity(), android.R.layout.simple_list_item_1,mission.getItems());
list.setOnItemClickListener(this);
list.setOnItemLongClickListener(this);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setAdapter(adapter);
Log.i( "LIST", "choice mode: " + list.getChoiceMode() );
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
editorListner = (OnEditorInteraction) ( activity);
}
@Override
public void onDestroy() {
super.onDestroy();
mission.removeOnMissionUpdateListner(this);
}
public void update() {
adapter.notifyDataSetChanged();
}
/*
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.d("T", "touched "+position);
DialogMissionFactory.getDialog(adapter.getItem(position), this.getActivity(), mission);
super.onListItemClick(l, v, position, id);
}*/
@Override
public void onMissionUpdate() {
update();
}
public void deleteSelected() {
SparseBooleanArray selected = list.getCheckedItemPositions();
ArrayList<MissionItem> toRemove = new ArrayList<MissionItem>();
for( int i = 0; i < selected.size(); i++ ) {
if( selected.valueAt( i ) ) {
MissionItem item = adapter.getItem(selected.keyAt(i));
toRemove.add(item);
}
}
mission.removeWaypoints(toRemove);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Log.d("LIST", "you onItemSelected "+ position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
Log.d("LIST", "you onNothingSelected ");
}
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position,
long id) {
Log.d("LIST", "you onItemClick "+ position);
MissionItem missionItem = (MissionItem) adapter.getItemAtPosition(position);
editorListner.onItemClick(missionItem);
}
@Override
public boolean onItemLongClick(AdapterView<?> adapter, View view,
int position, long id) {
Log.d("LIST", "you longcliked item "+position);
MissionItem missionItem = (MissionItem) adapter.getItemAtPosition(position);
return editorListner.onItemLongClick(missionItem);
}
}
| true | true | public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mission, container,
false);
list = (HListView) view.findViewById(R.id.listView1);
mission = ((DroidPlannerApp) getActivity().getApplication()).drone.mission;
mission.addOnMissionUpdateListner(this);
adapter = new MissionItemView(this.getActivity(), android.R.layout.simple_list_item_1,mission.getItems());
list.setOnItemClickListener(this);
list.setOnItemLongClickListener(this);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setAdapter(adapter);
Log.i( "LIST", "choice mode: " + list.getChoiceMode() );
return view;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mission_list, container,
false);
list = (HListView) view.findViewById(R.id.listView1);
mission = ((DroidPlannerApp) getActivity().getApplication()).drone.mission;
mission.addOnMissionUpdateListner(this);
adapter = new MissionItemView(this.getActivity(), android.R.layout.simple_list_item_1,mission.getItems());
list.setOnItemClickListener(this);
list.setOnItemLongClickListener(this);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setAdapter(adapter);
Log.i( "LIST", "choice mode: " + list.getChoiceMode() );
return view;
}
|
diff --git a/src/edu/jhu/thrax/util/CreateGlueGrammar.java b/src/edu/jhu/thrax/util/CreateGlueGrammar.java
index 3fdce71..6be3f0f 100644
--- a/src/edu/jhu/thrax/util/CreateGlueGrammar.java
+++ b/src/edu/jhu/thrax/util/CreateGlueGrammar.java
@@ -1,70 +1,70 @@
package edu.jhu.thrax.util;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import edu.jhu.thrax.util.io.LineReader;
public class CreateGlueGrammar {
private static HashSet<String> nts;
// [GOAL] ||| [GOAL,1] [X,2] ||| [GOAL,1] [X,2] ||| -1
// [GOAL] ||| [GOAL,1] </s> ||| [GOAL,1] </s> ||| 0
// [GOAL] ||| <s> ||| <s> ||| 0
private static final String R_START = "[%1$s] ||| <s> ||| <s> ||| 0";
private static final String R_TWO = "[%1$s] ||| [%1$s,1] [%2$s,2] ||| [%1$s,1] [%2$s,2] ||| -1";
private static final String R_END = "[%1$s] ||| [%1$s,1] </s> ||| [%1$s,1] </s> ||| 0";
// [GOAL] ||| <s> [X,1] </s> ||| <s> [X,1] </s> ||| 0
private static final String R_TOP = "[%1$s] ||| <s> [%2$s,1] </s> ||| <s> [%2$s,1] </s> ||| 0";
private static String GOAL = "GOAL";
public static void main(String[] argv) throws IOException {
String grammar_file_name = null;
if (argv.length > 0) grammar_file_name = argv[0];
if (argv.length > 1) GOAL = argv[1];
if (grammar_file_name == null) {
System.err.println("No grammar specified.");
System.exit(1);
}
File grammar_file = new File(grammar_file_name);
if (!grammar_file.exists()) {
System.err.println("Grammar file doesn't exist: " + grammar_file_name);
System.exit(1);
}
nts = new HashSet<String>();
if (grammar_file.isDirectory()) {
Vocabulary.read(grammar_file_name + File.separator + "vocabulary");
for (int i = 0; i < Vocabulary.size(); ++i) {
String token = Vocabulary.word(i);
- if (Vocabulary.nt(token)) nts.add(token.substring(1, token.length()));
+ if (Vocabulary.nt(token)) nts.add(token.substring(1, token.length() - 1));
}
} else {
LineReader reader = new LineReader(grammar_file_name);
while (reader.hasNext()) {
String line = reader.next();
int lhsStart = line.indexOf("[") + 1;
int lhsEnd = line.indexOf("]");
if (lhsStart < 1 || lhsEnd < 0) {
System.err.printf("malformed rule: %s\n", line);
continue;
}
String lhs = line.substring(lhsStart, lhsEnd);
nts.add(lhs);
}
}
System.out.println(String.format(R_START, GOAL));
for (String nt : nts)
System.out.println(String.format(R_TWO, GOAL, nt));
System.out.println(String.format(R_END, GOAL));
for (String nt : nts)
System.out.println(String.format(R_TOP, GOAL, nt));
}
}
| true | true | public static void main(String[] argv) throws IOException {
String grammar_file_name = null;
if (argv.length > 0) grammar_file_name = argv[0];
if (argv.length > 1) GOAL = argv[1];
if (grammar_file_name == null) {
System.err.println("No grammar specified.");
System.exit(1);
}
File grammar_file = new File(grammar_file_name);
if (!grammar_file.exists()) {
System.err.println("Grammar file doesn't exist: " + grammar_file_name);
System.exit(1);
}
nts = new HashSet<String>();
if (grammar_file.isDirectory()) {
Vocabulary.read(grammar_file_name + File.separator + "vocabulary");
for (int i = 0; i < Vocabulary.size(); ++i) {
String token = Vocabulary.word(i);
if (Vocabulary.nt(token)) nts.add(token.substring(1, token.length()));
}
} else {
LineReader reader = new LineReader(grammar_file_name);
while (reader.hasNext()) {
String line = reader.next();
int lhsStart = line.indexOf("[") + 1;
int lhsEnd = line.indexOf("]");
if (lhsStart < 1 || lhsEnd < 0) {
System.err.printf("malformed rule: %s\n", line);
continue;
}
String lhs = line.substring(lhsStart, lhsEnd);
nts.add(lhs);
}
}
System.out.println(String.format(R_START, GOAL));
for (String nt : nts)
System.out.println(String.format(R_TWO, GOAL, nt));
System.out.println(String.format(R_END, GOAL));
for (String nt : nts)
System.out.println(String.format(R_TOP, GOAL, nt));
}
| public static void main(String[] argv) throws IOException {
String grammar_file_name = null;
if (argv.length > 0) grammar_file_name = argv[0];
if (argv.length > 1) GOAL = argv[1];
if (grammar_file_name == null) {
System.err.println("No grammar specified.");
System.exit(1);
}
File grammar_file = new File(grammar_file_name);
if (!grammar_file.exists()) {
System.err.println("Grammar file doesn't exist: " + grammar_file_name);
System.exit(1);
}
nts = new HashSet<String>();
if (grammar_file.isDirectory()) {
Vocabulary.read(grammar_file_name + File.separator + "vocabulary");
for (int i = 0; i < Vocabulary.size(); ++i) {
String token = Vocabulary.word(i);
if (Vocabulary.nt(token)) nts.add(token.substring(1, token.length() - 1));
}
} else {
LineReader reader = new LineReader(grammar_file_name);
while (reader.hasNext()) {
String line = reader.next();
int lhsStart = line.indexOf("[") + 1;
int lhsEnd = line.indexOf("]");
if (lhsStart < 1 || lhsEnd < 0) {
System.err.printf("malformed rule: %s\n", line);
continue;
}
String lhs = line.substring(lhsStart, lhsEnd);
nts.add(lhs);
}
}
System.out.println(String.format(R_START, GOAL));
for (String nt : nts)
System.out.println(String.format(R_TWO, GOAL, nt));
System.out.println(String.format(R_END, GOAL));
for (String nt : nts)
System.out.println(String.format(R_TOP, GOAL, nt));
}
|
diff --git a/src/com/clarkparsia/utils/web/Request.java b/src/com/clarkparsia/utils/web/Request.java
index 556722c..4adf7e0 100644
--- a/src/com/clarkparsia/utils/web/Request.java
+++ b/src/com/clarkparsia/utils/web/Request.java
@@ -1,322 +1,322 @@
/*
* Copyright (c) 2005-2010 Clark & Parsia, LLC. <http://www.clarkparsia.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.clarkparsia.utils.web;
import com.clarkparsia.utils.io.Encoder;
import com.clarkparsia.utils.io.IOUtil;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Closeable;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
/**
* <p></p>
*
* @author Michael Grove
* @since 1.0
* @version 1.1
*/
public class Request {
private URL mURL;
private Method mMethod;
private ParameterList mParameters = new ParameterList();
private InputStream mBody;
private Map<String, Header> mHeaders = new HashMap<String, Header>();
private int mTimeout = -1;
private boolean mFollowRedirects;
public Request(String theURL) throws MalformedURLException {
this(Method.GET, new URL(theURL));
}
public Request(URL theURL) {
this(Method.GET, theURL);
}
public Request(Method theMethod, URL theURL) {
mMethod = theMethod;
mURL = theURL;
}
public static Request formPost(URL theURL, ParameterList theParams) {
Request aRequest = new Request(Method.POST, theURL);
aRequest.addHeader(new Header(HttpHeaders.ContentType.getName(), MimeTypes.FormUrlEncoded.getMimeType()));
aRequest.setBody(theParams.toString());
return aRequest;
}
/**
* Return the current timeout value
* @return the timeout value in milliseconds or -1 for no timeout
*/
public int getTimeout() {
return mTimeout;
}
/**
* Set the timeout associated associated with this request
* @param theTimeout the timeout in milliseconds, or -1 for no timeout
* @return this request
*/
public Request setTimeout(final int theTimeout) {
mTimeout = theTimeout;
return this;
}
/**
* Return whether or not this request will follow redirects
* @return true to follow redirects, false otherwise
*/
public boolean isFollowRedirects() {
return mFollowRedirects;
}
/**
* Set whether or not this request will follow redirects
* @param theFollowRedirects true to follow redirects, false otherwise
* @return this request
*/
public Request setFollowRedirects(final boolean theFollowRedirects) {
mFollowRedirects = theFollowRedirects;
return this;
}
/**
* Add a parameter to this web request
* @param theKey the parameter key
* @param theValue the parameter value
* @return this request
*/
public Request addParameter(String theKey, String theValue) {
return addParameter(new Parameter(theKey, theValue));
}
/**
* Adds a parameter to this web request
* @param theParameter the parameter to add
* @return this request
*/
public Request addParameter(Parameter theParameter) {
mParameters.add(theParameter);
return this;
}
/**
* Sets the list of parameters for this web request
* @param theParameters the list of parameters
* @return this request
*/
public Request setParameters(final ParameterList theParameters) {
mParameters = theParameters;
return this;
}
/**
* Add a header to this request
* @param theHeader the header to add
* @return this request
*/
public Request addHeader(Header theHeader) {
if (mHeaders.containsKey(theHeader.getName())) {
theHeader.addValues(mHeaders.get(theHeader.getName()).getValues());
}
mHeaders.put(theHeader.getName(), theHeader);
return this;
}
public Request addHeader(String theName, String... theValue) {
addHeader(new Header(theName, Arrays.asList(theValue)));
return this;
}
public Request setBody(String theString) {
try {
mBody = new ByteArrayInputStream(theString.getBytes(Encoder.UTF8.name()));
}
catch (UnsupportedEncodingException e) {
// can safely be ignored, we know java supports UTF8
}
return this;
}
public Request setBody(final InputStream theBody) {
mBody = theBody;
return this;
}
public URL getURL() {
return mURL;
}
public Method getMethod() {
return mMethod;
}
public ParameterList getParameters() {
return mParameters;
}
public InputStream getBody() {
return mBody;
}
public Collection<Header> getHeaders() {
return Collections.unmodifiableCollection(mHeaders.values());
}
private URL getURLWithParams() throws IOException {
if (getMethod().equals(Method.GET) && !getParameters().isEmpty()) {
try {
return new URL(getURL().toString() + "?" + getParameters().getURLEncoded());
}
catch (MalformedURLException e) {
throw new IOException(e.getMessage());
}
}
else {
return getURL();
}
}
public Header getHeader(String theName) {
return mHeaders.get(theName);
}
public Response execute() throws IOException {
// TODO: use-caches?, if-modified-since, HTTPS security twiddling, HTTP Authentication, chunking, user interactions?
InputStream aResponseStream = null;
InputStream aInput = null;
HttpURLConnection aConn = null;
try {
URLConnection aTempConn = getURLWithParams().openConnection();
if (!(aTempConn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("Only HTTP or HTTPS are supported");
}
aConn = (HttpURLConnection) aTempConn;
aConn.setDoInput(true);
if (getTimeout() != -1) {
aConn.setConnectTimeout(getTimeout());
}
aConn.setInstanceFollowRedirects(isFollowRedirects());
aConn.setRequestMethod(getMethod().name());
for (Header aHeader : getHeaders()) {
aConn.setRequestProperty(aHeader.getName(), aHeader.getHeaderValue());
}
aConn.setInstanceFollowRedirects(isFollowRedirects());
aConn.setRequestMethod(getMethod().name());
aInput = getBody();
if (aInput == null && getMethod() == Method.POST) {
aInput = new ByteArrayInputStream(new byte[0]);
}
- if (aInput != null) {
+ if (aInput != null && (getMethod() != Method.DELETE)) {
aConn.setDoOutput(true);
OutputStream aOut = aConn.getOutputStream();
IOUtil.transfer(aInput, aOut);
if (aOut != null) {
aOut.flush();
aOut.close();
}
aInput.close();
}
aConn.connect();
Collection<Header> aResponseHeaders = new HashSet<Header>();
Map<String, List<String>> aHeaderMap = aConn.getHeaderFields();
for (String aName : aHeaderMap.keySet()) {
aResponseHeaders.add(new Header(aName, aHeaderMap.get(aName)));
}
try {
aResponseStream = aConn.getInputStream();
// if this is GZIP encoded, then wrap the input stream
String contentEncoding = aConn.getContentEncoding();
if ("gzip".equals(contentEncoding)) {
aResponseStream = new GZIPInputStream(aResponseStream);
}
}
catch (IOException ex) {
// close the connection input stream
if (aResponseStream != null) {
aResponseStream.close();
}
aResponseStream = aConn.getErrorStream();
}
return new Response(aConn, aResponseHeaders);
}
finally {
close(aInput);
}
}
private void close(Closeable theClosable) {
try {
if (theClosable != null) {
theClosable.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
| true | true | public Response execute() throws IOException {
// TODO: use-caches?, if-modified-since, HTTPS security twiddling, HTTP Authentication, chunking, user interactions?
InputStream aResponseStream = null;
InputStream aInput = null;
HttpURLConnection aConn = null;
try {
URLConnection aTempConn = getURLWithParams().openConnection();
if (!(aTempConn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("Only HTTP or HTTPS are supported");
}
aConn = (HttpURLConnection) aTempConn;
aConn.setDoInput(true);
if (getTimeout() != -1) {
aConn.setConnectTimeout(getTimeout());
}
aConn.setInstanceFollowRedirects(isFollowRedirects());
aConn.setRequestMethod(getMethod().name());
for (Header aHeader : getHeaders()) {
aConn.setRequestProperty(aHeader.getName(), aHeader.getHeaderValue());
}
aConn.setInstanceFollowRedirects(isFollowRedirects());
aConn.setRequestMethod(getMethod().name());
aInput = getBody();
if (aInput == null && getMethod() == Method.POST) {
aInput = new ByteArrayInputStream(new byte[0]);
}
if (aInput != null) {
aConn.setDoOutput(true);
OutputStream aOut = aConn.getOutputStream();
IOUtil.transfer(aInput, aOut);
if (aOut != null) {
aOut.flush();
aOut.close();
}
aInput.close();
}
aConn.connect();
Collection<Header> aResponseHeaders = new HashSet<Header>();
Map<String, List<String>> aHeaderMap = aConn.getHeaderFields();
for (String aName : aHeaderMap.keySet()) {
aResponseHeaders.add(new Header(aName, aHeaderMap.get(aName)));
}
try {
aResponseStream = aConn.getInputStream();
// if this is GZIP encoded, then wrap the input stream
String contentEncoding = aConn.getContentEncoding();
if ("gzip".equals(contentEncoding)) {
aResponseStream = new GZIPInputStream(aResponseStream);
}
}
catch (IOException ex) {
// close the connection input stream
if (aResponseStream != null) {
aResponseStream.close();
}
aResponseStream = aConn.getErrorStream();
}
return new Response(aConn, aResponseHeaders);
}
finally {
close(aInput);
}
}
| public Response execute() throws IOException {
// TODO: use-caches?, if-modified-since, HTTPS security twiddling, HTTP Authentication, chunking, user interactions?
InputStream aResponseStream = null;
InputStream aInput = null;
HttpURLConnection aConn = null;
try {
URLConnection aTempConn = getURLWithParams().openConnection();
if (!(aTempConn instanceof HttpURLConnection)) {
throw new IllegalArgumentException("Only HTTP or HTTPS are supported");
}
aConn = (HttpURLConnection) aTempConn;
aConn.setDoInput(true);
if (getTimeout() != -1) {
aConn.setConnectTimeout(getTimeout());
}
aConn.setInstanceFollowRedirects(isFollowRedirects());
aConn.setRequestMethod(getMethod().name());
for (Header aHeader : getHeaders()) {
aConn.setRequestProperty(aHeader.getName(), aHeader.getHeaderValue());
}
aConn.setInstanceFollowRedirects(isFollowRedirects());
aConn.setRequestMethod(getMethod().name());
aInput = getBody();
if (aInput == null && getMethod() == Method.POST) {
aInput = new ByteArrayInputStream(new byte[0]);
}
if (aInput != null && (getMethod() != Method.DELETE)) {
aConn.setDoOutput(true);
OutputStream aOut = aConn.getOutputStream();
IOUtil.transfer(aInput, aOut);
if (aOut != null) {
aOut.flush();
aOut.close();
}
aInput.close();
}
aConn.connect();
Collection<Header> aResponseHeaders = new HashSet<Header>();
Map<String, List<String>> aHeaderMap = aConn.getHeaderFields();
for (String aName : aHeaderMap.keySet()) {
aResponseHeaders.add(new Header(aName, aHeaderMap.get(aName)));
}
try {
aResponseStream = aConn.getInputStream();
// if this is GZIP encoded, then wrap the input stream
String contentEncoding = aConn.getContentEncoding();
if ("gzip".equals(contentEncoding)) {
aResponseStream = new GZIPInputStream(aResponseStream);
}
}
catch (IOException ex) {
// close the connection input stream
if (aResponseStream != null) {
aResponseStream.close();
}
aResponseStream = aConn.getErrorStream();
}
return new Response(aConn, aResponseHeaders);
}
finally {
close(aInput);
}
}
|
diff --git a/src/main/java/uk/co/unclealex/music/sync/IpodSynchroniser.java b/src/main/java/uk/co/unclealex/music/sync/IpodSynchroniser.java
index e7fe831..222a719 100644
--- a/src/main/java/uk/co/unclealex/music/sync/IpodSynchroniser.java
+++ b/src/main/java/uk/co/unclealex/music/sync/IpodSynchroniser.java
@@ -1,183 +1,186 @@
/**
* Copyright 2012 Alex Jones
*
* 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.
*
* @author unclealex72
*
*/
package uk.co.unclealex.music.sync;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import uk.co.unclealex.music.configuration.IpodDevice;
import uk.co.unclealex.music.configuration.User;
import uk.co.unclealex.music.devices.DeviceService;
import uk.co.unclealex.music.files.DirectoryService;
import uk.co.unclealex.music.files.FileLocation;
import uk.co.unclealex.music.message.MessageService;
import uk.co.unclealex.process.builder.ProcessRequestBuilder;
import uk.co.unclealex.process.packages.PackagesRequired;
import uk.co.unclealex.process.stream.Executor;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.inject.assistedinject.Assisted;
/**
* The {@link Synchroniser} for iPods.
*
* @author alex
*
*/
@PackagesRequired({ "python-gpod", "python-eyed3", "python-gtk2", "pmount" })
public class IpodSynchroniser extends AbstractSynchroniser<IpodDevice> {
/**
* The {@link Executor} used to talk to the iPOD.
*/
private final Executor executor = new Executor("OK", Charsets.UTF_8);
/**
* Instantiates a new ipod synchroniser.
*
* @param messageService the message service
* @param directoryService the directory service
* @param deviceService the device service
* @param processRequestBuilder the process request builder
* @param owner the owner
* @param device the device
*/
@Inject
public IpodSynchroniser(
MessageService messageService,
DirectoryService directoryService,
DeviceService deviceService,
ProcessRequestBuilder processRequestBuilder,
@Assisted User owner,
@Assisted IpodDevice device) {
super(messageService, directoryService, deviceService, processRequestBuilder, owner, device);
}
/**
* {@inheritDoc}
*/
protected void initialise() throws IOException {
Executor executor = getExecutor();
String mountPoint = getDevice().getMountPoint().toString();
getProcessRequestBuilder()
.forResource("sync.py")
.withArguments("ipod", mountPoint)
.withStandardInputSupplier(executor)
.execute();
}
/**
* List device files.
*
* @return the sets the
* @throws IOException Signals that an I/O exception has occurred.
*/
public Set<DeviceFile> listDeviceFiles() throws IOException {
List<String> deviceFileStrings = executeCommand("LIST");
Function<String, DeviceFile> deviceFileParserFunction = new Function<String, DeviceFile>() {
@Override
public DeviceFile apply(String str) {
str = str.trim();
if (str.isEmpty() || str.startsWith("**")) {
return null;
}
else {
DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinuteSecond();
List<String> deviceFileParts = Lists.newArrayList(Splitter.on('|').split(str));
+ if (deviceFileParts.size() != 2) {
+ throw new IllegalStateException("Do not understand line: '" + str + "' sent from iPOD.");
+ }
DateTime dateTime = formatter.parseDateTime(deviceFileParts.get(2));
return new DeviceFile(deviceFileParts.get(0), deviceFileParts.get(1), dateTime.getMillis());
}
}
};
return Sets.newTreeSet(Iterables.filter(
Iterables.transform(deviceFileStrings, deviceFileParserFunction),
Predicates.notNull()));
}
/**
* Adds the.
*
* @param fileloLocation the filelo location
* @throws IOException Signals that an I/O exception has occurred.
*/
public void add(FileLocation fileloLocation) throws IOException {
executeCommand("ADD", fileloLocation.getRelativePath(), fileloLocation.resolve());
}
/**
* Removes the.
*
* @param deviceFile the device file
* @throws IOException Signals that an I/O exception has occurred.
*/
public void remove(DeviceFile deviceFile) throws IOException {
executeCommand("REMOVE", deviceFile.getId());
}
/**
* Close device.
*
* @throws IOException Signals that an I/O exception has occurred.
*/
public void closeDevice() throws IOException {
executeCommand("QUIT");
}
/**
* Execute command.
*
* @param command the command
* @return the list
* @throws IOException Signals that an I/O exception has occurred.
*/
protected List<String> executeCommand(Object... command) throws IOException {
String fullCommand = Joiner.on('|').join(command);
return getExecutor().executeCommand(fullCommand);
}
/**
* Gets the {@link Executor} used to talk to the iPOD.
*
* @return the {@link Executor} used to talk to the iPOD
*/
public Executor getExecutor() {
return executor;
}
}
| true | true | public Set<DeviceFile> listDeviceFiles() throws IOException {
List<String> deviceFileStrings = executeCommand("LIST");
Function<String, DeviceFile> deviceFileParserFunction = new Function<String, DeviceFile>() {
@Override
public DeviceFile apply(String str) {
str = str.trim();
if (str.isEmpty() || str.startsWith("**")) {
return null;
}
else {
DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinuteSecond();
List<String> deviceFileParts = Lists.newArrayList(Splitter.on('|').split(str));
DateTime dateTime = formatter.parseDateTime(deviceFileParts.get(2));
return new DeviceFile(deviceFileParts.get(0), deviceFileParts.get(1), dateTime.getMillis());
}
}
};
return Sets.newTreeSet(Iterables.filter(
Iterables.transform(deviceFileStrings, deviceFileParserFunction),
Predicates.notNull()));
}
| public Set<DeviceFile> listDeviceFiles() throws IOException {
List<String> deviceFileStrings = executeCommand("LIST");
Function<String, DeviceFile> deviceFileParserFunction = new Function<String, DeviceFile>() {
@Override
public DeviceFile apply(String str) {
str = str.trim();
if (str.isEmpty() || str.startsWith("**")) {
return null;
}
else {
DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinuteSecond();
List<String> deviceFileParts = Lists.newArrayList(Splitter.on('|').split(str));
if (deviceFileParts.size() != 2) {
throw new IllegalStateException("Do not understand line: '" + str + "' sent from iPOD.");
}
DateTime dateTime = formatter.parseDateTime(deviceFileParts.get(2));
return new DeviceFile(deviceFileParts.get(0), deviceFileParts.get(1), dateTime.getMillis());
}
}
};
return Sets.newTreeSet(Iterables.filter(
Iterables.transform(deviceFileStrings, deviceFileParserFunction),
Predicates.notNull()));
}
|
diff --git a/src/com/redhat/qe/auto/testng/TestNGListener.java b/src/com/redhat/qe/auto/testng/TestNGListener.java
index 40ae4b6..6da3ebc 100644
--- a/src/com/redhat/qe/auto/testng/TestNGListener.java
+++ b/src/com/redhat/qe/auto/testng/TestNGListener.java
@@ -1,132 +1,132 @@
package com.redhat.qe.auto.testng;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.testng.ISuite;
import org.testng.ISuiteListener;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.SkipException;
import org.testng.internal.IResultListener;
/**
* This class listens for TestNG events, and logs them using the
* standard java logging facility.
*
* In order to use this listener, the class name must be provided to testNG
* using the -listener option (or specified as the attribute 'listener'
* in an ant call to testng).
* @author jweiss
*
*/
public class TestNGListener implements IResultListener, ISuiteListener {
protected static Logger log = Logger.getLogger(TestNGListener.class.getName());
//Override TestNG's Test Listener methods for logging purposes
@Override
public void onFinish(ITestContext context){
log.log(Level.INFO, "Finished TestNG Script: " + context.getName(), LogMessageUtil.Style.Banner);
}
@Override
public void onStart(ITestContext context) {
log.log(Level.INFO, "Starting TestNG Script: " + context.getName(), LogMessageUtil.Style.Banner);
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
log.log(Level.WARNING, "Test Failed (but within success percentage): "+ result.getName(), result.getThrowable());
}
@Override
public void onTestFailure(ITestResult result) {
Reporter.setCurrentTestResult(result);
Throwable err = result.getThrowable();
LogRecord logRecord = new LogRecord(Level.SEVERE, "Test Failed: "+ result.getName());
logRecord.setThrown(err);
if (err != null && err instanceof AssertionError)
logRecord.setParameters(new Object[] {LogMessageUtil.Style.AssertFailed});
log.log(logRecord);
}
@Override
public void onTestSkipped(ITestResult result) {
Reporter.setCurrentTestResult(result);
- if (result.getThrowable() instanceof SkipException){
+ if (result.getThrowable() != null){
LogRecord r= new LogRecord(Level.INFO, "Skipping test " + result.getName() + ": " + result.getThrowable().getMessage());
r.setParameters(new Object[]{LogMessageUtil.Style.Banner});
log.log(r);
}
else {
log.log(Level.INFO, "Skipping Test " + result.getName() + ": Unsatisfied dependency", LogMessageUtil.Style.Banner);
}
}
@Override
public void onTestStart(ITestResult result) {
Reporter.setCurrentTestResult(result);
LogRecord r= new LogRecord(Level.INFO, String.format("Starting Test: %s%s", result.getName(), getParameters(result)));
r.setParameters(new Object[]{LogMessageUtil.Style.Banner, LogMessageUtil.Style.StartTest});
log.log(r);
}
@Override
public void onTestSuccess(ITestResult result) {
Reporter.setCurrentTestResult(result);
Throwable throwable = result.getThrowable();
if (throwable != null){
log.log(Level.INFO, "Expected exception of " + throwable.getClass().getName() + " '" + throwable.getMessage() + "' was in fact thrown." , LogMessageUtil.Style.Asserted);
}
log.log(Level.INFO, String.format("Test Passed: %s%s", result.getName(), getParameters(result)), LogMessageUtil.Style.Banner);
}
@Override
public void onConfigurationFailure(ITestResult result) {
Reporter.setCurrentTestResult(result);
log.log(Level.SEVERE, "Configuration Failed: " + result.getName(), result.getThrowable());
}
@Override
public void onConfigurationSkip(ITestResult result) {
Reporter.setCurrentTestResult(result);
LogRecord l = new LogRecord(Level.INFO, "Configuration skipped: " + result.getName());
l.setParameters(new Object[] {LogMessageUtil.Style.Banner });
if (result.getThrowable() != null){
l.setThrown(result.getThrowable());
}
log.log(l);
}
@Override
public void onConfigurationSuccess(ITestResult result) {
Reporter.setCurrentTestResult(result);
log.log(Level.FINE, "Configuration completed: " + result.getName(), LogMessageUtil.Style.Banner);
}
@Override
public void onFinish(ISuite suite) {
log.log(Level.INFO, "Finishing TestNG Suite:" + suite.getName(), LogMessageUtil.Style.Banner);
}
@Override
public void onStart(ISuite suite) {
log.log(Level.INFO, "Starting TestNG Suite:" +suite.getName(), LogMessageUtil.Style.Banner);
}
public String getParameters(ITestResult result) {
String params = "";
Object[] parameters = result.getParameters();
if (parameters != null && parameters.length > 0)
params = "(" + Arrays.deepToString(parameters) + ")";
return params;
}
}
| true | true | public void onTestSkipped(ITestResult result) {
Reporter.setCurrentTestResult(result);
if (result.getThrowable() instanceof SkipException){
LogRecord r= new LogRecord(Level.INFO, "Skipping test " + result.getName() + ": " + result.getThrowable().getMessage());
r.setParameters(new Object[]{LogMessageUtil.Style.Banner});
log.log(r);
}
else {
log.log(Level.INFO, "Skipping Test " + result.getName() + ": Unsatisfied dependency", LogMessageUtil.Style.Banner);
}
}
| public void onTestSkipped(ITestResult result) {
Reporter.setCurrentTestResult(result);
if (result.getThrowable() != null){
LogRecord r= new LogRecord(Level.INFO, "Skipping test " + result.getName() + ": " + result.getThrowable().getMessage());
r.setParameters(new Object[]{LogMessageUtil.Style.Banner});
log.log(r);
}
else {
log.log(Level.INFO, "Skipping Test " + result.getName() + ": Unsatisfied dependency", LogMessageUtil.Style.Banner);
}
}
|
diff --git a/plugins/org.scribble.protocol.designer/src/java/org/scribble/protocol/designer/osgi/Activator.java b/plugins/org.scribble.protocol.designer/src/java/org/scribble/protocol/designer/osgi/Activator.java
index d7c0445..32f3a23 100644
--- a/plugins/org.scribble.protocol.designer/src/java/org/scribble/protocol/designer/osgi/Activator.java
+++ b/plugins/org.scribble.protocol.designer/src/java/org/scribble/protocol/designer/osgi/Activator.java
@@ -1,347 +1,347 @@
/*
* Copyright 2009 www.scribble.org
* 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.scribble.protocol.designer.osgi;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.scribble.protocol.designer.DesignerServices;
import org.scribble.protocol.designer.editor.*;
import org.scribble.protocol.designer.editor.lang.*;
import org.scribble.protocol.designer.editor.util.*;
import org.scribble.protocol.designer.validator.ProtocolValidator;
import org.scribble.protocol.export.ProtocolExportManagerFactory;
import org.scribble.protocol.export.monitor.MonitorProtocolExporter;
import org.scribble.protocol.export.text.TextProtocolExporter;
import org.scribble.protocol.monitor.ProtocolMonitor;
import org.scribble.protocol.parser.ProtocolParser;
import org.scribble.protocol.parser.ProtocolParserManager;
import org.scribble.protocol.projection.ProtocolProjector;
import org.scribble.protocol.validation.DefaultProtocolValidationManager;
import org.scribble.protocol.validation.ProtocolValidationManager;
import java.util.logging.*;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.rules.RuleBasedScanner;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
//private static final String SERVICE_COMPONENT = "Service-Component";
// The plug-in ID
public static final String PLUGIN_ID = "org.scribble.protocol.designer";
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(final BundleContext context) throws Exception {
super.start(context);
plugin = this;
// Make sure any bundles, associated with scribble, are started (excluding
// the designer itself)
Bundle[] bundles=context.getBundles();
for (int i=0; i < bundles.length; i++) {
Bundle bundle=bundles[i];
if (bundle != null) {
//Object val=bundle.getHeaders().get(SERVICE_COMPONENT);
if (bundle.getSymbolicName().startsWith("org.scribble.") &&
bundle.getSymbolicName().endsWith("designer") == false) {
//if (bundle.getState() == Bundle.RESOLVED) {
logger.fine("Pre-empt bundle start: "+bundle);
bundle.start();
//}
}
}
}
// TODO: Obtain validation manager pre-initialised
// SCRIBBLE-29
ProtocolValidationManager vm=new DefaultProtocolValidationManager();
- vm.addValidator(new org.scribble.protocol.validation.rules.DefaultProtocolComponentValidator());
+ vm.getValidators().add(new org.scribble.protocol.validation.rules.DefaultProtocolComponentValidator());
DesignerServices.setValidationManager(vm);
// Obtain reference to protocol parser
ServiceReference sr=context.getServiceReference(ProtocolParserManager.class.getName());
ProtocolParserManager pp=null;
if (sr != null) {
pp = (ProtocolParserManager)context.getService(sr);
}
if (pp != null) {
DesignerServices.setParserManager(pp);
} else {
ServiceListener sl1 = new ServiceListener() {
public void serviceChanged(ServiceEvent ev) {
ServiceReference sr = ev.getServiceReference();
switch(ev.getType()) {
case ServiceEvent.REGISTERED:
ProtocolParserManager pp=
(ProtocolParserManager)context.getService(sr);
DesignerServices.setParserManager(pp);
break;
case ServiceEvent.UNREGISTERING:
break;
}
}
};
String filter1 = "(objectclass=" + ProtocolParser.class.getName() + ")";
try {
context.addServiceListener(sl1, filter1);
} catch(Exception e) {
e.printStackTrace();
}
}
// Obtain reference to protocol parser
sr=context.getServiceReference(ProtocolProjector.class.getName());
ProtocolProjector ppj=null;
if (sr != null) {
ppj = (ProtocolProjector)context.getService(sr);
}
if (ppj != null) {
DesignerServices.setProtocolProjector(ppj);
} else {
ServiceListener sl1 = new ServiceListener() {
public void serviceChanged(ServiceEvent ev) {
ServiceReference sr = ev.getServiceReference();
switch(ev.getType()) {
case ServiceEvent.REGISTERED:
ProtocolProjector ppj=
(ProtocolProjector)context.getService(sr);
DesignerServices.setProtocolProjector(ppj);
break;
case ServiceEvent.UNREGISTERING:
break;
}
}
};
String filter1 = "(objectclass=" + ProtocolProjector.class.getName() + ")";
try {
context.addServiceListener(sl1, filter1);
} catch(Exception e) {
e.printStackTrace();
}
}
// Create the export manager
DesignerServices.setProtocolExportManager(ProtocolExportManagerFactory.getExportManager());
- ProtocolExportManagerFactory.getExportManager().addExporter(new TextProtocolExporter());
- ProtocolExportManagerFactory.getExportManager().addExporter(new MonitorProtocolExporter());
+ ProtocolExportManagerFactory.getExportManager().getExporters().add(new TextProtocolExporter());
+ ProtocolExportManagerFactory.getExportManager().getExporters().add(new MonitorProtocolExporter());
// Register protocol monitor
sr=context.getServiceReference(ProtocolMonitor.class.getName());
ProtocolMonitor pm=null;
if (sr != null) {
pm = (ProtocolMonitor)context.getService(sr);
}
if (pm != null) {
DesignerServices.setProtocolMonitor(pm);
} else {
ServiceListener sl1 = new ServiceListener() {
public void serviceChanged(ServiceEvent ev) {
ServiceReference sr = ev.getServiceReference();
switch(ev.getType()) {
case ServiceEvent.REGISTERED:
ProtocolMonitor pm=
(ProtocolMonitor)context.getService(sr);
DesignerServices.setProtocolMonitor(pm);
break;
case ServiceEvent.UNREGISTERING:
break;
}
}
};
String filter1 = "(objectclass=" + ProtocolMonitor.class.getName() + ")";
try {
context.addServiceListener(sl1, filter1);
} catch(Exception e) {
e.printStackTrace();
}
}
// Register resource change listener
IResourceChangeListener rcl=
new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent evt) {
try {
evt.getDelta().accept(new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta) {
boolean ret=true;
IResource res = delta.getResource();
// Determine if the change is relevant
if (isChangeRelevant(res,
delta)) {
// Validate the resource
m_validator.validateResource(res);
}
return(ret);
}
});
} catch(Exception e) {
logger.log(Level.SEVERE,
"Failed to process resource change event",
e);
}
}
};
// Register the resource change listener
ResourcesPlugin.getWorkspace().addResourceChangeListener(rcl,
IResourceChangeEvent.POST_CHANGE);
}
protected boolean isChangeRelevant(IResource res, IResourceDelta delta) {
return(res instanceof IFile &&
DesignerServices.PROTOCOL_FILE_EXTENSION.equals(((IFile)res).getFileExtension()) &&
(((delta.getFlags() & IResourceDelta.CONTENT) != 0) ||
delta.getKind() == IResourceDelta.ADDED));
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* This method logs an error against the plugin.
*
* @param mesg The error message
* @param t The optional exception
*/
public static void logError(String mesg, Throwable t) {
if (getDefault() != null) {
Status status=new Status(IStatus.ERROR,
PLUGIN_ID, 0, mesg, t);
getDefault().getLog().log(status);
}
logger.severe("LOG ERROR: "+mesg+
(t == null ? "" : ": "+t));
}
/**
* Return a scanner for creating Java partitions.
*
* @return a scanner for creating Java partitions
*/
public ScribblePartitionScanner getScribblePartitionScanner() {
if (fPartitionScanner == null)
fPartitionScanner= new ScribblePartitionScanner();
return fPartitionScanner;
}
/**
* Returns the singleton Java code scanner.
*
* @return the singleton Java code scanner
*/
public RuleBasedScanner getScribbleCodeScanner() {
if (fCodeScanner == null)
fCodeScanner= new ScribbleCodeScanner(getScribbleColorProvider());
return fCodeScanner;
}
/**
* Returns the singleton Java color provider.
*
* @return the singleton Java color provider
*/
public ScribbleColorProvider getScribbleColorProvider() {
if (fColorProvider == null)
fColorProvider= new ScribbleColorProvider();
return fColorProvider;
}
private static Logger logger = Logger.getLogger("org.scribble.protocol.designer");
public final static String SCRIBBLE_PARTITIONING= "__scribble_partitioning"; //$NON-NLS-1$
private ScribblePartitionScanner fPartitionScanner;
private ScribbleColorProvider fColorProvider;
private ScribbleCodeScanner fCodeScanner;
private ProtocolValidator m_validator=new ProtocolValidator();
}
| false | true | public void start(final BundleContext context) throws Exception {
super.start(context);
plugin = this;
// Make sure any bundles, associated with scribble, are started (excluding
// the designer itself)
Bundle[] bundles=context.getBundles();
for (int i=0; i < bundles.length; i++) {
Bundle bundle=bundles[i];
if (bundle != null) {
//Object val=bundle.getHeaders().get(SERVICE_COMPONENT);
if (bundle.getSymbolicName().startsWith("org.scribble.") &&
bundle.getSymbolicName().endsWith("designer") == false) {
//if (bundle.getState() == Bundle.RESOLVED) {
logger.fine("Pre-empt bundle start: "+bundle);
bundle.start();
//}
}
}
}
// TODO: Obtain validation manager pre-initialised
// SCRIBBLE-29
ProtocolValidationManager vm=new DefaultProtocolValidationManager();
vm.addValidator(new org.scribble.protocol.validation.rules.DefaultProtocolComponentValidator());
DesignerServices.setValidationManager(vm);
// Obtain reference to protocol parser
ServiceReference sr=context.getServiceReference(ProtocolParserManager.class.getName());
ProtocolParserManager pp=null;
if (sr != null) {
pp = (ProtocolParserManager)context.getService(sr);
}
if (pp != null) {
DesignerServices.setParserManager(pp);
} else {
ServiceListener sl1 = new ServiceListener() {
public void serviceChanged(ServiceEvent ev) {
ServiceReference sr = ev.getServiceReference();
switch(ev.getType()) {
case ServiceEvent.REGISTERED:
ProtocolParserManager pp=
(ProtocolParserManager)context.getService(sr);
DesignerServices.setParserManager(pp);
break;
case ServiceEvent.UNREGISTERING:
break;
}
}
};
String filter1 = "(objectclass=" + ProtocolParser.class.getName() + ")";
try {
context.addServiceListener(sl1, filter1);
} catch(Exception e) {
e.printStackTrace();
}
}
// Obtain reference to protocol parser
sr=context.getServiceReference(ProtocolProjector.class.getName());
ProtocolProjector ppj=null;
if (sr != null) {
ppj = (ProtocolProjector)context.getService(sr);
}
if (ppj != null) {
DesignerServices.setProtocolProjector(ppj);
} else {
ServiceListener sl1 = new ServiceListener() {
public void serviceChanged(ServiceEvent ev) {
ServiceReference sr = ev.getServiceReference();
switch(ev.getType()) {
case ServiceEvent.REGISTERED:
ProtocolProjector ppj=
(ProtocolProjector)context.getService(sr);
DesignerServices.setProtocolProjector(ppj);
break;
case ServiceEvent.UNREGISTERING:
break;
}
}
};
String filter1 = "(objectclass=" + ProtocolProjector.class.getName() + ")";
try {
context.addServiceListener(sl1, filter1);
} catch(Exception e) {
e.printStackTrace();
}
}
// Create the export manager
DesignerServices.setProtocolExportManager(ProtocolExportManagerFactory.getExportManager());
ProtocolExportManagerFactory.getExportManager().addExporter(new TextProtocolExporter());
ProtocolExportManagerFactory.getExportManager().addExporter(new MonitorProtocolExporter());
// Register protocol monitor
sr=context.getServiceReference(ProtocolMonitor.class.getName());
ProtocolMonitor pm=null;
if (sr != null) {
pm = (ProtocolMonitor)context.getService(sr);
}
if (pm != null) {
DesignerServices.setProtocolMonitor(pm);
} else {
ServiceListener sl1 = new ServiceListener() {
public void serviceChanged(ServiceEvent ev) {
ServiceReference sr = ev.getServiceReference();
switch(ev.getType()) {
case ServiceEvent.REGISTERED:
ProtocolMonitor pm=
(ProtocolMonitor)context.getService(sr);
DesignerServices.setProtocolMonitor(pm);
break;
case ServiceEvent.UNREGISTERING:
break;
}
}
};
String filter1 = "(objectclass=" + ProtocolMonitor.class.getName() + ")";
try {
context.addServiceListener(sl1, filter1);
} catch(Exception e) {
e.printStackTrace();
}
}
// Register resource change listener
IResourceChangeListener rcl=
new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent evt) {
try {
evt.getDelta().accept(new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta) {
boolean ret=true;
IResource res = delta.getResource();
// Determine if the change is relevant
if (isChangeRelevant(res,
delta)) {
// Validate the resource
m_validator.validateResource(res);
}
return(ret);
}
});
} catch(Exception e) {
logger.log(Level.SEVERE,
"Failed to process resource change event",
e);
}
}
};
// Register the resource change listener
ResourcesPlugin.getWorkspace().addResourceChangeListener(rcl,
IResourceChangeEvent.POST_CHANGE);
}
| public void start(final BundleContext context) throws Exception {
super.start(context);
plugin = this;
// Make sure any bundles, associated with scribble, are started (excluding
// the designer itself)
Bundle[] bundles=context.getBundles();
for (int i=0; i < bundles.length; i++) {
Bundle bundle=bundles[i];
if (bundle != null) {
//Object val=bundle.getHeaders().get(SERVICE_COMPONENT);
if (bundle.getSymbolicName().startsWith("org.scribble.") &&
bundle.getSymbolicName().endsWith("designer") == false) {
//if (bundle.getState() == Bundle.RESOLVED) {
logger.fine("Pre-empt bundle start: "+bundle);
bundle.start();
//}
}
}
}
// TODO: Obtain validation manager pre-initialised
// SCRIBBLE-29
ProtocolValidationManager vm=new DefaultProtocolValidationManager();
vm.getValidators().add(new org.scribble.protocol.validation.rules.DefaultProtocolComponentValidator());
DesignerServices.setValidationManager(vm);
// Obtain reference to protocol parser
ServiceReference sr=context.getServiceReference(ProtocolParserManager.class.getName());
ProtocolParserManager pp=null;
if (sr != null) {
pp = (ProtocolParserManager)context.getService(sr);
}
if (pp != null) {
DesignerServices.setParserManager(pp);
} else {
ServiceListener sl1 = new ServiceListener() {
public void serviceChanged(ServiceEvent ev) {
ServiceReference sr = ev.getServiceReference();
switch(ev.getType()) {
case ServiceEvent.REGISTERED:
ProtocolParserManager pp=
(ProtocolParserManager)context.getService(sr);
DesignerServices.setParserManager(pp);
break;
case ServiceEvent.UNREGISTERING:
break;
}
}
};
String filter1 = "(objectclass=" + ProtocolParser.class.getName() + ")";
try {
context.addServiceListener(sl1, filter1);
} catch(Exception e) {
e.printStackTrace();
}
}
// Obtain reference to protocol parser
sr=context.getServiceReference(ProtocolProjector.class.getName());
ProtocolProjector ppj=null;
if (sr != null) {
ppj = (ProtocolProjector)context.getService(sr);
}
if (ppj != null) {
DesignerServices.setProtocolProjector(ppj);
} else {
ServiceListener sl1 = new ServiceListener() {
public void serviceChanged(ServiceEvent ev) {
ServiceReference sr = ev.getServiceReference();
switch(ev.getType()) {
case ServiceEvent.REGISTERED:
ProtocolProjector ppj=
(ProtocolProjector)context.getService(sr);
DesignerServices.setProtocolProjector(ppj);
break;
case ServiceEvent.UNREGISTERING:
break;
}
}
};
String filter1 = "(objectclass=" + ProtocolProjector.class.getName() + ")";
try {
context.addServiceListener(sl1, filter1);
} catch(Exception e) {
e.printStackTrace();
}
}
// Create the export manager
DesignerServices.setProtocolExportManager(ProtocolExportManagerFactory.getExportManager());
ProtocolExportManagerFactory.getExportManager().getExporters().add(new TextProtocolExporter());
ProtocolExportManagerFactory.getExportManager().getExporters().add(new MonitorProtocolExporter());
// Register protocol monitor
sr=context.getServiceReference(ProtocolMonitor.class.getName());
ProtocolMonitor pm=null;
if (sr != null) {
pm = (ProtocolMonitor)context.getService(sr);
}
if (pm != null) {
DesignerServices.setProtocolMonitor(pm);
} else {
ServiceListener sl1 = new ServiceListener() {
public void serviceChanged(ServiceEvent ev) {
ServiceReference sr = ev.getServiceReference();
switch(ev.getType()) {
case ServiceEvent.REGISTERED:
ProtocolMonitor pm=
(ProtocolMonitor)context.getService(sr);
DesignerServices.setProtocolMonitor(pm);
break;
case ServiceEvent.UNREGISTERING:
break;
}
}
};
String filter1 = "(objectclass=" + ProtocolMonitor.class.getName() + ")";
try {
context.addServiceListener(sl1, filter1);
} catch(Exception e) {
e.printStackTrace();
}
}
// Register resource change listener
IResourceChangeListener rcl=
new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent evt) {
try {
evt.getDelta().accept(new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta) {
boolean ret=true;
IResource res = delta.getResource();
// Determine if the change is relevant
if (isChangeRelevant(res,
delta)) {
// Validate the resource
m_validator.validateResource(res);
}
return(ret);
}
});
} catch(Exception e) {
logger.log(Level.SEVERE,
"Failed to process resource change event",
e);
}
}
};
// Register the resource change listener
ResourcesPlugin.getWorkspace().addResourceChangeListener(rcl,
IResourceChangeEvent.POST_CHANGE);
}
|
diff --git a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java
index 5e67e4d23..3b06c7207 100644
--- a/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java
+++ b/maven-core/src/main/java/org/apache/maven/lifecycle/internal/LifecycleStarter.java
@@ -1,142 +1,142 @@
package org.apache.maven.lifecycle.internal;
/*
* 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.util.List;
import java.util.Map;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.MavenExecutionResult;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.DefaultLifecycles;
import org.apache.maven.lifecycle.MissingProjectException;
import org.apache.maven.lifecycle.NoGoalSpecifiedException;
import org.apache.maven.lifecycle.internal.builder.Builder;
import org.apache.maven.lifecycle.internal.builder.BuilderNotFoundException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;
/**
* Starts the build life cycle
*
* @author Jason van Zyl
* @author Benjamin Bentmann
* @author Kristian Rosenvold
*/
@Component( role = LifecycleStarter.class )
public class LifecycleStarter
{
@Requirement
private ExecutionEventCatapult eventCatapult;
@Requirement
private DefaultLifecycles defaultLifeCycles;
@Requirement
private Logger logger;
@Requirement
private BuildListCalculator buildListCalculator;
@Requirement
private LifecycleDebugLogger lifecycleDebugLogger;
@Requirement
private LifecycleTaskSegmentCalculator lifecycleTaskSegmentCalculator;
@Requirement
private Map<String, Builder> builders;
public void execute( MavenSession session )
{
eventCatapult.fire( ExecutionEvent.Type.SessionStarted, session, null );
ReactorContext reactorContext = null;
ProjectBuildList projectBuilds = null;
MavenExecutionResult result = session.getResult();
try
{
if ( buildExecutionRequiresProject( session ) && projectIsNotPresent( session ) )
{
throw new MissingProjectException( "The goal you specified requires a project to execute"
+ " but there is no POM in this directory (" + session.getExecutionRootDirectory() + ")."
+ " Please verify you invoked Maven from the correct directory." );
}
List<TaskSegment> taskSegments = lifecycleTaskSegmentCalculator.calculateTaskSegments( session );
projectBuilds = buildListCalculator.calculateProjectBuilds( session, taskSegments );
if ( projectBuilds.isEmpty() )
{
throw new NoGoalSpecifiedException( "No goals have been specified for this build."
+ " You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or"
+ " <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>."
+ " Available lifecycle phases are: " + defaultLifeCycles.getLifecyclePhaseList() + "." );
}
ProjectIndex projectIndex = new ProjectIndex( session.getProjects() );
if ( logger.isDebugEnabled() )
{
lifecycleDebugLogger.debugReactorPlan( projectBuilds );
}
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
ReactorBuildStatus reactorBuildStatus = new ReactorBuildStatus( session.getProjectDependencyGraph() );
reactorContext = new ReactorContext( result, projectIndex, oldContextClassLoader, reactorBuildStatus );
String builderId = session.getRequest().getBuilderId();
Builder builder = builders.get( builderId );
if ( builder == null )
{
throw new BuilderNotFoundException( String.format( "The builder requested using id = %s cannot be found", builderId ) );
}
int degreeOfConcurrency = session.getRequest().getDegreeOfConcurrency();
if ( degreeOfConcurrency >= 2 )
{
logger.info( "" );
- logger.info( String.format( "Using the %s implemenation with a thread count of %d", builder.getClass().getSimpleName(), degreeOfConcurrency ) );
+ logger.info( String.format( "Using the %s implementation with a thread count of %d", builder.getClass().getSimpleName(), degreeOfConcurrency ) );
}
builder.build( session, reactorContext, projectBuilds, taskSegments, reactorBuildStatus );
}
catch ( Exception e )
{
result.addException( e );
}
finally
{
eventCatapult.fire( ExecutionEvent.Type.SessionEnded, session, null );
}
}
private boolean buildExecutionRequiresProject( MavenSession session )
{
return lifecycleTaskSegmentCalculator.requiresProject( session );
}
private boolean projectIsNotPresent( MavenSession session )
{
return !session.getRequest().isProjectPresent();
}
}
| true | true | public void execute( MavenSession session )
{
eventCatapult.fire( ExecutionEvent.Type.SessionStarted, session, null );
ReactorContext reactorContext = null;
ProjectBuildList projectBuilds = null;
MavenExecutionResult result = session.getResult();
try
{
if ( buildExecutionRequiresProject( session ) && projectIsNotPresent( session ) )
{
throw new MissingProjectException( "The goal you specified requires a project to execute"
+ " but there is no POM in this directory (" + session.getExecutionRootDirectory() + ")."
+ " Please verify you invoked Maven from the correct directory." );
}
List<TaskSegment> taskSegments = lifecycleTaskSegmentCalculator.calculateTaskSegments( session );
projectBuilds = buildListCalculator.calculateProjectBuilds( session, taskSegments );
if ( projectBuilds.isEmpty() )
{
throw new NoGoalSpecifiedException( "No goals have been specified for this build."
+ " You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or"
+ " <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>."
+ " Available lifecycle phases are: " + defaultLifeCycles.getLifecyclePhaseList() + "." );
}
ProjectIndex projectIndex = new ProjectIndex( session.getProjects() );
if ( logger.isDebugEnabled() )
{
lifecycleDebugLogger.debugReactorPlan( projectBuilds );
}
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
ReactorBuildStatus reactorBuildStatus = new ReactorBuildStatus( session.getProjectDependencyGraph() );
reactorContext = new ReactorContext( result, projectIndex, oldContextClassLoader, reactorBuildStatus );
String builderId = session.getRequest().getBuilderId();
Builder builder = builders.get( builderId );
if ( builder == null )
{
throw new BuilderNotFoundException( String.format( "The builder requested using id = %s cannot be found", builderId ) );
}
int degreeOfConcurrency = session.getRequest().getDegreeOfConcurrency();
if ( degreeOfConcurrency >= 2 )
{
logger.info( "" );
logger.info( String.format( "Using the %s implemenation with a thread count of %d", builder.getClass().getSimpleName(), degreeOfConcurrency ) );
}
builder.build( session, reactorContext, projectBuilds, taskSegments, reactorBuildStatus );
}
catch ( Exception e )
{
result.addException( e );
}
finally
{
eventCatapult.fire( ExecutionEvent.Type.SessionEnded, session, null );
}
}
| public void execute( MavenSession session )
{
eventCatapult.fire( ExecutionEvent.Type.SessionStarted, session, null );
ReactorContext reactorContext = null;
ProjectBuildList projectBuilds = null;
MavenExecutionResult result = session.getResult();
try
{
if ( buildExecutionRequiresProject( session ) && projectIsNotPresent( session ) )
{
throw new MissingProjectException( "The goal you specified requires a project to execute"
+ " but there is no POM in this directory (" + session.getExecutionRootDirectory() + ")."
+ " Please verify you invoked Maven from the correct directory." );
}
List<TaskSegment> taskSegments = lifecycleTaskSegmentCalculator.calculateTaskSegments( session );
projectBuilds = buildListCalculator.calculateProjectBuilds( session, taskSegments );
if ( projectBuilds.isEmpty() )
{
throw new NoGoalSpecifiedException( "No goals have been specified for this build."
+ " You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or"
+ " <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>."
+ " Available lifecycle phases are: " + defaultLifeCycles.getLifecyclePhaseList() + "." );
}
ProjectIndex projectIndex = new ProjectIndex( session.getProjects() );
if ( logger.isDebugEnabled() )
{
lifecycleDebugLogger.debugReactorPlan( projectBuilds );
}
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
ReactorBuildStatus reactorBuildStatus = new ReactorBuildStatus( session.getProjectDependencyGraph() );
reactorContext = new ReactorContext( result, projectIndex, oldContextClassLoader, reactorBuildStatus );
String builderId = session.getRequest().getBuilderId();
Builder builder = builders.get( builderId );
if ( builder == null )
{
throw new BuilderNotFoundException( String.format( "The builder requested using id = %s cannot be found", builderId ) );
}
int degreeOfConcurrency = session.getRequest().getDegreeOfConcurrency();
if ( degreeOfConcurrency >= 2 )
{
logger.info( "" );
logger.info( String.format( "Using the %s implementation with a thread count of %d", builder.getClass().getSimpleName(), degreeOfConcurrency ) );
}
builder.build( session, reactorContext, projectBuilds, taskSegments, reactorBuildStatus );
}
catch ( Exception e )
{
result.addException( e );
}
finally
{
eventCatapult.fire( ExecutionEvent.Type.SessionEnded, session, null );
}
}
|
diff --git a/src/main/java/org/jboss/modcluster/mcmp/impl/DefaultMCMPHandler.java b/src/main/java/org/jboss/modcluster/mcmp/impl/DefaultMCMPHandler.java
index dadbce97..4702834e 100644
--- a/src/main/java/org/jboss/modcluster/mcmp/impl/DefaultMCMPHandler.java
+++ b/src/main/java/org/jboss/modcluster/mcmp/impl/DefaultMCMPHandler.java
@@ -1,1047 +1,1051 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2009, Red Hat Middleware LLC, 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.modcluster.mcmp.impl;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Externalizable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.Writer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.net.SocketFactory;
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
import org.jboss.logging.Logger;
import org.jboss.modcluster.Strings;
import org.jboss.modcluster.config.MCMPHandlerConfiguration;
import org.jboss.modcluster.mcmp.MCMPConnectionListener;
import org.jboss.modcluster.mcmp.MCMPHandler;
import org.jboss.modcluster.mcmp.MCMPRequest;
import org.jboss.modcluster.mcmp.MCMPRequestFactory;
import org.jboss.modcluster.mcmp.MCMPResponseParser;
import org.jboss.modcluster.mcmp.MCMPServer;
import org.jboss.modcluster.mcmp.MCMPServerState;
import org.jboss.modcluster.mcmp.ResetRequestSource;
import org.jboss.modcluster.mcmp.MCMPServerState.State;
/**
* Default implementation of {@link MCMPHandler}.
*
* @author Jean-Frederic Clere
* @author Brian Stansberry
* @author Paul Ferraro
*/
@ThreadSafe
public class DefaultMCMPHandler implements MCMPHandler
{
private static final String NEW_LINE = "\r\n";
protected static final Logger log = Logger.getLogger(DefaultMCMPHandler.class);
// -------------------------------------------------------------- Constants
// ----------------------------------------------------------------- Fields
private final MCMPHandlerConfiguration config;
/** Source for reset requests when we need to reset a proxy. */
private final ResetRequestSource resetRequestSource;
private final MCMPRequestFactory requestFactory;
private final MCMPResponseParser responseParser;
private final ReadWriteLock proxiesLock = new ReentrantReadWriteLock();
private final Lock addRemoveProxiesLock = new ReentrantLock();
/** Proxies. */
@GuardedBy("proxiesLock")
private final List<Proxy> proxies = new ArrayList<Proxy>();
/** Add proxy list. */
@GuardedBy("addRemoveProxiesLock")
private final List<Proxy> addProxies = new ArrayList<Proxy>();
/** Remove proxy list. */
@GuardedBy("addRemoveProxiesLock")
private final List<Proxy> removeProxies = new ArrayList<Proxy>();
private final AtomicBoolean established = new AtomicBoolean(false);
private volatile MCMPConnectionListener connectionListener;
private volatile boolean init = false;
// ----------------------------------------------------------- Constructors
public DefaultMCMPHandler(MCMPHandlerConfiguration config, ResetRequestSource source,
MCMPRequestFactory requestFactory, MCMPResponseParser responseParser)
{
this.resetRequestSource = source;
this.config = config;
this.requestFactory = requestFactory;
this.responseParser = responseParser;
}
// ------------------------------------------------------------ MCMPHandler
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#init(java.util.List)
*/
public void init(List<InetSocketAddress> initialProxies, MCMPConnectionListener connectionListener)
{
this.connectionListener = connectionListener;
if (initialProxies != null)
{
Lock lock = this.proxiesLock.writeLock();
lock.lock();
try
{
for (InetSocketAddress initialProxy: initialProxies)
{
this.add(initialProxy);
}
this.status(false);
}
finally
{
lock.unlock();
}
}
this.init = true;
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#shutdown()
*/
public void shutdown()
{
this.init = false;
Lock lock = this.proxiesLock.readLock();
lock.lock();
try
{
for (Proxy proxy: this.proxies)
{
proxy.closeConnection();
}
}
finally
{
lock.unlock();
}
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#addProxy(java.net.InetSocketAddress)
*/
public void addProxy(InetSocketAddress socketAddress)
{
this.add(socketAddress);
}
private Proxy add(InetSocketAddress socketAddress)
{
Proxy proxy = new Proxy(socketAddress, this.config);
this.addRemoveProxiesLock.lock();
try
{
Lock lock = this.proxiesLock.readLock();
lock.lock();
try
{
for (Proxy candidate: this.proxies)
{
if (candidate.equals(proxy)) return candidate;
}
}
finally
{
lock.unlock();
}
for (Proxy candidate: this.addProxies)
{
if (candidate.equals(proxy)) return candidate;
}
for (Proxy candidate: this.removeProxies)
{
if (candidate.equals(proxy)) return candidate;
}
proxy.setState(Proxy.State.ERROR);
this.addProxies.add(proxy);
}
finally
{
this.addRemoveProxiesLock.unlock();
}
return proxy;
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#addProxy(java.net.InetSocketAddress, boolean)
*/
public void addProxy(InetSocketAddress socketAddress, boolean established)
{
this.add(socketAddress).setEstablished(established);
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#removeProxy(java.net.InetSocketAddress)
*/
public void removeProxy(InetSocketAddress socketAddress)
{
Proxy proxy = new Proxy(socketAddress, this.config);
this.addRemoveProxiesLock.lock();
try
{
this.removeProxies.add(proxy);
}
finally
{
this.addRemoveProxiesLock.unlock();
}
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#getProxyStates()
*/
public Set<MCMPServerState> getProxyStates()
{
Lock lock = this.proxiesLock.readLock();
lock.lock();
try
{
if (this.proxies.isEmpty()) return Collections.emptySet();
Set<MCMPServerState> result = new LinkedHashSet<MCMPServerState>(this.proxies.size());
for (Proxy proxy: this.proxies)
{
result.add(proxy);
}
return result;
}
finally
{
lock.unlock();
}
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#isProxyHealthOK()
*/
public boolean isProxyHealthOK()
{
Lock lock = this.proxiesLock.readLock();
lock.lock();
try
{
for (Proxy proxy: this.proxies)
{
if (proxy.getState() != MCMPServerState.State.OK)
{
return false;
}
}
return true;
}
finally
{
lock.unlock();
}
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#markProxiesInError()
*/
public void markProxiesInError()
{
Lock lock = this.proxiesLock.readLock();
lock.lock();
try
{
for (Proxy proxy: this.proxies)
{
if (proxy.getState() == MCMPServerState.State.OK)
{
proxy.setState(Proxy.State.ERROR);
}
}
}
finally
{
lock.unlock();
}
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#reset()
*/
public void reset()
{
Lock lock = this.proxiesLock.readLock();
lock.lock();
try
{
for (Proxy proxy: this.proxies)
{
if (proxy.getState() == Proxy.State.DOWN)
{
proxy.setState(Proxy.State.ERROR);
}
}
}
finally
{
lock.unlock();
}
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#status()
*/
public synchronized void status()
{
if (this.init)
{
this.processPendingDiscoveryEvents();
this.status(true);
}
}
/**
* Send a periodic status request.
* @param sendResetRequests if enabled, when in error state, the listener will attempt to refresh the configuration on the front end server
*/
private void status(boolean sendResetRequests)
{
Lock lock = this.proxiesLock.readLock();
lock.lock();
try
{
for (Proxy proxy: this.proxies)
{
// Attempt to reset any proxies in error
if (proxy.getState() == Proxy.State.ERROR)
{
proxy.setState(Proxy.State.OK);
String response = this.sendRequest(this.requestFactory.createInfoRequest(), proxy);
if (proxy.getState() == Proxy.State.OK)
{
// Only notify connection listener once
if (this.established.compareAndSet(false, true))
{
this.connectionListener.connectionEstablished(proxy.getLocalAddress());
}
if (sendResetRequests)
{
Map<String, Set<ResetRequestSource.VirtualHost>> parsedResponse = this.responseParser.parseInfoResponse(response);
List<MCMPRequest> requests = this.resetRequestSource.getResetRequests(parsedResponse);
log.trace(requests);
this.sendRequests(requests);
}
}
proxy.closeConnection();
}
}
}
finally
{
lock.unlock();
}
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#sendRequest(org.jboss.modcluster.mcmp.MCMPRequest)
*/
public Map<MCMPServerState, String> sendRequest(MCMPRequest request)
{
Map<MCMPServerState, String> map = new HashMap<MCMPServerState, String>();
Lock lock = this.proxiesLock.readLock();
lock.lock();
try
{
for (Proxy proxy: this.proxies)
{
map.put(proxy, this.sendRequest(request, proxy));
}
}
finally
{
lock.unlock();
}
return map;
}
/**
* {@inheritDoc}
* @see org.jboss.modcluster.mcmp.MCMPHandler#sendRequests(java.util.List)
*/
public Map<MCMPServerState, List<String>> sendRequests(List<MCMPRequest> requests)
{
Map<MCMPServerState, List<String>> map = new HashMap<MCMPServerState, List<String>>();
Lock lock = this.proxiesLock.readLock();
lock.lock();
try
{
for (Proxy proxy: this.proxies)
{
List<String> list = new ArrayList<String>(requests.size());
for (MCMPRequest request: requests)
{
list.add(this.sendRequest(request, proxy));
}
map.put(proxy, list);
}
}
finally
{
lock.unlock();
}
return map;
}
// ---------------------------------------------------------------- Private
private void processPendingDiscoveryEvents()
{
this.addRemoveProxiesLock.lock();
try
{
// Check to add or remove proxies, and rebuild a new list if needed
if (!this.addProxies.isEmpty() || !this.removeProxies.isEmpty())
{
Lock lock = this.proxiesLock.writeLock();
lock.lock();
try
{
this.proxies.addAll(this.addProxies);
this.proxies.removeAll(this.removeProxies);
this.addProxies.clear();
this.removeProxies.clear();
// Reset all connections
for (Proxy proxy: this.proxies)
{
proxy.closeConnection();
}
}
finally
{
lock.unlock();
}
}
}
finally
{
this.addRemoveProxiesLock.unlock();
}
}
private String sendRequest(Proxy proxy, String command, String body) throws IOException
{
Writer writer = proxy.getConnectionWriter();
writer.append(command).append(NEW_LINE);
writer.append("Content-Length: ").append(String.valueOf(body.length())).append(NEW_LINE);
writer.append("User-Agent: ClusterListener/1.0").append(NEW_LINE);
writer.append("Connection: Keep-Alive").append(NEW_LINE);
writer.write(NEW_LINE);
writer.write(body);
writer.write(NEW_LINE);
writer.flush();
// Read the first response line and skip the rest of the HTTP header
return proxy.getConnectionReader().readLine();
}
private void appendParameter(Appendable appender, String name, String value, boolean more) throws IOException
{
appender.append(URLEncoder.encode(name, "UTF-8")).append('=').append(URLEncoder.encode(value, "UTF-8"));
if (more)
{
appender.append('&');
}
}
private String sendRequest(MCMPRequest request, Proxy proxy)
{
// If there was an error, do nothing until the next periodic event, where the whole configuration
// will be refreshed
if (proxy.getState() != Proxy.State.OK) return null;
if (log.isTraceEnabled())
{
log.trace(Strings.REQUEST_SEND.getString(request, proxy));
}
String command = request.getRequestType().getCommand();
boolean wildcard = request.isWildcard();
String jvmRoute = request.getJvmRoute();
Map<String, String> parameters = request.getParameters();
StringBuilder bodyBuilder = new StringBuilder();
// First, encode the POST body
try
{
if (jvmRoute != null)
{
this.appendParameter(bodyBuilder, "JVMRoute", jvmRoute, !parameters.isEmpty());
}
Iterator<Map.Entry<String, String>> entries = parameters.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, String> entry = entries.next();
this.appendParameter(bodyBuilder, entry.getKey(), entry.getValue(), entries.hasNext());
}
}
catch (IOException e)
{
// Error encoding URL, should not happen
throw new IllegalArgumentException(e);
}
// Then, connect to the proxy
// Generate and write request
StringBuilder headBuilder = new StringBuilder();
headBuilder.append(command).append(" ");
String proxyURL = this.config.getProxyURL();
if (proxyURL != null)
{
headBuilder.append(proxyURL);
}
if (headBuilder.charAt(headBuilder.length() - 1) != '/')
{
headBuilder.append('/');
}
if (wildcard)
{
headBuilder.append('*');
}
- headBuilder.append(" HTTP/1.0");
+ headBuilder.append(" HTTP/1.1\r\n");
+ headBuilder.append("Host: ");
String head = headBuilder.toString();
String body = bodyBuilder.toString();
// Require exclusive access to proxy socket
synchronized (proxy)
{
try
{
String line = null;
+ StringBuilder proxyheadBuilder = new StringBuilder(head);
+ proxyheadBuilder.append(proxy.getSocketAddress().getHostName() + ":" + proxy.getSocketAddress().getPort());
+ String proxyhead = proxyheadBuilder.toString();
try
{
- line = sendRequest(proxy, head, body);
+ line = sendRequest(proxy, proxyhead, body);
}
catch (IOException e)
{
// Ignore first write failure
}
if (line == null)
{
// Retry failed read/write with fresh connection
proxy.closeConnection();
line = sendRequest(proxy, head, body);
}
BufferedReader reader = proxy.getConnectionReader();
// Parse the line, which is formed like HTTP/1.x YYY Message
int status = 500;
// String version = "0";
String message = null;
String errorType = null;
int contentLength = 0;
boolean close = false;
if (line != null)
{
try
{
int spaceIndex = line.indexOf(' ');
String responseStatus = line.substring(spaceIndex + 1, line.indexOf(' ', spaceIndex + 1));
status = Integer.parseInt(responseStatus);
line = reader.readLine();
while ((line != null) && (line.length() > 0))
{
int colon = line.indexOf(':');
String headerName = line.substring(0, colon).trim();
String headerValue = line.substring(colon + 1).trim();
if ("version".equalsIgnoreCase(headerName))
{
// version = headerValue;
}
else if ("type".equalsIgnoreCase(headerName))
{
errorType = headerValue;
}
else if ("mess".equalsIgnoreCase(headerName))
{
message = headerValue;
}
else if ("content-length".equalsIgnoreCase(headerName))
{
contentLength = Integer.parseInt(headerValue);
}
else if ("connection".equalsIgnoreCase(headerName))
{
close = "close".equalsIgnoreCase(headerValue);
}
line = reader.readLine();
}
}
catch (Exception e)
{
log.info(Strings.ERROR_HEADER_PARSE.getString(command), e);
}
}
// Mark as error if the front end server did not return 200; the configuration will
// be refreshed during the next periodic event
if (status == 200)
{
if (request.getRequestType().getEstablishesServer())
{
// We know the request succeeded, so if appropriate
// mark the proxy as established before any possible
// later exception happens
proxy.setEstablished(true);
}
}
else
{
if ("SYNTAX".equals(errorType))
{
// Syntax error means the protocol is incorrect, which cannot be automatically fixed
proxy.setState(Proxy.State.DOWN);
log.error(Strings.ERROR_REQUEST_SYNTAX.getString(command, proxy, errorType, message));
}
else
{
proxy.setState(Proxy.State.ERROR);
log.error(Strings.ERROR_REQUEST_SEND_OTHER.getString(command, proxy, errorType, message));
}
}
if (close)
{
contentLength = Integer.MAX_VALUE;
}
else if (contentLength == 0)
{
return null;
}
// Read the request body
StringBuilder result = new StringBuilder();
char[] buffer = new char[512];
while (contentLength > 0)
{
int bytes = reader.read(buffer, 0, (contentLength > buffer.length) ? buffer.length : contentLength);
if (bytes <= 0) break;
result.append(buffer, 0, bytes);
contentLength -= bytes;
}
if (proxy.getState() == State.OK)
{
proxy.setIoExceptionLogged(false);
}
return result.toString();
}
catch (IOException e)
{
// Most likely this is a connection error with the proxy
proxy.setState(Proxy.State.ERROR);
// Log it only if we haven't done so already. Don't spam the log
if (proxy.isIoExceptionLogged() == false)
{
log.info(Strings.ERROR_REQUEST_SEND_IO.getString(command, proxy), e);
proxy.setIoExceptionLogged(true);
}
return null;
}
finally
{
// If there's an error of any sort, or if the proxy did not return 200, it is an error
if (proxy.getState() != Proxy.State.OK)
{
proxy.closeConnection();
}
}
}
}
/**
* This class represents a front-end httpd server.
*/
@ThreadSafe
private static class Proxy implements MCMPServerState, Serializable
{
/** The serialVersionUID */
private static final long serialVersionUID = 5219680414337319908L;
private final InetSocketAddress socketAddress;
private volatile State state = State.OK;
private volatile boolean established = false;
private transient final int socketTimeout;
private transient final SocketFactory socketFactory;
private transient volatile boolean ioExceptionLogged = false;
private transient volatile InetAddress localAddress = null;
@GuardedBy("Proxy.this")
private transient volatile Socket socket = null;
@GuardedBy("Proxy.this")
private transient volatile BufferedReader reader = null;
@GuardedBy("Proxy.this")
private transient volatile BufferedWriter writer = null;
Proxy(InetSocketAddress socketAddress, MCMPHandlerConfiguration config)
{
this.socketAddress = socketAddress;
this.socketFactory = config.isSsl() ? new JSSESocketFactory(config) : SocketFactory.getDefault();
this.socketTimeout = config.getSocketTimeout();
}
// -------------------------------------------- MCMPServerState
public State getState()
{
return this.state;
}
// ----------------------------------------------------------- MCMPServer
public InetSocketAddress getSocketAddress()
{
return this.socketAddress;
}
public boolean isEstablished()
{
return this.established;
}
// ------------------------------------------------------------ Overrides
@Override
public String toString()
{
return this.socketAddress.toString();
}
@Override
public boolean equals(Object object)
{
if ((object == null) || !(object instanceof MCMPServer)) return false;
MCMPServer proxy = (MCMPServer) object;
return this.socketAddress.equals(proxy.getSocketAddress());
}
@Override
public int hashCode()
{
return this.socketAddress.hashCode();
}
// -------------------------------------------------------------- Private
void setState(State state)
{
if (state == null)
{
throw new IllegalArgumentException(Strings.ERROR_ARGUMENT_NULL.getString("state"));
}
this.state = state;
}
void setEstablished(boolean established)
{
this.established = established;
}
/**
* Return a reader to the proxy.
*/
private synchronized Socket getConnection() throws IOException
{
if ((this.socket == null) || this.socket.isClosed())
{
this.socket = this.socketFactory.createSocket();
this.socket.connect(this.socketAddress, this.socketTimeout);
this.socket.setSoTimeout(this.socketTimeout);
this.localAddress = this.socket.getLocalAddress();
}
return this.socket;
}
/**
* Convenience method that returns a reader to the proxy.
*/
synchronized BufferedReader getConnectionReader() throws IOException
{
if (this.reader == null)
{
this.reader = new BufferedReader(new InputStreamReader(this.getConnection().getInputStream()));
}
return this.reader;
}
/**
* Convenience method that returns a writer to the proxy.
*/
synchronized BufferedWriter getConnectionWriter() throws IOException
{
if (this.writer == null)
{
this.writer = new BufferedWriter(new OutputStreamWriter(this.getConnection().getOutputStream()));
}
return this.writer;
}
InetAddress getLocalAddress()
{
return this.localAddress;
}
/**
* Close connection.
*/
synchronized void closeConnection()
{
if (this.reader != null)
{
try
{
this.reader.close();
}
catch (IOException e)
{
// Ignore
}
this.reader = null;
}
if (this.writer != null)
{
try
{
this.writer.close();
}
catch (IOException e)
{
// Ignore
}
this.writer = null;
}
if (this.socket != null)
{
if (!this.socket.isClosed())
{
try
{
this.socket.close();
}
catch (IOException e)
{
// Ignore
}
}
this.socket = null;
}
}
boolean isIoExceptionLogged()
{
return this.ioExceptionLogged;
}
void setIoExceptionLogged(boolean ioErrorLogged)
{
this.ioExceptionLogged = ioErrorLogged;
}
}
static class VirtualHostImpl implements ResetRequestSource.VirtualHost, Externalizable
{
private final Set<String> aliases = new LinkedHashSet<String>();
private final Map<String, ResetRequestSource.Status> contexts = new HashMap<String, ResetRequestSource.Status>();
public VirtualHostImpl()
{
// Expose for deserialization
}
/**
* @{inheritDoc}
* @see org.jboss.modcluster.mcmp.ResetRequestSource.VirtualHost#getAliases()
*/
public Set<String> getAliases()
{
return this.aliases;
}
/**
* @{inheritDoc}
* @see org.jboss.modcluster.mcmp.ResetRequestSource.VirtualHost#getContexts()
*/
public Map<String, ResetRequestSource.Status> getContexts()
{
return this.contexts;
}
/**
* @{inheritDoc}
* @see java.io.Externalizable#readExternal(java.io.ObjectInput)
*/
public void readExternal(ObjectInput input) throws IOException
{
int aliases = input.readInt();
for (int i = 0; i < aliases; ++i)
{
this.aliases.add(input.readUTF());
}
ResetRequestSource.Status[] stati = ResetRequestSource.Status.values();
int contexts = input.readInt();
for (int i = 0; i < contexts; ++i)
{
this.contexts.put(input.readUTF(), stati[input.readInt()]);
}
}
/**
* @{inheritDoc}
* @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
*/
public void writeExternal(ObjectOutput output) throws IOException
{
output.writeInt(this.aliases.size());
for (String alias: this.aliases)
{
output.writeUTF(alias);
}
output.writeInt(this.contexts.size());
for (Map.Entry<String, ResetRequestSource.Status> context: this.contexts.entrySet())
{
output.writeUTF(context.getKey());
output.writeInt(context.getValue().ordinal());
}
}
}
}
| false | true | private String sendRequest(MCMPRequest request, Proxy proxy)
{
// If there was an error, do nothing until the next periodic event, where the whole configuration
// will be refreshed
if (proxy.getState() != Proxy.State.OK) return null;
if (log.isTraceEnabled())
{
log.trace(Strings.REQUEST_SEND.getString(request, proxy));
}
String command = request.getRequestType().getCommand();
boolean wildcard = request.isWildcard();
String jvmRoute = request.getJvmRoute();
Map<String, String> parameters = request.getParameters();
StringBuilder bodyBuilder = new StringBuilder();
// First, encode the POST body
try
{
if (jvmRoute != null)
{
this.appendParameter(bodyBuilder, "JVMRoute", jvmRoute, !parameters.isEmpty());
}
Iterator<Map.Entry<String, String>> entries = parameters.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, String> entry = entries.next();
this.appendParameter(bodyBuilder, entry.getKey(), entry.getValue(), entries.hasNext());
}
}
catch (IOException e)
{
// Error encoding URL, should not happen
throw new IllegalArgumentException(e);
}
// Then, connect to the proxy
// Generate and write request
StringBuilder headBuilder = new StringBuilder();
headBuilder.append(command).append(" ");
String proxyURL = this.config.getProxyURL();
if (proxyURL != null)
{
headBuilder.append(proxyURL);
}
if (headBuilder.charAt(headBuilder.length() - 1) != '/')
{
headBuilder.append('/');
}
if (wildcard)
{
headBuilder.append('*');
}
headBuilder.append(" HTTP/1.0");
String head = headBuilder.toString();
String body = bodyBuilder.toString();
// Require exclusive access to proxy socket
synchronized (proxy)
{
try
{
String line = null;
try
{
line = sendRequest(proxy, head, body);
}
catch (IOException e)
{
// Ignore first write failure
}
if (line == null)
{
// Retry failed read/write with fresh connection
proxy.closeConnection();
line = sendRequest(proxy, head, body);
}
BufferedReader reader = proxy.getConnectionReader();
// Parse the line, which is formed like HTTP/1.x YYY Message
int status = 500;
// String version = "0";
String message = null;
String errorType = null;
int contentLength = 0;
boolean close = false;
if (line != null)
{
try
{
int spaceIndex = line.indexOf(' ');
String responseStatus = line.substring(spaceIndex + 1, line.indexOf(' ', spaceIndex + 1));
status = Integer.parseInt(responseStatus);
line = reader.readLine();
while ((line != null) && (line.length() > 0))
{
int colon = line.indexOf(':');
String headerName = line.substring(0, colon).trim();
String headerValue = line.substring(colon + 1).trim();
if ("version".equalsIgnoreCase(headerName))
{
// version = headerValue;
}
else if ("type".equalsIgnoreCase(headerName))
{
errorType = headerValue;
}
else if ("mess".equalsIgnoreCase(headerName))
{
message = headerValue;
}
else if ("content-length".equalsIgnoreCase(headerName))
{
contentLength = Integer.parseInt(headerValue);
}
else if ("connection".equalsIgnoreCase(headerName))
{
close = "close".equalsIgnoreCase(headerValue);
}
line = reader.readLine();
}
}
catch (Exception e)
{
log.info(Strings.ERROR_HEADER_PARSE.getString(command), e);
}
}
// Mark as error if the front end server did not return 200; the configuration will
// be refreshed during the next periodic event
if (status == 200)
{
if (request.getRequestType().getEstablishesServer())
{
// We know the request succeeded, so if appropriate
// mark the proxy as established before any possible
// later exception happens
proxy.setEstablished(true);
}
}
else
{
if ("SYNTAX".equals(errorType))
{
// Syntax error means the protocol is incorrect, which cannot be automatically fixed
proxy.setState(Proxy.State.DOWN);
log.error(Strings.ERROR_REQUEST_SYNTAX.getString(command, proxy, errorType, message));
}
else
{
proxy.setState(Proxy.State.ERROR);
log.error(Strings.ERROR_REQUEST_SEND_OTHER.getString(command, proxy, errorType, message));
}
}
if (close)
{
contentLength = Integer.MAX_VALUE;
}
else if (contentLength == 0)
{
return null;
}
// Read the request body
StringBuilder result = new StringBuilder();
char[] buffer = new char[512];
while (contentLength > 0)
{
int bytes = reader.read(buffer, 0, (contentLength > buffer.length) ? buffer.length : contentLength);
if (bytes <= 0) break;
result.append(buffer, 0, bytes);
contentLength -= bytes;
}
if (proxy.getState() == State.OK)
{
proxy.setIoExceptionLogged(false);
}
return result.toString();
}
catch (IOException e)
{
// Most likely this is a connection error with the proxy
proxy.setState(Proxy.State.ERROR);
// Log it only if we haven't done so already. Don't spam the log
if (proxy.isIoExceptionLogged() == false)
{
log.info(Strings.ERROR_REQUEST_SEND_IO.getString(command, proxy), e);
proxy.setIoExceptionLogged(true);
}
return null;
}
finally
{
// If there's an error of any sort, or if the proxy did not return 200, it is an error
if (proxy.getState() != Proxy.State.OK)
{
proxy.closeConnection();
}
}
}
}
| private String sendRequest(MCMPRequest request, Proxy proxy)
{
// If there was an error, do nothing until the next periodic event, where the whole configuration
// will be refreshed
if (proxy.getState() != Proxy.State.OK) return null;
if (log.isTraceEnabled())
{
log.trace(Strings.REQUEST_SEND.getString(request, proxy));
}
String command = request.getRequestType().getCommand();
boolean wildcard = request.isWildcard();
String jvmRoute = request.getJvmRoute();
Map<String, String> parameters = request.getParameters();
StringBuilder bodyBuilder = new StringBuilder();
// First, encode the POST body
try
{
if (jvmRoute != null)
{
this.appendParameter(bodyBuilder, "JVMRoute", jvmRoute, !parameters.isEmpty());
}
Iterator<Map.Entry<String, String>> entries = parameters.entrySet().iterator();
while (entries.hasNext())
{
Map.Entry<String, String> entry = entries.next();
this.appendParameter(bodyBuilder, entry.getKey(), entry.getValue(), entries.hasNext());
}
}
catch (IOException e)
{
// Error encoding URL, should not happen
throw new IllegalArgumentException(e);
}
// Then, connect to the proxy
// Generate and write request
StringBuilder headBuilder = new StringBuilder();
headBuilder.append(command).append(" ");
String proxyURL = this.config.getProxyURL();
if (proxyURL != null)
{
headBuilder.append(proxyURL);
}
if (headBuilder.charAt(headBuilder.length() - 1) != '/')
{
headBuilder.append('/');
}
if (wildcard)
{
headBuilder.append('*');
}
headBuilder.append(" HTTP/1.1\r\n");
headBuilder.append("Host: ");
String head = headBuilder.toString();
String body = bodyBuilder.toString();
// Require exclusive access to proxy socket
synchronized (proxy)
{
try
{
String line = null;
StringBuilder proxyheadBuilder = new StringBuilder(head);
proxyheadBuilder.append(proxy.getSocketAddress().getHostName() + ":" + proxy.getSocketAddress().getPort());
String proxyhead = proxyheadBuilder.toString();
try
{
line = sendRequest(proxy, proxyhead, body);
}
catch (IOException e)
{
// Ignore first write failure
}
if (line == null)
{
// Retry failed read/write with fresh connection
proxy.closeConnection();
line = sendRequest(proxy, head, body);
}
BufferedReader reader = proxy.getConnectionReader();
// Parse the line, which is formed like HTTP/1.x YYY Message
int status = 500;
// String version = "0";
String message = null;
String errorType = null;
int contentLength = 0;
boolean close = false;
if (line != null)
{
try
{
int spaceIndex = line.indexOf(' ');
String responseStatus = line.substring(spaceIndex + 1, line.indexOf(' ', spaceIndex + 1));
status = Integer.parseInt(responseStatus);
line = reader.readLine();
while ((line != null) && (line.length() > 0))
{
int colon = line.indexOf(':');
String headerName = line.substring(0, colon).trim();
String headerValue = line.substring(colon + 1).trim();
if ("version".equalsIgnoreCase(headerName))
{
// version = headerValue;
}
else if ("type".equalsIgnoreCase(headerName))
{
errorType = headerValue;
}
else if ("mess".equalsIgnoreCase(headerName))
{
message = headerValue;
}
else if ("content-length".equalsIgnoreCase(headerName))
{
contentLength = Integer.parseInt(headerValue);
}
else if ("connection".equalsIgnoreCase(headerName))
{
close = "close".equalsIgnoreCase(headerValue);
}
line = reader.readLine();
}
}
catch (Exception e)
{
log.info(Strings.ERROR_HEADER_PARSE.getString(command), e);
}
}
// Mark as error if the front end server did not return 200; the configuration will
// be refreshed during the next periodic event
if (status == 200)
{
if (request.getRequestType().getEstablishesServer())
{
// We know the request succeeded, so if appropriate
// mark the proxy as established before any possible
// later exception happens
proxy.setEstablished(true);
}
}
else
{
if ("SYNTAX".equals(errorType))
{
// Syntax error means the protocol is incorrect, which cannot be automatically fixed
proxy.setState(Proxy.State.DOWN);
log.error(Strings.ERROR_REQUEST_SYNTAX.getString(command, proxy, errorType, message));
}
else
{
proxy.setState(Proxy.State.ERROR);
log.error(Strings.ERROR_REQUEST_SEND_OTHER.getString(command, proxy, errorType, message));
}
}
if (close)
{
contentLength = Integer.MAX_VALUE;
}
else if (contentLength == 0)
{
return null;
}
// Read the request body
StringBuilder result = new StringBuilder();
char[] buffer = new char[512];
while (contentLength > 0)
{
int bytes = reader.read(buffer, 0, (contentLength > buffer.length) ? buffer.length : contentLength);
if (bytes <= 0) break;
result.append(buffer, 0, bytes);
contentLength -= bytes;
}
if (proxy.getState() == State.OK)
{
proxy.setIoExceptionLogged(false);
}
return result.toString();
}
catch (IOException e)
{
// Most likely this is a connection error with the proxy
proxy.setState(Proxy.State.ERROR);
// Log it only if we haven't done so already. Don't spam the log
if (proxy.isIoExceptionLogged() == false)
{
log.info(Strings.ERROR_REQUEST_SEND_IO.getString(command, proxy), e);
proxy.setIoExceptionLogged(true);
}
return null;
}
finally
{
// If there's an error of any sort, or if the proxy did not return 200, it is an error
if (proxy.getState() != Proxy.State.OK)
{
proxy.closeConnection();
}
}
}
}
|
diff --git a/src/openmap/com/bbn/openmap/omGraphics/util/ImageWarp.java b/src/openmap/com/bbn/openmap/omGraphics/util/ImageWarp.java
index 61a740ce..6ec1d235 100644
--- a/src/openmap/com/bbn/openmap/omGraphics/util/ImageWarp.java
+++ b/src/openmap/com/bbn/openmap/omGraphics/util/ImageWarp.java
@@ -1,542 +1,542 @@
//**********************************************************************
//
//<copyright>
//
//BBN Technologies
//10 Moulton Street
//Cambridge, MA 02138
//(617) 873-8000
//
//Copyright (C) BBNT Solutions LLC. All rights reserved.
//
//</copyright>
//**********************************************************************
//
//$Source:
///cvs/darwars/ambush/aar/src/com/bbn/ambush/mission/MissionHandler.java,v
//$
//$RCSfile: MissionHandler.java,v $
//$Revision: 1.10 $
//$Date: 2004/10/21 20:08:31 $
//$Author: dietrick $
//
//**********************************************************************
package com.bbn.openmap.omGraphics.util;
import java.awt.Image;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.PixelGrabber;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.bbn.openmap.dataAccess.image.WorldFile;
import com.bbn.openmap.omGraphics.OMRaster;
import com.bbn.openmap.proj.Projection;
import com.bbn.openmap.proj.coords.GeoCoordTransformation;
import com.bbn.openmap.proj.coords.LatLonGCT;
import com.bbn.openmap.proj.coords.LatLonPoint;
import com.bbn.openmap.util.DataBounds;
import com.bbn.openmap.util.Debug;
/**
* The ImageTranslator is the object that takes a BufferedImage and creates an
* OMRaster from it based on a Projection object.
*/
public class ImageWarp {
public static Logger logger = Logger.getLogger("com.bbn.openmap.omGraphics.util.ImageWarp");
/**
* Source image pixels.
*/
protected int[] pixels = null;
/** Image width, */
protected int iwidth;
/** Image height, */
protected int iheight;
/**
* Horizontal units/pixel in the source BufferedImage projection. Assumed to
* be constant across the image.
*/
protected double hor_upp;
/**
* Vertical units/pixel in the source BufferedImage projection. Assumed to
* be constant across the image.
*/
protected double ver_upp;
/**
* The vertical origin pixel location in the source image for the coordinate
* system origin.
*/
protected double verOrigin;
/**
* The horizontal origin pixel location in the source image for the
* coordinate system origin.
*/
protected double horOrigin;
/**
* A transformation for the projection of the source image. If not set, the
* image is assumed to be equal arc projection.
*/
protected GeoCoordTransformation geoTrans = new LatLonGCT();
/**
* The coordinate bounds of the image, represented in the coordinate system
* of the image.
*/
protected DataBounds sourceImageBounds;
/**
* The coordinate image bounds of the projected image on the map window.
*/
protected DataBounds projectedImageBounds;
/**
* Create an image warp for an image assumed to be world wide coverage, with
* the top at 90 degrees, the bottom at -90, the left side at -180 and the
* right side at 180. Assumes the origin point is in the middle of the
* image.
*/
public ImageWarp(BufferedImage bi) {
this(bi, LatLonGCT.INSTANCE, new DataBounds(-180.0, -90.0, 180.0, 90.0));
}
/**
* Create an image warp with some additional transform information.
*
* @param bi BufferedImage of the source
* @param transform the GeoCoordTransformation for the projection of the
* image.
* @param imageBounds the bounds of the image in the image's coordinate
* system.
*/
public ImageWarp(BufferedImage bi, GeoCoordTransformation transform,
DataBounds imageBounds) {
if (bi != null) {
iwidth = bi.getWidth();
iheight = bi.getHeight();
setGeoTrans(transform);
setImageBounds(imageBounds);
pixels = getPixels(bi, 0, 0, iwidth, iheight);
// See if this saves on memory. Seems to.
bi = null;
}
}
/**
* Create an image warp with some additional transform information.
*
* @param bi BufferedImage of the source
* @param transform the GeoCoordTransformation for the projection of the
* image.
* @param worldFile the WorldFile describing the image's location.
*/
public ImageWarp(BufferedImage bi, GeoCoordTransformation transform,
WorldFile worldFile) {
if (bi != null) {
iwidth = bi.getWidth();
iheight = bi.getHeight();
setGeoTrans(transform);
setImageBounds(worldFile);
pixels = getPixels(bi, 0, 0, iwidth, iheight);
// See if this saves on memory. Seems to.
bi = null;
}
}
/**
* Create an image warp for an image assumed to be world wide coverage, with
* the top at 90 degrees, the bottom at -90, the left side at -180 and the
* right side at 180. Assumes the origin point is in the middle of the
* image.
* @param pix ARGB array of pixel values for image.
* @param width pixel width of image.
* @param height pixel height of image.
*/
public ImageWarp(int[] pix, int width, int height) {
this(pix, width, height, LatLonGCT.INSTANCE, new DataBounds(-180.0, -90.0, 180.0, 90.0));
}
/**
* Create an image warp with some additional transform information.
*
* @param pix ARGB array of pixel values for image.
* @param width pixel width of image.
* @param height pixel height of image.
* @param transform the GeoCoordTransformation for the projection of the
* image.
* @param imageBounds the bounds of the image in the image's coordinate
* system.
*/
public ImageWarp(int[] pix, int width, int height, GeoCoordTransformation transform,
DataBounds imageBounds) {
if (pix != null) {
iwidth = width;
iheight = height;
setGeoTrans(transform);
setImageBounds(imageBounds);
pixels = pix;
}
}
/**
* Create an image warp with some additional transform information.
*
* @param pix ARGB array of pixel values for image.
* @param width pixel width of image.
* @param height pixel height of image.
* @param transform the GeoCoordTransformation for the projection of the
* image.
* @param worldFile the WorldFile describing the image's location.
*/
public ImageWarp(int[] pix, int width, int height, GeoCoordTransformation transform,
WorldFile worldFile) {
if (pix != null) {
iwidth = width;
iheight = height;
setGeoTrans(transform);
setImageBounds(worldFile);
pixels = pix;
}
}
/**
* The pixels used in the OMRaster.
*/
// int[] tmpPixels = new int[0];
/**
* Return an OMRaster that covers the given projection, with the image
* warped for the projection.
*
* @param p map projection
* @return OMRaster or null if the image isn't within the current
* projection.
*/
public OMRaster getOMRaster(Projection p) {
int[] pixels = getImagePixels(p);
if (pixels != null && projectedImageBounds != null) {
int width = (int) projectedImageBounds.getWidth();
int height = (int) projectedImageBounds.getHeight();
int x = (int) projectedImageBounds.getMin().getX();
int y = (int) projectedImageBounds.getMin().getY();
OMRaster raster = new OMRaster(x, y, width, height, pixels);
raster.generate(p);
return raster;
}
return null;
}
/**
* Given a projection, return the pixels for an image that will cover the
* projection area.
*
* @param p map projection
* @return int[] of ARGB pixels for an image covering the given projection.
*/
public int[] getImagePixels(Projection p) {
if (pixels != null && p != null) {
projectedImageBounds = calculateProjectedImageBounds(p);
if (projectedImageBounds == null) {
// image isn't on the map.
return null;
}
int projHeight = (int) projectedImageBounds.getHeight();
int projWidth = (int) projectedImageBounds.getWidth();
// See if we can reuse the pixel array we have.
int[] tmpPixels = new int[projWidth * projHeight];
int numTmpPixels = tmpPixels.length;
logger.fine("tmpPixels[" + numTmpPixels + "]");
int clear = 0x00000000;
Point2D ctp = new Point2D.Double();
Point2D ddll = new Point2D.Double();
Point2D imageCoord = new Point2D.Double();
Point2D center = p.getCenter();
if (logger.isLoggable(Level.FINE)) {
logger.fine(projectedImageBounds.toString());
}
int minx = (int) Math.floor(projectedImageBounds.getMin().getX());
int miny = (int) Math.floor(projectedImageBounds.getMin().getY());
int maxx = (int) Math.ceil(projectedImageBounds.getMax().getX());
int maxy = (int) Math.ceil(projectedImageBounds.getMax().getY());
// i and j are map window pixel values.
for (int i = minx; i < maxx; i++) {
for (int j = miny; j < maxy; j++) {
// ix and iy are pixel coordinates of the destination image.
int ix = i - minx;
int iy = j - miny;
// index into the OMRaster pixel array
int tmpIndex = (ix + (iy * projWidth));
if (tmpIndex >= numTmpPixels) {
continue;
}
- p.inverse(i, j, ddll);
+ ddll = p.inverse(i, j, ddll);
// If the llp calculated isn't on the map,
// don't bother drawing it. Could be a space
// point in Orthographic projection, for
// instance.
if (ddll.equals(center)) {
p.forward(ddll, ctp);
if (ctp.getX() != i || ctp.getY() != j) {
tmpPixels[tmpIndex] = clear;
continue;
}
}
if (geoTrans != null) {
geoTrans.forward(ddll.getY(), ddll.getX(), imageCoord);
} else {
imageCoord = ddll;
}
if (!sourceImageBounds.contains(imageCoord)) {
tmpPixels[tmpIndex] = clear;
continue;
}
// Find the corresponding pixel location in
// the source image.
int horIndex = (int) (horOrigin + (imageCoord.getX() / hor_upp));
int verIndex = (int) (verOrigin + (imageCoord.getY() / ver_upp));
if (horIndex < 0 || horIndex >= iwidth || verIndex < 0
|| verIndex >= iheight) {
// pixel not on the source image. This
// happens if the image doesn't cover the
// entire earth.
continue;
}
int imageIndex = horIndex + (verIndex * iwidth);
if (imageIndex >= 0 && imageIndex < pixels.length) {
tmpPixels[tmpIndex] = pixels[imageIndex];
}
}
}
logger.fine("finished creating image");
return tmpPixels;
}
logger.warning("problem creating image, no pixels: "
+ (pixels == null ? "true" : "false") + ", no projection:"
+ (p == null ? "true" : "false"));
// If you get here, something's not right.
return null;
}
protected DataBounds calculateProjectedImageBounds(Projection p) {
if (geoTrans.equals(LatLonGCT.INSTANCE)) {
// whole earth
logger.fine("just using whole screen image");
return new DataBounds(0, 0, p.getWidth(), p.getHeight());
}
DataBounds db = null;
if (sourceImageBounds != null) {
int pw = p.getWidth();
int ph = p.getHeight();
Point2D min = sourceImageBounds.getMin();
Point2D max = sourceImageBounds.getMax();
double x1 = min.getX();
double y1 = min.getY();
double x2 = max.getX();
double y2 = max.getY();
double width = sourceImageBounds.getWidth();
double height = sourceImageBounds.getHeight();
LatLonPoint tmpG = new LatLonPoint.Double();
Point2D tmpP = new Point2D.Double();
db = new DataBounds();
db.setHardLimits(new DataBounds(0, 0, pw, ph));
db.add(p.forward(geoTrans.inverse(x1, y1, tmpG), tmpP));
double numSplits = 4;
double xSpacer = width / numSplits;
double ySpacer = height / numSplits;
for (int i = 1; i < numSplits; i++) {
db.add(p.forward(geoTrans.inverse(x1 + xSpacer * i, y1, tmpG),
tmpP));
db.add(p.forward(geoTrans.inverse(x1, y1 + ySpacer * i, tmpG),
tmpP));
db.add(p.forward(geoTrans.inverse(x1 + xSpacer * i, y2, tmpG),
tmpP));
db.add(p.forward(geoTrans.inverse(x2, y1 + ySpacer * i, tmpG),
tmpP));
}
if (db.getWidth() <= 0 || db.getHeight() <= 0) {
logger.fine("dimensions of data bounds bad, returning null "
+ db);
return null;
}
}
return db;
}
/**
* Get the pixels from the BufferedImage. If anything goes wrong, returns a
* int[0].
*/
protected int[] getPixels(Image img, int x, int y, int w, int h) {
int[] pixels = new int[w * h];
PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
try {
pg.grabPixels();
} catch (InterruptedException e) {
Debug.error("ImageTranslator: interrupted waiting for pixels!");
return new int[0];
}
if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
System.err.println("ImageTranslator: image fetch aborted or errored");
return new int[0];
}
return pixels;
}
public int getIwidth() {
return iwidth;
}
public void setIwidth(int iwidth) {
this.iwidth = iwidth;
}
public int getIheight() {
return iheight;
}
public void setIheight(int iheight) {
this.iheight = iheight;
}
public double getHor_dpp() {
return hor_upp;
}
public void setHor_dpp(double hor_dpp) {
this.hor_upp = hor_dpp;
}
public double getVer_dpp() {
return ver_upp;
}
public void setVer_dpp(double ver_dpp) {
this.ver_upp = ver_dpp;
}
public double getVerOrigin() {
return verOrigin;
}
public void setVerOrigin(double verOrigin) {
this.verOrigin = verOrigin;
}
public double getHorOrigin() {
return horOrigin;
}
public void setHorOrigin(double horOrigin) {
this.horOrigin = horOrigin;
}
public GeoCoordTransformation getGeoTrans() {
return geoTrans;
}
public void setGeoTrans(GeoCoordTransformation geoTrans) {
this.geoTrans = geoTrans;
}
public DataBounds getImageBounds() {
return sourceImageBounds;
}
public void setImageBounds(DataBounds imageBounds) {
this.sourceImageBounds = imageBounds;
hor_upp = imageBounds.getWidth() / iwidth;
// need the negative sign because latitudes increase in the opposite
// direction as y pixel values.
ver_upp = -imageBounds.getHeight() / iheight;
// We should be able to just go from the lower left corner of the image
// and find zero from there, the min of both bounds values.
double leftX = imageBounds.getMin().getX();
double upperY = imageBounds.getMax().getY();
verOrigin = -upperY / ver_upp; // number of Y pixels to origin.
horOrigin = -leftX / hor_upp; // number of X pixels to origin.
if (logger.isLoggable(Level.FINE)) {
logger.fine("getting image pixels w:" + iwidth + ", h:" + iheight
+ ", hor upp:" + hor_upp + ", ver upp:" + ver_upp
+ ", verOrigin:" + verOrigin + ", horOrigin:" + horOrigin);
logger.fine(imageBounds.toString());
}
}
public void setImageBounds(WorldFile worldFile) {
hor_upp = worldFile.getXDim();
// world file dimensions have direction, negative for going down
ver_upp = worldFile.getYDim();
double leftX = worldFile.getX();
double upperY = worldFile.getY();
verOrigin = -worldFile.getY() / ver_upp; // number of Y pixels to
// origin.
horOrigin = -leftX / hor_upp; // number of X pixels to origin.
sourceImageBounds = new DataBounds(leftX, worldFile.getY() + ver_upp
* iheight, leftX + hor_upp * iwidth, upperY);
if (logger.isLoggable(Level.FINE)) {
logger.fine("getting image pixels w:" + iwidth + ", h:" + iheight
+ ", hor upp:" + hor_upp + ", ver upp:" + ver_upp
+ ", verOrigin:" + verOrigin + ", horOrigin:" + horOrigin);
logger.fine(sourceImageBounds.toString());
}
}
public static void main(String[] args) {
new ImageWarp(new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB), LatLonGCT.INSTANCE, new DataBounds(25, -90, 180, 90));
}
}
| true | true | public int[] getImagePixels(Projection p) {
if (pixels != null && p != null) {
projectedImageBounds = calculateProjectedImageBounds(p);
if (projectedImageBounds == null) {
// image isn't on the map.
return null;
}
int projHeight = (int) projectedImageBounds.getHeight();
int projWidth = (int) projectedImageBounds.getWidth();
// See if we can reuse the pixel array we have.
int[] tmpPixels = new int[projWidth * projHeight];
int numTmpPixels = tmpPixels.length;
logger.fine("tmpPixels[" + numTmpPixels + "]");
int clear = 0x00000000;
Point2D ctp = new Point2D.Double();
Point2D ddll = new Point2D.Double();
Point2D imageCoord = new Point2D.Double();
Point2D center = p.getCenter();
if (logger.isLoggable(Level.FINE)) {
logger.fine(projectedImageBounds.toString());
}
int minx = (int) Math.floor(projectedImageBounds.getMin().getX());
int miny = (int) Math.floor(projectedImageBounds.getMin().getY());
int maxx = (int) Math.ceil(projectedImageBounds.getMax().getX());
int maxy = (int) Math.ceil(projectedImageBounds.getMax().getY());
// i and j are map window pixel values.
for (int i = minx; i < maxx; i++) {
for (int j = miny; j < maxy; j++) {
// ix and iy are pixel coordinates of the destination image.
int ix = i - minx;
int iy = j - miny;
// index into the OMRaster pixel array
int tmpIndex = (ix + (iy * projWidth));
if (tmpIndex >= numTmpPixels) {
continue;
}
p.inverse(i, j, ddll);
// If the llp calculated isn't on the map,
// don't bother drawing it. Could be a space
// point in Orthographic projection, for
// instance.
if (ddll.equals(center)) {
p.forward(ddll, ctp);
if (ctp.getX() != i || ctp.getY() != j) {
tmpPixels[tmpIndex] = clear;
continue;
}
}
if (geoTrans != null) {
geoTrans.forward(ddll.getY(), ddll.getX(), imageCoord);
} else {
imageCoord = ddll;
}
if (!sourceImageBounds.contains(imageCoord)) {
tmpPixels[tmpIndex] = clear;
continue;
}
// Find the corresponding pixel location in
// the source image.
int horIndex = (int) (horOrigin + (imageCoord.getX() / hor_upp));
int verIndex = (int) (verOrigin + (imageCoord.getY() / ver_upp));
if (horIndex < 0 || horIndex >= iwidth || verIndex < 0
|| verIndex >= iheight) {
// pixel not on the source image. This
// happens if the image doesn't cover the
// entire earth.
continue;
}
int imageIndex = horIndex + (verIndex * iwidth);
if (imageIndex >= 0 && imageIndex < pixels.length) {
tmpPixels[tmpIndex] = pixels[imageIndex];
}
}
}
logger.fine("finished creating image");
return tmpPixels;
}
logger.warning("problem creating image, no pixels: "
+ (pixels == null ? "true" : "false") + ", no projection:"
+ (p == null ? "true" : "false"));
// If you get here, something's not right.
return null;
}
| public int[] getImagePixels(Projection p) {
if (pixels != null && p != null) {
projectedImageBounds = calculateProjectedImageBounds(p);
if (projectedImageBounds == null) {
// image isn't on the map.
return null;
}
int projHeight = (int) projectedImageBounds.getHeight();
int projWidth = (int) projectedImageBounds.getWidth();
// See if we can reuse the pixel array we have.
int[] tmpPixels = new int[projWidth * projHeight];
int numTmpPixels = tmpPixels.length;
logger.fine("tmpPixels[" + numTmpPixels + "]");
int clear = 0x00000000;
Point2D ctp = new Point2D.Double();
Point2D ddll = new Point2D.Double();
Point2D imageCoord = new Point2D.Double();
Point2D center = p.getCenter();
if (logger.isLoggable(Level.FINE)) {
logger.fine(projectedImageBounds.toString());
}
int minx = (int) Math.floor(projectedImageBounds.getMin().getX());
int miny = (int) Math.floor(projectedImageBounds.getMin().getY());
int maxx = (int) Math.ceil(projectedImageBounds.getMax().getX());
int maxy = (int) Math.ceil(projectedImageBounds.getMax().getY());
// i and j are map window pixel values.
for (int i = minx; i < maxx; i++) {
for (int j = miny; j < maxy; j++) {
// ix and iy are pixel coordinates of the destination image.
int ix = i - minx;
int iy = j - miny;
// index into the OMRaster pixel array
int tmpIndex = (ix + (iy * projWidth));
if (tmpIndex >= numTmpPixels) {
continue;
}
ddll = p.inverse(i, j, ddll);
// If the llp calculated isn't on the map,
// don't bother drawing it. Could be a space
// point in Orthographic projection, for
// instance.
if (ddll.equals(center)) {
p.forward(ddll, ctp);
if (ctp.getX() != i || ctp.getY() != j) {
tmpPixels[tmpIndex] = clear;
continue;
}
}
if (geoTrans != null) {
geoTrans.forward(ddll.getY(), ddll.getX(), imageCoord);
} else {
imageCoord = ddll;
}
if (!sourceImageBounds.contains(imageCoord)) {
tmpPixels[tmpIndex] = clear;
continue;
}
// Find the corresponding pixel location in
// the source image.
int horIndex = (int) (horOrigin + (imageCoord.getX() / hor_upp));
int verIndex = (int) (verOrigin + (imageCoord.getY() / ver_upp));
if (horIndex < 0 || horIndex >= iwidth || verIndex < 0
|| verIndex >= iheight) {
// pixel not on the source image. This
// happens if the image doesn't cover the
// entire earth.
continue;
}
int imageIndex = horIndex + (verIndex * iwidth);
if (imageIndex >= 0 && imageIndex < pixels.length) {
tmpPixels[tmpIndex] = pixels[imageIndex];
}
}
}
logger.fine("finished creating image");
return tmpPixels;
}
logger.warning("problem creating image, no pixels: "
+ (pixels == null ? "true" : "false") + ", no projection:"
+ (p == null ? "true" : "false"));
// If you get here, something's not right.
return null;
}
|
diff --git a/src/java/org/apache/cassandra/utils/IntervalTree.java b/src/java/org/apache/cassandra/utils/IntervalTree.java
index 7ccc75f72..ec8e16620 100644
--- a/src/java/org/apache/cassandra/utils/IntervalTree.java
+++ b/src/java/org/apache/cassandra/utils/IntervalTree.java
@@ -1,458 +1,458 @@
/*
* 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.cassandra.utils;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import com.google.common.base.Joiner;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Iterators;
import com.google.common.collect.Ordering;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.io.ISerializer;
import org.apache.cassandra.io.IVersionedSerializer;
public class IntervalTree<C, D, I extends Interval<C, D>> implements Iterable<I>
{
private static final Logger logger = LoggerFactory.getLogger(IntervalTree.class);
@SuppressWarnings("unchecked")
private static final IntervalTree EMPTY_TREE = new IntervalTree(null, null);
private final IntervalNode head;
private final int count;
private final Comparator<C> comparator;
final Ordering<I> minOrdering;
final Ordering<I> maxOrdering;
protected IntervalTree(Collection<I> intervals, Comparator<C> comparator)
{
this.comparator = comparator;
final IntervalTree it = this;
this.minOrdering = new Ordering<I>()
{
public int compare(I interval1, I interval2)
{
return it.comparePoints(interval1.min, interval2.min);
}
};
this.maxOrdering = new Ordering<I>()
{
public int compare(I interval1, I interval2)
{
return it.comparePoints(interval1.max, interval2.max);
}
};
this.head = intervals == null || intervals.isEmpty() ? null : new IntervalNode(intervals);
this.count = intervals == null ? 0 : intervals.size();
}
public static <C, D, I extends Interval<C, D>> IntervalTree<C, D, I> build(Collection<I> intervals, Comparator<C> comparator)
{
if (intervals == null || intervals.isEmpty())
return emptyTree();
return new IntervalTree<C, D, I>(intervals, comparator);
}
public static <C extends Comparable<C>, D, I extends Interval<C, D>> IntervalTree<C, D, I> build(Collection<I> intervals)
{
if (intervals == null || intervals.isEmpty())
return emptyTree();
return new IntervalTree<C, D, I>(intervals, null);
}
public static <C, D, I extends Interval<C, D>> Serializer<C, D, I> serializer(ISerializer<C> pointSerializer, ISerializer<D> dataSerializer, Constructor<I> constructor)
{
return new Serializer(pointSerializer, dataSerializer, constructor);
}
@SuppressWarnings("unchecked")
public static <C, D, I extends Interval<C, D>> IntervalTree<C, D, I> emptyTree()
{
return (IntervalTree<C, D, I>)EMPTY_TREE;
}
public Comparator<C> comparator()
{
return comparator;
}
public int intervalCount()
{
return count;
}
public boolean isEmpty()
{
return head == null;
}
public C max()
{
if (head == null)
throw new IllegalStateException();
return head.high;
}
public C min()
{
if (head == null)
throw new IllegalStateException();
return head.low;
}
public List<D> search(Interval<C, D> searchInterval)
{
if (head == null)
return Collections.<D>emptyList();
List<D> results = new ArrayList<D>();
head.searchInternal(searchInterval, results);
return results;
}
public List<D> search(C point)
{
return search(Interval.<C, D>create(point, point, null));
}
public Iterator<I> iterator()
{
if (head == null)
return Iterators.<I>emptyIterator();
return new TreeIterator(head);
}
@Override
public String toString()
{
return "<" + Joiner.on(", ").join(this) + ">";
}
@Override
public boolean equals(Object o)
{
if(!(o instanceof IntervalTree))
return false;
IntervalTree that = (IntervalTree)o;
return Iterators.elementsEqual(iterator(), that.iterator());
}
@Override
public final int hashCode()
{
int result = comparator.hashCode();
for (Interval<C, D> interval : this)
result = 31 * result + interval.hashCode();
return result;
}
private int comparePoints(C point1, C point2)
{
if (comparator != null)
{
return comparator.compare(point1, point2);
}
else
{
assert point1 instanceof Comparable;
assert point2 instanceof Comparable;
return ((Comparable<C>)point1).compareTo(point2);
}
}
private boolean encloses(Interval<C, D> enclosing, Interval<C, D> enclosed)
{
return comparePoints(enclosing.min, enclosed.min) <= 0
&& comparePoints(enclosing.max, enclosed.max) >= 0;
}
private boolean contains(Interval<C, D> interval, C point)
{
return comparePoints(interval.min, point) <= 0
&& comparePoints(interval.max, point) >= 0;
}
private boolean intersects(Interval<C, D> interval1, Interval<C, D> interval2)
{
return contains(interval1, interval2.min) || contains(interval1, interval2.max);
}
private class IntervalNode
{
final C center;
final C low;
final C high;
final List<I> intersectsLeft;
final List<I> intersectsRight;
final IntervalNode left;
final IntervalNode right;
public IntervalNode(Collection<I> toBisect)
{
assert !toBisect.isEmpty();
logger.debug("Creating IntervalNode from {}", toBisect);
// Building IntervalTree with one interval will be a reasonably
// common case for range tombstones, so it's worth optimizing
if (toBisect.size() == 1)
{
I interval = toBisect.iterator().next();
low = interval.min;
center = interval.max;
high = interval.max;
List<I> l = Collections.singletonList(interval);
intersectsLeft = l;
intersectsRight = l;
left = null;
right = null;
}
else
{
// Find min, median and max
List<C> allEndpoints = new ArrayList<C>(toBisect.size() * 2);
for (I interval : toBisect)
{
assert (comparator == null ? ((Comparable)interval.min).compareTo(interval.max)
: comparator.compare(interval.min, interval.max)) <= 0 : "Interval min > max";
allEndpoints.add(interval.min);
allEndpoints.add(interval.max);
}
- if (comparator == null)
+ if (comparator != null)
Collections.sort(allEndpoints, comparator);
else
Collections.sort((List<Comparable>)allEndpoints);
low = allEndpoints.get(0);
center = allEndpoints.get(toBisect.size());
high = allEndpoints.get(allEndpoints.size() - 1);
// Separate interval in intersecting center, left of center and right of center
List<I> intersects = new ArrayList<I>();
List<I> leftSegment = new ArrayList<I>();
List<I> rightSegment = new ArrayList<I>();
for (I candidate : toBisect)
{
if (comparePoints(candidate.max, center) < 0)
leftSegment.add(candidate);
else if (comparePoints(candidate.min, center) > 0)
rightSegment.add(candidate);
else
intersects.add(candidate);
}
intersectsLeft = minOrdering.sortedCopy(intersects);
intersectsRight = maxOrdering.reverse().sortedCopy(intersects);
left = leftSegment.isEmpty() ? null : new IntervalNode(leftSegment);
right = rightSegment.isEmpty() ? null : new IntervalNode(rightSegment);
assert (intersects.size() + leftSegment.size() + rightSegment.size()) == toBisect.size() :
"intersects (" + String.valueOf(intersects.size()) +
") + leftSegment (" + String.valueOf(leftSegment.size()) +
") + rightSegment (" + String.valueOf(rightSegment.size()) +
") != toBisect (" + String.valueOf(toBisect.size()) + ")";
}
}
void searchInternal(Interval<C, D> searchInterval, List<D> results)
{
if (contains(searchInterval, center))
{
// Adds every interval contained in this node to the result set then search left and right for further
// overlapping intervals
for (Interval<C, D> interval : intersectsLeft)
results.add(interval.data);
if (left != null)
left.searchInternal(searchInterval, results);
if (right != null)
right.searchInternal(searchInterval, results);
}
else if (comparePoints(center, searchInterval.min) < 0)
{
// Adds intervals i in intersects right as long as i.max >= searchInterval.min
// then search right
for (Interval<C, D> interval : intersectsRight)
{
if (comparePoints(interval.max, searchInterval.min) >= 0)
results.add(interval.data);
else
break;
}
if (right != null)
right.searchInternal(searchInterval, results);
}
else
{
assert comparePoints(center, searchInterval.max) > 0;
// Adds intervals i in intersects left as long as i.min >= searchInterval.max
// then search left
for (Interval<C, D> interval : intersectsLeft)
{
if (comparePoints(interval.min, searchInterval.max) <= 0)
results.add(interval.data);
else
break;
}
if (left != null)
left.searchInternal(searchInterval, results);
}
}
}
private class TreeIterator extends AbstractIterator<I>
{
private final Deque<IntervalNode> stack = new ArrayDeque<IntervalNode>();
private Iterator<I> current;
TreeIterator(IntervalNode node)
{
super();
gotoMinOf(node);
}
protected I computeNext()
{
if (current != null && current.hasNext())
return current.next();
IntervalNode node = stack.pollFirst();
if (node == null)
return endOfData();
current = node.intersectsLeft.iterator();
// We know this is the smaller not returned yet, but before doing
// its parent, we must do everyone on it's right.
gotoMinOf(node.right);
return computeNext();
}
private void gotoMinOf(IntervalNode node)
{
while (node != null)
{
stack.offerFirst(node);
node = node.left;
}
}
}
public static class Serializer<C, D, I extends Interval<C, D>> implements IVersionedSerializer<IntervalTree<C, D, I>>
{
private final ISerializer<C> pointSerializer;
private final ISerializer<D> dataSerializer;
private final Constructor<I> constructor;
private Serializer(ISerializer<C> pointSerializer, ISerializer<D> dataSerializer, Constructor<I> constructor)
{
this.pointSerializer = pointSerializer;
this.dataSerializer = dataSerializer;
this.constructor = constructor;
}
public void serialize(IntervalTree<C, D, I> it, DataOutput dos, int version) throws IOException
{
dos.writeInt(it.count);
for (Interval<C, D> interval : it)
{
pointSerializer.serialize(interval.min, dos);
pointSerializer.serialize(interval.max, dos);
dataSerializer.serialize(interval.data, dos);
}
}
/**
* Deserialize an IntervalTree whose keys use the natural ordering.
* Use deserialize(DataInput, int, Comparator) instead if the interval
* tree is to use a custom comparator, as the comparator is *not*
* serialized.
*/
public IntervalTree<C, D, I> deserialize(DataInput dis, int version) throws IOException
{
return deserialize(dis, version, null);
}
public IntervalTree<C, D, I> deserialize(DataInput dis, int version, Comparator<C> comparator) throws IOException
{
try
{
int count = dis.readInt();
List<Interval<C, D>> intervals = new ArrayList<Interval<C, D>>(count);
for (int i = 0; i < count; i++)
{
C min = pointSerializer.deserialize(dis);
C max = pointSerializer.deserialize(dis);
D data = dataSerializer.deserialize(dis);
intervals.add(constructor.newInstance(min, max, data));
}
return new IntervalTree(intervals, comparator);
}
catch (InstantiationException e)
{
throw new RuntimeException(e);
}
catch (InvocationTargetException e)
{
throw new RuntimeException(e);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
}
public long serializedSize(IntervalTree<C, D, I> it, TypeSizes typeSizes, int version)
{
long size = typeSizes.sizeof(0);
for (Interval<C, D> interval : it)
{
size += pointSerializer.serializedSize(interval.min, typeSizes);
size += pointSerializer.serializedSize(interval.max, typeSizes);
size += dataSerializer.serializedSize(interval.data, typeSizes);
}
return size;
}
public long serializedSize(IntervalTree<C, D, I> it, int version)
{
return serializedSize(it, TypeSizes.NATIVE, version);
}
}
}
| true | true | public IntervalNode(Collection<I> toBisect)
{
assert !toBisect.isEmpty();
logger.debug("Creating IntervalNode from {}", toBisect);
// Building IntervalTree with one interval will be a reasonably
// common case for range tombstones, so it's worth optimizing
if (toBisect.size() == 1)
{
I interval = toBisect.iterator().next();
low = interval.min;
center = interval.max;
high = interval.max;
List<I> l = Collections.singletonList(interval);
intersectsLeft = l;
intersectsRight = l;
left = null;
right = null;
}
else
{
// Find min, median and max
List<C> allEndpoints = new ArrayList<C>(toBisect.size() * 2);
for (I interval : toBisect)
{
assert (comparator == null ? ((Comparable)interval.min).compareTo(interval.max)
: comparator.compare(interval.min, interval.max)) <= 0 : "Interval min > max";
allEndpoints.add(interval.min);
allEndpoints.add(interval.max);
}
if (comparator == null)
Collections.sort(allEndpoints, comparator);
else
Collections.sort((List<Comparable>)allEndpoints);
low = allEndpoints.get(0);
center = allEndpoints.get(toBisect.size());
high = allEndpoints.get(allEndpoints.size() - 1);
// Separate interval in intersecting center, left of center and right of center
List<I> intersects = new ArrayList<I>();
List<I> leftSegment = new ArrayList<I>();
List<I> rightSegment = new ArrayList<I>();
for (I candidate : toBisect)
{
if (comparePoints(candidate.max, center) < 0)
leftSegment.add(candidate);
else if (comparePoints(candidate.min, center) > 0)
rightSegment.add(candidate);
else
intersects.add(candidate);
}
intersectsLeft = minOrdering.sortedCopy(intersects);
intersectsRight = maxOrdering.reverse().sortedCopy(intersects);
left = leftSegment.isEmpty() ? null : new IntervalNode(leftSegment);
right = rightSegment.isEmpty() ? null : new IntervalNode(rightSegment);
assert (intersects.size() + leftSegment.size() + rightSegment.size()) == toBisect.size() :
"intersects (" + String.valueOf(intersects.size()) +
") + leftSegment (" + String.valueOf(leftSegment.size()) +
") + rightSegment (" + String.valueOf(rightSegment.size()) +
") != toBisect (" + String.valueOf(toBisect.size()) + ")";
}
}
| public IntervalNode(Collection<I> toBisect)
{
assert !toBisect.isEmpty();
logger.debug("Creating IntervalNode from {}", toBisect);
// Building IntervalTree with one interval will be a reasonably
// common case for range tombstones, so it's worth optimizing
if (toBisect.size() == 1)
{
I interval = toBisect.iterator().next();
low = interval.min;
center = interval.max;
high = interval.max;
List<I> l = Collections.singletonList(interval);
intersectsLeft = l;
intersectsRight = l;
left = null;
right = null;
}
else
{
// Find min, median and max
List<C> allEndpoints = new ArrayList<C>(toBisect.size() * 2);
for (I interval : toBisect)
{
assert (comparator == null ? ((Comparable)interval.min).compareTo(interval.max)
: comparator.compare(interval.min, interval.max)) <= 0 : "Interval min > max";
allEndpoints.add(interval.min);
allEndpoints.add(interval.max);
}
if (comparator != null)
Collections.sort(allEndpoints, comparator);
else
Collections.sort((List<Comparable>)allEndpoints);
low = allEndpoints.get(0);
center = allEndpoints.get(toBisect.size());
high = allEndpoints.get(allEndpoints.size() - 1);
// Separate interval in intersecting center, left of center and right of center
List<I> intersects = new ArrayList<I>();
List<I> leftSegment = new ArrayList<I>();
List<I> rightSegment = new ArrayList<I>();
for (I candidate : toBisect)
{
if (comparePoints(candidate.max, center) < 0)
leftSegment.add(candidate);
else if (comparePoints(candidate.min, center) > 0)
rightSegment.add(candidate);
else
intersects.add(candidate);
}
intersectsLeft = minOrdering.sortedCopy(intersects);
intersectsRight = maxOrdering.reverse().sortedCopy(intersects);
left = leftSegment.isEmpty() ? null : new IntervalNode(leftSegment);
right = rightSegment.isEmpty() ? null : new IntervalNode(rightSegment);
assert (intersects.size() + leftSegment.size() + rightSegment.size()) == toBisect.size() :
"intersects (" + String.valueOf(intersects.size()) +
") + leftSegment (" + String.valueOf(leftSegment.size()) +
") + rightSegment (" + String.valueOf(rightSegment.size()) +
") != toBisect (" + String.valueOf(toBisect.size()) + ")";
}
}
|
diff --git a/core/src/main/java/org/biojavax/bio/seq/SimpleRichLocation.java b/core/src/main/java/org/biojavax/bio/seq/SimpleRichLocation.java
index d641e56..710eb29 100644
--- a/core/src/main/java/org/biojavax/bio/seq/SimpleRichLocation.java
+++ b/core/src/main/java/org/biojavax/bio/seq/SimpleRichLocation.java
@@ -1,755 +1,755 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojavax.bio.seq;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import org.biojava.bio.Annotation;
import org.biojava.bio.seq.DNATools;
import org.biojava.bio.seq.RNATools;
import org.biojava.bio.seq.io.ParseException;
import org.biojava.bio.symbol.Alphabet;
import org.biojava.bio.symbol.AlphabetManager;
import org.biojava.bio.symbol.IllegalAlphabetException;
import org.biojava.bio.symbol.Location;
import org.biojava.bio.symbol.SymbolList;
import org.biojava.bio.symbol.SymbolListViews;
import org.biojava.utils.AbstractChangeable;
import org.biojava.utils.ChangeEvent;
import org.biojava.utils.ChangeSupport;
import org.biojava.utils.ChangeVetoException;
import org.biojavax.CrossRef;
import org.biojavax.CrossReferenceResolver;
import org.biojavax.Namespace;
import org.biojavax.RichAnnotation;
import org.biojavax.RichObjectFactory;
import org.biojavax.SimpleRichAnnotation;
import org.biojavax.bio.seq.io.GenbankLocationParser;
import org.biojavax.ontology.ComparableTerm;
/**
* A simple implementation of RichLocation.
* @author Richard Holland
* @author Mark Schreiber
* @author George Waldon
* @since 1.5
*/
public class SimpleRichLocation extends AbstractChangeable implements RichLocation {
private CrossRef crossRef;
private RichAnnotation notes = new SimpleRichAnnotation();
protected ComparableTerm term;
private Position min;
private Position max;
private PositionResolver pr = RichObjectFactory.getDefaultPositionResolver();
private CrossReferenceResolver crr = RichObjectFactory.getDefaultCrossReferenceResolver();
private Strand strand;
private int rank;
protected int circularLength = 0;
private RichFeature feature;
/**
* Creates a new instance of SimpleRichSequenceLocation that points to a
* single position on the positive strand.
* @param pos the location position (a point).
* @param rank Rank of location.
*/
public SimpleRichLocation(Position pos, int rank) {
this(pos,pos,rank,Strand.POSITIVE_STRAND);
}
/**
* Creates a new instance of SimpleRichSequenceLocation that points to a
* single position.
* @param pos the location position (a point).
* @param rank Rank of location.
* @param strand The strand of the location
*/
public SimpleRichLocation(Position pos, int rank, Strand strand) {
this(pos,pos,rank,strand,null);
}
/**
* Creates a new instance of SimpleRichSequenceLocation that points to a
* single position on another sequence.
* @param pos the location position (a point).
* @param rank Rank of location.
* @param strand the strand of the location
* @param crossRef a cross reference to another object (null for parent sequence)
*/
public SimpleRichLocation(Position pos, int rank, Strand strand, CrossRef crossRef) {
this(pos,pos,rank,strand,crossRef);
}
/**
* Creates a new instance of SimpleRichSequenceLocation that points to a
* range position on the positive strand.
* @param min the minimum bound of the location
* @param max the maximum bound of the location
* @param rank Rank of location.
*
*/
public SimpleRichLocation(Position min, Position max, int rank) {
this(min,max,rank,Strand.POSITIVE_STRAND);
}
/**
* Creates a new instance of SimpleRichSequenceLocation that points to a
* range position.
* @param min the minimum bound of the location
* @param max the maximum bound of the location
* @param rank Rank of location.
* @param strand the strand of the location
*/
public SimpleRichLocation(Position min, Position max, int rank, Strand strand) {
this(min,max,rank,strand,null);
}
/**
* Creates a new instance of SimpleRichSequenceLocation that points to a
* range position on another sequence.
* @param min the minimum bound of the location
* @param max the maximum bound of the location
* @param rank Rank of location.
* @param strand the strand of the location
* @param crossRef a cross reference to another object (null for parent sequence)
*/
public SimpleRichLocation(Position min, Position max, int rank, Strand strand, CrossRef crossRef) {
this.min = min;
this.max = max;
this.rank = rank;
this.strand = strand;
this.crossRef = crossRef;
this.feature = null;
}
// Hibernate requirement - not for public use.
protected SimpleRichLocation() {}
/**
* {@inheritDoc}
*/
public void sort() {}
/**
* {@inheritDoc}
*/
public RichFeature getFeature() { return this.feature; }
/**
* {@inheritDoc}
*/
public void setFeature(RichFeature feature) throws ChangeVetoException {
if(!this.hasListeners(RichLocation.FEATURE)) {
this.feature = feature;
} else {
ChangeEvent ce = new ChangeEvent(
this,
RichLocation.FEATURE,
feature,
this.feature
);
ChangeSupport cs = this.getChangeSupport(RichLocation.FEATURE);
synchronized(cs) {
cs.firePreChangeEvent(ce);
this.feature = feature;
cs.firePostChangeEvent(ce);
}
}
}
/**
* {@inheritDoc}
*/
public CrossRef getCrossRef() { return this.crossRef; }
// Hibernate requirement - not for public use.
protected void setCrossRef(CrossRef crossRef) { this.crossRef = crossRef; }
/**
* {@inheritDoc}
*/
public Annotation getAnnotation() { return getRichAnnotation(); }
/**
* {@inheritDoc}
*/
public RichAnnotation getRichAnnotation() { return this.notes; }
/**
* {@inheritDoc}
* <b>Warning</b> this method gives access to the original
* Collection not a copy. This is required by Hibernate. If you
* modify the object directly the behaviour may be unpredictable.
*/
public Set getNoteSet() { return this.notes.getNoteSet(); }
/**
* {@inheritDoc}
* <b>Warning</b> this method gives access to the original
* Collection not a copy. This is required by Hibernate. If you
* modify the object directly the behaviour may be unpredictable.
*/
public void setNoteSet(Set notes) throws ChangeVetoException { this.notes.setNoteSet(notes); }
/**
* {@inheritDoc}
*/
public ComparableTerm getTerm() { return this.term; }
/**
* {@inheritDoc}
*/
public void setTerm(ComparableTerm term) throws ChangeVetoException {
if(!this.hasListeners(RichLocation.TERM)) {
this.term = term;
} else {
ChangeEvent ce = new ChangeEvent(
this,
RichLocation.TERM,
term,
this.term
);
ChangeSupport cs = this.getChangeSupport(RichLocation.TERM);
synchronized(cs) {
cs.firePreChangeEvent(ce);
this.term = term;
cs.firePostChangeEvent(ce);
}
}
}
/**
* {@inheritDoc}
*/
public int getCircularLength() { return this.circularLength; }
/**
* {@inheritDoc}
*/
public void setCircularLength(int circularLength) throws ChangeVetoException {
if(!this.hasListeners(RichLocation.CIRCULAR)) {
this.circularLength = circularLength;
} else {
ChangeEvent ce = new ChangeEvent(
this,
RichLocation.CIRCULAR,
new Integer(circularLength),
new Integer(this.circularLength)
);
ChangeSupport cs = this.getChangeSupport(RichLocation.CIRCULAR);
synchronized(cs) {
cs.firePreChangeEvent(ce);
this.circularLength = circularLength;
cs.firePostChangeEvent(ce);
}
}
}
/**
* {@inheritDoc}
*/
public Strand getStrand() { return this.strand; }
// Hibernate requirement - not for public use.
protected void setStrand(Strand strand) { this.strand = strand; }
// Hibernate requirement - not for public use.
int getStrandNum() { return this.strand.intValue(); }
// Hibernate requirement - not for public use.
void setStrandNum(int token) { this.strand = Strand.forValue(token); }
/**
* {@inheritDoc}
*/
public int getRank() { return this.rank; }
/**
* {@inheritDoc}
*/
public void setRank(int rank) throws ChangeVetoException {
if(!this.hasListeners(RichLocation.RANK)) {
this.rank = rank;
} else {
ChangeEvent ce = new ChangeEvent(
this,
RichLocation.RANK,
new Integer(rank),
new Integer(this.rank)
);
ChangeSupport cs = this.getChangeSupport(RichLocation.RANK);
synchronized(cs) {
cs.firePreChangeEvent(ce);
this.rank = rank;
cs.firePostChangeEvent(ce);
}
}
}
/**
* {@inheritDoc}
*/
public int getMax() {
if (this.max.equals(this.min)) return this.getMin(); // because resolver might resolve differently
else return this.pr.getMax(this.max);
}
// Hibernate requirement - not for public use.
void setMax(int max) { this.max = new SimplePosition(false,false,max); }
/**
* {@inheritDoc}
*/
public int getMin() { return this.pr.getMin(this.min); }
// Hibernate requirement - not for public use.
void setMin(int min) { this.min = new SimplePosition(false,false,min); }
/**
* {@inheritDoc}
*/
public Position getMinPosition() { return this.min; }
// Hibernate requirement - not for public use.
protected void setMinPosition(Position min) { this.min = min; }
/**
* {@inheritDoc}
*/
public Position getMaxPosition() { return this.max; }
// Hibernate requirement - not for public use.
protected void setMaxPosition(Position max) { this.max = max; }
/**
* {@inheritDoc}
*/
public void setPositionResolver(PositionResolver p) { this.pr = p; }
/**
* {@inheritDoc}
*/
public Iterator blockIterator() { return Collections.singleton(this).iterator(); }
/**
* {@inheritDoc}
*/
public boolean isContiguous() { return true; }
/**
* {@inheritDoc}
*/
public boolean contains(int p) {
int modStart = this.getMin();
int modEnd = this.getMax();
if (this.circularLength>0) {
// Modulate the point to fall inside our sequence
p = RichLocation.Tools.modulateCircularIndex(p, this.circularLength);
// Modulate our location to the earliest possible point in our sequence
int[] ourModParts = RichLocation.Tools.modulateCircularLocation(modStart, modEnd, this.circularLength);
modStart = ourModParts[0];
modEnd = ourModParts[1];
// If we wrap and the point occurs before us, increment point to fall in correct range
if (modEnd>this.circularLength && p<modStart) p+=this.circularLength;
}
return (p>=modStart && p<=modEnd);
}
/**
* {@inheritDoc}
*/
public Location getDecorator(Class decoratorClass) { return null; }
/**
* {@inheritDoc}
*/
public Location newInstance(Location loc) { return loc; }
/**
* {@inheritDoc}
*/
public Location translate(int dist) {
return new SimpleRichLocation(this.min.translate(dist),this.max.translate(dist),0,this.strand,this.crossRef);
}
/**
* {@inheritDoc}
* A location contains another location if it overlaps it, and the coordinates
* enclose those of the other location at both ends, and they fall on
* the same strand.
*/
public boolean contains(Location l) {
if (!(l instanceof RichLocation)) l = RichLocation.Tools.enrich(l);
if (l instanceof EmptyRichLocation) return false;
else {
RichLocation rl = (RichLocation)l;
// Simple vs. simple
if (!this.overlaps(rl)) return false; // No overlap = no possible contain
if (!this.getStrand().equals(rl.getStrand())) return false; // Diff strand = not contained
if (this.circularLength>0) {
// Modulate to shortest possible equivalent region
int parts[] = RichLocation.Tools.modulateCircularLocationPair(this,rl,this.circularLength);
int ourModStart = parts[0];
int ourModEnd = parts[1];
int theirModStart = parts[2];
int theirModEnd = parts[3];
return (ourModStart <= theirModStart && ourModEnd >= theirModEnd);
} else {
return (this.getMin() <= rl.getMin() && this.getMax() >= rl.getMax());
}
}
}
/**
* {@inheritDoc}
* A location overlaps another location if it is on the same sequence, and
* the coordinates overlap, and both are of the same circularity.
*/
public boolean overlaps(Location l) {
if (!(l instanceof RichLocation)) l = RichLocation.Tools.enrich(l);
if (l instanceof EmptyRichLocation) return false;
else if (l instanceof CompoundRichLocation) return l.overlaps(this);
else {
// Simple vs. simple
RichLocation rl = (RichLocation)l;
// Mismatch of crossref is no overlap.
if (rl.getCrossRef()!=null || this.crossRef!=null) {
if (rl.getCrossRef()!=null && this.crossRef!=null) {
if (!this.crossRef.equals(rl.getCrossRef())) return false;
} else return false;
}
if (this.circularLength!=rl.getCircularLength()) return false; // Diff circularLength location sizes = not overlapping
// Modulate our start/end to shortest possible equivalent region
if (this.circularLength>0) {
int parts[] = RichLocation.Tools.modulateCircularLocationPair(this,rl,this.circularLength);
int ourModStart = parts[0];
int ourModEnd = parts[1];
int theirModStart = parts[2];
int theirModEnd = parts[3];
return (ourModStart<=theirModEnd && ourModEnd>=theirModStart);
} else {
return (this.getMin()<=rl.getMax() && this.getMax()>=rl.getMin());
}
}
}
/**
* {@inheritDoc}
* A merged SimpleRichLocation is returned if the two locations overlap and are on
* the same strand. Otherwise, a CompoundRichLocation is returned containing
* the two locations as members.
*/
public Location union(Location l) {
if (!(l instanceof RichLocation)) l = RichLocation.Tools.enrich(l);
if (l instanceof EmptyRichLocation) return this;
else if (l instanceof CompoundRichLocation) return l.union(this);
else {
// Simple vs. simple
RichLocation rl = (RichLocation)l;
if (this.overlaps(rl) && this.getStrand().equals(rl.getStrand())) {
// We can do the one-v-one overlapping same-strand union
if (this.circularLength>0) {
// Union of Overlapping circular locations
// Modulate our start/end to shortest possible equivalent region
int parts[] = RichLocation.Tools.modulateCircularLocationPair(this,rl,this.circularLength);
int ourModStart = parts[0];
int ourModEnd = parts[1];
int theirModStart = parts[2];
int theirModEnd = parts[3];
// Now we can select the minimum and maximum positions using the modded locations
Position startPos = (ourModStart<theirModStart)?this.min:rl.getMinPosition();
Position endPos = (ourModEnd>theirModEnd)?this.max:rl.getMaxPosition();
return new SimpleRichLocation(startPos,endPos,0,this.strand,this.crossRef);
} else {
// Union of Overlapping non-circular locations
return new SimpleRichLocation(this.posmin(this.min,rl.getMinPosition()),this.posmax(this.max,rl.getMaxPosition()),0,this.strand,this.crossRef);
}
}
// We can do the one-v-one non-overlapping or different-strand union too
Collection members = new ArrayList();
members.add(this);
members.add(l);
if (RichLocation.Tools.isMultiSource(members)) return new MultiSourceCompoundRichLocation(members);
else return new CompoundRichLocation(members);
}
}
/**
* {@inheritDoc}
* If the locations overlap and are on the same strand, the intersection
* is returned. If they overlap but are on different strands, a CompoundRichLocation
* of the overlapping portions is returned. If they do not overlap, the empty
* sequence is returned.
*/
public Location intersection(Location l) {
if (!(l instanceof RichLocation)) l = RichLocation.Tools.enrich(l);
if (l instanceof EmptyRichLocation) return l;
else if (l instanceof CompoundRichLocation) return l.intersection(this);
else {
RichLocation rl = (RichLocation)l;
if (this.overlaps(l)) {
if (this.getStrand().equals(rl.getStrand())) {
// We can do the one-v-one same-strand overlapping intersection here
if (this.circularLength>0) {
// Modulate our start/end to shortest possible equivalent region
int parts[] = RichLocation.Tools.modulateCircularLocationPair(this,rl,this.circularLength);
int ourModStart = parts[0];
int ourModEnd = parts[1];
int theirModStart = parts[2];
int theirModEnd = parts[3];
// Now we can select the minimum and maximum positions using the modded locations
Position startPos = (ourModStart>theirModStart)?this.min:rl.getMinPosition();
Position endPos = (ourModEnd<theirModEnd)?this.max:rl.getMaxPosition();
return new SimpleRichLocation(startPos,endPos,0,this.strand,this.crossRef);
} else {
return new SimpleRichLocation(this.posmax(this.min,rl.getMinPosition()),this.posmin(this.max,rl.getMaxPosition()),0,this.strand,this.crossRef);
}
}
// We can do the one-v-one different-strand overlapping intersection here
Collection members = new ArrayList();
members.add(new SimpleRichLocation(this.posmax(this.min,rl.getMinPosition()),this.posmin(this.max,rl.getMaxPosition()),0,this.strand,this.crossRef));
members.add(new SimpleRichLocation(this.posmax(this.min,rl.getMinPosition()),this.posmin(this.max,rl.getMaxPosition()),0,rl.getStrand(),this.crossRef));
if (RichLocation.Tools.isMultiSource(members)) return new MultiSourceCompoundRichLocation(members);
else return new CompoundRichLocation(members);
} else {
// We can do the one-v-one non-overlapping intersection here
return RichLocation.EMPTY_LOCATION;
}
}
}
// calculates the smaller of the two positions, based on their resolver output
protected Position posmin(Position a, Position b) {
int ar = this.pr.getMin(a);
int br = this.pr.getMin(b);
if (ar<=br) return a;
else return b;
}
// calculates the smaller of the two positions, based on their resolver output
protected Position posmax(Position a, Position b) {
int ar = this.pr.getMax(a);
int br = this.pr.getMax(b);
if (ar>br) return a;
else return b;
}
/**
* {@inheritDoc}
*/
public void setCrossRefResolver(CrossReferenceResolver r) {
if (r==null) throw new IllegalArgumentException("Resolver cannot be null");
this.crr = r;
}
/**
* {@inheritDoc}
* If the location is circular but the sequence is not, or they are both
* circular but of different circular lengths, an exception is thrown.
* The symbol list passed in is the sequence used to obtain symbols
* if the cross reference for this location has not been set. If the cross
* reference has been set, then the symbol list passed in is only used
* if it has the same accession, namespace and version as the cross
* reference on this location. Otherwise, the cross referenced symbol list
* is looked up and used instead.
*/
public SymbolList symbols(SymbolList seq) {
if (seq==null) throw new IllegalArgumentException("Sequence cannot be null");
if (seq instanceof RichSequence) {
RichSequence rs = (RichSequence)seq;
if (this.getCircularLength()>0) {
if (!rs.getCircular()) throw new IllegalArgumentException("Attempt to apply circular location to non-circular sequence");
- if (rs.length()==this.getCircularLength()) throw new IllegalArgumentException("Attempt to apply circular location to circular sequence of different length");
+ if (rs.length()!=this.getCircularLength()) throw new IllegalArgumentException("Attempt to apply circular location to circular sequence of different length");
}
}
// Resolve cross-references to remote sequences
if (this.getCrossRef()!=null) {
CrossRef cr = this.getCrossRef();
if (seq instanceof RichSequence) {
RichSequence rs = (RichSequence)seq;
String accession = rs.getAccession();
Namespace ns = rs.getNamespace();
String raccession = cr.getAccession();
String rnamespace = cr.getDbname();
if (!(accession.equals(raccession) && ns.getName().equals(rnamespace))) {
// It really is remote - the xref doesn't point to the sequence we just got passed
seq = this.crr.getRemoteSymbolList(cr, seq.getAlphabet());
}
} else {
// It's assumed to be remote because we can't tell what the sequence we were passed really is
seq = this.crr.getRemoteSymbolList(this.getCrossRef(), seq.getAlphabet());
}
}
// Carry on as before
seq = seq.subList(this.getMin(),this.getMax());
try {
if (this.strand==Strand.NEGATIVE_STRAND) {
Alphabet a = seq.getAlphabet();
if (a==AlphabetManager.alphabetForName("DNA")) {
seq = DNATools.reverseComplement(seq);
} else if (a==AlphabetManager.alphabetForName("RNA")) {
seq = RNATools.reverseComplement(seq);
} else {
seq = SymbolListViews.reverse(seq);// no complement as no such thing
}
}
} catch (IllegalAlphabetException e) {
IllegalArgumentException ex =
new IllegalArgumentException("Could not understand alphabet of passed sequence");
ex.initCause(e);
throw ex;
}
return seq;
}
/**
* {@inheritDoc}
*/
public int hashCode() {
int code = 17;
// Hibernate comparison - we haven't been populated yet
if (this.strand==null) return code;
// Normal comparison
if (this.term!=null) code = 31*code + this.term.hashCode();
code = 31*code + this.getMin();
code = 31*code + this.getMax();
code = 31*code + this.strand.hashCode();
code = 31*code + this.rank;
if (this.crossRef!=null) code = 31*code + this.crossRef.hashCode();
return code;
}
/**
* {@inheritDoc}
* Locations are equal if their term, min, max, strand, and crossref are
* the same, and if their rank is the same too.
*/
public boolean equals(Object o) {
if (! (o instanceof RichLocation)) return false;
// Hibernate comparison - we haven't been populated yet
if (this.strand==null) return false;
// Normal comparison
RichLocation fo = (RichLocation) o;
if (this.term!=null || fo.getTerm()!=null) {
if (this.term!=null && fo.getTerm()!=null) {
if (!this.term.equals(fo.getTerm())) return false;
} else return false;
}
if (this.getMin()!=fo.getMin()) return false;
if (this.getMax()!=fo.getMax()) return false;
if (!this.strand.equals(fo.getStrand())) return false;
if (this.crossRef!=null || fo.getCrossRef()!=null) {
if (this.crossRef!=null && fo.getCrossRef()!=null) {
if(!this.crossRef.equals(fo.getCrossRef())) return false;
} else return false;
}
return this.rank==fo.getRank();
}
/**
* {@inheritDoc}
* Locations are sorted first by rank, then crossref, then
* strand, then term, then min, then max.
*/
public int compareTo(Object o) {
if (o==this) return 0;
// Hibernate comparison - we haven't been populated yet
if (this.strand==null) return -1;
// Check if we can really compare at all
if (!(o instanceof RichLocation)) return -1;
// Normal comparison
RichLocation fo = (RichLocation) o;
if (this.rank!=fo.getRank()) return this.rank-fo.getRank();
if (this.crossRef!=null || fo.getCrossRef()!=null) {
if (this.crossRef!=null && fo.getCrossRef()!=null) {
return this.crossRef.compareTo(fo.getCrossRef());
} else return -1;
}
if (!this.strand.equals(fo.getStrand())) return this.strand.compareTo(fo.getStrand());
if (this.term!=null || fo.getTerm()!=null) {
if (this.term!=null && fo.getTerm()!=null && !this.term.equals(fo.getTerm())) return this.term.compareTo(fo.getTerm());
else return -1;
}
if (this.getMin()!=fo.getMin()) return this.getMin()-fo.getMin();
return this.getMax()-fo.getMax();
}
/**
* {@inheritDoc}
* Form: "start..end" or just "point" for point locations
*/
public String toString() {
if (this.max.equals(this.min)) {
return this.min.toString();
} else {
return this.min+".."+this.max;
}
}
// Internal use only.
void setLocationText(final String theLocation) throws ParseException {
// System.out.println("SimpleRichLocation.setLocationText-theLocation: ["+theLocation+"]");
if (theLocation == null) {
setMinPosition(RichLocation.EMPTY_LOCATION.getMinPosition());
setMaxPosition(RichLocation.EMPTY_LOCATION.getMaxPosition());
} else {
final RichLocation location = GenbankLocationParser.parseLocation(RichObjectFactory.getDefaultNamespace(), null, theLocation);
setMinPosition(location.getMinPosition());
setMaxPosition(location.getMaxPosition());
}
// System.out.println("SimpleRichLocation.setLocationText-this: ["+this+"]");
}
// Internal use only.
String getLocationText() {
// System.out.println("SimpleRichLocation.getLocationText-returns: ["+GenbankLocationParser.writeLocation(new SimpleRichLocation(getMinPosition(), getMaxPosition(), getRank()))+"], this: ["+this+"]");
return GenbankLocationParser.writeLocation(new SimpleRichLocation(getMinPosition(), getMaxPosition(), getRank()));
}
// Hibernate requirement - not for public use.
private Integer id;
/**
* Gets the Hibernate ID. Should be used with caution.
* @return the Hibernate ID, if using Hibernate.
*/
public Integer getId() { return this.id; }
/**
* Sets the Hibernate ID. Should be used with caution.
* @param id the Hibernate ID, if using Hibernate.
*/
public void setId(Integer id) { this.id = id;}
}
| true | true | public SymbolList symbols(SymbolList seq) {
if (seq==null) throw new IllegalArgumentException("Sequence cannot be null");
if (seq instanceof RichSequence) {
RichSequence rs = (RichSequence)seq;
if (this.getCircularLength()>0) {
if (!rs.getCircular()) throw new IllegalArgumentException("Attempt to apply circular location to non-circular sequence");
if (rs.length()==this.getCircularLength()) throw new IllegalArgumentException("Attempt to apply circular location to circular sequence of different length");
}
}
// Resolve cross-references to remote sequences
if (this.getCrossRef()!=null) {
CrossRef cr = this.getCrossRef();
if (seq instanceof RichSequence) {
RichSequence rs = (RichSequence)seq;
String accession = rs.getAccession();
Namespace ns = rs.getNamespace();
String raccession = cr.getAccession();
String rnamespace = cr.getDbname();
if (!(accession.equals(raccession) && ns.getName().equals(rnamespace))) {
// It really is remote - the xref doesn't point to the sequence we just got passed
seq = this.crr.getRemoteSymbolList(cr, seq.getAlphabet());
}
} else {
// It's assumed to be remote because we can't tell what the sequence we were passed really is
seq = this.crr.getRemoteSymbolList(this.getCrossRef(), seq.getAlphabet());
}
}
// Carry on as before
seq = seq.subList(this.getMin(),this.getMax());
try {
if (this.strand==Strand.NEGATIVE_STRAND) {
Alphabet a = seq.getAlphabet();
if (a==AlphabetManager.alphabetForName("DNA")) {
seq = DNATools.reverseComplement(seq);
} else if (a==AlphabetManager.alphabetForName("RNA")) {
seq = RNATools.reverseComplement(seq);
} else {
seq = SymbolListViews.reverse(seq);// no complement as no such thing
}
}
} catch (IllegalAlphabetException e) {
IllegalArgumentException ex =
new IllegalArgumentException("Could not understand alphabet of passed sequence");
ex.initCause(e);
throw ex;
}
return seq;
}
| public SymbolList symbols(SymbolList seq) {
if (seq==null) throw new IllegalArgumentException("Sequence cannot be null");
if (seq instanceof RichSequence) {
RichSequence rs = (RichSequence)seq;
if (this.getCircularLength()>0) {
if (!rs.getCircular()) throw new IllegalArgumentException("Attempt to apply circular location to non-circular sequence");
if (rs.length()!=this.getCircularLength()) throw new IllegalArgumentException("Attempt to apply circular location to circular sequence of different length");
}
}
// Resolve cross-references to remote sequences
if (this.getCrossRef()!=null) {
CrossRef cr = this.getCrossRef();
if (seq instanceof RichSequence) {
RichSequence rs = (RichSequence)seq;
String accession = rs.getAccession();
Namespace ns = rs.getNamespace();
String raccession = cr.getAccession();
String rnamespace = cr.getDbname();
if (!(accession.equals(raccession) && ns.getName().equals(rnamespace))) {
// It really is remote - the xref doesn't point to the sequence we just got passed
seq = this.crr.getRemoteSymbolList(cr, seq.getAlphabet());
}
} else {
// It's assumed to be remote because we can't tell what the sequence we were passed really is
seq = this.crr.getRemoteSymbolList(this.getCrossRef(), seq.getAlphabet());
}
}
// Carry on as before
seq = seq.subList(this.getMin(),this.getMax());
try {
if (this.strand==Strand.NEGATIVE_STRAND) {
Alphabet a = seq.getAlphabet();
if (a==AlphabetManager.alphabetForName("DNA")) {
seq = DNATools.reverseComplement(seq);
} else if (a==AlphabetManager.alphabetForName("RNA")) {
seq = RNATools.reverseComplement(seq);
} else {
seq = SymbolListViews.reverse(seq);// no complement as no such thing
}
}
} catch (IllegalAlphabetException e) {
IllegalArgumentException ex =
new IllegalArgumentException("Could not understand alphabet of passed sequence");
ex.initCause(e);
throw ex;
}
return seq;
}
|
diff --git a/src/com/mareksebera/simpledilbert/DilbertFragment.java b/src/com/mareksebera/simpledilbert/DilbertFragment.java
index a1f42b5..d9b650d 100644
--- a/src/com/mareksebera/simpledilbert/DilbertFragment.java
+++ b/src/com/mareksebera/simpledilbert/DilbertFragment.java
@@ -1,252 +1,254 @@
package com.mareksebera.simpledilbert;
import org.joda.time.DateMidnight;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
public class DilbertFragment extends SherlockFragment {
private static final int MENU_SAVE = -1, MENU_FAVORITE = -2,
MENU_ZOOM = -3, MENU_SHARE = -4, MENU_REFRESH = -5;
public static final String ARGUMENT_DATE = "string_ARGUMENT_DATE";
private PhotoView image;
private ProgressBar progress;
private DilbertPreferences preferences;
private GetStripUrl loadTask;
private ImageLoader imageLoader = ImageLoader.getInstance();
private GetStripUrlInterface getStripUrilListener = new GetStripUrlInterface() {
@Override
public void imageLoadFailed(String url, FailReason reason) {
dilbertImageLoadingListener.onLoadingFailed(url, image, reason);
}
@Override
public void displayImage(String url) {
boolean hqIsEnabled = preferences.isHighQualityOn();
url = hqIsEnabled ? preferences.toHighQuality(url) : preferences
.toLowQuality(getDateFromArguments(), url);
imageLoader.displayImage(url, image, dilbertImageLoadingListener);
}
};
private ImageLoadingListener dilbertImageLoadingListener = new ImageLoadingListener() {
@Override
public void onLoadingCancelled(String imageUri, View view) {
image.setImageResource(R.drawable.cancel);
progress.setVisibility(View.GONE);
}
@Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
progress.setVisibility(View.GONE);
image.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
progress.setVisibility(View.GONE);
image.setVisibility(View.VISIBLE);
image.setImageResource(R.drawable.cancel);
if (getSherlockActivity() != null)
Toast.makeText(getSherlockActivity(),
R.string.loading_exception_error, Toast.LENGTH_SHORT)
.show();
}
@Override
public void onLoadingStarted(String imageUri, View view) {
image.setVisibility(View.GONE);
progress.setVisibility(View.VISIBLE);
}
};
private OnLongClickListener imageLongClickListener = new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
try {
if (getSherlockActivity().getSupportActionBar().isShowing())
getSherlockActivity().getSupportActionBar().hide();
else
getSherlockActivity().getSupportActionBar().show();
} catch (Throwable t) {
t.printStackTrace();
}
return true;
}
};
private OnPhotoTapListener photoTapListener = new OnPhotoTapListener() {
@Override
public void onPhotoTap(View view, float x, float y) {
refreshAction();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.preferences = new DilbertPreferences(getActivity());
setHasOptionsMenu(true);
}
private DateMidnight getDateFromArguments() {
return DateMidnight.parse(getArguments().getString(ARGUMENT_DATE),
DilbertPreferences.DATE_FORMATTER);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragment = inflater.inflate(R.layout.fragment_dilbert, container,
false);
this.image = (PhotoView) fragment.findViewById(R.id.fragment_imageview);
this.image.setOnLongClickListener(imageLongClickListener);
this.image.setOnPhotoTapListener(photoTapListener);
this.progress = (ProgressBar) fragment
.findViewById(R.id.fragment_progressbar);
this.loadTask = new GetStripUrl(getStripUrilListener, preferences,
getDateFromArguments());
this.image.setVisibility(View.GONE);
this.loadTask.execute();
return fragment;
}
@Override
public void onStop() {
imageLoader.cancelDisplayTask(this.image);
super.onStop();
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
if (menu.findItem(MENU_FAVORITE) != null) {
MenuItem favorite = menu.findItem(MENU_FAVORITE);
modifyFavoriteItem(favorite);
}
}
private void modifyFavoriteItem(MenuItem favorite) {
boolean isFavorite = preferences.isFavorited(getDateFromArguments());
favorite.setTitle(isFavorite ? R.string.menu_favorite_remove
: R.string.menu_favorite_add);
favorite.setIcon(isFavorite ? R.drawable.ic_menu_favorited
: R.drawable.ic_menu_not_favorited);
}
private int zoomLevel = 0;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_FAVORITE:
preferences.toggleIsFavorited(getDateFromArguments());
modifyFavoriteItem(item);
return true;
case MENU_ZOOM:
if (image != null && image.canZoom()) {
+ int center_x = image.getWidth() / 2;
+ int center_y = image.getHeight() / 2;
switch (zoomLevel) {
case 0:
- image.zoomTo(image.getMidScale(), image.getPivotX(),
- image.getPivotY());
+ image.zoomTo(image.getMidScale(), center_x,
+ center_y);
break;
case 1:
- image.zoomTo(image.getMaxScale(), image.getPivotX(),
- image.getPivotY());
+ image.zoomTo(image.getMaxScale(), center_x,
+ center_y);
break;
case 2:
- image.zoomTo(image.getMinScale(), image.getPivotX(),
- image.getPivotY());
+ image.zoomTo(image.getMinScale(), center_x,
+ center_y);
break;
}
zoomLevel = (zoomLevel + 1) % 3;
}
return true;
case MENU_SHARE:
shareCurrentStrip();
return true;
case MENU_REFRESH:
refreshAction();
break;
case MENU_SAVE:
preferences.downloadImageViaManager(getSherlockActivity(),
preferences.getCachedUrl(getDateFromArguments()),
getDateFromArguments());
return true;
}
return super.onOptionsItemSelected(item);
}
private void refreshAction() {
preferences.removeCache(getDateFromArguments());
if (this.loadTask != null
&& this.loadTask.getStatus() != Status.PENDING) {
this.loadTask = new GetStripUrl(getStripUrilListener, preferences,
getDateFromArguments());
}
this.loadTask.execute();
}
private void shareCurrentStrip() {
try {
String date = getDateFromArguments().toString(
DilbertPreferences.DATE_FORMATTER);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "Dilbert " + date
+ " #simpledilbert");
i.putExtra(Intent.EXTRA_TEXT, "Dilbert " + date
+ " #simpledilbert http://dilbert.com/strips/comic/" + date);
startActivity(Intent.createChooser(i,
getString(R.string.share_chooser)));
} catch (Exception e) {
if (getSherlockActivity() != null)
Toast.makeText(getSherlockActivity(),
R.string.loading_exception_error, Toast.LENGTH_LONG)
.show();
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
int category = 0;
menu.add(category, MENU_FAVORITE, 1, R.string.menu_favorite_remove)
.setIcon(R.drawable.ic_menu_not_favorited)
.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(category, MENU_ZOOM, 4, R.string.menu_zoom)
.setIcon(R.drawable.ic_menu_zoom)
.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(category, MENU_SAVE, 3, R.string.menu_download)
.setIcon(R.drawable.ic_menu_save)
.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(category, MENU_SHARE, 2, R.string.menu_share)
.setIcon(R.drawable.ic_menu_share)
.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(category, MENU_REFRESH, 5, R.string.menu_refresh)
.setIcon(R.drawable.ic_menu_refresh)
.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_NEVER);
}
}
| false | true | public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_FAVORITE:
preferences.toggleIsFavorited(getDateFromArguments());
modifyFavoriteItem(item);
return true;
case MENU_ZOOM:
if (image != null && image.canZoom()) {
switch (zoomLevel) {
case 0:
image.zoomTo(image.getMidScale(), image.getPivotX(),
image.getPivotY());
break;
case 1:
image.zoomTo(image.getMaxScale(), image.getPivotX(),
image.getPivotY());
break;
case 2:
image.zoomTo(image.getMinScale(), image.getPivotX(),
image.getPivotY());
break;
}
zoomLevel = (zoomLevel + 1) % 3;
}
return true;
case MENU_SHARE:
shareCurrentStrip();
return true;
case MENU_REFRESH:
refreshAction();
break;
case MENU_SAVE:
preferences.downloadImageViaManager(getSherlockActivity(),
preferences.getCachedUrl(getDateFromArguments()),
getDateFromArguments());
return true;
}
return super.onOptionsItemSelected(item);
}
| public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_FAVORITE:
preferences.toggleIsFavorited(getDateFromArguments());
modifyFavoriteItem(item);
return true;
case MENU_ZOOM:
if (image != null && image.canZoom()) {
int center_x = image.getWidth() / 2;
int center_y = image.getHeight() / 2;
switch (zoomLevel) {
case 0:
image.zoomTo(image.getMidScale(), center_x,
center_y);
break;
case 1:
image.zoomTo(image.getMaxScale(), center_x,
center_y);
break;
case 2:
image.zoomTo(image.getMinScale(), center_x,
center_y);
break;
}
zoomLevel = (zoomLevel + 1) % 3;
}
return true;
case MENU_SHARE:
shareCurrentStrip();
return true;
case MENU_REFRESH:
refreshAction();
break;
case MENU_SAVE:
preferences.downloadImageViaManager(getSherlockActivity(),
preferences.getCachedUrl(getDateFromArguments()),
getDateFromArguments());
return true;
}
return super.onOptionsItemSelected(item);
}
|
diff --git a/src/replicatorg/app/ui/controlpanel/ExtruderPanel.java b/src/replicatorg/app/ui/controlpanel/ExtruderPanel.java
index 716f4f09..1d48c743 100644
--- a/src/replicatorg/app/ui/controlpanel/ExtruderPanel.java
+++ b/src/replicatorg/app/ui/controlpanel/ExtruderPanel.java
@@ -1,661 +1,661 @@
package replicatorg.app.ui.controlpanel;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.TickUnits;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYStepRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeTableXYDataset;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import replicatorg.app.Base;
import replicatorg.app.ui.CallbackTextField;
import replicatorg.drivers.RetryException;
import replicatorg.drivers.commands.DriverCommand.AxialDirection;
import replicatorg.machine.MachineInterface;
import replicatorg.machine.model.ToolModel;
public class ExtruderPanel extends JPanel implements FocusListener, ActionListener, ItemListener {
private ToolModel toolModel;
private MachineInterface machine;
public ToolModel getTool() { return toolModel; }
protected JFormattedTextField currentTempField;
protected JFormattedTextField platformCurrentTempField;
protected double targetTemperature;
protected double targetPlatformTemperature;
final private static Color targetColor = Color.BLUE;
final private static Color measuredColor = Color.RED;
final private static Color targetPlatformColor = Color.YELLOW;
final private static Color measuredPlatformColor = Color.WHITE;
long startMillis = System.currentTimeMillis();
private TimeTableXYDataset measuredDataset = new TimeTableXYDataset();
private TimeTableXYDataset targetDataset = new TimeTableXYDataset();
private TimeTableXYDataset measuredPlatformDataset = new TimeTableXYDataset();
private TimeTableXYDataset targetPlatformDataset = new TimeTableXYDataset();
protected Pattern extrudeTimePattern;
protected String[] extrudeTimeStrings = { /* "Continuous Move", */ "1s", "2s", "5s", "10s", "30s", "60s", "300s" };
protected boolean continuousJogMode = false;
protected long extrudeTime;
private final String EXTRUDE_TIME_PREF_NAME = "extruderpanel.extrudetime";
// protected Driver driver;
/**
* Make a label with an icon indicating its color on the graph.
* @param text The text of the label
* @param c The color of the matching line on the graph
* @return the generated label
*/
private JLabel makeKeyLabel(String text, Color c) {
BufferedImage image = new BufferedImage(10,10,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(c);
g.fillRect(0,0,10,10);
//image.getGraphics().fillRect(0,0,10,10);
Icon icon = new ImageIcon(image);
return new JLabel(text,icon,SwingConstants.LEFT);
}
public ChartPanel makeChart(ToolModel t) {
JFreeChart chart = ChartFactory.createXYLineChart(null, null, null,
measuredDataset, PlotOrientation.VERTICAL,
false, false, false);
chart.setBorderVisible(false);
chart.setBackgroundPaint(null);
XYPlot plot = chart.getXYPlot();
ValueAxis axis = plot.getDomainAxis();
axis.setLowerMargin(0);
axis.setFixedAutoRange(3L*60L*1000L); // auto range to three minutes
TickUnits unitSource = new TickUnits();
unitSource.add(new NumberTickUnit(60L*1000L)); // minutes
unitSource.add(new NumberTickUnit(1L*1000L)); // seconds
axis.setStandardTickUnits(unitSource);
axis.setTickLabelsVisible(false); // We don't need to see the millisecond count
axis = plot.getRangeAxis();
axis.setRange(0,300); // set termperature range from 0 to 300 degrees C so you can see overshoots
// Tweak L&F of chart
//((XYAreaRenderer)plot.getRenderer()).setOutline(true);
XYStepRenderer renderer = new XYStepRenderer();
plot.setDataset(1, targetDataset);
plot.setRenderer(1, renderer);
plot.getRenderer(1).setSeriesPaint(0, targetColor);
plot.getRenderer(0).setSeriesPaint(0, measuredColor);
if (t.hasHeatedPlatform()) {
plot.setDataset(2,measuredPlatformDataset);
plot.setRenderer(2, new XYLineAndShapeRenderer(true,false));
plot.getRenderer(2).setSeriesPaint(0, measuredPlatformColor);
plot.setDataset(3,targetPlatformDataset);
plot.setRenderer(3, new XYStepRenderer());
plot.getRenderer(3).setSeriesPaint(0, targetPlatformColor);
}
plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(400,160));
chartPanel.setOpaque(false);
return chartPanel;
}
private final Dimension labelMinimumSize = new Dimension(175, 25);
private JLabel makeLabel(String text) {
JLabel label = new JLabel();
label.setText(text);
label.setMinimumSize(labelMinimumSize);
label.setMaximumSize(labelMinimumSize);
label.setPreferredSize(labelMinimumSize);
label.setHorizontalAlignment(JLabel.LEFT);
return label;
}
private void setExtrudeTime(String mode) {
if ("Continuous Jog".equals(mode)) {
continuousJogMode = true;
extrudeTime = 0;
} else {
// If we were in continuous jog mode, send a stop to be safe
if (continuousJogMode) {
this.machine.stopMotion();
}
continuousJogMode = false;
Matcher jogMatcher = extrudeTimePattern.matcher(mode);
if (jogMatcher.find())
extrudeTime = Long.parseLong(jogMatcher.group(1));
}
if (mode != null && mode.length() > 0) {
Base.preferences.put(EXTRUDE_TIME_PREF_NAME,mode);
}
}
public ExtruderPanel(MachineInterface machine, ToolModel t) {
this.machine = machine;
this.toolModel = t;
Dimension panelSize = new Dimension(420, 30);
extrudeTimePattern = Pattern.compile("([.0-9]+)");
// create our initial panel
setLayout(new MigLayout());
// create our motor options
if (t.hasMotor()) {
// Due to current implementation issues, we need to send the PWM
// before the RPM for a stepper motor. Thus we display both controls in these
// cases. This shouldn't be necessary for a Gen4 stepper extruder. (it's not!)
if ((t.getMotorStepperAxis() == null) && !(t.motorHasEncoder() || t.motorIsStepper())) {
// our motor speed vars
JLabel label = makeLabel("Motor Speed (PWM)");
JFormattedTextField field = new CallbackTextField(this, "handleTextField", "motor-speed-pwm", 9, Base.getLocalFormat());
- field.setValue(Integer.toString(machine.getDriverQueryInterface().getMotorSpeedPWM()));
+ field.setValue(machine.getDriverQueryInterface().getMotorSpeedPWM());
add(label);
add(field,"wrap");
}
if (t.motorHasEncoder() || t.motorIsStepper()) {
// our motor speed vars
JLabel label = makeLabel("Motor Speed (RPM)");
JFormattedTextField field = new CallbackTextField(this, "handleTextField", "motor-speed", 9, Base.getLocalFormat());
field.setValue(machine.getDriverQueryInterface().getMotorRPM());
add(label);
add(field,"wrap");
if (this.toolModel.getMotorStepperAxis() != null) {
label = makeLabel("Extrude duration");
JComboBox timeList = new JComboBox(extrudeTimeStrings);
timeList.setSelectedItem(Base.preferences.get(EXTRUDE_TIME_PREF_NAME,"5s"));
timeList.setActionCommand("Extrude-duration");
timeList.addActionListener(this);
setExtrudeTime((String)timeList.getSelectedItem());
add(label);
add(timeList,"wrap");
}
}
// create our motor options
JLabel motorEnabledLabel = makeLabel("Motor Control");
if (t.motorHasEncoder() || (t.motorIsStepper() && this.toolModel.getMotorStepperAxis() != null)) {
JButton motorReverseButton = new JButton("reverse");
motorReverseButton.setActionCommand("reverse");
motorReverseButton.addActionListener(this);
JButton motorStoppedButton = new JButton("stop");
motorStoppedButton.setActionCommand("stop");
motorStoppedButton.addActionListener(this);
JButton motorForwardButton = new JButton("forward");
motorForwardButton.setActionCommand("forward");
motorForwardButton.addActionListener(this);
ButtonGroup motorControl = new ButtonGroup();
motorControl.add(motorReverseButton);
motorControl.add(motorStoppedButton);
motorControl.add(motorForwardButton);
// add components in.
add(motorEnabledLabel,"split,spanx");
add(motorReverseButton);
add(motorStoppedButton);
add(motorForwardButton,"wrap");
}
else {
JRadioButton motorReverseButton = new JRadioButton("reverse");
motorReverseButton.setName("motor-reverse");
motorReverseButton.setActionCommand("motor-reverse");
motorReverseButton.addItemListener(this);
JRadioButton motorStoppedButton = new JRadioButton("stop");
motorStoppedButton.setName("motor-stop");
motorStoppedButton.setActionCommand("motor-stop");
motorStoppedButton.addItemListener(this);
JRadioButton motorForwardButton = new JRadioButton("forward");
motorForwardButton.setName("motor-forward");
motorForwardButton.setActionCommand("motor-forward");
motorForwardButton.addItemListener(this);
ButtonGroup motorControl = new ButtonGroup();
motorControl.add(motorReverseButton);
motorControl.add(motorStoppedButton);
motorControl.add(motorForwardButton);
// add components in.
add(motorEnabledLabel,"split,spanx");
add(motorReverseButton);
add(motorStoppedButton);
add(motorForwardButton,"wrap");
}
}
// our temperature fields
if (t.hasHeater()) {
JLabel targetTempLabel = makeKeyLabel("Target Temperature (C)",targetColor);
JFormattedTextField targetTempField = new CallbackTextField(this, "handleTextField", "target-temp", 9, Base.getLocalFormat());
targetTemperature = machine.getDriverQueryInterface().getTemperatureSetting();
targetTempField.setValue(targetTemperature);
JLabel currentTempLabel = makeKeyLabel("Current Temperature (C)",measuredColor);
currentTempField = new JFormattedTextField(Base.getLocalFormat());
currentTempField.setColumns(9);
currentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(currentTempField,"wrap");
}
// our heated platform fields
if (t.hasHeatedPlatform()) {
JLabel targetTempLabel = makeKeyLabel("Platform Target Temp (C)",targetPlatformColor);
JFormattedTextField targetTempField = new CallbackTextField(this, "handleTextField", "platform-target-temp", 9, Base.getLocalFormat());
targetPlatformTemperature = machine.getDriverQueryInterface().getPlatformTemperatureSetting();
targetTempField.setValue(targetPlatformTemperature);
JLabel currentTempLabel = makeKeyLabel("Platform Current Temp (C)",measuredPlatformColor);
platformCurrentTempField = new JFormattedTextField(Base.getLocalFormat());
platformCurrentTempField.setColumns(9);
platformCurrentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(platformCurrentTempField,"wrap");
}
if (t.hasHeater() || t.hasHeatedPlatform()) {
add(new JLabel("Temperature Chart"),"growx,spanx,wrap");
add(makeChart(t),"growx,spanx,wrap");
}
// flood coolant controls
if (t.hasFloodCoolant()) {
JLabel floodCoolantLabel = makeLabel("Flood Coolant");
JCheckBox floodCoolantCheck = new JCheckBox("enable");
floodCoolantCheck.setName("flood-coolant");
floodCoolantCheck.addItemListener(this);
add(floodCoolantLabel);
add(floodCoolantCheck,"wrap");
}
// mist coolant controls
if (t.hasMistCoolant()) {
JLabel mistCoolantLabel = makeLabel("Mist Coolant");
JCheckBox mistCoolantCheck = new JCheckBox("enable");
mistCoolantCheck.setName("mist-coolant");
mistCoolantCheck.addItemListener(this);
add(mistCoolantLabel);
add(mistCoolantCheck,"wrap");
}
// cooling fan controls
if (t.hasFan()) {
String fanString = "Cooling Fan";
String enableString = "enable";
Element xml = findMappingNode(t.getXml(),"fan");
if (xml != null) {
fanString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel fanLabel = makeLabel(fanString);
JCheckBox fanCheck = new JCheckBox(enableString);
fanCheck.setName("fan-check");
fanCheck.addItemListener(this);
add(fanLabel);
add(fanCheck,"wrap");
}
// cooling fan controls
if (t.hasAutomatedPlatform()) {
String abpString = "Build platform belt";
String enableString = "enable";
JLabel abpLabel = makeLabel(abpString);
JCheckBox abpCheck = new JCheckBox(enableString);
abpCheck.setName("abp-check");
abpCheck.addItemListener(this);
add(abpLabel);
add(abpCheck,"wrap");
}
// valve controls
if (t.hasValve()) {
String valveString = "Valve";
String enableString = "open";
Element xml = findMappingNode(t.getXml(),"valve");
if (xml != null) {
valveString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel valveLabel = makeLabel(valveString);
JCheckBox valveCheck = new JCheckBox(enableString);
valveCheck.setName("valve-check");
valveCheck.addItemListener(this);
add(valveLabel);
add(valveCheck,"wrap");
}
// valve controls
if (t.hasCollet()) {
JLabel colletLabel = makeLabel("Collet");
JCheckBox colletCheck = new JCheckBox("open");
colletCheck.setName("collet-check");
colletCheck.addItemListener(this);
JPanel colletPanel = new JPanel();
colletPanel.setLayout(new BoxLayout(colletPanel,
BoxLayout.LINE_AXIS));
colletPanel.setMaximumSize(panelSize);
colletPanel.setMinimumSize(panelSize);
colletPanel.setPreferredSize(panelSize);
add(colletLabel);
add(colletCheck,"wrap");
}
}
private Element findMappingNode(Node xml,String portName) {
// scan the remapping nodes.
NodeList children = xml.getChildNodes();
for (int j=0; j<children.getLength(); j++) {
Node child = children.item(j);
if (child.getNodeName().equals("remap")) {
Element e = (Element)child;
if (e.getAttribute("port").equals(portName)) {
return e;
}
}
}
return null;
}
public void updateStatus() {
Second second = new Second(new Date(System.currentTimeMillis() - startMillis));
if (machine.getModel().currentTool() == toolModel && toolModel.hasHeater()) {
double temperature = machine.getDriverQueryInterface().getTemperature();
updateTemperature(second, temperature);
}
if (machine.getModel().currentTool() == toolModel && toolModel.hasHeatedPlatform()) {
double temperature = machine.getDriverQueryInterface().getPlatformTemperature();
updatePlatformTemperature(second, temperature);
}
}
synchronized public void updateTemperature(Second second, double temperature)
{
currentTempField.setValue(temperature);
measuredDataset.add(second, temperature,"a");
targetDataset.add(second, targetTemperature,"a");
}
synchronized public void updatePlatformTemperature(Second second, double temperature)
{
platformCurrentTempField.setValue(temperature);
measuredPlatformDataset.add(second, temperature,"a");
targetPlatformDataset.add(second, targetPlatformTemperature,"a");
}
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
JFormattedTextField source = (JFormattedTextField) e.getSource();
try {
handleChangedTextField(source);
} catch (RetryException e1) {
Base.logger.severe("Could not execute command; machine busy.");
}
}
//
// Check the temperature range and insure that the target is within bounds. If not,
// query the user to see if they want to make an exception.
// agm: I've removed the "set this as the new limit" option. This should be set in the
// preferences or some other hard-to-reach place. Accidentally clicking a button
// to set a potentially dangerous limit would suck.
// @return Double.MIN_VALUE if cancelled; the target temperature otherwise.
//
// NOTE: copy of this in preferences window
private double confirmTemperature(double target, String limitPrefName, double defaultLimit) {
double limit = Base.preferences.getDouble("temperature.acceptedLimit", defaultLimit);
if (target > limit){
// Temperature warning dialog!
int n = JOptionPane.showConfirmDialog(this,
"<html>Setting the temperature to <b>" + Double.toString(target) + "\u00b0C</b> may<br>"+
"involve health and/or safety risks or cause damage to your machine!<br>"+
"The maximum recommended temperature is <b>"+Double.toString(limit)+"</b>.<br>"+
"Do you accept the risk and still want to set this temperature?",
"Danger",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (n == JOptionPane.YES_OPTION) {
return target;
} else if (n == JOptionPane.NO_OPTION) {
return Double.MIN_VALUE;
} else { // Cancel or whatnot
return Double.MIN_VALUE;
}
} else {
return target;
}
}
public void handleChangedTextField(JFormattedTextField source) throws RetryException
{
String name = source.getName();
if (source.getText().length() > 0) {
double target = ((Number)source.getValue()).doubleValue();
Base.logger.severe("target is " + target);
if (name.equals("target-temp") || name.equals("platform-target-temp")) {
if(name.equals("target-temp")) {
target = confirmTemperature(target,"temperature.acceptedLimit",260.0);
if (target == Double.MIN_VALUE) {
return;
}
machine.runCommand(new replicatorg.drivers.commands.SetTemperature(target));
targetTemperature = target;
} else {
target = confirmTemperature(target,"temperature.acceptedLimit.bed",130.0);
if (target == Double.MIN_VALUE) {
return;
}
machine.runCommand(new replicatorg.drivers.commands.SetPlatformTemperature(target));
targetPlatformTemperature = target;
}
} else if (name.equals("motor-speed")) {
machine.runCommand(new replicatorg.drivers.commands.SetMotorSpeedRPM(target));
} else if (name.equals("motor-speed-pwm")) {
machine.runCommand(new replicatorg.drivers.commands.SetMotorSpeedPWM((int)target));
} else {
Base.logger.warning("Unhandled text field: "+name);
}
}
}
public void itemStateChanged(ItemEvent e) {
Component source = (Component) e.getItemSelectable();
String name = source.getName();
if (e.getStateChange() == ItemEvent.SELECTED) {
/* Handle DC extruder commands */
if (name.equals("motor-forward")) {
machine.runCommand(new replicatorg.drivers.commands.SetMotorDirection(AxialDirection.CLOCKWISE));
// TODO: Hack to support RepRap/Ultimaker- always re-send RPM
if (toolModel.motorHasEncoder() || toolModel.motorIsStepper()) {
machine.runCommand(new replicatorg.drivers.commands.SetMotorSpeedRPM(machine.getDriver().getMotorRPM()));
}
machine.runCommand(new replicatorg.drivers.commands.EnableMotor());
} else if (name.equals("motor-reverse")) {
machine.runCommand(new replicatorg.drivers.commands.SetMotorDirection(AxialDirection.COUNTERCLOCKWISE));
// TODO: Hack to support RepRap/Ultimaker- always re-send RPM
if (toolModel.motorHasEncoder() || toolModel.motorIsStepper()) {
machine.runCommand(new replicatorg.drivers.commands.SetMotorSpeedRPM(machine.getDriver().getMotorRPM()));
}
machine.runCommand(new replicatorg.drivers.commands.EnableMotor());
} else if (name.equals("motor-stop")) {
machine.runCommand(new replicatorg.drivers.commands.DisableMotor());
}
else if (name.equals("spindle-enabled"))
machine.runCommand(new replicatorg.drivers.commands.EnableSpindle());
else if (name.equals("flood-coolant"))
machine.runCommand(new replicatorg.drivers.commands.EnableFloodCoolant());
else if (name.equals("mist-coolant"))
machine.runCommand(new replicatorg.drivers.commands.EnableMistCoolant());
else if (name.equals("fan-check"))
machine.runCommand(new replicatorg.drivers.commands.EnableFan());
else if (name.equals("abp-check")) {
// TODO: Debugging. Run both!
machine.runCommand(new replicatorg.drivers.commands.ToggleAutomatedBuildPlatform(true));
machine.runCommand(new replicatorg.drivers.commands.EnableFan());
}
else if (name.equals("valve-check"))
machine.runCommand(new replicatorg.drivers.commands.OpenValve());
else if (name.equals("collet-check"))
machine.runCommand(new replicatorg.drivers.commands.OpenCollet());
else
Base.logger.warning("checkbox selected: " + source.getName());
} else {
if (name.equals("motor-enabled"))
machine.runCommand(new replicatorg.drivers.commands.DisableMotor());
else if (name.equals("spindle-enabled"))
machine.runCommand(new replicatorg.drivers.commands.DisableSpindle());
else if (name.equals("flood-coolant"))
machine.runCommand(new replicatorg.drivers.commands.DisableFloodCoolant());
else if (name.equals("mist-coolant"))
machine.runCommand(new replicatorg.drivers.commands.DisableMistCoolant());
else if (name.equals("fan-check"))
machine.runCommand(new replicatorg.drivers.commands.DisableFan());
else if (name.equals("abp-check")) {
// TODO: Debugging. Run both!
machine.runCommand(new replicatorg.drivers.commands.ToggleAutomatedBuildPlatform(false));
machine.runCommand(new replicatorg.drivers.commands.DisableFan());
}
else if (name.equals("valve-check"))
machine.runCommand(new replicatorg.drivers.commands.CloseValve());
else if (name.equals("collet-check"))
machine.runCommand(new replicatorg.drivers.commands.CloseCollet());
}
}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if(s.equals("handleTextField"))
{
JFormattedTextField source = (JFormattedTextField) e.getSource();
try {
handleChangedTextField(source);
} catch (RetryException e1) {
Base.logger.severe("Could not execute command; machine busy.");
}
source.selectAll();
}
else if (s.equals("Extrude-duration")) {
JComboBox cb = (JComboBox) e.getSource();
String timeText = (String) cb.getSelectedItem();
setExtrudeTime(timeText);
}
/* Handle stepper extruder commands */
if (s.equals("forward")) {
if (this.toolModel.getMotorStepperAxis() != null) {
machine.runCommand(new replicatorg.drivers.commands.SetMotorDirection(AxialDirection.CLOCKWISE));
// Reverted to one single command for RepRap5D driver
if (machine.getDriver().getDriverName().equals("RepRap5D")) {
machine.runCommand(new replicatorg.drivers.commands.EnableMotor(extrudeTime*1000));
} else {
machine.runCommand(new replicatorg.drivers.commands.EnableMotor());
machine.runCommand(new replicatorg.drivers.commands.Delay(extrudeTime*1000));
machine.runCommand(new replicatorg.drivers.commands.DisableMotor());
}
}
} else if (s.equals("reverse")) {
if (this.toolModel.getMotorStepperAxis() != null) {
machine.runCommand(new replicatorg.drivers.commands.SetMotorDirection(AxialDirection.COUNTERCLOCKWISE));
// Reverted to one single command for RepRap5D driver
if (machine.getDriver().getDriverName().equals("RepRap5D")) {
machine.runCommand(new replicatorg.drivers.commands.EnableMotor(extrudeTime*1000));
} else {
machine.runCommand(new replicatorg.drivers.commands.EnableMotor());
machine.runCommand(new replicatorg.drivers.commands.Delay(extrudeTime*1000));
machine.runCommand(new replicatorg.drivers.commands.DisableMotor());
}
}
} else if (s.equals("stop")) {
machine.runCommand(new replicatorg.drivers.commands.DisableMotor());
if (this.toolModel.getMotorStepperAxis() != null) {
machine.stopMotion();
}
}
}
}
| true | true | public ExtruderPanel(MachineInterface machine, ToolModel t) {
this.machine = machine;
this.toolModel = t;
Dimension panelSize = new Dimension(420, 30);
extrudeTimePattern = Pattern.compile("([.0-9]+)");
// create our initial panel
setLayout(new MigLayout());
// create our motor options
if (t.hasMotor()) {
// Due to current implementation issues, we need to send the PWM
// before the RPM for a stepper motor. Thus we display both controls in these
// cases. This shouldn't be necessary for a Gen4 stepper extruder. (it's not!)
if ((t.getMotorStepperAxis() == null) && !(t.motorHasEncoder() || t.motorIsStepper())) {
// our motor speed vars
JLabel label = makeLabel("Motor Speed (PWM)");
JFormattedTextField field = new CallbackTextField(this, "handleTextField", "motor-speed-pwm", 9, Base.getLocalFormat());
field.setValue(Integer.toString(machine.getDriverQueryInterface().getMotorSpeedPWM()));
add(label);
add(field,"wrap");
}
if (t.motorHasEncoder() || t.motorIsStepper()) {
// our motor speed vars
JLabel label = makeLabel("Motor Speed (RPM)");
JFormattedTextField field = new CallbackTextField(this, "handleTextField", "motor-speed", 9, Base.getLocalFormat());
field.setValue(machine.getDriverQueryInterface().getMotorRPM());
add(label);
add(field,"wrap");
if (this.toolModel.getMotorStepperAxis() != null) {
label = makeLabel("Extrude duration");
JComboBox timeList = new JComboBox(extrudeTimeStrings);
timeList.setSelectedItem(Base.preferences.get(EXTRUDE_TIME_PREF_NAME,"5s"));
timeList.setActionCommand("Extrude-duration");
timeList.addActionListener(this);
setExtrudeTime((String)timeList.getSelectedItem());
add(label);
add(timeList,"wrap");
}
}
// create our motor options
JLabel motorEnabledLabel = makeLabel("Motor Control");
if (t.motorHasEncoder() || (t.motorIsStepper() && this.toolModel.getMotorStepperAxis() != null)) {
JButton motorReverseButton = new JButton("reverse");
motorReverseButton.setActionCommand("reverse");
motorReverseButton.addActionListener(this);
JButton motorStoppedButton = new JButton("stop");
motorStoppedButton.setActionCommand("stop");
motorStoppedButton.addActionListener(this);
JButton motorForwardButton = new JButton("forward");
motorForwardButton.setActionCommand("forward");
motorForwardButton.addActionListener(this);
ButtonGroup motorControl = new ButtonGroup();
motorControl.add(motorReverseButton);
motorControl.add(motorStoppedButton);
motorControl.add(motorForwardButton);
// add components in.
add(motorEnabledLabel,"split,spanx");
add(motorReverseButton);
add(motorStoppedButton);
add(motorForwardButton,"wrap");
}
else {
JRadioButton motorReverseButton = new JRadioButton("reverse");
motorReverseButton.setName("motor-reverse");
motorReverseButton.setActionCommand("motor-reverse");
motorReverseButton.addItemListener(this);
JRadioButton motorStoppedButton = new JRadioButton("stop");
motorStoppedButton.setName("motor-stop");
motorStoppedButton.setActionCommand("motor-stop");
motorStoppedButton.addItemListener(this);
JRadioButton motorForwardButton = new JRadioButton("forward");
motorForwardButton.setName("motor-forward");
motorForwardButton.setActionCommand("motor-forward");
motorForwardButton.addItemListener(this);
ButtonGroup motorControl = new ButtonGroup();
motorControl.add(motorReverseButton);
motorControl.add(motorStoppedButton);
motorControl.add(motorForwardButton);
// add components in.
add(motorEnabledLabel,"split,spanx");
add(motorReverseButton);
add(motorStoppedButton);
add(motorForwardButton,"wrap");
}
}
// our temperature fields
if (t.hasHeater()) {
JLabel targetTempLabel = makeKeyLabel("Target Temperature (C)",targetColor);
JFormattedTextField targetTempField = new CallbackTextField(this, "handleTextField", "target-temp", 9, Base.getLocalFormat());
targetTemperature = machine.getDriverQueryInterface().getTemperatureSetting();
targetTempField.setValue(targetTemperature);
JLabel currentTempLabel = makeKeyLabel("Current Temperature (C)",measuredColor);
currentTempField = new JFormattedTextField(Base.getLocalFormat());
currentTempField.setColumns(9);
currentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(currentTempField,"wrap");
}
// our heated platform fields
if (t.hasHeatedPlatform()) {
JLabel targetTempLabel = makeKeyLabel("Platform Target Temp (C)",targetPlatformColor);
JFormattedTextField targetTempField = new CallbackTextField(this, "handleTextField", "platform-target-temp", 9, Base.getLocalFormat());
targetPlatformTemperature = machine.getDriverQueryInterface().getPlatformTemperatureSetting();
targetTempField.setValue(targetPlatformTemperature);
JLabel currentTempLabel = makeKeyLabel("Platform Current Temp (C)",measuredPlatformColor);
platformCurrentTempField = new JFormattedTextField(Base.getLocalFormat());
platformCurrentTempField.setColumns(9);
platformCurrentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(platformCurrentTempField,"wrap");
}
if (t.hasHeater() || t.hasHeatedPlatform()) {
add(new JLabel("Temperature Chart"),"growx,spanx,wrap");
add(makeChart(t),"growx,spanx,wrap");
}
// flood coolant controls
if (t.hasFloodCoolant()) {
JLabel floodCoolantLabel = makeLabel("Flood Coolant");
JCheckBox floodCoolantCheck = new JCheckBox("enable");
floodCoolantCheck.setName("flood-coolant");
floodCoolantCheck.addItemListener(this);
add(floodCoolantLabel);
add(floodCoolantCheck,"wrap");
}
// mist coolant controls
if (t.hasMistCoolant()) {
JLabel mistCoolantLabel = makeLabel("Mist Coolant");
JCheckBox mistCoolantCheck = new JCheckBox("enable");
mistCoolantCheck.setName("mist-coolant");
mistCoolantCheck.addItemListener(this);
add(mistCoolantLabel);
add(mistCoolantCheck,"wrap");
}
// cooling fan controls
if (t.hasFan()) {
String fanString = "Cooling Fan";
String enableString = "enable";
Element xml = findMappingNode(t.getXml(),"fan");
if (xml != null) {
fanString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel fanLabel = makeLabel(fanString);
JCheckBox fanCheck = new JCheckBox(enableString);
fanCheck.setName("fan-check");
fanCheck.addItemListener(this);
add(fanLabel);
add(fanCheck,"wrap");
}
// cooling fan controls
if (t.hasAutomatedPlatform()) {
String abpString = "Build platform belt";
String enableString = "enable";
JLabel abpLabel = makeLabel(abpString);
JCheckBox abpCheck = new JCheckBox(enableString);
abpCheck.setName("abp-check");
abpCheck.addItemListener(this);
add(abpLabel);
add(abpCheck,"wrap");
}
// valve controls
if (t.hasValve()) {
String valveString = "Valve";
String enableString = "open";
Element xml = findMappingNode(t.getXml(),"valve");
if (xml != null) {
valveString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel valveLabel = makeLabel(valveString);
JCheckBox valveCheck = new JCheckBox(enableString);
valveCheck.setName("valve-check");
valveCheck.addItemListener(this);
add(valveLabel);
add(valveCheck,"wrap");
}
// valve controls
if (t.hasCollet()) {
JLabel colletLabel = makeLabel("Collet");
JCheckBox colletCheck = new JCheckBox("open");
colletCheck.setName("collet-check");
colletCheck.addItemListener(this);
JPanel colletPanel = new JPanel();
colletPanel.setLayout(new BoxLayout(colletPanel,
BoxLayout.LINE_AXIS));
colletPanel.setMaximumSize(panelSize);
colletPanel.setMinimumSize(panelSize);
colletPanel.setPreferredSize(panelSize);
add(colletLabel);
add(colletCheck,"wrap");
}
}
| public ExtruderPanel(MachineInterface machine, ToolModel t) {
this.machine = machine;
this.toolModel = t;
Dimension panelSize = new Dimension(420, 30);
extrudeTimePattern = Pattern.compile("([.0-9]+)");
// create our initial panel
setLayout(new MigLayout());
// create our motor options
if (t.hasMotor()) {
// Due to current implementation issues, we need to send the PWM
// before the RPM for a stepper motor. Thus we display both controls in these
// cases. This shouldn't be necessary for a Gen4 stepper extruder. (it's not!)
if ((t.getMotorStepperAxis() == null) && !(t.motorHasEncoder() || t.motorIsStepper())) {
// our motor speed vars
JLabel label = makeLabel("Motor Speed (PWM)");
JFormattedTextField field = new CallbackTextField(this, "handleTextField", "motor-speed-pwm", 9, Base.getLocalFormat());
field.setValue(machine.getDriverQueryInterface().getMotorSpeedPWM());
add(label);
add(field,"wrap");
}
if (t.motorHasEncoder() || t.motorIsStepper()) {
// our motor speed vars
JLabel label = makeLabel("Motor Speed (RPM)");
JFormattedTextField field = new CallbackTextField(this, "handleTextField", "motor-speed", 9, Base.getLocalFormat());
field.setValue(machine.getDriverQueryInterface().getMotorRPM());
add(label);
add(field,"wrap");
if (this.toolModel.getMotorStepperAxis() != null) {
label = makeLabel("Extrude duration");
JComboBox timeList = new JComboBox(extrudeTimeStrings);
timeList.setSelectedItem(Base.preferences.get(EXTRUDE_TIME_PREF_NAME,"5s"));
timeList.setActionCommand("Extrude-duration");
timeList.addActionListener(this);
setExtrudeTime((String)timeList.getSelectedItem());
add(label);
add(timeList,"wrap");
}
}
// create our motor options
JLabel motorEnabledLabel = makeLabel("Motor Control");
if (t.motorHasEncoder() || (t.motorIsStepper() && this.toolModel.getMotorStepperAxis() != null)) {
JButton motorReverseButton = new JButton("reverse");
motorReverseButton.setActionCommand("reverse");
motorReverseButton.addActionListener(this);
JButton motorStoppedButton = new JButton("stop");
motorStoppedButton.setActionCommand("stop");
motorStoppedButton.addActionListener(this);
JButton motorForwardButton = new JButton("forward");
motorForwardButton.setActionCommand("forward");
motorForwardButton.addActionListener(this);
ButtonGroup motorControl = new ButtonGroup();
motorControl.add(motorReverseButton);
motorControl.add(motorStoppedButton);
motorControl.add(motorForwardButton);
// add components in.
add(motorEnabledLabel,"split,spanx");
add(motorReverseButton);
add(motorStoppedButton);
add(motorForwardButton,"wrap");
}
else {
JRadioButton motorReverseButton = new JRadioButton("reverse");
motorReverseButton.setName("motor-reverse");
motorReverseButton.setActionCommand("motor-reverse");
motorReverseButton.addItemListener(this);
JRadioButton motorStoppedButton = new JRadioButton("stop");
motorStoppedButton.setName("motor-stop");
motorStoppedButton.setActionCommand("motor-stop");
motorStoppedButton.addItemListener(this);
JRadioButton motorForwardButton = new JRadioButton("forward");
motorForwardButton.setName("motor-forward");
motorForwardButton.setActionCommand("motor-forward");
motorForwardButton.addItemListener(this);
ButtonGroup motorControl = new ButtonGroup();
motorControl.add(motorReverseButton);
motorControl.add(motorStoppedButton);
motorControl.add(motorForwardButton);
// add components in.
add(motorEnabledLabel,"split,spanx");
add(motorReverseButton);
add(motorStoppedButton);
add(motorForwardButton,"wrap");
}
}
// our temperature fields
if (t.hasHeater()) {
JLabel targetTempLabel = makeKeyLabel("Target Temperature (C)",targetColor);
JFormattedTextField targetTempField = new CallbackTextField(this, "handleTextField", "target-temp", 9, Base.getLocalFormat());
targetTemperature = machine.getDriverQueryInterface().getTemperatureSetting();
targetTempField.setValue(targetTemperature);
JLabel currentTempLabel = makeKeyLabel("Current Temperature (C)",measuredColor);
currentTempField = new JFormattedTextField(Base.getLocalFormat());
currentTempField.setColumns(9);
currentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(currentTempField,"wrap");
}
// our heated platform fields
if (t.hasHeatedPlatform()) {
JLabel targetTempLabel = makeKeyLabel("Platform Target Temp (C)",targetPlatformColor);
JFormattedTextField targetTempField = new CallbackTextField(this, "handleTextField", "platform-target-temp", 9, Base.getLocalFormat());
targetPlatformTemperature = machine.getDriverQueryInterface().getPlatformTemperatureSetting();
targetTempField.setValue(targetPlatformTemperature);
JLabel currentTempLabel = makeKeyLabel("Platform Current Temp (C)",measuredPlatformColor);
platformCurrentTempField = new JFormattedTextField(Base.getLocalFormat());
platformCurrentTempField.setColumns(9);
platformCurrentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(platformCurrentTempField,"wrap");
}
if (t.hasHeater() || t.hasHeatedPlatform()) {
add(new JLabel("Temperature Chart"),"growx,spanx,wrap");
add(makeChart(t),"growx,spanx,wrap");
}
// flood coolant controls
if (t.hasFloodCoolant()) {
JLabel floodCoolantLabel = makeLabel("Flood Coolant");
JCheckBox floodCoolantCheck = new JCheckBox("enable");
floodCoolantCheck.setName("flood-coolant");
floodCoolantCheck.addItemListener(this);
add(floodCoolantLabel);
add(floodCoolantCheck,"wrap");
}
// mist coolant controls
if (t.hasMistCoolant()) {
JLabel mistCoolantLabel = makeLabel("Mist Coolant");
JCheckBox mistCoolantCheck = new JCheckBox("enable");
mistCoolantCheck.setName("mist-coolant");
mistCoolantCheck.addItemListener(this);
add(mistCoolantLabel);
add(mistCoolantCheck,"wrap");
}
// cooling fan controls
if (t.hasFan()) {
String fanString = "Cooling Fan";
String enableString = "enable";
Element xml = findMappingNode(t.getXml(),"fan");
if (xml != null) {
fanString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel fanLabel = makeLabel(fanString);
JCheckBox fanCheck = new JCheckBox(enableString);
fanCheck.setName("fan-check");
fanCheck.addItemListener(this);
add(fanLabel);
add(fanCheck,"wrap");
}
// cooling fan controls
if (t.hasAutomatedPlatform()) {
String abpString = "Build platform belt";
String enableString = "enable";
JLabel abpLabel = makeLabel(abpString);
JCheckBox abpCheck = new JCheckBox(enableString);
abpCheck.setName("abp-check");
abpCheck.addItemListener(this);
add(abpLabel);
add(abpCheck,"wrap");
}
// valve controls
if (t.hasValve()) {
String valveString = "Valve";
String enableString = "open";
Element xml = findMappingNode(t.getXml(),"valve");
if (xml != null) {
valveString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel valveLabel = makeLabel(valveString);
JCheckBox valveCheck = new JCheckBox(enableString);
valveCheck.setName("valve-check");
valveCheck.addItemListener(this);
add(valveLabel);
add(valveCheck,"wrap");
}
// valve controls
if (t.hasCollet()) {
JLabel colletLabel = makeLabel("Collet");
JCheckBox colletCheck = new JCheckBox("open");
colletCheck.setName("collet-check");
colletCheck.addItemListener(this);
JPanel colletPanel = new JPanel();
colletPanel.setLayout(new BoxLayout(colletPanel,
BoxLayout.LINE_AXIS));
colletPanel.setMaximumSize(panelSize);
colletPanel.setMinimumSize(panelSize);
colletPanel.setPreferredSize(panelSize);
add(colletLabel);
add(colletCheck,"wrap");
}
}
|
diff --git a/src/org/rascalmpl/library/vis/util/KeySymTranslate.java b/src/org/rascalmpl/library/vis/util/KeySymTranslate.java
index ad5f661cf5..00ef7b8f5f 100644
--- a/src/org/rascalmpl/library/vis/util/KeySymTranslate.java
+++ b/src/org/rascalmpl/library/vis/util/KeySymTranslate.java
@@ -1,121 +1,121 @@
package org.rascalmpl.library.vis.util;
import org.eclipse.imp.pdb.facts.IMap;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.impl.fast.ValueFactory;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.rascalmpl.interpreter.IEvaluatorContext;
import static org.rascalmpl.library.vis.KeySymFactory.*;
public class KeySymTranslate {
static final Type[] empty = {};
// static final Type[] modifiers = {"modCtrl","modCommand","modAlt","modShift"};
static final Type[] modifiers = {KeyModifier_modCtrl,KeyModifier_modCommand,KeyModifier_modAlt,KeyModifier_modShift};
static final int[] modifiersSWT = {SWT.CTRL, SWT.COMMAND, SWT.ALT, SWT.SHIFT };
public static IMap toRascalModifiers(KeyEvent e,IMap prevMap,IEvaluatorContext ctx){
ValueFactory vf = ValueFactory.getInstance();
for(int i = 0 ; i < modifiers.length ;i++){
Type controlType = modifiers[i];
IValue cons = vf.constructor(controlType);
prevMap = prevMap.put(cons, vf.bool((e.stateMask & modifiersSWT[i]) != 0));
}
return prevMap;
}
public static IValue toRascalKey(KeyEvent e,IEvaluatorContext ctx){
ValueFactory vf = ValueFactory.getInstance();
if(e.keyCode >= ' ' && e.keyCode < '~'){
String keySym = "" + (char)e.keyCode;
return vf.constructor(KeySym_keyPrintable, vf.string(keySym));
} else {
Type cons = unPrintableKeyName(e);
if(cons == KeySym_keyUnknown){
return vf.constructor(KeySym_keyUnknown,vf.integer(e.keyCode));
} else {
return vf.constructor(cons);
}
}
}
public static Type unPrintableKeyName(KeyEvent e){
switch(e.keyCode){
case SWT.ALT:
if(e.keyCode == SWT.LEFT) return KeySym_keyAltLeft;
else return KeySym_keyAltRight;
case SWT.ARROW_DOWN: return KeySym_keyArrowDown;
case SWT.ARROW_LEFT: return KeySym_keyArrowLeft;
case SWT.ARROW_RIGHT: return KeySym_keyArrowRight;
case SWT.ARROW_UP: return KeySym_keyArrowUp;
case SWT.BREAK: return KeySym_keyBreak;
case SWT.CAPS_LOCK: return KeySym_keyCapsLock;
- case SWT.COMMAND:
- if(e.keyLocation == SWT.LEFT) return KeySym_keyCommandLeft;
- else return KeySym_keyCommandRight;
- case SWT.CTRL:
- if(e.keyLocation == SWT.LEFT) return KeySym_keyControlLeft;
- else return KeySym_keyControlRight;
+ case SWT.COMMAND: return KeySym_keyCommandLeft;
+ //if(e.keyLocation == SWT.LEFT) return KeySym_keyCommandLeft;
+ //else return KeySym_keyCommandRight;
+ case SWT.CTRL: return KeySym_keyControlLeft;
+ //if(e.keyLocation == SWT.LEFT) return KeySym_keyControlLeft;
+ //else return KeySym_keyControlRight;
case SWT.END: return KeySym_keyEnd;
case SWT.F1: return KeySym_keyF1;
case SWT.F10: return KeySym_keyF10;
case SWT.F11: return KeySym_keyF11;
case SWT.F12: return KeySym_keyF12;
case SWT.F13: return KeySym_keyF13;
case SWT.F14: return KeySym_keyF14;
case SWT.F15: return KeySym_keyF15;
- case SWT.F16: return KeySym_keyF16;
- case SWT.F17: return KeySym_keyF17;
- case SWT.F18: return KeySym_keyF18;
- case SWT.F19: return KeySym_keyF19;
+ //case SWT.F16: return KeySym_keyF16;
+ //case SWT.F17: return KeySym_keyF17;
+ //case SWT.F18: return KeySym_keyF18;
+ //case SWT.F19: return KeySym_keyF19;
case SWT.F2: return KeySym_keyF2;
- case SWT.F20: return KeySym_keyF20;
+ //case SWT.F20: return KeySym_keyF20;
case SWT.F3: return KeySym_keyF3;
case SWT.F4: return KeySym_keyF4;
case SWT.F5: return KeySym_keyF5;
case SWT.F6: return KeySym_keyF6;
case SWT.F7: return KeySym_keyF7;
case SWT.F8: return KeySym_keyF8;
case SWT.F9: return KeySym_keyF9;
case SWT.HELP: return KeySym_keyHelp;
case SWT.HOME: return KeySym_keyHome;
case SWT.INSERT: return KeySym_keyInsert;
case SWT.KEYPAD_0: return KeySym_keyKeypad0;
case SWT.KEYPAD_1: return KeySym_keyKeypad1;
case SWT.KEYPAD_2: return KeySym_keyKeypad2;
case SWT.KEYPAD_3: return KeySym_keyKeypad3;
case SWT.KEYPAD_4: return KeySym_keyKeypad4;
case SWT.KEYPAD_5: return KeySym_keyKeypad5;
case SWT.KEYPAD_6: return KeySym_keyKeypad6;
case SWT.KEYPAD_7: return KeySym_keyKeypad7;
case SWT.KEYPAD_8: return KeySym_keyKeypad8;
case SWT.KEYPAD_9: return KeySym_keyKeypad9;
case SWT.KEYPAD_ADD: return KeySym_keyKeypadAdd;
case SWT.KEYPAD_CR: return KeySym_keyKeypadCr;
case SWT.KEYPAD_DECIMAL: return KeySym_keyKeypadDecimal;
case SWT.KEYPAD_DIVIDE: return KeySym_keyKeypadDivide;
case SWT.KEYPAD_EQUAL: return KeySym_keyKeypadEqual;
case SWT.KEYPAD_MULTIPLY: return KeySym_keyKeypadMultiply;
case SWT.KEYPAD_SUBTRACT: return KeySym_keyKeypadSubtract;
case SWT.NUM_LOCK: return KeySym_keyNumLock;
case SWT.PAGE_DOWN: return KeySym_keyPageDown;
case SWT.PAGE_UP: return KeySym_keyPageUp;
case SWT.PAUSE: return KeySym_keyPause;
case SWT.PRINT_SCREEN: return KeySym_keyPrintScreen;
case SWT.SCROLL_LOCK: return KeySym_keyScrollLock;
- case SWT.SHIFT:
- if(e.keyLocation == SWT.LEFT) return KeySym_keyShiftLeft;
- else return KeySym_keyShiftRight;
+ case SWT.SHIFT: return KeySym_keyShiftLeft;
+ //if(e.keyLocation == SWT.LEFT) return KeySym_keyShiftLeft;
+ //else return KeySym_keyShiftRight;
case 8 : return KeySym_keyBackSpace;
case '\t': return KeySym_keyTab;
case 13: return KeySym_keyEnter;
case 27: return KeySym_keyEscape;
default: return KeySym_keyUnknown;
}
}
}
| false | true | public static Type unPrintableKeyName(KeyEvent e){
switch(e.keyCode){
case SWT.ALT:
if(e.keyCode == SWT.LEFT) return KeySym_keyAltLeft;
else return KeySym_keyAltRight;
case SWT.ARROW_DOWN: return KeySym_keyArrowDown;
case SWT.ARROW_LEFT: return KeySym_keyArrowLeft;
case SWT.ARROW_RIGHT: return KeySym_keyArrowRight;
case SWT.ARROW_UP: return KeySym_keyArrowUp;
case SWT.BREAK: return KeySym_keyBreak;
case SWT.CAPS_LOCK: return KeySym_keyCapsLock;
case SWT.COMMAND:
if(e.keyLocation == SWT.LEFT) return KeySym_keyCommandLeft;
else return KeySym_keyCommandRight;
case SWT.CTRL:
if(e.keyLocation == SWT.LEFT) return KeySym_keyControlLeft;
else return KeySym_keyControlRight;
case SWT.END: return KeySym_keyEnd;
case SWT.F1: return KeySym_keyF1;
case SWT.F10: return KeySym_keyF10;
case SWT.F11: return KeySym_keyF11;
case SWT.F12: return KeySym_keyF12;
case SWT.F13: return KeySym_keyF13;
case SWT.F14: return KeySym_keyF14;
case SWT.F15: return KeySym_keyF15;
case SWT.F16: return KeySym_keyF16;
case SWT.F17: return KeySym_keyF17;
case SWT.F18: return KeySym_keyF18;
case SWT.F19: return KeySym_keyF19;
case SWT.F2: return KeySym_keyF2;
case SWT.F20: return KeySym_keyF20;
case SWT.F3: return KeySym_keyF3;
case SWT.F4: return KeySym_keyF4;
case SWT.F5: return KeySym_keyF5;
case SWT.F6: return KeySym_keyF6;
case SWT.F7: return KeySym_keyF7;
case SWT.F8: return KeySym_keyF8;
case SWT.F9: return KeySym_keyF9;
case SWT.HELP: return KeySym_keyHelp;
case SWT.HOME: return KeySym_keyHome;
case SWT.INSERT: return KeySym_keyInsert;
case SWT.KEYPAD_0: return KeySym_keyKeypad0;
case SWT.KEYPAD_1: return KeySym_keyKeypad1;
case SWT.KEYPAD_2: return KeySym_keyKeypad2;
case SWT.KEYPAD_3: return KeySym_keyKeypad3;
case SWT.KEYPAD_4: return KeySym_keyKeypad4;
case SWT.KEYPAD_5: return KeySym_keyKeypad5;
case SWT.KEYPAD_6: return KeySym_keyKeypad6;
case SWT.KEYPAD_7: return KeySym_keyKeypad7;
case SWT.KEYPAD_8: return KeySym_keyKeypad8;
case SWT.KEYPAD_9: return KeySym_keyKeypad9;
case SWT.KEYPAD_ADD: return KeySym_keyKeypadAdd;
case SWT.KEYPAD_CR: return KeySym_keyKeypadCr;
case SWT.KEYPAD_DECIMAL: return KeySym_keyKeypadDecimal;
case SWT.KEYPAD_DIVIDE: return KeySym_keyKeypadDivide;
case SWT.KEYPAD_EQUAL: return KeySym_keyKeypadEqual;
case SWT.KEYPAD_MULTIPLY: return KeySym_keyKeypadMultiply;
case SWT.KEYPAD_SUBTRACT: return KeySym_keyKeypadSubtract;
case SWT.NUM_LOCK: return KeySym_keyNumLock;
case SWT.PAGE_DOWN: return KeySym_keyPageDown;
case SWT.PAGE_UP: return KeySym_keyPageUp;
case SWT.PAUSE: return KeySym_keyPause;
case SWT.PRINT_SCREEN: return KeySym_keyPrintScreen;
case SWT.SCROLL_LOCK: return KeySym_keyScrollLock;
case SWT.SHIFT:
if(e.keyLocation == SWT.LEFT) return KeySym_keyShiftLeft;
else return KeySym_keyShiftRight;
case 8 : return KeySym_keyBackSpace;
case '\t': return KeySym_keyTab;
case 13: return KeySym_keyEnter;
case 27: return KeySym_keyEscape;
default: return KeySym_keyUnknown;
}
}
| public static Type unPrintableKeyName(KeyEvent e){
switch(e.keyCode){
case SWT.ALT:
if(e.keyCode == SWT.LEFT) return KeySym_keyAltLeft;
else return KeySym_keyAltRight;
case SWT.ARROW_DOWN: return KeySym_keyArrowDown;
case SWT.ARROW_LEFT: return KeySym_keyArrowLeft;
case SWT.ARROW_RIGHT: return KeySym_keyArrowRight;
case SWT.ARROW_UP: return KeySym_keyArrowUp;
case SWT.BREAK: return KeySym_keyBreak;
case SWT.CAPS_LOCK: return KeySym_keyCapsLock;
case SWT.COMMAND: return KeySym_keyCommandLeft;
//if(e.keyLocation == SWT.LEFT) return KeySym_keyCommandLeft;
//else return KeySym_keyCommandRight;
case SWT.CTRL: return KeySym_keyControlLeft;
//if(e.keyLocation == SWT.LEFT) return KeySym_keyControlLeft;
//else return KeySym_keyControlRight;
case SWT.END: return KeySym_keyEnd;
case SWT.F1: return KeySym_keyF1;
case SWT.F10: return KeySym_keyF10;
case SWT.F11: return KeySym_keyF11;
case SWT.F12: return KeySym_keyF12;
case SWT.F13: return KeySym_keyF13;
case SWT.F14: return KeySym_keyF14;
case SWT.F15: return KeySym_keyF15;
//case SWT.F16: return KeySym_keyF16;
//case SWT.F17: return KeySym_keyF17;
//case SWT.F18: return KeySym_keyF18;
//case SWT.F19: return KeySym_keyF19;
case SWT.F2: return KeySym_keyF2;
//case SWT.F20: return KeySym_keyF20;
case SWT.F3: return KeySym_keyF3;
case SWT.F4: return KeySym_keyF4;
case SWT.F5: return KeySym_keyF5;
case SWT.F6: return KeySym_keyF6;
case SWT.F7: return KeySym_keyF7;
case SWT.F8: return KeySym_keyF8;
case SWT.F9: return KeySym_keyF9;
case SWT.HELP: return KeySym_keyHelp;
case SWT.HOME: return KeySym_keyHome;
case SWT.INSERT: return KeySym_keyInsert;
case SWT.KEYPAD_0: return KeySym_keyKeypad0;
case SWT.KEYPAD_1: return KeySym_keyKeypad1;
case SWT.KEYPAD_2: return KeySym_keyKeypad2;
case SWT.KEYPAD_3: return KeySym_keyKeypad3;
case SWT.KEYPAD_4: return KeySym_keyKeypad4;
case SWT.KEYPAD_5: return KeySym_keyKeypad5;
case SWT.KEYPAD_6: return KeySym_keyKeypad6;
case SWT.KEYPAD_7: return KeySym_keyKeypad7;
case SWT.KEYPAD_8: return KeySym_keyKeypad8;
case SWT.KEYPAD_9: return KeySym_keyKeypad9;
case SWT.KEYPAD_ADD: return KeySym_keyKeypadAdd;
case SWT.KEYPAD_CR: return KeySym_keyKeypadCr;
case SWT.KEYPAD_DECIMAL: return KeySym_keyKeypadDecimal;
case SWT.KEYPAD_DIVIDE: return KeySym_keyKeypadDivide;
case SWT.KEYPAD_EQUAL: return KeySym_keyKeypadEqual;
case SWT.KEYPAD_MULTIPLY: return KeySym_keyKeypadMultiply;
case SWT.KEYPAD_SUBTRACT: return KeySym_keyKeypadSubtract;
case SWT.NUM_LOCK: return KeySym_keyNumLock;
case SWT.PAGE_DOWN: return KeySym_keyPageDown;
case SWT.PAGE_UP: return KeySym_keyPageUp;
case SWT.PAUSE: return KeySym_keyPause;
case SWT.PRINT_SCREEN: return KeySym_keyPrintScreen;
case SWT.SCROLL_LOCK: return KeySym_keyScrollLock;
case SWT.SHIFT: return KeySym_keyShiftLeft;
//if(e.keyLocation == SWT.LEFT) return KeySym_keyShiftLeft;
//else return KeySym_keyShiftRight;
case 8 : return KeySym_keyBackSpace;
case '\t': return KeySym_keyTab;
case 13: return KeySym_keyEnter;
case 27: return KeySym_keyEscape;
default: return KeySym_keyUnknown;
}
}
|
diff --git a/src/main/java/com/concursive/connect/web/controller/servlets/LinkGenerator.java b/src/main/java/com/concursive/connect/web/controller/servlets/LinkGenerator.java
index 9554f5d..48822c2 100644
--- a/src/main/java/com/concursive/connect/web/controller/servlets/LinkGenerator.java
+++ b/src/main/java/com/concursive/connect/web/controller/servlets/LinkGenerator.java
@@ -1,237 +1,237 @@
/*
* ConcourseConnect
* Copyright 2009 Concursive Corporation
* http://www.concursive.com
*
* This file is part of ConcourseConnect, an open source social business
* software and community platform.
*
* Concursive ConcourseConnect 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, version 3 of the License.
*
* Under the terms of the GNU Affero General Public License you must release the
* complete source code for any application that uses any part of ConcourseConnect
* (system header files and libraries used by the operating system are excluded).
* These terms must be included in any work that has ConcourseConnect components.
* If you are developing and distributing open source applications under the
* GNU Affero General Public License, then you are free to use ConcourseConnect
* under the GNU Affero General Public License.
*
* If you are deploying a web site in which users interact with any portion of
* ConcourseConnect over a network, the complete source code changes must be made
* available. For example, include a link to the source archive directly from
* your web site.
*
* For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their
* products, and do not license and distribute their source code under the GNU
* Affero General Public License, Concursive provides a flexible commercial
* license.
*
* To anyone in doubt, we recommend the commercial license. Our commercial license
* is competitively priced and will eliminate any confusion about how
* ConcourseConnect can be used and distributed.
*
* ConcourseConnect 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 ConcourseConnect. If not, see <http://www.gnu.org/licenses/>.
*
* Attribution Notice: ConcourseConnect is an Original Work of software created
* by Concursive Corporation
*/
package com.concursive.connect.web.controller.servlets;
import com.concursive.commons.text.StringUtils;
import com.concursive.connect.Constants;
import com.concursive.connect.web.controller.beans.URLControllerBean;
import com.concursive.connect.web.modules.issues.utils.TicketUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Static methods for building and reusing specific urls
*
* @author matt rajkowski
* @created Apr 8, 2008
*/
public class LinkGenerator {
private static Log LOG = LogFactory.getLog(LinkGenerator.class);
public static String getProfileImageLink(int projectId, String imageUrl) {
return "Portal.do?command=Img&pid=" + projectId + "&url=" + imageUrl;
}
public static String getRemoveProfileImageLink(int projectId, String imageUrl) {
return "ProjectManagementProfile.do?command=DeleteImg&pid=" + projectId + "&url=" + imageUrl;
}
public static String getSetProfileImageLink(int projectId, String imageUrl) {
return "ProjectManagementProfile.do?command=SetImg&pid=" + projectId + "&url=" + imageUrl;
}
public static String getDashboardLink(int projectId, String dashboard) {
return "ProjectManagement.do?command=ProjectCenter&portlet-section=Dashboard&pid=" + projectId + (dashboard != null ? "&dash=" + dashboard : "");
}
public static String getProjectPortalLink(URLControllerBean bean) {
if (LOG.isTraceEnabled()) {
LOG.trace(bean.toString());
}
return "ProjectManagement.do?command=ProjectCenter" +
"&portlet-action=" + StringUtils.toString(bean.getAction()) +
"&portlet-pid=" + bean.getProjectId() +
"&portlet-object=" + StringUtils.toString(bean.getDomainObject()) +
"&portlet-value=" + StringUtils.toString(bean.getObjectValue()) +
"&portlet-params=" + StringUtils.toString(bean.getParams());
}
/**
* Method for
*
* @param bean
* @return
*/
public static String getProjectActionLink(URLControllerBean bean) {
if (LOG.isTraceEnabled()) {
LOG.trace(bean.toString());
}
// Generate a servlet URL class action
String[] newAction = bean.getDomainObject().split("-");
StringBuffer actionBuffer = new StringBuffer();
for (String thisAction : newAction) {
actionBuffer.append(thisAction.substring(0, 1).toUpperCase()).append(thisAction.substring(1));
}
// Generate a servlet URL method command
return actionBuffer.toString() + ".do?command=" + bean.getAction().substring(0, 1).toUpperCase() + bean.getAction().substring(1) +
"&pid=" + bean.getProjectId() +
"&portlet-value=" + StringUtils.toString(bean.getObjectValue()) +
"&portlet-params=" + StringUtils.toString(bean.getParams());
}
public static String getBlogImageLink(int projectId, String image) {
return "BlogActions.do?command=Img&pid=" + projectId + "&subject=" + image;
}
public static String getWikiImageLink(int projectId, String image) {
return "ProjectManagementWiki.do?command=Img&pid=" + projectId + "&subject=" + image;
}
public static String getListsLink(int projectId) {
return "ProjectManagementListsBuckets.do?command=Categories&pid=" + projectId;
}
public static String getListDetailsLink(int projectId, int listId) {
return "ProjectManagement.do?command=ProjectCenter&portlet-section=Lists&pid=" + projectId + "&cid=" + listId;
}
public static String getPlanLink(int projectId) {
return "ProjectManagement.do?command=ProjectCenter&portlet-section=Requirements&pid=" + projectId;
}
public static String getPlanLink(int projectId, int planId) {
return "ProjectManagement.do?command=ProjectCenter&portlet-section=Assignments&pid=" + projectId + "&rid=" + planId;
}
public static String getTicketsLink(int projectId) {
return "ProjectManagement.do?command=ProjectCenter&portlet-section=Tickets&pid=" + projectId;
}
public static String getTicketDetailsLink(int projectId, int projectTicketId) {
int ticketId = TicketUtils.retrieveTicketIdFromProjectTicketId(projectId, projectTicketId);
return "ProjectManagementTickets.do?command=Details&pid=" + projectId + "&id=" + ticketId;
}
public static String getTeamLink(int projectId) {
return "ProjectManagement.do?command=ProjectCenter&portlet-section=Team&pid=" + projectId;
}
public static String getAdsLink(int projectId) {
return "ProjectManagement.do?command=ProjectCenter&portlet-section=Ads&pid=" + projectId;
}
public static String getDetailsLink(int projectId) {
return "ProjectManagement.do?command=ProjectCenter&portlet-section=Details&pid=" + projectId;
}
public static String getSetupLink(int projectId) {
return "ProjectManagement.do?command=ProjectCenter&portlet-section=Setup&pid=" + projectId;
}
public static String getCustomizeLink(int projectId) {
return "ProjectManagement.do?command=CustomizeProject&pid=" + projectId;
}
public static String getPermissionsLink(int projectId) {
return "ProjectManagement.do?command=ConfigurePermissions&pid=" + projectId;
}
public static String getCustomizeStyleLink(int projectId) {
return "ProjectManagement.do?command=CustomizeStyle&pid=" + projectId;
}
public static String getStyleImageLink(int projectId, String image) {
return "ProjectManagement.do?command=StyleImg&pid=" + projectId + "&subject=" + image;
}
public static String getPageLink(int projectId, String page) {
return "ProjectManagementPage.do?command=ShowPortalPage&pid=" + projectId + "&name=" + page;
}
public static String getToolsLink(int projectId, String url) {
return "ProjectManagementTools.do?command=Default&pid=" + projectId + "&linkTo=" + url;
}
public static String getItemLink(int linkModuleId, int linkItemId, int linkAnchor) {
return (getItemLink(linkModuleId, linkItemId) + "#" + linkAnchor);
}
public static String getItemLink(int linkModuleId, int linkItemId) {
return getItemLink(linkModuleId, String.valueOf(linkItemId));
}
/**
* Return the link to the item (an promotion, classified or blog)
* TODO: may be there is a better way to do this as this information is already in project-portal-config.xml
*
* @param linkModuleId the module's id
* @param linkItemId the object's id within the module
* @return the object's url part
*/
public static String getItemLink(int linkModuleId, String linkItemId) {
String itemLink = null;
if (linkModuleId != -1) {
if (linkModuleId == Constants.PROJECT_CLASSIFIEDS_FILES) {
itemLink = "classified-ad/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_BLOG_FILES) {
itemLink = "post/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_AD_FILES) {
itemLink = "promotion/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_REVIEW_FILES) {
itemLink = "review/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_WIKI_FILES) {
itemLink = "wiki"; //TODO: needs to consider wiki subject
} else if (linkModuleId == Constants.DISCUSSION_FILES_TOPIC) {
- itemLink = "post/" + linkItemId;
+ itemLink = "topic/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_WIKI_COMMENT_FILES) {
itemLink = "wiki"; //TODO: needs to consider wiki subject
} else if (linkModuleId == Constants.BLOG_POST_COMMENT_FILES) {
itemLink = "post/" + linkItemId;
} else if (linkModuleId == Constants.PROJECTS_FILES) {
itemLink = "file/" + linkItemId;
} else if (linkModuleId == Constants.PROJECTS_CALENDAR_EVENT_FILES) {
itemLink = "calendar/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_IMAGE_FILES) {
itemLink = "";
} else if (linkModuleId == Constants.PROJECT_MESSAGES_FILES) {
itemLink = "message/inbox/" + linkItemId;
}
}
return itemLink;
}
}
| true | true | public static String getItemLink(int linkModuleId, String linkItemId) {
String itemLink = null;
if (linkModuleId != -1) {
if (linkModuleId == Constants.PROJECT_CLASSIFIEDS_FILES) {
itemLink = "classified-ad/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_BLOG_FILES) {
itemLink = "post/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_AD_FILES) {
itemLink = "promotion/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_REVIEW_FILES) {
itemLink = "review/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_WIKI_FILES) {
itemLink = "wiki"; //TODO: needs to consider wiki subject
} else if (linkModuleId == Constants.DISCUSSION_FILES_TOPIC) {
itemLink = "post/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_WIKI_COMMENT_FILES) {
itemLink = "wiki"; //TODO: needs to consider wiki subject
} else if (linkModuleId == Constants.BLOG_POST_COMMENT_FILES) {
itemLink = "post/" + linkItemId;
} else if (linkModuleId == Constants.PROJECTS_FILES) {
itemLink = "file/" + linkItemId;
} else if (linkModuleId == Constants.PROJECTS_CALENDAR_EVENT_FILES) {
itemLink = "calendar/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_IMAGE_FILES) {
itemLink = "";
} else if (linkModuleId == Constants.PROJECT_MESSAGES_FILES) {
itemLink = "message/inbox/" + linkItemId;
}
}
return itemLink;
}
| public static String getItemLink(int linkModuleId, String linkItemId) {
String itemLink = null;
if (linkModuleId != -1) {
if (linkModuleId == Constants.PROJECT_CLASSIFIEDS_FILES) {
itemLink = "classified-ad/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_BLOG_FILES) {
itemLink = "post/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_AD_FILES) {
itemLink = "promotion/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_REVIEW_FILES) {
itemLink = "review/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_WIKI_FILES) {
itemLink = "wiki"; //TODO: needs to consider wiki subject
} else if (linkModuleId == Constants.DISCUSSION_FILES_TOPIC) {
itemLink = "topic/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_WIKI_COMMENT_FILES) {
itemLink = "wiki"; //TODO: needs to consider wiki subject
} else if (linkModuleId == Constants.BLOG_POST_COMMENT_FILES) {
itemLink = "post/" + linkItemId;
} else if (linkModuleId == Constants.PROJECTS_FILES) {
itemLink = "file/" + linkItemId;
} else if (linkModuleId == Constants.PROJECTS_CALENDAR_EVENT_FILES) {
itemLink = "calendar/" + linkItemId;
} else if (linkModuleId == Constants.PROJECT_IMAGE_FILES) {
itemLink = "";
} else if (linkModuleId == Constants.PROJECT_MESSAGES_FILES) {
itemLink = "message/inbox/" + linkItemId;
}
}
return itemLink;
}
|
diff --git a/src/com/ijuru/refract/activity/SettingsActivity.java b/src/com/ijuru/refract/activity/SettingsActivity.java
index c00618d..65f2546 100644
--- a/src/com/ijuru/refract/activity/SettingsActivity.java
+++ b/src/com/ijuru/refract/activity/SettingsActivity.java
@@ -1,122 +1,122 @@
/**
* Copyright 2011 Rowan Seymour
*
* This file is part of Refract.
*
* Refract 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.
*
* Refract 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 Refract. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ijuru.refract.activity;
import com.ijuru.refract.R;
import com.ijuru.refract.utils.Utils;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.widget.Toast;
/**
* Activity for application preferences
*/
public class SettingsActivity extends PreferenceActivity implements OnPreferenceChangeListener {
private ListPreference iterFunctionPref, paletteMappingPref;
private EditTextPreference itersPerFramePref, paletteSizePref;
/**
* @see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
iterFunctionPref = (ListPreference)getPreferenceScreen().findPreference("iterfunction");
iterFunctionPref.setOnPreferenceChangeListener(this);
itersPerFramePref = (EditTextPreference)getPreferenceScreen().findPreference("itersperframe");
itersPerFramePref.setOnPreferenceChangeListener(this);
paletteMappingPref = (ListPreference)getPreferenceScreen().findPreference("palettemapping");
- iterFunctionPref.setOnPreferenceChangeListener(this);
+ paletteMappingPref.setOnPreferenceChangeListener(this);
paletteSizePref = (EditTextPreference)getPreferenceScreen().findPreference("palettesize");
paletteSizePref.setOnPreferenceChangeListener(this);
updatePreferenceSummary(iterFunctionPref, iterFunctionPref.getValue());
updatePreferenceSummary(itersPerFramePref, itersPerFramePref.getText());
updatePreferenceSummary(paletteMappingPref, paletteMappingPref.getValue());
updatePreferenceSummary(paletteSizePref, paletteSizePref.getText());
}
/**
* @see android.preference.Preference.OnPreferenceChangeListener#onPreferenceChange(Preference, Object)
*/
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
Resources res = getResources();
if (preference == itersPerFramePref) {
if (!validateRange(value, res.getInteger(R.integer.min_itersperframe), res.getInteger(R.integer.max_itersperframe)))
return false;
}
else if (preference == paletteSizePref) {
if (!validateRange(value, res.getInteger(R.integer.min_palettesize), res.getInteger(R.integer.max_palettesize)))
return false;
}
updatePreferenceSummary(preference, value);
return true;
}
/**
* Updates the summary of the given preference based on the given value (not necessarily the value itself)
* @param preference the preference
* @param value the value
*/
private void updatePreferenceSummary(Preference preference, Object value) {
if (preference instanceof ListPreference) {
ListPreference listPref = (ListPreference)preference;
CharSequence[] entries = listPref.getEntries();
int index = listPref.findIndexOfValue(value.toString());
if (index >= 0)
listPref.setSummary(entries[index]);
}
else {
preference.setSummary(value.toString());
}
}
/**
* Validates a integer value to check that it is in the given range
* @param value the integer value
* @param min the minimum
* @param max the maximum
* @return true if valid
*/
private boolean validateRange(Object value, int min, int max) {
Integer val = Utils.parseInteger(value.toString());
if (val == null || val < min || val > max) {
String message = String.format(getString(R.string.err_numberrange), min, max);
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
iterFunctionPref = (ListPreference)getPreferenceScreen().findPreference("iterfunction");
iterFunctionPref.setOnPreferenceChangeListener(this);
itersPerFramePref = (EditTextPreference)getPreferenceScreen().findPreference("itersperframe");
itersPerFramePref.setOnPreferenceChangeListener(this);
paletteMappingPref = (ListPreference)getPreferenceScreen().findPreference("palettemapping");
iterFunctionPref.setOnPreferenceChangeListener(this);
paletteSizePref = (EditTextPreference)getPreferenceScreen().findPreference("palettesize");
paletteSizePref.setOnPreferenceChangeListener(this);
updatePreferenceSummary(iterFunctionPref, iterFunctionPref.getValue());
updatePreferenceSummary(itersPerFramePref, itersPerFramePref.getText());
updatePreferenceSummary(paletteMappingPref, paletteMappingPref.getValue());
updatePreferenceSummary(paletteSizePref, paletteSizePref.getText());
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
iterFunctionPref = (ListPreference)getPreferenceScreen().findPreference("iterfunction");
iterFunctionPref.setOnPreferenceChangeListener(this);
itersPerFramePref = (EditTextPreference)getPreferenceScreen().findPreference("itersperframe");
itersPerFramePref.setOnPreferenceChangeListener(this);
paletteMappingPref = (ListPreference)getPreferenceScreen().findPreference("palettemapping");
paletteMappingPref.setOnPreferenceChangeListener(this);
paletteSizePref = (EditTextPreference)getPreferenceScreen().findPreference("palettesize");
paletteSizePref.setOnPreferenceChangeListener(this);
updatePreferenceSummary(iterFunctionPref, iterFunctionPref.getValue());
updatePreferenceSummary(itersPerFramePref, itersPerFramePref.getText());
updatePreferenceSummary(paletteMappingPref, paletteMappingPref.getValue());
updatePreferenceSummary(paletteSizePref, paletteSizePref.getText());
}
|
diff --git a/src/VASSAL/build/module/map/ImageSaver.java b/src/VASSAL/build/module/map/ImageSaver.java
index 230cec77..83b410a5 100644
--- a/src/VASSAL/build/module/map/ImageSaver.java
+++ b/src/VASSAL/build/module/map/ImageSaver.java
@@ -1,553 +1,553 @@
/*
* $Id$
*
* Copyright (c) 2000-2010 by Rodney Kinney, Joel Uckelman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.build.module.map;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.event.IIOWriteProgressListener;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.SwingUtilities;
import org.jdesktop.swingworker.SwingWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.AutoConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.Map;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.Configurer;
import VASSAL.configure.ConfigurerFactory;
import VASSAL.configure.IconConfigurer;
import VASSAL.i18n.Resources;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.LaunchButton;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.WriteErrorDialog;
import VASSAL.tools.filechooser.FileChooser;
import VASSAL.tools.io.IOUtils;
import VASSAL.tools.swing.ProgressDialog;
// FIXME: Replace this in 3.2 with tiling code.
/**
* This allows the user to capture a snapshot of the entire map into
* a PNG file.
*/
public class ImageSaver extends AbstractConfigurable {
private static final Logger logger =
LoggerFactory.getLogger(ImageSaver.class);
protected LaunchButton launch;
protected Map map;
protected boolean promptToSplit = false;
protected static final String DEFAULT_ICON = "/images/camera.gif";
protected static ProgressDialog dialog;
public ImageSaver() {
final ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
writeMapAsImage();
}
};
launch =
new LaunchButton(null, TOOLTIP, BUTTON_TEXT, HOTKEY, ICON_NAME, al);
// Set defaults for backward compatibility
launch.setAttribute(TOOLTIP, "Save Map as PNG image");
launch.setAttribute(BUTTON_TEXT, "");
launch.setAttribute(ICON_NAME, DEFAULT_ICON);
}
public ImageSaver(Map m) {
super();
map = m;
}
/**
* Expects to be added to a {@link Map}. Adds a button to the map window
* toolbar that initiates the capture
*/
public void addTo(Buildable b) {
map = (Map) b;
map.getToolBar().add(launch);
}
public void removeFrom(Buildable b) {
map = (Map) b;
map.getToolBar().remove(launch);
map.getToolBar().revalidate();
}
protected static final String HOTKEY = "hotkey";
protected static final String BUTTON_TEXT = "buttonText";
protected static final String TOOLTIP = "tooltip";
protected static final String ICON_NAME = "icon";
public String[] getAttributeNames() {
return new String[] {
BUTTON_TEXT,
TOOLTIP,
ICON_NAME,
HOTKEY
};
}
public String[] getAttributeDescriptions() {
return new String[] {
Resources.getString(Resources.BUTTON_TEXT),
Resources.getString(Resources.TOOLTIP_TEXT),
Resources.getString(Resources.BUTTON_ICON),
Resources.getString(Resources.HOTKEY_LABEL),
};
}
public Class<?>[] getAttributeTypes() {
return new Class<?>[] {
String.class,
String.class,
IconConfig.class,
NamedKeyStroke.class
};
}
public static class IconConfig implements ConfigurerFactory {
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new IconConfigurer(key, name, DEFAULT_ICON);
}
}
public void setAttribute(String key, Object value) {
launch.setAttribute(key, value);
}
public String getAttributeValueString(String key) {
return launch.getAttributeValueString(key);
}
/**
* Write a PNG-encoded snapshot of the map.
*/
public void writeMapAsImage() {
// prompt user for image filename
final FileChooser fc = GameModule.getGameModule().getFileChooser();
fc.setSelectedFile(new File(fc.getCurrentDirectory(),
GameModule.getGameModule().getLocalizedGameName() + "Map.png"));
final Frame frame =
(Frame) SwingUtilities.getAncestorOfClass(Frame.class, map.getView());
if (fc.showSaveDialog(frame) != FileChooser.APPROVE_OPTION) return;
final File file = fc.getSelectedFile();
dialog = new ProgressDialog(frame, "Saving Map Image",
"Saving map image...");
// force the dialog to be a reasonable width
// FIXME: this is not really a good way to do this---should do
// something with the minimum size or font metrics
final int l = "Saving map image as ".length() + file.getName().length() + 6;
final StringBuilder b = new StringBuilder();
for (int i = 0; i < l; i++) b.append("N");
dialog.setLabel(b.toString());
dialog.pack();
dialog.setLabel("Saving map image as ");
dialog.setIndeterminate(true);
dialog.setLocationRelativeTo(frame);
// get the dimensions of the image to write
final Dimension s = map.mapSize();
if (s.width == 0) s.width = 1;
if (s.height == 0) s.height = 1;
int w = (int) Math.round(s.width * map.getZoom());
int h = (int) Math.round(s.height * map.getZoom());
// ensure that the resulting image is at least 1x1
if (w < 1 || h < 1) {
if (s.width < s.height) {
w = 1;
h = s.height/s.width;
}
else {
h = 1;
w = s.width/s.height;
}
}
writeMapRectAsImage(file, 0, 0, w, h);
dialog.setVisible(true);
}
/**
* Helper method for writing images.
*
* @param file the file to write
* @param x the left edge of the map area to write
* @param y the top edge of the map area to write
* @param w the width of the map area to write
* @param h the height of the map area to write
*/
protected void writeMapRectAsImage(File file, int x, int y, int w, int h) {
final SnapshotTask task = new SnapshotTask(file, x, y, w, h);
task.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if ("progress".equals(e.getPropertyName())) {
dialog.setProgress((Integer) e.getNewValue());
}
else if ("state".equals(e.getPropertyName())) {
if ((SwingWorker.StateValue) e.getNewValue() ==
SwingWorker.StateValue.DONE) {
// close the dialog on cancellation or completion
dialog.setVisible(false);
dialog.dispose();
}
}
}
});
dialog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
task.cancel(true);
}
});
task.execute();
}
private class SnapshotTask extends SwingWorker<Void,Void> {
private int tiles;
private int tilesDone = 0;
private final File file;
@SuppressWarnings("unused")
private final int x;
@SuppressWarnings("unused")
private final int y;
private final int w;
private final int h;
private final Color bg = ColorConfigurer.stringToColor(
map.getAttributeValueString(Map.BACKGROUND_COLOR));
private final List<File> files = new ArrayList<File>();
// FIXME: SnapshotTask ignores x,y!
public SnapshotTask(File file, int x, int y, int w, int h) {
this.file = file;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
private void writeImage(final File f, BufferedImage img, Rectangle r)
throws IOException {
files.add(f);
// make sure that we can write the file before proceeding
if (f.exists()) {
if (!f.canWrite()) {
throw new IOException(
"Cannot write to the file \"" + f.getAbsolutePath() + "\""
);
}
}
else {
final File p = f.getParentFile();
if (p.isDirectory() && !p.canWrite()) {
throw new IOException(
"Cannot write to the directory \"" + p.getAbsolutePath() + "\""
);
}
}
// update the dialog on the EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
dialog.setLabel("Saving map image as " + f.getName() + ":");
dialog.setIndeterminate(true);
}
});
// FIXME: do something to estimate how long painting will take
final Graphics2D g = img.createGraphics();
final Color oc = g.getColor();
g.setColor(bg);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
g.setColor(oc);
g.translate(-r.x, -r.y);
- map.paintRegion(g, r);
+ map.paintRegion(g, r, null);
g.dispose();
// update the dialog on the EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
dialog.setIndeterminate(false);
}
});
final ImageWriter iw = ImageIO.getImageWritersByFormatName("png").next();
iw.addIIOWriteProgressListener(new IIOWriteProgressListener() {
public void imageComplete(ImageWriter source) { }
public void imageProgress(ImageWriter source, float percentageDone) {
setProgress(Math.round((100*tilesDone + percentageDone)/tiles));
}
public void imageStarted(ImageWriter source, int imageIndex) { }
public void thumbnailComplete(ImageWriter source) { }
public void thumbnailProgress(ImageWriter source,
float percentageDone) { }
public void thumbnailStarted(ImageWriter source,
int imageIndex, int thumbnailIndex) { }
public void writeAborted(ImageWriter source) { }
});
ImageOutputStream os = null;
try {
os = ImageIO.createImageOutputStream(f);
if (os == null) {
throw new IOException("Failed to write file " + f.getAbsolutePath());
}
iw.setOutput(os);
iw.write(img);
os.close();
}
finally {
iw.dispose();
IOUtils.closeQuietly(os);
}
}
@Override
public Void doInBackground() throws IOException {
setProgress(0);
int tw = w;
int th = h;
BufferedImage img = null;
// ensure that the size of the image data array (4 bytes per pixel)
// does not exceed the maximum array size, 2^31-1 elements;
// otherwise we'll overflow an int and have a negavive array size
while ((long)tw * (long)th > Integer.MAX_VALUE/4) {
if (tw > th) {
tw = (int) Math.ceil(tw/2.0);
}
else {
th = (int) Math.ceil(th/2.0);
}
}
// find a size of BufferedImage we can allocate successfully
while (img == null) {
try {
img = new BufferedImage(tw, th, BufferedImage.TYPE_INT_ARGB);
}
catch (OutOfMemoryError e) {
if (tw > th) {
tw = (int) Math.ceil(tw/2.0);
}
else {
th = (int) Math.ceil(th/2.0);
}
}
}
if (tw == w && th == h) {
// write the whole map as one image
tiles = 1;
writeImage(file, img, new Rectangle(0, 0, w, h));
}
else {
// get the base name of the files to write
final String base;
final String suffix;
final String s = file.getName();
if (s.endsWith(".png")) {
base = s.substring(0, s.lastIndexOf('.'));
suffix = ".png";
}
else {
base = s;
suffix = "";
}
// calculate total tiles
final int tcols = (int) Math.ceil((double) w / tw);
final int trows = (int) Math.ceil((double) h / th);
tiles = tcols * trows;
// tile across the map with images of size tw by th.
for (int tx = 0; tx < tcols; ++tx) {
for (int ty = 0; ty < trows; ++ty) {
final File f = new File(file.getParent(),
base + "." + tx + "." + ty + suffix);
final Rectangle r = new Rectangle(
tw*tx,
th*ty,
Math.min(tw, w - tw*tx),
Math.min(th, h - th*ty)
);
writeImage(f, img, r);
++tilesDone;
}
}
}
return null;
}
@Override
protected void done() {
try {
get();
}
catch (CancellationException e) {
// on cancellation, remove all files we created
for (File f : files) f.delete();
}
catch (InterruptedException e) {
ErrorDialog.bug(e);
}
catch (ExecutionException e) {
final Throwable c = e.getCause();
if (c instanceof IOException) {
WriteErrorDialog.error(e, (IOException) c, files.get(files.size()-1));
}
else {
ErrorDialog.bug(e);
}
}
}
}
/**
* Write a PNG-encoded snapshot of the map to the given OutputStreams,
* dividing the map into vertical sections, one per stream
*
* @deprecated
*/
@Deprecated
public void writeImage(OutputStream[] out) throws IOException {
Dimension buffer = map.getEdgeBuffer();
int totalWidth =
(int) ((map.mapSize().width - 2 * buffer.width) * map.getZoom());
int totalHeight =
(int) ((map.mapSize().height - 2 * buffer.height) * map.getZoom());
for (int i = 0; i < out.length; ++i) {
int height = totalHeight / out.length;
if (i == out.length - 1) {
height = totalHeight - height * (out.length - 1);
}
Image output = map.getView().createImage(totalWidth, height);
Graphics2D gg = (Graphics2D) output.getGraphics();
map.paintRegion(gg, new Rectangle(
-(int) (map.getZoom() * buffer.width),
-(int) (map.getZoom() * buffer.height) + height * i,
totalWidth, totalHeight), null);
gg.dispose();
try {
MediaTracker t = new MediaTracker(map.getView());
t.addImage(output, 0);
t.waitForID(0);
}
catch (Exception e) {
logger.error("", e);
}
try {
if (output instanceof RenderedImage) {
ImageIO.write((RenderedImage) output, "png", out[i]);
}
else {
throw new IOException("Bad image type");
}
}
finally {
try {
out[i].close();
}
catch (IOException e) {
logger.error("", e);
}
}
}
}
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("Map.htm", "ImageCapture");
}
public static String getConfigureTypeName() {
return Resources.getString("Editor.ImageSaver.component_type"); //$NON-NLS-1$
}
public Class<?>[] getAllowableConfigureComponents() {
return new Class<?>[0];
}
}
| true | true | private void writeImage(final File f, BufferedImage img, Rectangle r)
throws IOException {
files.add(f);
// make sure that we can write the file before proceeding
if (f.exists()) {
if (!f.canWrite()) {
throw new IOException(
"Cannot write to the file \"" + f.getAbsolutePath() + "\""
);
}
}
else {
final File p = f.getParentFile();
if (p.isDirectory() && !p.canWrite()) {
throw new IOException(
"Cannot write to the directory \"" + p.getAbsolutePath() + "\""
);
}
}
// update the dialog on the EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
dialog.setLabel("Saving map image as " + f.getName() + ":");
dialog.setIndeterminate(true);
}
});
// FIXME: do something to estimate how long painting will take
final Graphics2D g = img.createGraphics();
final Color oc = g.getColor();
g.setColor(bg);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
g.setColor(oc);
g.translate(-r.x, -r.y);
map.paintRegion(g, r);
g.dispose();
// update the dialog on the EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
dialog.setIndeterminate(false);
}
});
final ImageWriter iw = ImageIO.getImageWritersByFormatName("png").next();
iw.addIIOWriteProgressListener(new IIOWriteProgressListener() {
public void imageComplete(ImageWriter source) { }
public void imageProgress(ImageWriter source, float percentageDone) {
setProgress(Math.round((100*tilesDone + percentageDone)/tiles));
}
public void imageStarted(ImageWriter source, int imageIndex) { }
public void thumbnailComplete(ImageWriter source) { }
public void thumbnailProgress(ImageWriter source,
float percentageDone) { }
public void thumbnailStarted(ImageWriter source,
int imageIndex, int thumbnailIndex) { }
public void writeAborted(ImageWriter source) { }
});
ImageOutputStream os = null;
try {
os = ImageIO.createImageOutputStream(f);
if (os == null) {
throw new IOException("Failed to write file " + f.getAbsolutePath());
}
iw.setOutput(os);
iw.write(img);
os.close();
}
finally {
iw.dispose();
IOUtils.closeQuietly(os);
}
}
| private void writeImage(final File f, BufferedImage img, Rectangle r)
throws IOException {
files.add(f);
// make sure that we can write the file before proceeding
if (f.exists()) {
if (!f.canWrite()) {
throw new IOException(
"Cannot write to the file \"" + f.getAbsolutePath() + "\""
);
}
}
else {
final File p = f.getParentFile();
if (p.isDirectory() && !p.canWrite()) {
throw new IOException(
"Cannot write to the directory \"" + p.getAbsolutePath() + "\""
);
}
}
// update the dialog on the EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
dialog.setLabel("Saving map image as " + f.getName() + ":");
dialog.setIndeterminate(true);
}
});
// FIXME: do something to estimate how long painting will take
final Graphics2D g = img.createGraphics();
final Color oc = g.getColor();
g.setColor(bg);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
g.setColor(oc);
g.translate(-r.x, -r.y);
map.paintRegion(g, r, null);
g.dispose();
// update the dialog on the EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
dialog.setIndeterminate(false);
}
});
final ImageWriter iw = ImageIO.getImageWritersByFormatName("png").next();
iw.addIIOWriteProgressListener(new IIOWriteProgressListener() {
public void imageComplete(ImageWriter source) { }
public void imageProgress(ImageWriter source, float percentageDone) {
setProgress(Math.round((100*tilesDone + percentageDone)/tiles));
}
public void imageStarted(ImageWriter source, int imageIndex) { }
public void thumbnailComplete(ImageWriter source) { }
public void thumbnailProgress(ImageWriter source,
float percentageDone) { }
public void thumbnailStarted(ImageWriter source,
int imageIndex, int thumbnailIndex) { }
public void writeAborted(ImageWriter source) { }
});
ImageOutputStream os = null;
try {
os = ImageIO.createImageOutputStream(f);
if (os == null) {
throw new IOException("Failed to write file " + f.getAbsolutePath());
}
iw.setOutput(os);
iw.write(img);
os.close();
}
finally {
iw.dispose();
IOUtils.closeQuietly(os);
}
}
|
diff --git a/src/main/java/net/gravitydevelopment/anticheat/command/CommandHandler.java b/src/main/java/net/gravitydevelopment/anticheat/command/CommandHandler.java
index 03ad189..5ca0a8b 100644
--- a/src/main/java/net/gravitydevelopment/anticheat/command/CommandHandler.java
+++ b/src/main/java/net/gravitydevelopment/anticheat/command/CommandHandler.java
@@ -1,68 +1,68 @@
/*
* AntiCheat for Bukkit.
* Copyright (C) 2012-2014 AntiCheat Team | http://gravitydevelopment.net
*
* 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 net.gravitydevelopment.anticheat.command;
import net.gravitydevelopment.anticheat.command.executors.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
public class CommandHandler implements CommandExecutor {
private List<CommandBase> commands = new ArrayList<CommandBase>();
public CommandHandler() {
commands.add(new CommandHelp());
commands.add(new CommandCalibrate());
commands.add(new CommandCheck());
commands.add(new CommandDebug());
commands.add(new CommandDeveloper());
commands.add(new CommandLog());
commands.add(new CommandReload());
commands.add(new CommandReport());
commands.add(new CommandReset());
commands.add(new CommandSpy());
commands.add(new CommandUpdate());
commands.add(new CommandXray());
}
@Override
public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) {
if (args.length >= 1) {
String command = args[0];
// Shift args down
String[] newArgs = new String[args.length-1];
for (int i=1;i<args.length;i++) {
newArgs[i-1] = args[i];
}
for (CommandBase base : commands) {
if (base.getCommand().equalsIgnoreCase(command)) {
- base.execute(cs, newArgs);
+ base.run(cs, newArgs);
}
}
} else {
// Send help
- commands.get(0).execute(cs, null);
+ commands.get(0).run(cs, null);
}
return true;
}
}
| false | true | public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) {
if (args.length >= 1) {
String command = args[0];
// Shift args down
String[] newArgs = new String[args.length-1];
for (int i=1;i<args.length;i++) {
newArgs[i-1] = args[i];
}
for (CommandBase base : commands) {
if (base.getCommand().equalsIgnoreCase(command)) {
base.execute(cs, newArgs);
}
}
} else {
// Send help
commands.get(0).execute(cs, null);
}
return true;
}
| public boolean onCommand(CommandSender cs, Command cmd, String alias, String[] args) {
if (args.length >= 1) {
String command = args[0];
// Shift args down
String[] newArgs = new String[args.length-1];
for (int i=1;i<args.length;i++) {
newArgs[i-1] = args[i];
}
for (CommandBase base : commands) {
if (base.getCommand().equalsIgnoreCase(command)) {
base.run(cs, newArgs);
}
}
} else {
// Send help
commands.get(0).run(cs, null);
}
return true;
}
|
diff --git a/src/edu/caltech/nanodb/commands/QueryCommand.java b/src/edu/caltech/nanodb/commands/QueryCommand.java
index 24519e8..0aa9943 100755
--- a/src/edu/caltech/nanodb/commands/QueryCommand.java
+++ b/src/edu/caltech/nanodb/commands/QueryCommand.java
@@ -1,163 +1,168 @@
package edu.caltech.nanodb.commands;
import java.io.IOException;
import edu.caltech.nanodb.qeval.PlanCost;
import org.apache.log4j.Logger;
import edu.caltech.nanodb.plans.PlanNode;
import edu.caltech.nanodb.qeval.EvalStats;
import edu.caltech.nanodb.qeval.QueryEvaluator;
import edu.caltech.nanodb.qeval.TupleProcessor;
import edu.caltech.nanodb.relations.SchemaNameException;
/**
* This class represents all SQL query commands, including <tt>SELECT</tt>,
* <tt>INSERT</tt>, <tt>UPDATE</tt>, and <tt>DELETE</tt>. The main difference
* between these commands is simply what happens with the tuples that are
* retrieved from the database.
*/
public abstract class QueryCommand extends Command {
/** Typesafe enumeration of query-command types. */
public enum Type {
/** A SELECT query, which simply retrieves rows of data. */
SELECT,
/** An INSERT query, which adds new rows of data to a table. */
INSERT,
/**
* An UPDATE query, which retrieves and then modifies rows of data in
* a table.
*/
UPDATE,
/**
* A DELETE query, which retrieves and then deletes rows of data in
* a table.
*/
DELETE
}
/** A logging object for reporting anything interesting that happens. */
private static Logger logger = Logger.getLogger(QueryCommand.class);
/** The type of this query command, from the {@link Type} enum. */
private QueryCommand.Type queryType;
protected PlanNode plan;
/**
* If this flag is true then the command is to be explained only. Otherwise
* the command is to be executed normally.
*/
protected boolean explain = false;
/**
* Initializes a new query-command object.
*
* @param queryType the kind of query command that is being executed
*/
protected QueryCommand(QueryCommand.Type queryType) {
super(Command.Type.DML);
this.queryType = queryType;
}
public void setExplain(boolean f) {
explain = f;
}
public void execute() throws ExecutionException {
try {
prepareQueryPlan();
if (!explain) {
// Debug: print out the plan and its costing details.
logger.debug("Generated execution plan:\n" +
PlanNode.printNodeTreeToString(plan, true));
PlanCost cost = plan.getCost();
if (cost != null) {
logger.debug(String.format(
"Estimated %f tuples with average size %f bytes",
cost.numTuples, cost.tupleSize));
logger.debug("Estimated number of block IOs: " +
cost.numBlockIOs);
logger.debug("Estimated CPU cost: " + cost.cpuCost);
}
// Execute the query plan, then print out the evaluation stats.
TupleProcessor processor = getTupleProcessor();
EvalStats stats = QueryEvaluator.executePlan(plan, processor);
// Print out the evaluation statistics.
out.printf("%s took %f sec to evaluate.%n", queryType,
stats.getElapsedTimeSecs());
String desc;
switch (queryType) {
case SELECT:
desc = "Selected ";
break;
case INSERT:
desc = "Inserted ";
break;
case UPDATE:
desc = "Updated ";
break;
case DELETE:
desc = "Deleted ";
break;
default:
desc = "(UNKNOWN) ";
}
out.println(desc + stats.getRowsProduced() + " rows.");
}
else {
out.println("Explain Plan:");
plan.printNodeTree(out, true, " ");
out.println();
PlanCost cost = plan.getCost();
- out.printf("Estimated %f tuples with average size %f%n",
- cost.numTuples, cost.tupleSize);
- out.println("Estimated number of block IOs: " +
- cost.numBlockIOs);
- logger.debug("Estimated CPU cost: " + cost.cpuCost);
+ if (cost != null) {
+ out.printf("Estimated %f tuples with average size %f%n",
+ cost.numTuples, cost.tupleSize);
+ out.println("Estimated number of block IOs: " +
+ cost.numBlockIOs);
+ logger.debug("Estimated CPU cost: " + cost.cpuCost);
+ }
+ else {
+ out.println("Plan cost is not available.");
+ }
}
}
catch (ExecutionException e) {
throw e;
}
catch (Exception e) {
throw new ExecutionException(e);
}
}
protected abstract void prepareQueryPlan()
throws IOException, SchemaNameException;
protected abstract TupleProcessor getTupleProcessor();
}
| true | true | public void execute() throws ExecutionException {
try {
prepareQueryPlan();
if (!explain) {
// Debug: print out the plan and its costing details.
logger.debug("Generated execution plan:\n" +
PlanNode.printNodeTreeToString(plan, true));
PlanCost cost = plan.getCost();
if (cost != null) {
logger.debug(String.format(
"Estimated %f tuples with average size %f bytes",
cost.numTuples, cost.tupleSize));
logger.debug("Estimated number of block IOs: " +
cost.numBlockIOs);
logger.debug("Estimated CPU cost: " + cost.cpuCost);
}
// Execute the query plan, then print out the evaluation stats.
TupleProcessor processor = getTupleProcessor();
EvalStats stats = QueryEvaluator.executePlan(plan, processor);
// Print out the evaluation statistics.
out.printf("%s took %f sec to evaluate.%n", queryType,
stats.getElapsedTimeSecs());
String desc;
switch (queryType) {
case SELECT:
desc = "Selected ";
break;
case INSERT:
desc = "Inserted ";
break;
case UPDATE:
desc = "Updated ";
break;
case DELETE:
desc = "Deleted ";
break;
default:
desc = "(UNKNOWN) ";
}
out.println(desc + stats.getRowsProduced() + " rows.");
}
else {
out.println("Explain Plan:");
plan.printNodeTree(out, true, " ");
out.println();
PlanCost cost = plan.getCost();
out.printf("Estimated %f tuples with average size %f%n",
cost.numTuples, cost.tupleSize);
out.println("Estimated number of block IOs: " +
cost.numBlockIOs);
logger.debug("Estimated CPU cost: " + cost.cpuCost);
}
}
catch (ExecutionException e) {
throw e;
}
catch (Exception e) {
throw new ExecutionException(e);
}
}
| public void execute() throws ExecutionException {
try {
prepareQueryPlan();
if (!explain) {
// Debug: print out the plan and its costing details.
logger.debug("Generated execution plan:\n" +
PlanNode.printNodeTreeToString(plan, true));
PlanCost cost = plan.getCost();
if (cost != null) {
logger.debug(String.format(
"Estimated %f tuples with average size %f bytes",
cost.numTuples, cost.tupleSize));
logger.debug("Estimated number of block IOs: " +
cost.numBlockIOs);
logger.debug("Estimated CPU cost: " + cost.cpuCost);
}
// Execute the query plan, then print out the evaluation stats.
TupleProcessor processor = getTupleProcessor();
EvalStats stats = QueryEvaluator.executePlan(plan, processor);
// Print out the evaluation statistics.
out.printf("%s took %f sec to evaluate.%n", queryType,
stats.getElapsedTimeSecs());
String desc;
switch (queryType) {
case SELECT:
desc = "Selected ";
break;
case INSERT:
desc = "Inserted ";
break;
case UPDATE:
desc = "Updated ";
break;
case DELETE:
desc = "Deleted ";
break;
default:
desc = "(UNKNOWN) ";
}
out.println(desc + stats.getRowsProduced() + " rows.");
}
else {
out.println("Explain Plan:");
plan.printNodeTree(out, true, " ");
out.println();
PlanCost cost = plan.getCost();
if (cost != null) {
out.printf("Estimated %f tuples with average size %f%n",
cost.numTuples, cost.tupleSize);
out.println("Estimated number of block IOs: " +
cost.numBlockIOs);
logger.debug("Estimated CPU cost: " + cost.cpuCost);
}
else {
out.println("Plan cost is not available.");
}
}
}
catch (ExecutionException e) {
throw e;
}
catch (Exception e) {
throw new ExecutionException(e);
}
}
|
diff --git a/sslr-tests/src/test/java/com/sonar/sslr/squid/checks/AbstractSingleLineCommentsSyntaxCheckTest.java b/sslr-tests/src/test/java/com/sonar/sslr/squid/checks/AbstractSingleLineCommentsSyntaxCheckTest.java
index b275e9d5..21323c18 100644
--- a/sslr-tests/src/test/java/com/sonar/sslr/squid/checks/AbstractSingleLineCommentsSyntaxCheckTest.java
+++ b/sslr-tests/src/test/java/com/sonar/sslr/squid/checks/AbstractSingleLineCommentsSyntaxCheckTest.java
@@ -1,35 +1,35 @@
/*
* Copyright (C) 2010 SonarSource SA
* All rights reserved
* mailto:contact AT sonarsource DOT com
*/
package com.sonar.sslr.squid.checks;
import com.sonar.sslr.test.miniC.MiniCGrammar;
import org.junit.Test;
import static com.sonar.sslr.squid.metrics.ResourceParser.*;
import static com.sonar.sslr.test.squid.CheckMatchers.*;
public class AbstractSingleLineCommentsSyntaxCheckTest {
private static class SingleLineCommentsSyntaxCheck extends AbstractSingleLineCommentsSyntaxCheck<MiniCGrammar> {
@Override
public String getSingleLineCommentSyntaxPrefix() {
return "//";
}
}
@Test
public void singleLineCommentsSyntax() {
- setCurrentSourceFile(scanFile("/checks/single_line_comment_syntax.mc", new SingleLineCommentsSyntaxCheck()));
+ setCurrentSourceFile(scanFile("/checks/single_line_comments_syntax.mc", new SingleLineCommentsSyntaxCheck()));
assertNumberOfViolations(2);
assertViolation().atLine(1).withMessage("This single line comment should use the single line comment syntax \"//\"");
assertViolation().atLine(15);
}
}
| true | true | public void singleLineCommentsSyntax() {
setCurrentSourceFile(scanFile("/checks/single_line_comment_syntax.mc", new SingleLineCommentsSyntaxCheck()));
assertNumberOfViolations(2);
assertViolation().atLine(1).withMessage("This single line comment should use the single line comment syntax \"//\"");
assertViolation().atLine(15);
}
| public void singleLineCommentsSyntax() {
setCurrentSourceFile(scanFile("/checks/single_line_comments_syntax.mc", new SingleLineCommentsSyntaxCheck()));
assertNumberOfViolations(2);
assertViolation().atLine(1).withMessage("This single line comment should use the single line comment syntax \"//\"");
assertViolation().atLine(15);
}
|
diff --git a/temp2/CA/src/DM.java b/temp2/CA/src/DM.java
index 9b6ee15..48227ff 100644
--- a/temp2/CA/src/DM.java
+++ b/temp2/CA/src/DM.java
@@ -1,33 +1,33 @@
import java.util.ArrayList;
public class DM {
ArrayList<String> memory = new ArrayList<String>();
ArrayList<String> index = new ArrayList<String>();
public String readData(String address){
if (index.contains(address)) {
int i = index.indexOf(address);
return memory.get(i);
} else {
return "null";
}
}
public void writeData(String address, String data){
long temp = 0;
String binaryValue = "";
index.add(address);
- memory.add(data.substring(0, 7));
+ memory.add(data.substring(0, 8));
temp = Long.parseLong(address,2)+1;
binaryValue = Long.toBinaryString(temp);
index.add(binaryValue);
- memory.add(data.substring(8, 15));
+ memory.add(data.substring(8, 16));
temp = Long.parseLong(address,2)+2;
binaryValue = Long.toBinaryString(temp);
index.add(binaryValue);
- memory.add(data.substring(16, 24));
+ memory.add(data.substring(16, 25));
temp = Long.parseLong(address,2)+3;
binaryValue = Long.toBinaryString(temp);
index.add(binaryValue);
- memory.add(data.substring(25, 31));
+ memory.add(data.substring(25, 32));
}
}
| false | true | public void writeData(String address, String data){
long temp = 0;
String binaryValue = "";
index.add(address);
memory.add(data.substring(0, 7));
temp = Long.parseLong(address,2)+1;
binaryValue = Long.toBinaryString(temp);
index.add(binaryValue);
memory.add(data.substring(8, 15));
temp = Long.parseLong(address,2)+2;
binaryValue = Long.toBinaryString(temp);
index.add(binaryValue);
memory.add(data.substring(16, 24));
temp = Long.parseLong(address,2)+3;
binaryValue = Long.toBinaryString(temp);
index.add(binaryValue);
memory.add(data.substring(25, 31));
}
| public void writeData(String address, String data){
long temp = 0;
String binaryValue = "";
index.add(address);
memory.add(data.substring(0, 8));
temp = Long.parseLong(address,2)+1;
binaryValue = Long.toBinaryString(temp);
index.add(binaryValue);
memory.add(data.substring(8, 16));
temp = Long.parseLong(address,2)+2;
binaryValue = Long.toBinaryString(temp);
index.add(binaryValue);
memory.add(data.substring(16, 25));
temp = Long.parseLong(address,2)+3;
binaryValue = Long.toBinaryString(temp);
index.add(binaryValue);
memory.add(data.substring(25, 32));
}
|
diff --git a/scjp/operators/Tricky.java b/scjp/operators/Tricky.java
index 025192d..45427f5 100644
--- a/scjp/operators/Tricky.java
+++ b/scjp/operators/Tricky.java
@@ -1,14 +1,14 @@
public class Tricky {
public static void main (String[] args) {
int x = 1;
if( (4 > x) ^ // true, x = 1
- ((++x + 2) > 3)) // true, x = 3
+ ((++x + 2) > 3)) // true, x = 2
x++; // does not execute, fails XOR
- if( (4 > ++x) ^ // false, x = 4
- !(++x == 5)) // false, x = 5 but !(expression) reserves the previous value of x
+ if( (4 > ++x) ^ // true, x = 3
+ !(++x == 5)) // true, x = 4
x++; // does not execute, fails XOR
System.out.println(x); // prints '4'
}
}
| false | true | public static void main (String[] args) {
int x = 1;
if( (4 > x) ^ // true, x = 1
((++x + 2) > 3)) // true, x = 3
x++; // does not execute, fails XOR
if( (4 > ++x) ^ // false, x = 4
!(++x == 5)) // false, x = 5 but !(expression) reserves the previous value of x
x++; // does not execute, fails XOR
System.out.println(x); // prints '4'
}
| public static void main (String[] args) {
int x = 1;
if( (4 > x) ^ // true, x = 1
((++x + 2) > 3)) // true, x = 2
x++; // does not execute, fails XOR
if( (4 > ++x) ^ // true, x = 3
!(++x == 5)) // true, x = 4
x++; // does not execute, fails XOR
System.out.println(x); // prints '4'
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java
index 042ef7173..82103a67c 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java
@@ -1,240 +1,240 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2005 Oliver Burn
//
// 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 com.puppycrawl.tools.checkstyle.checks.blocks;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.Utils;
import com.puppycrawl.tools.checkstyle.checks.AbstractOptionCheck;
/**
* <p>
* Checks the placement of left curly braces on types, methods and
* other blocks:
* {@link TokenTypes#LITERAL_CATCH LITERAL_CATCH}, {@link
* TokenTypes#LITERAL_DO LITERAL_DO}, {@link TokenTypes#LITERAL_ELSE
* LITERAL_ELSE}, {@link TokenTypes#LITERAL_FINALLY LITERAL_FINALLY}, {@link
* TokenTypes#LITERAL_FOR LITERAL_FOR}, {@link TokenTypes#LITERAL_IF
* LITERAL_IF}, {@link TokenTypes#LITERAL_SWITCH LITERAL_SWITCH}, {@link
* TokenTypes#LITERAL_SYNCHRONIZED LITERAL_SYNCHRONIZED}, {@link
* TokenTypes#LITERAL_TRY LITERAL_TRY}, {@link TokenTypes#LITERAL_WHILE
* LITERAL_WHILE}.
* </p>
*
* <p>
* The policy to verify is specified using the {@link LeftCurlyOption} class and
* defaults to {@link LeftCurlyOption#EOL}. Policies {@link LeftCurlyOption#EOL}
* and {@link LeftCurlyOption#NLOW} take into account property maxLineLength.
* The default value for maxLineLength is 80.
* </p>
* <p>
* An example of how to configure the check is:
* </p>
* <pre>
* <module name="LeftCurly"/>
* </pre>
* <p>
* An example of how to configure the check with policy
* {@link LeftCurlyOption#NLOW} and maxLineLength 120 is:
* </p>
* <pre>
* <module name="LeftCurly">
* <property name="option"
* value="nlow"/> <property name="maxLineLength" value="120"/> <
* /module>
* </pre>
*
* @author Oliver Burn
* @author lkuehne
* @version 1.0
*/
public class LeftCurlyCheck
extends AbstractOptionCheck
{
/** default maximum line length */
private static final int DEFAULT_MAX_LINE_LENGTH = 80;
/** TODO: replace this ugly hack **/
private int mMaxLineLength = DEFAULT_MAX_LINE_LENGTH;
/**
* Creates a default instance and sets the policy to EOL.
*/
public LeftCurlyCheck()
{
super(LeftCurlyOption.EOL);
}
/**
* Sets the maximum line length used in calculating the placement of the
* left curly brace.
* @param aMaxLineLength the max allowed line length
*/
public void setMaxLineLength(int aMaxLineLength)
{
mMaxLineLength = aMaxLineLength;
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getDefaultTokens()
{
return new int[] {
TokenTypes.INTERFACE_DEF,
TokenTypes.CLASS_DEF,
TokenTypes.ANNOTATION_DEF,
TokenTypes.ENUM_DEF,
TokenTypes.CTOR_DEF,
TokenTypes.METHOD_DEF,
TokenTypes.ENUM_CONSTANT_DEF,
TokenTypes.LITERAL_WHILE,
TokenTypes.LITERAL_TRY,
TokenTypes.LITERAL_CATCH,
TokenTypes.LITERAL_FINALLY,
TokenTypes.LITERAL_SYNCHRONIZED,
TokenTypes.LITERAL_SWITCH,
TokenTypes.LITERAL_DO,
TokenTypes.LITERAL_IF,
TokenTypes.LITERAL_ELSE,
TokenTypes.LITERAL_FOR,
// TODO: need to handle....
//TokenTypes.STATIC_INIT,
};
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public void visitToken(DetailAST aAST)
{
final DetailAST startToken;
final DetailAST brace;
switch (aAST.getType()) {
case TokenTypes.CTOR_DEF :
case TokenTypes.METHOD_DEF :
startToken = aAST;
brace = aAST.findFirstToken(TokenTypes.SLIST);
break;
case TokenTypes.INTERFACE_DEF :
case TokenTypes.CLASS_DEF :
case TokenTypes.ANNOTATION_DEF :
case TokenTypes.ENUM_DEF :
case TokenTypes.ENUM_CONSTANT_DEF :
startToken = (DetailAST) aAST.getFirstChild();
final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK);
brace = (objBlock == null)
- ? null
+ ? null
: (DetailAST) objBlock.getFirstChild();
break;
case TokenTypes.LITERAL_WHILE:
case TokenTypes.LITERAL_CATCH:
case TokenTypes.LITERAL_SYNCHRONIZED:
case TokenTypes.LITERAL_FOR:
case TokenTypes.LITERAL_TRY:
case TokenTypes.LITERAL_FINALLY:
case TokenTypes.LITERAL_DO:
case TokenTypes.LITERAL_IF :
startToken = aAST;
brace = aAST.findFirstToken(TokenTypes.SLIST);
break;
case TokenTypes.LITERAL_ELSE :
startToken = aAST;
final DetailAST candidate = (DetailAST) aAST.getFirstChild();
brace =
(candidate.getType() == TokenTypes.SLIST)
? candidate
: null; // silently ignore
break;
case TokenTypes.LITERAL_SWITCH :
startToken = aAST;
brace = aAST.findFirstToken(TokenTypes.LCURLY);
break;
default :
startToken = null;
brace = null;
}
if ((brace != null) && (startToken != null)) {
verifyBrace(brace, startToken);
}
}
/**
* Verifies that a specified left curly brace is placed correctly
* according to policy.
* @param aBrace token for left curly brace
* @param aStartToken token for start of expression
*/
private void verifyBrace(final DetailAST aBrace,
final DetailAST aStartToken)
{
final String braceLine = getLines()[aBrace.getLineNo() - 1];
// calculate the previous line length without trailing whitespace. Need
// to handle the case where there is no previous line, cause the line
// being check is the first line in the file.
final int prevLineLen = (aBrace.getLineNo() == 1)
? mMaxLineLength
: Utils.lengthMinusTrailingWhitespace(
getLines()[aBrace.getLineNo() - 2]);
// Check for being told to ignore, or have '{}' which is a special case
if ((braceLine.length() > (aBrace.getColumnNo() + 1))
&& (braceLine.charAt(aBrace.getColumnNo() + 1) == '}'))
{
; // ignore
}
else if (getAbstractOption() == LeftCurlyOption.NL) {
if (!Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)) {
log(aBrace.getLineNo(), aBrace.getColumnNo(),
"line.new", "{");
}
}
else if (getAbstractOption() == LeftCurlyOption.EOL) {
if (Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)
&& ((prevLineLen + 2) <= mMaxLineLength))
{
log(aBrace.getLineNo(), aBrace.getColumnNo(),
"line.previous", "{");
}
}
else if (getAbstractOption() == LeftCurlyOption.NLOW) {
if (aStartToken.getLineNo() == aBrace.getLineNo()) {
; // all ok as on the same line
}
else if ((aStartToken.getLineNo() + 1) == aBrace.getLineNo()) {
if (!Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)) {
log(aBrace.getLineNo(), aBrace.getColumnNo(),
"line.new", "{");
}
else if ((prevLineLen + 2) <= mMaxLineLength) {
log(aBrace.getLineNo(), aBrace.getColumnNo(),
"line.previous", "{");
}
}
else if (!Utils.whitespaceBefore(aBrace.getColumnNo(), braceLine)) {
log(aBrace.getLineNo(), aBrace.getColumnNo(),
"line.new", "{");
}
}
}
}
| true | true | public void visitToken(DetailAST aAST)
{
final DetailAST startToken;
final DetailAST brace;
switch (aAST.getType()) {
case TokenTypes.CTOR_DEF :
case TokenTypes.METHOD_DEF :
startToken = aAST;
brace = aAST.findFirstToken(TokenTypes.SLIST);
break;
case TokenTypes.INTERFACE_DEF :
case TokenTypes.CLASS_DEF :
case TokenTypes.ANNOTATION_DEF :
case TokenTypes.ENUM_DEF :
case TokenTypes.ENUM_CONSTANT_DEF :
startToken = (DetailAST) aAST.getFirstChild();
final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK);
brace = (objBlock == null)
? null
: (DetailAST) objBlock.getFirstChild();
break;
case TokenTypes.LITERAL_WHILE:
case TokenTypes.LITERAL_CATCH:
case TokenTypes.LITERAL_SYNCHRONIZED:
case TokenTypes.LITERAL_FOR:
case TokenTypes.LITERAL_TRY:
case TokenTypes.LITERAL_FINALLY:
case TokenTypes.LITERAL_DO:
case TokenTypes.LITERAL_IF :
startToken = aAST;
brace = aAST.findFirstToken(TokenTypes.SLIST);
break;
case TokenTypes.LITERAL_ELSE :
startToken = aAST;
final DetailAST candidate = (DetailAST) aAST.getFirstChild();
brace =
(candidate.getType() == TokenTypes.SLIST)
? candidate
: null; // silently ignore
break;
case TokenTypes.LITERAL_SWITCH :
startToken = aAST;
brace = aAST.findFirstToken(TokenTypes.LCURLY);
break;
default :
startToken = null;
brace = null;
}
if ((brace != null) && (startToken != null)) {
verifyBrace(brace, startToken);
}
}
| public void visitToken(DetailAST aAST)
{
final DetailAST startToken;
final DetailAST brace;
switch (aAST.getType()) {
case TokenTypes.CTOR_DEF :
case TokenTypes.METHOD_DEF :
startToken = aAST;
brace = aAST.findFirstToken(TokenTypes.SLIST);
break;
case TokenTypes.INTERFACE_DEF :
case TokenTypes.CLASS_DEF :
case TokenTypes.ANNOTATION_DEF :
case TokenTypes.ENUM_DEF :
case TokenTypes.ENUM_CONSTANT_DEF :
startToken = (DetailAST) aAST.getFirstChild();
final DetailAST objBlock = aAST.findFirstToken(TokenTypes.OBJBLOCK);
brace = (objBlock == null)
? null
: (DetailAST) objBlock.getFirstChild();
break;
case TokenTypes.LITERAL_WHILE:
case TokenTypes.LITERAL_CATCH:
case TokenTypes.LITERAL_SYNCHRONIZED:
case TokenTypes.LITERAL_FOR:
case TokenTypes.LITERAL_TRY:
case TokenTypes.LITERAL_FINALLY:
case TokenTypes.LITERAL_DO:
case TokenTypes.LITERAL_IF :
startToken = aAST;
brace = aAST.findFirstToken(TokenTypes.SLIST);
break;
case TokenTypes.LITERAL_ELSE :
startToken = aAST;
final DetailAST candidate = (DetailAST) aAST.getFirstChild();
brace =
(candidate.getType() == TokenTypes.SLIST)
? candidate
: null; // silently ignore
break;
case TokenTypes.LITERAL_SWITCH :
startToken = aAST;
brace = aAST.findFirstToken(TokenTypes.LCURLY);
break;
default :
startToken = null;
brace = null;
}
if ((brace != null) && (startToken != null)) {
verifyBrace(brace, startToken);
}
}
|
diff --git a/src/org/devtcg/five/util/ThreadStoppable.java b/src/org/devtcg/five/util/ThreadStoppable.java
index ddc748c..2ea3918 100644
--- a/src/org/devtcg/five/util/ThreadStoppable.java
+++ b/src/org/devtcg/five/util/ThreadStoppable.java
@@ -1,57 +1,57 @@
/*
* $Id$
*
* Copyright (C) 2008 Josh Guilfoyle <[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, 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.
*/
package org.devtcg.five.util;
public class ThreadStoppable extends Thread
{
protected boolean mStopped = false;
public ThreadStoppable()
{
super();
}
public ThreadStoppable(Runnable target)
{
super(target);
}
/**
* Interrupts the running thread and schedules it to be stopped. It is up
* to the subclass to implement the stop behaviour accordingly. Failure to
* do so will result in a dead lock.
*
* Do not call this method from within the subclassed thread.
*/
public void interruptAndStop()
{
mStopped = true;
interrupt();
while (true)
{
- try { join(); }
+ try { join(); break; }
catch (InterruptedException e) { }
}
}
public boolean isStopped()
{
return mStopped;
}
}
| true | true | public void interruptAndStop()
{
mStopped = true;
interrupt();
while (true)
{
try { join(); }
catch (InterruptedException e) { }
}
}
| public void interruptAndStop()
{
mStopped = true;
interrupt();
while (true)
{
try { join(); break; }
catch (InterruptedException e) { }
}
}
|
diff --git a/xstream/src/test/com/thoughtworks/acceptance/PersistenceTest.java b/xstream/src/test/com/thoughtworks/acceptance/PersistenceTest.java
index 0a1d56f1..0dda549f 100644
--- a/xstream/src/test/com/thoughtworks/acceptance/PersistenceTest.java
+++ b/xstream/src/test/com/thoughtworks/acceptance/PersistenceTest.java
@@ -1,112 +1,112 @@
/*
* Copyright (C) 2008 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 24. November 2008 by Joerg Schaible
*/
package com.thoughtworks.acceptance;
import com.thoughtworks.acceptance.objects.SampleLists;
import com.thoughtworks.acceptance.objects.Software;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
import com.thoughtworks.xstream.persistence.XmlArrayList;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
/**
* Tests the persistence package.
*
* @author Jörg Schaible
*/
public class PersistenceTest extends AbstractAcceptanceTest {
private File dir;
protected void setUp() throws Exception {
super.setUp();
dir = new File("target/test-storage");
dir.mkdirs();
cleanUp();
}
protected void tearDown() throws Exception {
cleanUp();
dir.delete();
super.tearDown();
}
private void cleanUp() {
File[] files = dir.listFiles();
for(int i = 0; i < files.length; ++i) {
if (files[i].isFile()) {
files[i].delete();
}
}
}
private final class PersistenceArrayListConverter implements Converter {
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
final XmlArrayList list = new XmlArrayList(new FilePersistenceStrategy(dir, xstream));
context.convertAnother(dir);
list.addAll((Collection)source);
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
final File directory = (File)context.convertAnother(null, File.class);
final XmlArrayList persistentList = new XmlArrayList(new FilePersistenceStrategy(directory, xstream));
final ArrayList list = new ArrayList(persistentList);
//persistentList.clear(); // remove files
return list;
}
public boolean canConvert(Class type) {
return type == ArrayList.class;
}
}
public void testCanUsePersistenceCollectionAsConverter() throws IOException {
xstream.alias("lists", SampleLists.class);
xstream.alias("software", Software.class);
xstream.registerLocalConverter(SampleLists.class, "good", new PersistenceArrayListConverter());
SampleLists lists = new SampleLists();
lists.good.add("Guilherme");
lists.good.add(new Integer(1970));
lists.good.add(new Software("Codehaus", "XStream"));
String expected = "" +
"<lists>\n" +
- " <good>target/test-storage</good>\n" +
+ " <good>" + dir.getPath() + "</good>\n" +
" <bad class=\"list\"/>\n" +
"</lists>";
// assumes 'lists' is serialized first
SampleLists serialized = (SampleLists)assertBothWays(lists, expected);
// compare original list and list written in separate XML file
assertEquals(lists.good, serialized.good);
// retrieve value from external file
FileInputStream inputStream = new FileInputStream(new File(dir, "[email protected]"));
try {
assertEquals(lists.good.get(2), xstream.fromXML(inputStream));
} finally {
inputStream.close();
}
}
}
| true | true | public void testCanUsePersistenceCollectionAsConverter() throws IOException {
xstream.alias("lists", SampleLists.class);
xstream.alias("software", Software.class);
xstream.registerLocalConverter(SampleLists.class, "good", new PersistenceArrayListConverter());
SampleLists lists = new SampleLists();
lists.good.add("Guilherme");
lists.good.add(new Integer(1970));
lists.good.add(new Software("Codehaus", "XStream"));
String expected = "" +
"<lists>\n" +
" <good>target/test-storage</good>\n" +
" <bad class=\"list\"/>\n" +
"</lists>";
// assumes 'lists' is serialized first
SampleLists serialized = (SampleLists)assertBothWays(lists, expected);
// compare original list and list written in separate XML file
assertEquals(lists.good, serialized.good);
// retrieve value from external file
FileInputStream inputStream = new FileInputStream(new File(dir, "[email protected]"));
try {
assertEquals(lists.good.get(2), xstream.fromXML(inputStream));
} finally {
inputStream.close();
}
}
| public void testCanUsePersistenceCollectionAsConverter() throws IOException {
xstream.alias("lists", SampleLists.class);
xstream.alias("software", Software.class);
xstream.registerLocalConverter(SampleLists.class, "good", new PersistenceArrayListConverter());
SampleLists lists = new SampleLists();
lists.good.add("Guilherme");
lists.good.add(new Integer(1970));
lists.good.add(new Software("Codehaus", "XStream"));
String expected = "" +
"<lists>\n" +
" <good>" + dir.getPath() + "</good>\n" +
" <bad class=\"list\"/>\n" +
"</lists>";
// assumes 'lists' is serialized first
SampleLists serialized = (SampleLists)assertBothWays(lists, expected);
// compare original list and list written in separate XML file
assertEquals(lists.good, serialized.good);
// retrieve value from external file
FileInputStream inputStream = new FileInputStream(new File(dir, "[email protected]"));
try {
assertEquals(lists.good.get(2), xstream.fromXML(inputStream));
} finally {
inputStream.close();
}
}
|
diff --git a/xcmis-spi/src/main/java/org/xcmis/spi/utils/CmisDocumentReaderService.java b/xcmis-spi/src/main/java/org/xcmis/spi/utils/CmisDocumentReaderService.java
index e3336e65..68d47d21 100644
--- a/xcmis-spi/src/main/java/org/xcmis/spi/utils/CmisDocumentReaderService.java
+++ b/xcmis-spi/src/main/java/org/xcmis/spi/utils/CmisDocumentReaderService.java
@@ -1,111 +1,111 @@
/*
* Copyright (C) 2010 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xcmis.spi.utils;
import org.exoplatform.container.component.ComponentPlugin;
import org.exoplatform.container.xml.InitParams;
import org.exoplatform.services.document.DocumentReader;
import org.exoplatform.services.document.DocumentReaderService;
import org.exoplatform.services.document.HandlerNotFoundException;
import org.exoplatform.services.document.impl.BaseDocumentReader;
import org.exoplatform.services.document.impl.HTMLDocumentReader;
import org.exoplatform.services.document.impl.MSExcelDocumentReader;
import org.exoplatform.services.document.impl.MSOutlookDocumentReader;
import org.exoplatform.services.document.impl.MSWordDocumentReader;
import org.exoplatform.services.document.impl.OpenOfficeDocumentReader;
import org.exoplatform.services.document.impl.PPTDocumentReader;
import org.exoplatform.services.document.impl.TextPlainDocumentReader;
import org.exoplatform.services.document.impl.XMLDocumentReader;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of {@link DocumentReaderService} with predefined parsers.
*/
public class CmisDocumentReaderService implements DocumentReaderService
{
private static final Log LOG = ExoLogger.getLogger(CmisDocumentReaderService.class);
private Map<String, BaseDocumentReader> readers;
/**
* Instantiates a new cmis document reader sercice.
*/
public CmisDocumentReaderService()
{
this.readers = new HashMap<String, BaseDocumentReader>();
addDocumentReader(new CmisPDFDocumentReader());
addDocumentReader(new MSWordDocumentReader());
addDocumentReader(new MSExcelDocumentReader());
addDocumentReader(new MSOutlookDocumentReader());
addDocumentReader(new PPTDocumentReader());
addDocumentReader(new HTMLDocumentReader());
addDocumentReader(new XMLDocumentReader());
addDocumentReader(new OpenOfficeDocumentReader());
- addDocumentReader(new TextPlainDocumentReader());
+ addDocumentReader(new TextPlainDocumentReader(new InitParams()));
}
/**
* @see org.exoplatform.services.document.DocumentReaderService#getContentAsText(java.lang.String, java.io.InputStream)
*/
public String getContentAsText(String mimeType, InputStream is) throws Exception
{
BaseDocumentReader reader = readers.get(mimeType.toLowerCase());
if (reader != null)
{
return reader.getContentAsText(is);
}
throw new Exception("Cannot handle the document type: " + mimeType);
}
/**
* @see org.exoplatform.services.document.DocumentReaderService#getDocumentReader(java.lang.String)
*/
public DocumentReader getDocumentReader(String mimeType) throws HandlerNotFoundException
{
BaseDocumentReader reader = readers.get(mimeType.toLowerCase());
if (reader != null)
{
return reader;
}
else
{
throw new HandlerNotFoundException("No appropriate properties extractor for " + mimeType);
}
}
/**
* @param plugin ComponentPlugin
*/
public void addDocumentReader(ComponentPlugin plugin)
{
BaseDocumentReader reader = (BaseDocumentReader)plugin;
for (String mimeType : reader.getMimeTypes())
{
readers.put(mimeType.toLowerCase(), reader);
}
}
}
| true | true | public CmisDocumentReaderService()
{
this.readers = new HashMap<String, BaseDocumentReader>();
addDocumentReader(new CmisPDFDocumentReader());
addDocumentReader(new MSWordDocumentReader());
addDocumentReader(new MSExcelDocumentReader());
addDocumentReader(new MSOutlookDocumentReader());
addDocumentReader(new PPTDocumentReader());
addDocumentReader(new HTMLDocumentReader());
addDocumentReader(new XMLDocumentReader());
addDocumentReader(new OpenOfficeDocumentReader());
addDocumentReader(new TextPlainDocumentReader());
}
| public CmisDocumentReaderService()
{
this.readers = new HashMap<String, BaseDocumentReader>();
addDocumentReader(new CmisPDFDocumentReader());
addDocumentReader(new MSWordDocumentReader());
addDocumentReader(new MSExcelDocumentReader());
addDocumentReader(new MSOutlookDocumentReader());
addDocumentReader(new PPTDocumentReader());
addDocumentReader(new HTMLDocumentReader());
addDocumentReader(new XMLDocumentReader());
addDocumentReader(new OpenOfficeDocumentReader());
addDocumentReader(new TextPlainDocumentReader(new InitParams()));
}
|
diff --git a/src/com/stackframe/pattymelt/Console.java b/src/com/stackframe/pattymelt/Console.java
index 8c74834..c32f863 100644
--- a/src/com/stackframe/pattymelt/Console.java
+++ b/src/com/stackframe/pattymelt/Console.java
@@ -1,67 +1,67 @@
/*
* Copyright 2012, Gene McCulley
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package com.stackframe.pattymelt;
import javax.swing.JComponent;
import javax.swing.JTextArea;
/**
* A console for DCPU-16.
*
* @author mcculley
*/
public class Console {
// FIXME: Add keyboard support
private final int address;
private final short[] memory;
private final JTextArea textArea;
private static final int numRows = 16, numColumns = 32, grid = numRows * numColumns;
public Console(int address, short[] memory) {
this.address = address;
this.memory = memory;
textArea = new JTextArea(numRows, numColumns);
}
public JComponent getWidget() {
return textArea;
}
public void update() {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < grid; i++) {
short word = memory[address + i];
- char c = (char) (word & 0xff);
+ char c = (char) (word & 0x7f);
buf.append(c);
}
textArea.setText(buf.toString());
}
}
| true | true | public void update() {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < grid; i++) {
short word = memory[address + i];
char c = (char) (word & 0xff);
buf.append(c);
}
textArea.setText(buf.toString());
}
| public void update() {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < grid; i++) {
short word = memory[address + i];
char c = (char) (word & 0x7f);
buf.append(c);
}
textArea.setText(buf.toString());
}
|
diff --git a/ui/isometric/builder/BuilderInterface.java b/ui/isometric/builder/BuilderInterface.java
index e23208e..2c368db 100644
--- a/ui/isometric/builder/BuilderInterface.java
+++ b/ui/isometric/builder/BuilderInterface.java
@@ -1,528 +1,527 @@
package ui.isometric.builder;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.filechooser.FileFilter;
import client.ClientMessageHandler;
import data.Database;
import serialization.ParseException;
import ui.isometric.IsoCanvas;
import ui.isometric.IsoInterface;
import ui.isometric.abstractions.IsoObject;
import ui.isometric.abstractions.IsoPlayer;
import ui.isometric.builder.things.ThingCreator;
import ui.isometric.builder.things.ThingCreatorDnD;
import ui.isometric.datasource.IsoChangeLevelDataSource;
import ui.isometric.libraries.IsoRendererLibrary;
import util.Direction;
import util.ImagePanel;
import util.Resources;
import game.*;
/**
*
* The overall class that manages a builder user interface
*
* @author melby
*
*/
public class BuilderInterface implements IsoInterface {
private JFrame frame;
private InspectorPanel inspector;
private LibraryFrame library;
private String frameName;
private ToolPanel tools;
private IsoCanvas canvas;
private GameWorld world;
private IsoChangeLevelDataSource dataSource;
private static final String EXTENTION = "wblrd";
private ThingCreator storedCreator = null;
private GameThing moving = null;
private Mode mode = Mode.ADD;
/**
* The world builder mode
* @author ruarusmelb
*
*/
private enum Mode {
ADD,
DELETE,
MOVE;
}
/**
* The tool panel at the top of the WorldBuilder
* @author ruarusmelb
*
*/
private class ToolPanel extends JPanel {
private static final long serialVersionUID = 1L;
private LevelPanel level;
private ImagePanel image;
private ImagePanel movingImage;
private JRadioButton add;
private JRadioButton delete;
private JRadioButton move;
/**
* Create a default ToolPanel
*/
public ToolPanel() {
JButton up = new JButton("Up a Level");
up.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
levelUp();
}
});
this.add(up);
JButton down = new JButton("Down a Level");
down.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
levelDown();
}
});
this.add(down);
JButton rotate = new JButton("Rotate");
rotate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
rotate();
}
});
this.add(rotate);
level = new LevelPanel(dataSource.level());
this.add(level);
add = new JRadioButton("Add");
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setMode(Mode.ADD);
}
});
this.add(add);
delete = new JRadioButton("Delete");
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setMode(Mode.DELETE);
}
});
this.add(delete);
move = new JRadioButton("Move");
move.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setMode(Mode.MOVE);
}
});
this.add(move);
ButtonGroup group = new ButtonGroup();
group.add(add);
group.add(delete);
group.add(move);
image = new ImagePanel(IsoRendererLibrary.maskTile());
image.setDropTarget(new DropTarget(canvas, new ThingCreatorDnD.ThingDropListener(new ThingCreatorDnD.ThingDropListener.ThingDropListenerAction() {
@Override
public void thingCreatorDroped(Component onto, Point location, ThingCreator creator) {
setCreator(creator);
}
})));
this.add(image);
movingImage = new ImagePanel(null);
this.add(movingImage);
refreshMode();
}
/**
* Notify this toolpanel that the level has changed
*/
public void refreshLevel() {
level.setLevel(dataSource.level());
}
/**
* Notify this ToolPanel that the creator has changed
*/
public void refreshCreator() {
BufferedImage i = (storedCreator != null)?storedCreator.previewImage():IsoRendererLibrary.maskTile();
image.setImage(i);
this.validate();
this.repaint();
}
/**
* Notify this ToolPanel that the mode has changed
*/
public void refreshMode() {
add.setSelected(mode == Mode.ADD);
delete.setSelected(mode == Mode.DELETE);
move.setSelected(mode == Mode.MOVE);
}
/**
* Notify this ToolPanel that the moving thing has changed
*/
public void refreshMoving() {
BufferedImage i = (moving != null)?IsoRendererLibrary.imageForRendererName(moving.renderer(), Direction.NORTH).image():null;
movingImage.setImage(i);
this.doLayout();
this.validate();
this.repaint();
}
}
/**
* Create a world builder interface with a given GameWorld and ClientMessageHandler
* @param name
* @param world
* @param logic
*/
public BuilderInterface(String name, final GameWorld world, ClientMessageHandler logic) {
this.world = world;
this.frameName = name;
dataSource = new IsoChangeLevelDataSource(this.world);
frame = new JFrame(name);
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem save = new JMenuItem("Save");
file.add(save);
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
save();
}
});
JMenuItem load = new JMenuItem("Load");
file.add(load);
load.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
load();
}
});
bar.add(file);
frame.setJMenuBar(bar);
frame.setLayout(new BorderLayout());
tools = new ToolPanel();
frame.add(tools, BorderLayout.NORTH);
canvas = new IsoCanvas(dataSource);
canvas.addSelectionCallback(new IsoCanvas.SelectionCallback() {
@Override
public void selected(final IsoObject i, final Location l, MouseEvent event) {
if(event.getButton() == MouseEvent.BUTTON3 || event.isControlDown()) { // Right click
if(mode == Mode.ADD && storedCreator != null) {
if(storedCreator != null) {
canvas.calculateTypesAtAtPoint(event.getPoint());
l.put(storedCreator.createThing(world, l));
}
}
if(mode == Mode.DELETE) {
if(i != null && i.gameThing() != null) {
LocationS.NOWHERE.put(i.gameThing());
world.forget(i.gameThing());
}
}
if(mode == Mode.MOVE) {
if(moving == null) {
if(i != null && i.gameThing() != null) {
LocationS.NOWHERE.put(i.gameThing());
setMoving(i.gameThing());
}
}
else {
if(moving != null) {
l.put(moving);
setMoving(null);
}
}
}
}
else {
if(event.isShiftDown()) {
if(i != null) {
Location loc = i.gameThing().location();
if(loc instanceof Level.Location) {
((Level.Location)loc).rotate(Direction.EAST).put(i.gameThing());
}
}
}
else {
- storedCreator = null;
inspect(l);
}
}
}
});
canvas.setDropTarget(new DropTarget(canvas, new ThingCreatorDnD.ThingDropListener(new ThingCreatorDnD.ThingDropListener.ThingDropListenerAction() {
@Override
public void thingCreatorDroped(Component onto, Point location, ThingCreator creator) {
if(onto instanceof IsoCanvas) {
setCreator(creator);
IsoCanvas canvas = (IsoCanvas)onto;
canvas.calculateTypesAtAtPoint(location);
Location l = dataSource.level().location(canvas.getCachedSelectedSquarePosition(), Direction.NORTH);
l.put(creator.createThing(world, l));
}
}
})));
frame.add(canvas, BorderLayout.CENTER);
inspector = new InspectorPanel(this);
inspector.getContentPane().setLayout(new BoxLayout(inspector.getContentPane(), BoxLayout.Y_AXIS));
inspector.getContentPane().add(Box.createVerticalGlue());
inspector.validate();
library = new LibraryFrame(this);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
screen.height -= 100;
double perx = 0.3;
library.setLocation(0, 0);
library.setSize((int)(screen.width*perx), (int)(screen.height*0.5));
inspector.setLocation(0, (int)(screen.height*0.5));
inspector.setSize((int)(screen.width*perx), (int)(screen.height*0.5));
frame.setLocation((int)(screen.width*perx), 0);
frame.setSize((int)(screen.width*(1-perx)), (int)(screen.height));
}
/**
* Set the moving character
* @param t
*/
private void setMoving(GameThing t) {
if(moving != null && t != null) {
if(JOptionPane.showConfirmDialog(frame, "Are you sure you wish to reset the current item being moved?") == JOptionPane.CANCEL_OPTION) {
tools.refreshMoving();
return;
}
}
moving = t;
tools.refreshMoving();
}
/**
* Set the stored creator
* @param creator
*/
private void setCreator(ThingCreator creator) {
storedCreator = creator;
tools.refreshCreator();
}
/**
* Set the mode
* @param m
*/
private void setMode(Mode m) {
if(mode == Mode.MOVE && m != Mode.MOVE && moving != null) {
if(JOptionPane.showConfirmDialog(frame, "Are you sure you wish to delete the current item being moved?") == JOptionPane.CANCEL_OPTION) {
tools.refreshMode();
return;
}
setMoving(null);
}
mode = m;
tools.refreshMode();
}
/**
* Move up a level
*/
private void levelUp() {
dataSource.goUp();
tools.refreshLevel();
}
/**
* Move down a level
*/
private void levelDown() {
dataSource.goDown();
tools.refreshLevel();
}
/**
* Rotate
*/
private void rotate() {
canvas.setViewDirection(canvas.viewDirection().compose(Direction.EAST));
}
@Override
public void show() {
frame.setVisible(true);
inspector.setVisible(true);
library.setVisible(true);
}
/**
* Inspect a given location
* @param l
*/
private void inspect(Location l) {
inspector.inspect(l);
}
@Override
public GameWorld world() {
return world;
}
/**
* Save the world
*/
public void save() {
String file = Database.treeToXML(world.toTree());
JFileChooser chooser = new JFileChooser();
if(chooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
File save = chooser.getSelectedFile().getAbsoluteFile();
if(!save.getAbsolutePath().endsWith("."+EXTENTION)) {
save = new File(save.getAbsolutePath() + "." + EXTENTION);
}
if(save.exists()) {
if(JOptionPane.showConfirmDialog(frame, "This file exists, are you sure you wish to overwrite it?", null, JOptionPane.OK_CANCEL_OPTION, 0) == JOptionPane.CANCEL_OPTION) {
return;
}
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(save));
writer.write(file);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Load the world
*/
public void load() {
String loaded = null;
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileFilter() {
@Override
public boolean accept(File arg0) {
return arg0.isFile() && arg0.getAbsolutePath().endsWith(EXTENTION);
}
@Override
public String getDescription() {
return "World Builder File";
}
});
if(chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
File load = chooser.getSelectedFile().getAbsoluteFile();
try {
loaded = Resources.loadTextFile(load.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
else {
return;
}
if(loaded == null) {
JOptionPane.showMessageDialog(frame, "Error loading file");
return;
}
try {
world.fromTree(Database.xmlToTree(loaded));
} catch (ParseException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(frame, "Error loading file");
}
}
/**
* Get the name of the frame
* @return
*/
public String frameName() {
return frameName;
}
@Override
public IsoCanvas canvas() {
return canvas;
}
@Override
public void performActionOn(String interaction, GameThing thing) {
thing.interact(interaction, null);
}
@Override
public IsoPlayer player() {
return null;
}
@Override
public void incomingChat(String message, Color color) {
System.out.println("Got Chat: "+message);
}
@Override
public void sendChatMessage(String message) {
System.out.println("Send Chat: "+message);
}
}
| true | true | public BuilderInterface(String name, final GameWorld world, ClientMessageHandler logic) {
this.world = world;
this.frameName = name;
dataSource = new IsoChangeLevelDataSource(this.world);
frame = new JFrame(name);
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem save = new JMenuItem("Save");
file.add(save);
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
save();
}
});
JMenuItem load = new JMenuItem("Load");
file.add(load);
load.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
load();
}
});
bar.add(file);
frame.setJMenuBar(bar);
frame.setLayout(new BorderLayout());
tools = new ToolPanel();
frame.add(tools, BorderLayout.NORTH);
canvas = new IsoCanvas(dataSource);
canvas.addSelectionCallback(new IsoCanvas.SelectionCallback() {
@Override
public void selected(final IsoObject i, final Location l, MouseEvent event) {
if(event.getButton() == MouseEvent.BUTTON3 || event.isControlDown()) { // Right click
if(mode == Mode.ADD && storedCreator != null) {
if(storedCreator != null) {
canvas.calculateTypesAtAtPoint(event.getPoint());
l.put(storedCreator.createThing(world, l));
}
}
if(mode == Mode.DELETE) {
if(i != null && i.gameThing() != null) {
LocationS.NOWHERE.put(i.gameThing());
world.forget(i.gameThing());
}
}
if(mode == Mode.MOVE) {
if(moving == null) {
if(i != null && i.gameThing() != null) {
LocationS.NOWHERE.put(i.gameThing());
setMoving(i.gameThing());
}
}
else {
if(moving != null) {
l.put(moving);
setMoving(null);
}
}
}
}
else {
if(event.isShiftDown()) {
if(i != null) {
Location loc = i.gameThing().location();
if(loc instanceof Level.Location) {
((Level.Location)loc).rotate(Direction.EAST).put(i.gameThing());
}
}
}
else {
storedCreator = null;
inspect(l);
}
}
}
});
canvas.setDropTarget(new DropTarget(canvas, new ThingCreatorDnD.ThingDropListener(new ThingCreatorDnD.ThingDropListener.ThingDropListenerAction() {
@Override
public void thingCreatorDroped(Component onto, Point location, ThingCreator creator) {
if(onto instanceof IsoCanvas) {
setCreator(creator);
IsoCanvas canvas = (IsoCanvas)onto;
canvas.calculateTypesAtAtPoint(location);
Location l = dataSource.level().location(canvas.getCachedSelectedSquarePosition(), Direction.NORTH);
l.put(creator.createThing(world, l));
}
}
})));
frame.add(canvas, BorderLayout.CENTER);
inspector = new InspectorPanel(this);
inspector.getContentPane().setLayout(new BoxLayout(inspector.getContentPane(), BoxLayout.Y_AXIS));
inspector.getContentPane().add(Box.createVerticalGlue());
inspector.validate();
library = new LibraryFrame(this);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
screen.height -= 100;
double perx = 0.3;
library.setLocation(0, 0);
library.setSize((int)(screen.width*perx), (int)(screen.height*0.5));
inspector.setLocation(0, (int)(screen.height*0.5));
inspector.setSize((int)(screen.width*perx), (int)(screen.height*0.5));
frame.setLocation((int)(screen.width*perx), 0);
frame.setSize((int)(screen.width*(1-perx)), (int)(screen.height));
}
| public BuilderInterface(String name, final GameWorld world, ClientMessageHandler logic) {
this.world = world;
this.frameName = name;
dataSource = new IsoChangeLevelDataSource(this.world);
frame = new JFrame(name);
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem save = new JMenuItem("Save");
file.add(save);
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
save();
}
});
JMenuItem load = new JMenuItem("Load");
file.add(load);
load.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
load();
}
});
bar.add(file);
frame.setJMenuBar(bar);
frame.setLayout(new BorderLayout());
tools = new ToolPanel();
frame.add(tools, BorderLayout.NORTH);
canvas = new IsoCanvas(dataSource);
canvas.addSelectionCallback(new IsoCanvas.SelectionCallback() {
@Override
public void selected(final IsoObject i, final Location l, MouseEvent event) {
if(event.getButton() == MouseEvent.BUTTON3 || event.isControlDown()) { // Right click
if(mode == Mode.ADD && storedCreator != null) {
if(storedCreator != null) {
canvas.calculateTypesAtAtPoint(event.getPoint());
l.put(storedCreator.createThing(world, l));
}
}
if(mode == Mode.DELETE) {
if(i != null && i.gameThing() != null) {
LocationS.NOWHERE.put(i.gameThing());
world.forget(i.gameThing());
}
}
if(mode == Mode.MOVE) {
if(moving == null) {
if(i != null && i.gameThing() != null) {
LocationS.NOWHERE.put(i.gameThing());
setMoving(i.gameThing());
}
}
else {
if(moving != null) {
l.put(moving);
setMoving(null);
}
}
}
}
else {
if(event.isShiftDown()) {
if(i != null) {
Location loc = i.gameThing().location();
if(loc instanceof Level.Location) {
((Level.Location)loc).rotate(Direction.EAST).put(i.gameThing());
}
}
}
else {
inspect(l);
}
}
}
});
canvas.setDropTarget(new DropTarget(canvas, new ThingCreatorDnD.ThingDropListener(new ThingCreatorDnD.ThingDropListener.ThingDropListenerAction() {
@Override
public void thingCreatorDroped(Component onto, Point location, ThingCreator creator) {
if(onto instanceof IsoCanvas) {
setCreator(creator);
IsoCanvas canvas = (IsoCanvas)onto;
canvas.calculateTypesAtAtPoint(location);
Location l = dataSource.level().location(canvas.getCachedSelectedSquarePosition(), Direction.NORTH);
l.put(creator.createThing(world, l));
}
}
})));
frame.add(canvas, BorderLayout.CENTER);
inspector = new InspectorPanel(this);
inspector.getContentPane().setLayout(new BoxLayout(inspector.getContentPane(), BoxLayout.Y_AXIS));
inspector.getContentPane().add(Box.createVerticalGlue());
inspector.validate();
library = new LibraryFrame(this);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
screen.height -= 100;
double perx = 0.3;
library.setLocation(0, 0);
library.setSize((int)(screen.width*perx), (int)(screen.height*0.5));
inspector.setLocation(0, (int)(screen.height*0.5));
inspector.setSize((int)(screen.width*perx), (int)(screen.height*0.5));
frame.setLocation((int)(screen.width*perx), 0);
frame.setSize((int)(screen.width*(1-perx)), (int)(screen.height));
}
|
diff --git a/org.dawb.passerelle.actors/src/org/dawb/passerelle/actors/data/DataImportSource.java b/org.dawb.passerelle.actors/src/org/dawb/passerelle/actors/data/DataImportSource.java
index a43bb8c..3708faf 100644
--- a/org.dawb.passerelle.actors/src/org/dawb/passerelle/actors/data/DataImportSource.java
+++ b/org.dawb.passerelle.actors/src/org/dawb/passerelle/actors/data/DataImportSource.java
@@ -1,817 +1,817 @@
/*
* Copyright (c) 2012 European Synchrotron Radiation Facility,
* Diamond Light Source Ltd.
*
* 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.dawb.passerelle.actors.data;
import java.io.File;
import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.dawb.common.python.PythonUtils;
import org.dawb.common.ui.slicing.DimsDataList;
import org.dawb.common.ui.slicing.SliceUtils;
import org.dawb.common.util.io.FileUtils;
import org.dawb.common.util.io.SortingUtils;
import org.dawb.gda.extensions.util.DatasetTitleUtils;
import org.dawb.passerelle.actors.data.config.SliceParameter;
import org.dawb.passerelle.common.DatasetConstants;
import org.dawb.passerelle.common.actors.AbstractDataMessageSource;
import org.dawb.passerelle.common.message.AbstractDatasetProvider;
import org.dawb.passerelle.common.message.DataMessageComponent;
import org.dawb.passerelle.common.message.DataMessageException;
import org.dawb.passerelle.common.message.IVariable;
import org.dawb.passerelle.common.message.IVariable.VARIABLE_TYPE;
import org.dawb.passerelle.common.message.IVariableProvider;
import org.dawb.passerelle.common.message.MessageUtils;
import org.dawb.passerelle.common.message.Variable;
import org.dawb.passerelle.common.parameter.ParameterUtils;
import org.dawnsci.io.h5.H5LazyDataset;
import org.dawnsci.io.h5.H5Loader;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.gmf.runtime.common.core.util.StringMatcher;
import org.eclipse.swt.SWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ptolemy.data.BooleanToken;
import ptolemy.data.expr.Parameter;
import ptolemy.data.expr.StringParameter;
import ptolemy.kernel.CompositeEntity;
import ptolemy.kernel.util.Attribute;
import ptolemy.kernel.util.IllegalActionException;
import ptolemy.kernel.util.NameDuplicationException;
import ptolemy.kernel.util.Settable;
import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset;
import uk.ac.diamond.scisoft.analysis.dataset.DatasetUtils;
import uk.ac.diamond.scisoft.analysis.dataset.ILazyDataset;
import uk.ac.diamond.scisoft.analysis.io.DataHolder;
import uk.ac.diamond.scisoft.analysis.io.IMetaData;
import uk.ac.diamond.scisoft.analysis.io.LoaderFactory;
import uk.ac.diamond.scisoft.analysis.io.SliceObject;
import uk.ac.gda.util.map.MapUtils;
import com.isencia.passerelle.actor.InitializationException;
import com.isencia.passerelle.actor.ProcessingException;
import com.isencia.passerelle.actor.TerminationException;
import com.isencia.passerelle.core.PasserelleException;
import com.isencia.passerelle.message.ManagedMessage;
import com.isencia.passerelle.message.MessageException;
import com.isencia.passerelle.message.MessageFactory;
import com.isencia.passerelle.util.EnvironmentUtils;
import com.isencia.passerelle.util.ptolemy.IAvailableChoices;
import com.isencia.passerelle.util.ptolemy.IAvailableMap;
import com.isencia.passerelle.util.ptolemy.RegularExpressionParameter;
import com.isencia.passerelle.util.ptolemy.ResourceParameter;
import com.isencia.passerelle.util.ptolemy.StringChoiceParameter;
import com.isencia.passerelle.util.ptolemy.StringMapParameter;
import com.isencia.passerelle.workbench.model.actor.IResourceActor;
import com.isencia.passerelle.workbench.model.actor.ResourceObject;
import com.isencia.passerelle.workbench.model.utils.ModelUtils;
import com.isencia.util.StringConvertor;
/**
* Reads a file or directory using LoaderFactory and makes the data available to subsequent nodes
* which can request certain data sets for use.
*
* @author gerring
*
*/
public class DataImportSource extends AbstractDataMessageSource implements IResourceActor, IVariableProvider {
private static final Logger logger = LoggerFactory.getLogger(DataImportSource.class);
private static final String[] DATA_TYPES = new String[] {"Complete data as numerical arrays", "Just path and file name"};
private static final String[] SLICE_TYPES = new String[] {"Unique name for each slice", "Same name for each slice"};
// Read internally
protected Parameter folderParam;
protected Parameter relativePathParam;
protected boolean isPathRelative = true;
protected Parameter metaParam;
protected boolean isMetaRequired = false;
private final RegularExpressionParameter filterParam;
private final ResourceParameter path;
private final StringChoiceParameter names;
private final StringMapParameter rename;
private final StringParameter dataType;
private final StringParameter sliceNameType;
private final SliceParameter slicing;
private List<TriggerObject> fileQueue;
/**
* Required because sometimes the uk.ac.diamond.scisoft.analysis.osgi
* does not run in the workflow run configuration.
*/
static {
try {
for (String ext : H5Loader.EXT) {
LoaderFactory.registerLoader(ext, H5Loader.class,0);
}
} catch (Exception ne) {
logger.error("Cannot ensure that H5Loader is the default!", ne);
}
}
/**
*
*/
private static final long serialVersionUID = -851384753061854424L;
public DataImportSource(CompositeEntity container, String name) throws IllegalActionException, NameDuplicationException {
this(container, name, false);
}
/**
*
* @param container
* @param name
* @throws IllegalActionException
* @throws NameDuplicationException
*/
protected DataImportSource(CompositeEntity container, String name, boolean isFolder) throws IllegalActionException, NameDuplicationException {
super(container, ModelUtils.findUniqueActorName(container, ModelUtils.getLegalName(name)));
relativePathParam = new Parameter(this, "Relative Path", new BooleanToken(true));
registerConfigurableParameter(relativePathParam);
folderParam = new Parameter(this, "Folder", new BooleanToken(isFolder));
folderParam.setVisibility(Settable.NONE);
- metaParam = new Parameter(this, "Include Meta Data", new BooleanToken(false));
+ metaParam = new Parameter(this, "Include Metadata", new BooleanToken(false));
registerConfigurableParameter(metaParam);
filterParam = new RegularExpressionParameter(this, "File Filter", true);
registerConfigurableParameter(filterParam);
path = new ResourceParameter(this, "Path", "Data files", LoaderFactory.getSupportedExtensions().toArray(new String[0]));
try {
URI baseURI = new File(StringConvertor.convertPathDelimiters(EnvironmentUtils.getApplicationRootFolder())).toURI();
path.setBaseDirectory(baseURI);
} catch (Exception e) {
logger.error("Cannot set base directory for "+getClass().getName(), e);
}
registerConfigurableParameter(path);
names = new StringChoiceParameter(this, "Data Sets", new IAvailableChoices() {
@Override
public String[] getChoices() {
return getAllDatasetsInFile();
}
@Override
public Map<String,String> getVisibleChoices() {
getAllDatasetsInFile();
return DatasetTitleUtils.getChoppedNames(cachedDatasets);
}
}, SWT.MULTI);
registerConfigurableParameter(names);
rename = new StringMapParameter(this, "Rename Data Sets", new IAvailableMap() {
@Override
public Map<String,String> getMap() {
return getDataSetsRenameName();
}
@Override
public Map<String,String> getVisibleKeyChoices() {
getAllDatasetsInFile();
return DatasetTitleUtils.getChoppedNames(cachedDatasets);
}
@Override
public Collection<String> getSelectedChoices() {
final String[] ds = names.getValue();
return ds!=null ? Arrays.asList(ds) : null;
}
});
registerConfigurableParameter(rename);
slicing = new SliceParameter(this, "Data Set Slice");
registerConfigurableParameter(slicing);
dataType = new StringParameter(this,"Data Type") {
public String[] getChoices() {
return DATA_TYPES;
}
};
dataType.setExpression(DATA_TYPES[0]);
registerConfigurableParameter(dataType);
sliceNameType = new StringParameter(this,"Slice Name Type") {
public String[] getChoices() {
return SLICE_TYPES;
}
};
sliceNameType.setExpression(SLICE_TYPES[0]);
registerConfigurableParameter(sliceNameType);
}
/**
* @param attribute The attribute that changed.
* @exception IllegalActionException */
public void attributeChanged(Attribute attribute) throws IllegalActionException {
if(logger.isTraceEnabled()) logger.trace(getInfo()+" :"+attribute);
if (attribute == path) {
cachedDatasets = null;
cachedShapes = null;
} else if (attribute == relativePathParam) {
isPathRelative = ((BooleanToken)relativePathParam.getToken()).booleanValue();
} else if (attribute == metaParam) {
isMetaRequired = ((BooleanToken)metaParam.getToken()).booleanValue();
} else if (attribute == folderParam) {
// You cannot change this, it is set in the constuctor and is fixed.
} else if (attribute == names) {
logger.trace("Data set names changed to : " + names.getExpression());
}
super.attributeChanged(attribute);
}
@Override
public void doPreInitialize() {
fileQueue = null;
cachedDatasets = null;
cachedShapes = null;
}
@Override
protected void doInitialize() throws InitializationException {
super.doInitialize();
fileQueue = new ArrayList<TriggerObject>(89);
if (!isTriggerConnected()) {
appendQueue(null); // Otherwise the trigger will call create on the iterator.
}
}
/**
* triggerMsg may be null
* @param triggerMsg
*/
private void appendQueue(final ManagedMessage triggerMsg) {
if ((getManager()!=null) && (getSourcePath(triggerMsg)!=null)){
final File file = new File(getSourcePath(triggerMsg));
if (file.isDirectory()) {
final List<File> fileList = SortingUtils.getSortedFileList(file);
for (File f : fileList) {
if (!isFileLegal(f, triggerMsg)) continue;
final TriggerObject ob = new TriggerObject();
ob.setTrigger(triggerMsg);
ob.setFile(f);
fileQueue.add(ob);
}
} else {
if (isFileLegal(file, triggerMsg)) {
if (isH5Slicing(triggerMsg)) {
try {
final IMetaData meta = LoaderFactory.getMetaData(file.getAbsolutePath(), null);
final int[] shape = meta.getDataShapes().get(getDataSetNames()[0]);
final List<SliceObject> slices = SliceUtils.getExpandedSlices(shape, slicing.getBeanFromValue(DimsDataList.class));
int index = 0;
for (SliceObject sliceObject : slices) {
final TriggerObject ob = new TriggerObject();
ob.setTrigger(triggerMsg);
ob.setFile(file);
ob.setSlice(sliceObject);
ob.setIndex(index);
fileQueue.add(ob);
index++;
}
} catch (Exception ne) {
// This is the end!
logger.error("Problem reading slices in data import.", ne);
requestFinish();
}
} else {
final TriggerObject ob = new TriggerObject();
ob.setTrigger(triggerMsg);
ob.setFile(file);
fileQueue.add(ob);
}
}
}
if (fileQueue!=null && fileQueue.isEmpty()) {
logger.info("No files found in '"+file.getAbsolutePath()+"'. Filter is set to: "+filterParam.getExpression());
}
}
}
private boolean isH5Slicing(final ManagedMessage triggerMsg) {
final String ext = FileUtils.getFileExtension(getSourcePath(triggerMsg));
final boolean isH5File = LoaderFactory.getLoaderClass(ext) == H5Loader.class;
return isH5File && this.slicing.getExpression()!=null
&& !"".equals(slicing.getExpression())
&& getDataSetNames()!=null
&& getDataSetNames().length==1;
}
private boolean isFileLegal(File file, final ManagedMessage triggerMsg) {
if (file.isDirectory()) return false;
if (file.isHidden()) return false;
if (file.getName().startsWith(".")) return false;
if (!isRequiredFileName(file.getName(), triggerMsg)) return false;
return true;
}
public boolean hasNoMoreMessages() {
if (fileQueue == null) return true;
return fileQueue.isEmpty() && super.hasNoMoreMessages();
}
protected ManagedMessage getDataMessage() throws ProcessingException {
if (fileQueue == null) return null;
if (fileQueue.isEmpty()) return null;
if (isFinishRequested()) {
fileQueue.clear();
return null;
}
ManagedMessage msg = MessageFactory.getInstance().createMessage();
final TriggerObject file = fileQueue.remove(0);
try {
msg.setBodyContent(getData(file), DatasetConstants.CONTENT_TYPE_DATA);
} catch (MessageException e) {
logger.error("Cannot set map of data in message body!", e);
msg = MessageFactory.getInstance().createErrorMessage(new PasserelleException("Cannot set map of data in message body!", "application/x-data", e));
fileQueue.clear();
} catch (Exception ne) {
fileQueue.clear();
throw new DataMessageException("Cannot read data from '"+getSourcePath(msg)+"'", this, ne);
}
try {
msg.setBodyHeader("TITLE", file.getFile().getName());
} catch (MessageException e) {
msg = MessageFactory.getInstance().createErrorMessage(new PasserelleException("Cannot set header in message!", "application/x-data", e));
}
return msg;
}
protected void doWrapUp() throws TerminationException {
super.doWrapUp();
if (isFinishRequested()) {
fileQueue.clear();
if (cachedDatasets!=null) cachedDatasets.clear();
if (cachedShapes!=null) cachedShapes.clear();
}
}
private boolean isRequiredFileName(String fileName, final ManagedMessage triggerMsg) {
String fileFilter;
try {
fileFilter = ParameterUtils.getSubstituedValue(filterParam, MessageUtils.coerceMessage(triggerMsg));
} catch (Throwable ne) {
fileFilter = filterParam.getExpression();
}
if (fileFilter==null || "".equals(fileFilter)) return true;
if (filterParam.isJustWildCard()) {
final StringMatcher matcher = new StringMatcher(fileFilter, true, false);
return matcher.match(fileName);
} else {
return fileName.matches(fileFilter);
}
}
private Collection<String> cachedDatasets = null;
private Map<String,int[]> cachedShapes = null;
protected String[] getAllDatasetsInFile() {
if (cachedDatasets==null && getSourcePath(null)!=null) {
try {
String path = getSourcePath(null);
File file = new File(path);
if (!file.exists()) return null;
// For directories we assume that all files contain the same data sets.
if (file.isDirectory()) {
final File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (!files[i].isDirectory()) {
file = files[i];
break;
}
}
}
final IMetaData meta = LoaderFactory.getMetaData(file.getAbsolutePath(), null);
if (meta!=null && meta.getDataNames()!=null) {
Collection<String> names = meta.getDataNames();
Map<String,int[]> shapes= meta.getDataShapes();
// If single image, rename
if (names!=null&&names.size()==1&&shapes!=null&&shapes.size()==1 && shapes.get(names.iterator().next())!=null && shapes.get(names.iterator().next()).length==2) {
final int[] shape = shapes.get(names.iterator().next());
cachedDatasets = Arrays.asList(new String[]{"image"});
cachedShapes = new HashMap<String,int[]>(1);
cachedShapes.put("image", shape);
} else {
cachedDatasets = names;
cachedShapes = shapes;
}
}
} catch (Exception e) {
logger.error("Cannot get data set names from "+getSourcePath(null), e);
cachedDatasets = Collections.emptyList();
cachedShapes = Collections.emptyMap();
}
}
if (cachedDatasets!=null&&!cachedDatasets.isEmpty()) {
return cachedDatasets.toArray(new String[cachedDatasets.size()]);
}
return null;
}
private Map<String, String> getDataSetsRenameName() {
final String[] sets = getAllDatasetsInFile();
if (sets == null || sets.length<1) return null;
String rootName = DatasetTitleUtils.getRootName(cachedDatasets);
if (rootName==null) rootName = "";
final Map<String,String> ret = new LinkedHashMap<String,String>(7);
for (String setName : sets) {
try {
ret.put(setName, PythonUtils.getLegalVarName(setName.substring(rootName.length()), ret.values()));
} catch (Exception e) {
ret.put(setName, setName);
}
}
if (rename.getExpression()==null) {
return ret;
}
final Map<String,String> existing = MapUtils.getMap(rename.getExpression());
if (existing!=null) {
existing.keySet().retainAll(ret.keySet());
ret.putAll(existing);
}
return ret;
}
protected DataMessageComponent getData(final TriggerObject trigOb) throws Exception {
// Add everything non-data from upstream that we can, then decide on the details
// like data slicing.
final DataMessageComponent comp = new DataMessageComponent();
if (trigOb.getTrigger()!=null) {
try {
DataMessageComponent dmc = MessageUtils.coerceMessage(trigOb.getTrigger());
comp.addScalar(dmc.getScalar());
comp.addRois(dmc.getRois());
comp.addFunctions(dmc.getFunctions());
} catch (Throwable ignored) {
// triggers to not have to be DataMessageComponent
}
}
final File file = trigOb.getFile();
final ManagedMessage triggerMsg= trigOb.getTrigger();
final String filePath = file.getAbsolutePath();
final Map<String,Serializable> datasets;
if (trigOb.getSlice()!=null) {
final SliceObject slice = trigOb.getSlice();
slice.setPath(file.getAbsolutePath());
final String datasetPath = getDataSetNames()[0];
slice.setName(datasetPath);
String sliceName = getMappedName(datasetPath);
if (SLICE_TYPES[0].equals(sliceNameType.getExpression())) {
sliceName = sliceName+"_slice_"+trigOb.getIndex();
}
final String pyName = PythonUtils.getLegalVarName(sliceName, null);
final DataHolder dh = LoaderFactory.getData(slice.getPath());
final ILazyDataset ld = dh.getLazyDataset(slice.getName());
final AbstractDataset set = SliceUtils.getSlice(ld, slice, null);
set.setName(pyName);
datasets = new HashMap<String,Serializable>(1);
datasets.put(pyName, set);
} else {
datasets = getDatasets(filePath, trigOb);
}
// Add messages from upsteam, if any.
if (triggerMsg!=null) {
try {
final DataMessageComponent c = MessageUtils.coerceMessage(triggerMsg);
comp.addScalar(c.getScalar());
} catch (Exception ignored) {
logger.debug("Trigger for "+getName()+" is not DataMessageComponent, no data added.");
}
}
if (datasets!=null) comp.setList(datasets);
if (isMetaRequired) {
IMetaData meta = LoaderFactory.getMetaData(filePath, null);
comp.setMeta(meta);
}
comp.putScalar("file_path", filePath);
comp.putScalar("file_name", new File(filePath).getName());
comp.putScalar("file_dir", FileUtils.getDirectory(filePath));
return comp;
}
/**
*
*/
public String[] getDataSetNames() {
return names.getValue();
}
private Map<String,Serializable> getDatasets(String filePath, final TriggerObject trigOb) throws Exception {
if (!DATA_TYPES[0].equals(dataType.getExpression())) return null;
final String[] ds = names.getValue();
// TODO Eclipse progress?
Map<String, ILazyDataset> data = null;
if (ds!=null&&ds.length>0) {
data = LoaderFactory.getDataSets(filePath, Arrays.asList(ds), null);
}
if (data == null) {
DataHolder dh = LoaderFactory.getData(filePath, null);
data = dh.getMap();
if (ds!=null&&ds.length>0) {
data.keySet().retainAll(Arrays.asList(ds));
}
}
final Map<String, Object> raw;
if (ds==null) {
raw = new LinkedHashMap<String, Object>();
if (isSingleImage(data)) {
final ILazyDataset image = data.values().iterator().next();
final String name = trigOb!=null && trigOb.getIndex()>-1
? "image"
: "image"+trigOb.getIndex();
image.setName(name);
raw.put(name, image);
} else {
raw.putAll(data);
}
} else {
raw = new LinkedHashMap<String, Object>();
for (String name : ds) {
raw.put(name, data.get(name));
}
}
final Map<String,String> nameMap = getDataSetNameMap();
final Map<String,Serializable> ret = new HashMap<String,Serializable>(raw.size());
// Set name and not to print data in string
for (String name : raw.keySet()) {
final ILazyDataset lazy = (ILazyDataset)raw.get(name);
if (lazy==null) continue;
if (nameMap!=null) {
final String newName = nameMap.get(name);
if (newName!=null && !"".equals(newName)) {
name = newName;
}
}
/**
* We load the data, this is an import actor
*/
final AbstractDataset set = getLoadedData(lazy);
set.setName(name);
ret.put(name, set);
}
return ret;
}
private boolean isSingleImage(Map<String, ILazyDataset> data) {
if (data.size()!=1) return false;
final ILazyDataset set = data.values().iterator().next();
return set.getShape()!=null && set.getShape().length==2;
}
private AbstractDataset getLoadedData(ILazyDataset lazy) throws Exception {
if (lazy instanceof H5LazyDataset) {
return ((H5LazyDataset)lazy).getCompleteData(null);
} else if (lazy instanceof AbstractDataset) {
return (AbstractDataset) lazy;
}
return DatasetUtils.convertToAbstractDataset(lazy.getSlice());
}
private Map<String, String> getDataSetNameMap() {
final String map = this.rename.getExpression();
if (map == null) return null;
final Map<String,String> nameMap = MapUtils.getMap(map);
if (nameMap==null || nameMap.isEmpty()) return null;
return nameMap;
}
private String getMappedName(final String hdfName) {
final Map<String,String> nameMap = getDataSetNameMap();
if (nameMap==null) return hdfName;
if (!nameMap.containsKey(hdfName)) return hdfName;
return nameMap.get(hdfName);
}
@Override
protected String getExtendedInfo() {
return "A source which uses the GDA 'LoaderFactory' to read a DataHandler which can be used to access data";
}
public String getSourcePath() {
return getSourcePath(null);
}
private String getSourcePath(final ManagedMessage manMsg) {
String sourcePath=null;
try {
final DataMessageComponent comp = manMsg!=null ? MessageUtils.coerceMessage(manMsg) : null;
sourcePath = ParameterUtils.getSubstituedValue(this.path, comp);
} catch (Exception e) {
// Can happen when they have an expand in the parameter that
// is not resolved until run time.
logger.info("Cannot substitute parameter "+path, e);
}
if (isPathRelative) {
try {
final IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(sourcePath, true);
if (res==null) return null;
sourcePath = res.getLocation().toOSString();
} catch (NullPointerException ne) {
return null;
}
}
getStandardMessageHeaders().put(ManagedMessage.SystemHeader.HEADER_SOURCE_INFO,sourcePath);
return sourcePath;
}
private Object getResource() {
if (isPathRelative) {
String sourcePath = this.path.getExpression();
try {
sourcePath = ParameterUtils.substitute(sourcePath, this);
} catch (Exception e) {
logger.error("Cannot ret resource "+sourcePath, e);
return null;
}
return ResourcesPlugin.getWorkspace().getRoot().findMember(sourcePath, true);
} else {
return new File(getSourcePath(null));
}
}
private String getResourceTypeName() {
final File file = new File(getSourcePath(null));
return file!=null ? "'"+file.getName()+"'" : "";
}
@Override
public int getResourceCount() {
return 1;
}
@Override
public ResourceObject getResource(int num) {
if (num==0) {
final ResourceObject ret = new ResourceObject();
ret.setResource(getResource());
ret.setResourceTypeName(getResourceTypeName());
return ret;
}
return null;
}
@Override
public void setMomlResource(IResource momlFile) {
// Do nothing
}
@Override
public List<IVariable> getOutputVariables() {
final List<IVariable> ret = new ArrayList<IVariable>(7);
if (getSourcePath(null)==null) {
final String msg = "Invalid Path '"+path.getExpression()+"'";
ret.add(new Variable("file_path", VARIABLE_TYPE.PATH, msg, String.class));
ret.add(new Variable("file_name", VARIABLE_TYPE.SCALAR, msg, String.class));
ret.add(new Variable("file_dir", VARIABLE_TYPE.PATH, msg, String.class));
return ret;
}
ret.add(new Variable("file_path", VARIABLE_TYPE.PATH, getSourcePath(null), String.class));
ret.add(new Variable("file_name", VARIABLE_TYPE.SCALAR, new File(getSourcePath(null)).getName(), String.class));
ret.add(new Variable("file_dir", VARIABLE_TYPE.PATH, FileUtils.getDirectory(getSourcePath(null)), String.class));
if (DATA_TYPES[0].equals(dataType.getExpression())) {
getAllDatasetsInFile();// Sets up cache of sizes, which means we can return VARIABLE_TYPE.IMAGE
String[] ds = names.getValue();
if (ds==null||ds.length<1) ds = getAllDatasetsInFile();
if (ds!=null&&ds.length>0) {
for (int i = 0; i < ds.length; i++) {
final Map<String,String> varNames = getDataSetNameMap();
final String name = varNames!=null&&varNames.containsKey(ds[i])
? varNames.get(ds[i])
: ds[i];
if (cachedShapes!=null) {
final int[] shape = cachedShapes.get(ds[i]);
final VARIABLE_TYPE type = shape!=null&&shape.length==2
? VARIABLE_TYPE.IMAGE
: VARIABLE_TYPE.ARRAY;
final AbstractDatasetProvider example = new AbstractDatasetProvider(shape);
ret.add(new Variable(name, type, example, AbstractDataset.class));
} else {
ret.add(new Variable(name, VARIABLE_TYPE.ARRAY, new AbstractDatasetProvider(), AbstractDataset.class));
}
}
}
}
return ret;
}
private boolean triggeredOnce = false;
@Override
protected boolean mustWaitForTrigger() {
if (!isTriggerConnected()) return false;
if (!triggeredOnce) return true;
return fileQueue.isEmpty();
}
/**
* "callback"-method that can be overridden by TriggeredSource implementations,
* if they want to act e.g. on the contents of a received trigger message.
*
* @param triggerMsg
*/
protected void acceptTriggerMessage(ManagedMessage triggerMsg) {
triggeredOnce = true;
appendQueue(triggerMsg);
}
}
| true | true | protected DataImportSource(CompositeEntity container, String name, boolean isFolder) throws IllegalActionException, NameDuplicationException {
super(container, ModelUtils.findUniqueActorName(container, ModelUtils.getLegalName(name)));
relativePathParam = new Parameter(this, "Relative Path", new BooleanToken(true));
registerConfigurableParameter(relativePathParam);
folderParam = new Parameter(this, "Folder", new BooleanToken(isFolder));
folderParam.setVisibility(Settable.NONE);
metaParam = new Parameter(this, "Include Meta Data", new BooleanToken(false));
registerConfigurableParameter(metaParam);
filterParam = new RegularExpressionParameter(this, "File Filter", true);
registerConfigurableParameter(filterParam);
path = new ResourceParameter(this, "Path", "Data files", LoaderFactory.getSupportedExtensions().toArray(new String[0]));
try {
URI baseURI = new File(StringConvertor.convertPathDelimiters(EnvironmentUtils.getApplicationRootFolder())).toURI();
path.setBaseDirectory(baseURI);
} catch (Exception e) {
logger.error("Cannot set base directory for "+getClass().getName(), e);
}
registerConfigurableParameter(path);
names = new StringChoiceParameter(this, "Data Sets", new IAvailableChoices() {
@Override
public String[] getChoices() {
return getAllDatasetsInFile();
}
@Override
public Map<String,String> getVisibleChoices() {
getAllDatasetsInFile();
return DatasetTitleUtils.getChoppedNames(cachedDatasets);
}
}, SWT.MULTI);
registerConfigurableParameter(names);
rename = new StringMapParameter(this, "Rename Data Sets", new IAvailableMap() {
@Override
public Map<String,String> getMap() {
return getDataSetsRenameName();
}
@Override
public Map<String,String> getVisibleKeyChoices() {
getAllDatasetsInFile();
return DatasetTitleUtils.getChoppedNames(cachedDatasets);
}
@Override
public Collection<String> getSelectedChoices() {
final String[] ds = names.getValue();
return ds!=null ? Arrays.asList(ds) : null;
}
});
registerConfigurableParameter(rename);
slicing = new SliceParameter(this, "Data Set Slice");
registerConfigurableParameter(slicing);
dataType = new StringParameter(this,"Data Type") {
public String[] getChoices() {
return DATA_TYPES;
}
};
dataType.setExpression(DATA_TYPES[0]);
registerConfigurableParameter(dataType);
sliceNameType = new StringParameter(this,"Slice Name Type") {
public String[] getChoices() {
return SLICE_TYPES;
}
};
sliceNameType.setExpression(SLICE_TYPES[0]);
registerConfigurableParameter(sliceNameType);
}
| protected DataImportSource(CompositeEntity container, String name, boolean isFolder) throws IllegalActionException, NameDuplicationException {
super(container, ModelUtils.findUniqueActorName(container, ModelUtils.getLegalName(name)));
relativePathParam = new Parameter(this, "Relative Path", new BooleanToken(true));
registerConfigurableParameter(relativePathParam);
folderParam = new Parameter(this, "Folder", new BooleanToken(isFolder));
folderParam.setVisibility(Settable.NONE);
metaParam = new Parameter(this, "Include Metadata", new BooleanToken(false));
registerConfigurableParameter(metaParam);
filterParam = new RegularExpressionParameter(this, "File Filter", true);
registerConfigurableParameter(filterParam);
path = new ResourceParameter(this, "Path", "Data files", LoaderFactory.getSupportedExtensions().toArray(new String[0]));
try {
URI baseURI = new File(StringConvertor.convertPathDelimiters(EnvironmentUtils.getApplicationRootFolder())).toURI();
path.setBaseDirectory(baseURI);
} catch (Exception e) {
logger.error("Cannot set base directory for "+getClass().getName(), e);
}
registerConfigurableParameter(path);
names = new StringChoiceParameter(this, "Data Sets", new IAvailableChoices() {
@Override
public String[] getChoices() {
return getAllDatasetsInFile();
}
@Override
public Map<String,String> getVisibleChoices() {
getAllDatasetsInFile();
return DatasetTitleUtils.getChoppedNames(cachedDatasets);
}
}, SWT.MULTI);
registerConfigurableParameter(names);
rename = new StringMapParameter(this, "Rename Data Sets", new IAvailableMap() {
@Override
public Map<String,String> getMap() {
return getDataSetsRenameName();
}
@Override
public Map<String,String> getVisibleKeyChoices() {
getAllDatasetsInFile();
return DatasetTitleUtils.getChoppedNames(cachedDatasets);
}
@Override
public Collection<String> getSelectedChoices() {
final String[] ds = names.getValue();
return ds!=null ? Arrays.asList(ds) : null;
}
});
registerConfigurableParameter(rename);
slicing = new SliceParameter(this, "Data Set Slice");
registerConfigurableParameter(slicing);
dataType = new StringParameter(this,"Data Type") {
public String[] getChoices() {
return DATA_TYPES;
}
};
dataType.setExpression(DATA_TYPES[0]);
registerConfigurableParameter(dataType);
sliceNameType = new StringParameter(this,"Slice Name Type") {
public String[] getChoices() {
return SLICE_TYPES;
}
};
sliceNameType.setExpression(SLICE_TYPES[0]);
registerConfigurableParameter(sliceNameType);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.