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/openelis/src/us/mn/state/health/lims/result/action/ResultsLogbookUpdateAction.java b/openelis/src/us/mn/state/health/lims/result/action/ResultsLogbookUpdateAction.java
index ce6c4491..1cdf9c9a 100644
--- a/openelis/src/us/mn/state/health/lims/result/action/ResultsLogbookUpdateAction.java
+++ b/openelis/src/us/mn/state/health/lims/result/action/ResultsLogbookUpdateAction.java
@@ -1,756 +1,756 @@
/**
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* The Original Code is OpenELIS code.
*
* Copyright (C) CIRG, University of Washington, Seattle WA. All Rights Reserved.
*
*/
package us.mn.state.health.lims.result.action;
import org.apache.commons.validator.GenericValidator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.*;
import org.hibernate.StaleObjectStateException;
import org.hibernate.Transaction;
import us.mn.state.health.lims.analysis.dao.AnalysisDAO;
import us.mn.state.health.lims.analysis.daoimpl.AnalysisDAOImpl;
import us.mn.state.health.lims.analysis.valueholder.Analysis;
import us.mn.state.health.lims.common.action.BaseAction;
import us.mn.state.health.lims.common.action.BaseActionForm;
import us.mn.state.health.lims.common.action.IActionConstants;
import us.mn.state.health.lims.common.exception.LIMSDuplicateRecordException;
import us.mn.state.health.lims.common.exception.LIMSRuntimeException;
import us.mn.state.health.lims.common.formfields.FormFields;
import us.mn.state.health.lims.common.formfields.FormFields.Field;
import us.mn.state.health.lims.common.services.IResultSaveService;
import us.mn.state.health.lims.common.services.registration.ResultUpdateRegister;
import us.mn.state.health.lims.common.services.registration.interfaces.IResultUpdate;
import us.mn.state.health.lims.common.util.ConfigurationProperties;
import us.mn.state.health.lims.common.util.ConfigurationProperties.Property;
import us.mn.state.health.lims.common.util.DateUtil;
import us.mn.state.health.lims.common.util.StringUtil;
import us.mn.state.health.lims.common.util.validator.ActionError;
import us.mn.state.health.lims.hibernate.HibernateUtil;
import us.mn.state.health.lims.note.dao.NoteDAO;
import us.mn.state.health.lims.note.daoimpl.NoteDAOImpl;
import us.mn.state.health.lims.note.util.NoteUtil;
import us.mn.state.health.lims.note.valueholder.Note;
import us.mn.state.health.lims.patient.valueholder.Patient;
import us.mn.state.health.lims.referral.dao.ReferralDAO;
import us.mn.state.health.lims.referral.dao.ReferralResultDAO;
import us.mn.state.health.lims.referral.dao.ReferralTypeDAO;
import us.mn.state.health.lims.referral.daoimpl.ReferralDAOImpl;
import us.mn.state.health.lims.referral.daoimpl.ReferralResultDAOImpl;
import us.mn.state.health.lims.referral.daoimpl.ReferralTypeDAOImpl;
import us.mn.state.health.lims.referral.valueholder.Referral;
import us.mn.state.health.lims.referral.valueholder.ReferralResult;
import us.mn.state.health.lims.referral.valueholder.ReferralType;
import us.mn.state.health.lims.result.action.util.*;
import us.mn.state.health.lims.result.dao.ResultDAO;
import us.mn.state.health.lims.result.dao.ResultInventoryDAO;
import us.mn.state.health.lims.result.dao.ResultSignatureDAO;
import us.mn.state.health.lims.result.daoimpl.ResultDAOImpl;
import us.mn.state.health.lims.result.daoimpl.ResultInventoryDAOImpl;
import us.mn.state.health.lims.result.daoimpl.ResultSignatureDAOImpl;
import us.mn.state.health.lims.result.valueholder.Result;
import us.mn.state.health.lims.result.valueholder.ResultInventory;
import us.mn.state.health.lims.result.valueholder.ResultSignature;
import us.mn.state.health.lims.resultlimits.dao.ResultLimitDAO;
import us.mn.state.health.lims.resultlimits.daoimpl.ResultLimitDAOImpl;
import us.mn.state.health.lims.resultlimits.valueholder.ResultLimit;
import us.mn.state.health.lims.sample.dao.SampleDAO;
import us.mn.state.health.lims.sample.daoimpl.SampleDAOImpl;
import us.mn.state.health.lims.sample.valueholder.Sample;
import us.mn.state.health.lims.samplehuman.dao.SampleHumanDAO;
import us.mn.state.health.lims.samplehuman.daoimpl.SampleHumanDAOImpl;
import us.mn.state.health.lims.samplehuman.valueholder.SampleHuman;
import us.mn.state.health.lims.statusofsample.util.StatusOfSampleUtil;
import us.mn.state.health.lims.statusofsample.util.StatusOfSampleUtil.AnalysisStatus;
import us.mn.state.health.lims.statusofsample.util.StatusOfSampleUtil.OrderStatus;
import us.mn.state.health.lims.test.beanItems.TestResultItem;
import us.mn.state.health.lims.testanalyte.valueholder.TestAnalyte;
import us.mn.state.health.lims.testreflex.action.util.TestReflexBean;
import us.mn.state.health.lims.testreflex.action.util.TestReflexUtil;
import us.mn.state.health.lims.testresult.dao.TestResultDAO;
import us.mn.state.health.lims.testresult.daoimpl.TestResultDAOImpl;
import us.mn.state.health.lims.testresult.valueholder.TestResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;
public class ResultsLogbookUpdateAction extends BaseAction implements IResultSaveService {
private List<TestResultItem> modifiedItems;
private List<ResultSet> modifiedResults;
private List<ResultSet> newResults;
private List<Analysis> modifiedAnalysis;
private List<Result> deletableResults;
private AnalysisDAO analysisDAO = new AnalysisDAOImpl();
private ResultDAO resultDAO = new ResultDAOImpl();
private TestResultDAO testResultDAO = new TestResultDAOImpl();
private ResultSignatureDAO resultSigDAO = new ResultSignatureDAOImpl();
private ResultInventoryDAO resultInventoryDAO = new ResultInventoryDAOImpl();
private NoteDAO noteDAO = new NoteDAOImpl();
private SampleDAO sampleDAO = new SampleDAOImpl();
private SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
private ReferralDAO referralDAO = new ReferralDAOImpl();
private ReferralResultDAO referralResultDAO = new ReferralResultDAOImpl();
private ResultLimitDAO resultLimitDAO = new ResultLimitDAOImpl();
private static Logger logger = LogManager.getLogger(ResultsLogbookUpdateAction.class);
private static final String RESULT_SUBJECT = "Result Note";
private static String REFERRAL_CONFORMATION_ID;
private boolean useTechnicianName = ConfigurationProperties.getInstance().isPropertyValueEqual(Property.resultTechnicianName, "true");
private boolean alwaysValidate = ConfigurationProperties.getInstance().isPropertyValueEqual(Property.ALWAYS_VALIDATE_RESULTS, "true");
private boolean supportReferrals = FormFields.getInstance().useField(Field.ResultsReferral);
private String statusRuleSet = ConfigurationProperties.getInstance().getPropertyValueUpperCase(Property.StatusRules);
private Analysis previousAnalysis;
private ResultsValidation resultValidation = new ResultsValidation();
static {
ReferralTypeDAO referralTypeDAO = new ReferralTypeDAOImpl();
ReferralType referralType = referralTypeDAO.getReferralTypeByName("Confirmation");
if (referralType != null) {
REFERRAL_CONFORMATION_ID = referralType.getId();
}
}
protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
+ Transaction tx = HibernateUtil.getSession().beginTransaction();
String forward = FWD_SUCCESS;
String referer = request.getParameter("referer");
List<IResultUpdate> updaters = ResultUpdateRegister.getRegisteredUpdaters();
BaseActionForm dynaForm = (BaseActionForm) form;
resultValidation.setSupportReferrals(supportReferrals);
resultValidation.setUseTechnicianName(useTechnicianName);
ResultsPaging paging = new ResultsPaging();
paging.updatePagedResults(request, dynaForm);
List<TestResultItem> tests = paging.getResults(request);
setModifiedItems(tests);
ActionMessages errors = resultValidation.validateModifiedItems(modifiedItems);
if (errors.size() > 0) {
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward(FWD_VALIDATION_ERROR);
}
initializeLists();
createResultsFromItems();
- Transaction tx = HibernateUtil.getSession().beginTransaction();
try {
for (ResultSet resultSet : newResults) {
resultDAO.insertData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
resultSigDAO.insertData(resultSet.signature);
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
resultInventoryDAO.insertData(resultSet.testKit);
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
noteDAO.insertData(resultSet.note);
}
if (resultSet.newReferral != null) {
insertNewReferralAndReferralResult(resultSet);
}
}
for (ResultSet resultSet : modifiedResults) {
resultDAO.updateData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
if (resultSet.alwaysInsertSignature) {
resultSigDAO.insertData(resultSet.signature);
} else {
resultSigDAO.updateData(resultSet.signature);
}
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
if (resultSet.testKit.getId() == null) {
resultInventoryDAO.insertData(resultSet.testKit);
} else {
resultInventoryDAO.updateData(resultSet.testKit);
}
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
if (resultSet.note.getId() == null) {
noteDAO.insertData(resultSet.note);
} else {
noteDAO.updateData(resultSet.note);
}
}
if (resultSet.newReferral != null) {
// we can't just create a referral with a blank result,
// because referral page assumes a referralResult and a
// result.
insertNewReferralAndReferralResult(resultSet);
}
if (resultSet.existingReferral != null) {
referralDAO.updateData(resultSet.existingReferral);
}
}
for (Analysis analysis : modifiedAnalysis) {
analysisDAO.updateData(analysis);
}
removeDeletedResults();
setTestReflexes();
setSampleStatus();
for (IResultUpdate updater : updaters) {
updater.transactionalUpdate(this);
}
tx.commit();
} catch (LIMSRuntimeException lre) {
logger.error("Could not update Results", lre);
tx.rollback();
ActionError error = null;
if (lre instanceof LIMSDuplicateRecordException) {
//error = new ActionError("errors.StaleViewException", ((LIMSDuplicateRecordException) lre).getObjectDescription(), "http://google.com?q=mujir", null);
error = new ActionError("errors.StaleViewException", null, null);
}
if (lre.getException() instanceof StaleObjectStateException) {
error = new ActionError("errors.OptimisticLockException", null, null);
}
if (error == null) {
lre.printStackTrace();
error = new ActionError("errors.UpdateException", null, null);
}
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward("error");
}
for (IResultUpdate updater : updaters) {
updater.postTransactionalCommitUpdate(this);
}
setSuccessFlag(request, forward);
if(referer != null && referer.matches("LabDashboard")) {
return mapping.findForward(FWD_DASHBOARD);
}
if (GenericValidator.isBlankOrNull(dynaForm.getString("logbookType"))) {
return mapping.findForward(forward);
} else {
Map<String, String> params = new HashMap<String, String>();
params.put("type", dynaForm.getString("logbookType"));
params.put("forward", forward);
return getForwardWithParameters(mapping.findForward(forward), params);
}
}
private void insertNewReferralAndReferralResult(ResultSet resultSet) {
referralDAO.insertData(resultSet.newReferral);
ReferralResult referralResult = new ReferralResult();
referralResult.setReferralId(resultSet.newReferral.getId());
referralResult.setSysUserId(currentUserId);
referralResult.setResult(resultSet.result);
referralResultDAO.saveOrUpdateData(referralResult);
}
private void removeDeletedResults() {
for (Result result : deletableResults) {
List<ResultSignature> signatures = resultSigDAO.getResultSignaturesByResult(result);
List<ReferralResult> referrals = referralResultDAO.getReferralsByResultId(result.getId());
for (ResultSignature signature : signatures) {
signature.setSysUserId(currentUserId);
}
resultSigDAO.deleteData(signatures);
for (ReferralResult referral : referrals) {
referral.setSysUserId(currentUserId);
referralResultDAO.deleteData(referral);
}
result.setSysUserId(currentUserId);
resultDAO.deleteData(result);
}
}
protected void setTestReflexes() {
TestReflexUtil testReflexUtil = new TestReflexUtil();
testReflexUtil.setCurrentUserId(currentUserId);
testReflexUtil.addNewTestsToDBForReflexTests(convertToTestReflexBeanList(newResults));
testReflexUtil.updateModifiedReflexes(convertToTestReflexBeanList(modifiedResults));
}
private List<TestReflexBean> convertToTestReflexBeanList(List<ResultSet> resultSetList) {
List<TestReflexBean> reflexBeanList = new ArrayList<TestReflexBean>();
for (ResultSet resultSet : resultSetList) {
TestReflexBean reflex = new TestReflexBean();
reflex.setPatient(resultSet.patient);
reflex.setReflexSelectionId(resultSet.actionSelectionId);
reflex.setResult(resultSet.result);
reflex.setSample(resultSet.sample);
reflexBeanList.add(reflex);
}
return reflexBeanList;
}
private void setSampleStatus() {
Set<Sample> sampleSet = new HashSet<Sample>();
for (ResultSet resultSet : newResults) {
sampleSet.add(resultSet.sample);
}
String sampleTestingStartedId = StatusOfSampleUtil.getStatusID(OrderStatus.Started);
String sampleNonConformingId = StatusOfSampleUtil.getStatusID(OrderStatus.NonConforming_depricated);
for (Sample sample : sampleSet) {
if (!(sample.getStatusId().equals(sampleNonConformingId) || sample.getStatusId().equals(sampleTestingStartedId))) {
Sample newSample = new Sample();
newSample.setId(sample.getId());
sampleDAO.getData(newSample);
newSample.setStatusId(sampleTestingStartedId);
newSample.setSysUserId(currentUserId);
sampleDAO.updateData(newSample);
}
}
}
private void setModifiedItems(List<TestResultItem> allItems) {
modifiedItems = new ArrayList<TestResultItem>();
for (TestResultItem item : allItems) {
if (item.getIsModified() && (ResultUtil.areResults(item) || ResultUtil.areNotes(item) || item.isReferredOut())) {
modifiedItems.add(item);
}
}
}
private void createResultsFromItems() {
for (TestResultItem testResultItem : modifiedItems) {
Analysis analysis = analysisDAO.getAnalysisById(testResultItem.getAnalysisId());
List<Result> results = createResultFromTestResultItem(testResultItem, analysis);
for (Result result : results) {
addResult(result, testResultItem, analysis);
if (resultHasValueOrIsReferral(testResultItem, result)) {
updateAndAddAnalysisToModifiedList(testResultItem, testResultItem.getTestDate(), analysis);
}
}
}
}
protected void initializeLists() {
modifiedResults = new ArrayList<ResultSet>();
newResults = new ArrayList<ResultSet>();
modifiedAnalysis = new ArrayList<Analysis>();
deletableResults = new ArrayList<Result>();
}
protected boolean resultHasValueOrIsReferral(TestResultItem testResultItem, Result result) {
return result != null && !GenericValidator.isBlankOrNull(result.getValue())
|| (supportReferrals && testResultItem.isReferredOut());
}
private void addResult(Result result, TestResultItem testResultItem, Analysis analysis) {
boolean newResult = result.getId() == null;
boolean newAnalysisInLoop = analysis != previousAnalysis;
ResultSignature technicianResultSignature = null;
if (useTechnicianName && newAnalysisInLoop) {
technicianResultSignature = createTechnicianSignatureFromResultItem(testResultItem);
}
ResultInventory testKit = createTestKitLinkIfNeeded(testResultItem, ResultsLoadUtility.TESTKIT);
Note note = NoteUtil.createSavableNote(null, testResultItem.getNote(), testResultItem.getResultId(),
ResultsLoadUtility.getResultReferenceTableId(), RESULT_SUBJECT, currentUserId);
setAnalysisStatus(testResultItem, analysis);
analysis.setEnteredDate(DateUtil.getNowAsTimestamp());
if (newResult) {
analysis.setEnteredDate(DateUtil.getNowAsTimestamp());
analysis.setRevision("1");
} else if (newAnalysisInLoop) {
analysis.setRevision(String.valueOf(Integer.parseInt(analysis.getRevision()) + 1));
}
Sample sample = sampleDAO.getSampleByAccessionNumber(testResultItem.getAccessionNumber());
Patient patient = null;
if ("H".equals(sample.getDomain())) {
SampleHuman sampleHuman = new SampleHuman();
sampleHuman.setSampleId(sample.getId());
sampleHumanDAO.getDataBySample(sampleHuman);
patient = new Patient();
patient.setId(sampleHuman.getPatientId());
}
Referral referral = null;
Referral existingReferral = null;
if (supportReferrals) {
// referredOut means the referral checkbox was checked, repeating
// analysis means that we have multi-select results, so only do one.
if (testResultItem.isReferredOut() && newAnalysisInLoop) {
// If it is a new result or there is no referral ID that means
// that a new referral has to be created if it was checked and
// it was canceled then we are un-canceling a canceled referral
if (newResult || GenericValidator.isBlankOrNull(testResultItem.getReferralId())) {
referral = new Referral();
referral.setReferralTypeId(REFERRAL_CONFORMATION_ID);
referral.setSysUserId(currentUserId);
referral.setRequestDate(new Timestamp(new Date().getTime()));
referral.setRequesterName(testResultItem.getTechnician());
referral.setAnalysis(analysis);
referral.setReferralReasonId(testResultItem.getReferralReasonId());
} else if (testResultItem.isReferralCanceled()) {
existingReferral = referralDAO.getReferralById(testResultItem.getReferralId());
existingReferral.setCanceled(false);
existingReferral.setSysUserId(currentUserId);
existingReferral.setRequesterName(testResultItem.getTechnician());
existingReferral.setReferralReasonId(testResultItem.getReferralReasonId());
}
}
}
String actionSelectionId = testResultItem.getReflexSelectionId();
if (newResult) {
newResults.add(new ResultSet(result, technicianResultSignature, testKit, note, patient, sample, actionSelectionId, referral,
existingReferral));
} else {
modifiedResults.add(new ResultSet(result, technicianResultSignature, testKit, note, patient, sample, actionSelectionId,
referral, existingReferral));
}
previousAnalysis = analysis;
}
private void setAnalysisStatus(TestResultItem testResultItem, Analysis analysis) {
if (supportReferrals && testResultItem.isReferredOut()) {
analysis.setStatusId(StatusOfSampleUtil.getStatusID(AnalysisStatus.ReferedOut));
} else {
analysis.setStatusId(getStatusForTestResult(testResultItem));
}
}
private String getStatusForTestResult(TestResultItem testResult) {
if (alwaysValidate || !testResult.isValid()) {
return StatusOfSampleUtil.getStatusID(AnalysisStatus.TechnicalAcceptance);
} else {
ResultLimit resultLimit = resultLimitDAO.getResultLimitById(testResult.getResultLimitId());
if (resultLimit != null && resultLimit.isAlwaysValidate()) {
return StatusOfSampleUtil.getStatusID(AnalysisStatus.TechnicalAcceptance);
}
return StatusOfSampleUtil.getStatusID(AnalysisStatus.Finalized);
}
}
private ResultInventory createTestKitLinkIfNeeded(TestResultItem testResult, String testKitName) {
ResultInventory testKit = null;
if ((TestResultItem.ResultDisplayType.SYPHILIS == testResult.getRawResultDisplayType() || TestResultItem.ResultDisplayType.HIV == testResult
.getRawResultDisplayType()) && ResultsLoadUtility.TESTKIT.equals(testKitName)) {
testKit = creatTestKit(testResult, testKitName, testResult.getTestKitId());
}
return testKit;
}
private ResultInventory creatTestKit(TestResultItem testResult, String testKitName, String testKitId) throws LIMSRuntimeException {
ResultInventory testKit;
testKit = new ResultInventory();
if (!GenericValidator.isBlankOrNull(testKitId)) {
testKit.setId(testKitId);
resultInventoryDAO.getData(testKit);
}
testKit.setInventoryLocationId(testResult.getTestKitInventoryId());
testKit.setDescription(testKitName);
testKit.setSysUserId(currentUserId);
return testKit;
}
private void updateAndAddAnalysisToModifiedList(TestResultItem testResultItem, String testDate, Analysis analysis) {
String testMethod = testResultItem.getAnalysisMethod();
analysis.setAnalysisType(testMethod);
analysis.setStartedDateForDisplay(testDate);
//This needs to be refactored -- part of the logic is in getStatusForTestResult
if (statusRuleSet.equals(IActionConstants.STATUS_RULES_RETROCI)) {
if (analysis.getStatusId() != StatusOfSampleUtil.getStatusID(AnalysisStatus.Canceled)) {
analysis.setCompletedDate(DateUtil.convertStringDateToSqlDate(testDate));
analysis.setStatusId(StatusOfSampleUtil.getStatusID(AnalysisStatus.TechnicalAcceptance));
}
} else if (analysis.getStatusId() == StatusOfSampleUtil.getStatusID(AnalysisStatus.Finalized) ||
analysis.getStatusId() == StatusOfSampleUtil.getStatusID(AnalysisStatus.TechnicalAcceptance) ||
(analysis.getStatusId() == StatusOfSampleUtil.getStatusID(AnalysisStatus.ReferedOut) && !GenericValidator
.isBlankOrNull(testResultItem.getResultValue()))) {
analysis.setCompletedDate(DateUtil.convertStringDateToSqlDate(testDate));
}
analysis.setSysUserId(currentUserId);
modifiedAnalysis.add(analysis);
}
@SuppressWarnings("unchecked")
private List<Result> createResultFromTestResultItem(TestResultItem testResultItem, Analysis analysis) {
List<Result> results = new ArrayList<Result>();
if ("M".equals(testResultItem.getResultType())) {
String[] multiResults = testResultItem.getMultiSelectResultValues().split(",");
List<Result> existingResults = resultDAO.getResultsByAnalysis(analysis);
for (int i = 0; i < multiResults.length; i++) {
Result existingResultFromDB = null;
for (Result existingResult : existingResults) {
if (multiResults[i].equals(existingResult.getValue())) {
existingResultFromDB = existingResult;
break;
}
}
if (existingResultFromDB != null) {
existingResults.remove(existingResultFromDB);
existingResultFromDB.setSysUserId(currentUserId);
results.add(existingResultFromDB);
continue;
}
Result result = new Result();
setTestResultsForDictionaryResult(testResultItem.getTestId(), multiResults[i], result);
setNewResultValues(testResultItem, analysis, result);
setStandardResultValues(multiResults[i], result);
result.setSortOrder(getResultSortOrder(analysis, result.getValue()));
results.add(result);
}
deletableResults.addAll(existingResults);
} else {
Result result = new Result();
Result qualifiedResult = null;
boolean newResult = GenericValidator.isBlankOrNull(testResultItem.getResultId());
boolean isQualifiedResult = "Q".equals(testResultItem.getResultType());
if (!newResult) {
result.setId(testResultItem.getResultId());
resultDAO.getData(result);
if (!GenericValidator.isBlankOrNull(testResultItem.getQualifiedResultId())) {
qualifiedResult = new Result();
qualifiedResult.setId(testResultItem.getQualifiedResultId());
resultDAO.getData(qualifiedResult);
}
}
if ("D".equals(testResultItem.getResultType()) || isQualifiedResult) {
setTestResultsForDictionaryResult(testResultItem.getTestId(), testResultItem.getResultValue(), result);
} else {
List<TestResult> testResultList = testResultDAO.getTestResultsByTest(testResultItem.getTestId());
// we are assuming there is only one testResult for a numeric
// type result
if (!testResultList.isEmpty()) {
result.setTestResult(testResultList.get(0));
}
}
if (newResult) {
setNewResultValues(testResultItem, analysis, result);
if (isQualifiedResult) {
qualifiedResult = new Result();
setNewResultValues(testResultItem, analysis, qualifiedResult);
qualifiedResult.setResultType("A");
qualifiedResult.setParentResult(result);
}
} else {
setAnalyteForResult(result);
}
setStandardResultValues(testResultItem.getResultValue(), result);
results.add(result);
if (isQualifiedResult) {
setStandardResultValues(testResultItem.getQualifiedResultValue(), qualifiedResult);
results.add(qualifiedResult);
}
}
return results;
}
private String getResultSortOrder(Analysis analysis, String resultValue) {
TestResult testResult = testResultDAO.getTestResultsByTestAndDictonaryResult(analysis.getTest().getId(), resultValue);
return testResult == null ? "0" : testResult.getSortOrder();
}
private void setStandardResultValues(String value, Result result) {
result.setValue(value);
result.setSysUserId(currentUserId);
result.setSortOrder("0");
}
private void setNewResultValues(TestResultItem testResultItem, Analysis analysis, Result result) {
result.setAnalysis(analysis);
result.setAnalysisId(testResultItem.getAnalysisId());
result.setIsReportable(testResultItem.getReportable());
result.setResultType(testResultItem.getResultType());
result.setMinNormal(testResultItem.getLowerNormalRange());
result.setMaxNormal(testResultItem.getUpperNormalRange());
setAnalyteForResult(result);
}
private void setAnalyteForResult(Result result) {
TestAnalyte testAnalyte = ResultUtil.getTestAnalyteForResult(result);
if (testAnalyte != null) {
result.setAnalyte(testAnalyte.getAnalyte());
}
}
private TestResult setTestResultsForDictionaryResult(String testId, String dictValue, Result result) {
TestResult testResult = null;
testResult = testResultDAO.getTestResultsByTestAndDictonaryResult(testId, dictValue);
if (testResult != null) {
result.setTestResult(testResult);
}
return testResult;
}
private ResultSignature createTechnicianSignatureFromResultItem(TestResultItem testResult) {
ResultSignature sig = null;
// The technician signature may be blank if the user changed a
// conclusion and then changed it back. It will be dirty
// but will not need a signature
if (!GenericValidator.isBlankOrNull(testResult.getTechnician())) {
sig = new ResultSignature();
if (!GenericValidator.isBlankOrNull(testResult.getTechnicianSignatureId())) {
sig.setId(testResult.getTechnicianSignatureId());
resultSigDAO.getData(sig);
}
sig.setIsSupervisor(false);
sig.setNonUserName(testResult.getTechnician());
sig.setSysUserId(currentUserId);
}
return sig;
}
protected ActionForward getForward(ActionForward forward, String accessionNumber) {
ActionRedirect redirect = new ActionRedirect(forward);
if (!StringUtil.isNullorNill(accessionNumber))
redirect.addParameter(ACCESSION_NUMBER, accessionNumber);
return redirect;
}
protected ActionForward getForward(ActionForward forward, String accessionNumber, String analysisId) {
ActionRedirect redirect = new ActionRedirect(forward);
if (!StringUtil.isNullorNill(accessionNumber))
redirect.addParameter(ACCESSION_NUMBER, accessionNumber);
if (!StringUtil.isNullorNill(analysisId))
redirect.addParameter(ANALYSIS_ID, analysisId);
return redirect;
}
@Override
protected String getPageSubtitleKey() {
return "banner.menu.results";
}
@Override
protected String getPageTitleKey() {
return "banner.menu.results";
}
@Override
public String getCurrentUserId() {
return currentUserId;
}
@Override
public List<ResultSet> getNewResults() {
return newResults;
}
@Override
public List<ResultSet> getModifiedResults() {
return modifiedResults;
}
}
| false | true | protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
String forward = FWD_SUCCESS;
String referer = request.getParameter("referer");
List<IResultUpdate> updaters = ResultUpdateRegister.getRegisteredUpdaters();
BaseActionForm dynaForm = (BaseActionForm) form;
resultValidation.setSupportReferrals(supportReferrals);
resultValidation.setUseTechnicianName(useTechnicianName);
ResultsPaging paging = new ResultsPaging();
paging.updatePagedResults(request, dynaForm);
List<TestResultItem> tests = paging.getResults(request);
setModifiedItems(tests);
ActionMessages errors = resultValidation.validateModifiedItems(modifiedItems);
if (errors.size() > 0) {
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward(FWD_VALIDATION_ERROR);
}
initializeLists();
createResultsFromItems();
Transaction tx = HibernateUtil.getSession().beginTransaction();
try {
for (ResultSet resultSet : newResults) {
resultDAO.insertData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
resultSigDAO.insertData(resultSet.signature);
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
resultInventoryDAO.insertData(resultSet.testKit);
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
noteDAO.insertData(resultSet.note);
}
if (resultSet.newReferral != null) {
insertNewReferralAndReferralResult(resultSet);
}
}
for (ResultSet resultSet : modifiedResults) {
resultDAO.updateData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
if (resultSet.alwaysInsertSignature) {
resultSigDAO.insertData(resultSet.signature);
} else {
resultSigDAO.updateData(resultSet.signature);
}
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
if (resultSet.testKit.getId() == null) {
resultInventoryDAO.insertData(resultSet.testKit);
} else {
resultInventoryDAO.updateData(resultSet.testKit);
}
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
if (resultSet.note.getId() == null) {
noteDAO.insertData(resultSet.note);
} else {
noteDAO.updateData(resultSet.note);
}
}
if (resultSet.newReferral != null) {
// we can't just create a referral with a blank result,
// because referral page assumes a referralResult and a
// result.
insertNewReferralAndReferralResult(resultSet);
}
if (resultSet.existingReferral != null) {
referralDAO.updateData(resultSet.existingReferral);
}
}
for (Analysis analysis : modifiedAnalysis) {
analysisDAO.updateData(analysis);
}
removeDeletedResults();
setTestReflexes();
setSampleStatus();
for (IResultUpdate updater : updaters) {
updater.transactionalUpdate(this);
}
tx.commit();
} catch (LIMSRuntimeException lre) {
logger.error("Could not update Results", lre);
tx.rollback();
ActionError error = null;
if (lre instanceof LIMSDuplicateRecordException) {
//error = new ActionError("errors.StaleViewException", ((LIMSDuplicateRecordException) lre).getObjectDescription(), "http://google.com?q=mujir", null);
error = new ActionError("errors.StaleViewException", null, null);
}
if (lre.getException() instanceof StaleObjectStateException) {
error = new ActionError("errors.OptimisticLockException", null, null);
}
if (error == null) {
lre.printStackTrace();
error = new ActionError("errors.UpdateException", null, null);
}
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward("error");
}
for (IResultUpdate updater : updaters) {
updater.postTransactionalCommitUpdate(this);
}
setSuccessFlag(request, forward);
if(referer != null && referer.matches("LabDashboard")) {
return mapping.findForward(FWD_DASHBOARD);
}
if (GenericValidator.isBlankOrNull(dynaForm.getString("logbookType"))) {
return mapping.findForward(forward);
} else {
Map<String, String> params = new HashMap<String, String>();
params.put("type", dynaForm.getString("logbookType"));
params.put("forward", forward);
return getForwardWithParameters(mapping.findForward(forward), params);
}
}
| protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Transaction tx = HibernateUtil.getSession().beginTransaction();
String forward = FWD_SUCCESS;
String referer = request.getParameter("referer");
List<IResultUpdate> updaters = ResultUpdateRegister.getRegisteredUpdaters();
BaseActionForm dynaForm = (BaseActionForm) form;
resultValidation.setSupportReferrals(supportReferrals);
resultValidation.setUseTechnicianName(useTechnicianName);
ResultsPaging paging = new ResultsPaging();
paging.updatePagedResults(request, dynaForm);
List<TestResultItem> tests = paging.getResults(request);
setModifiedItems(tests);
ActionMessages errors = resultValidation.validateModifiedItems(modifiedItems);
if (errors.size() > 0) {
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward(FWD_VALIDATION_ERROR);
}
initializeLists();
createResultsFromItems();
try {
for (ResultSet resultSet : newResults) {
resultDAO.insertData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
resultSigDAO.insertData(resultSet.signature);
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
resultInventoryDAO.insertData(resultSet.testKit);
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
noteDAO.insertData(resultSet.note);
}
if (resultSet.newReferral != null) {
insertNewReferralAndReferralResult(resultSet);
}
}
for (ResultSet resultSet : modifiedResults) {
resultDAO.updateData(resultSet.result);
if (resultSet.signature != null) {
resultSet.signature.setResultId(resultSet.result.getId());
if (resultSet.alwaysInsertSignature) {
resultSigDAO.insertData(resultSet.signature);
} else {
resultSigDAO.updateData(resultSet.signature);
}
}
if (resultSet.testKit != null && resultSet.testKit.getInventoryLocationId() != null) {
resultSet.testKit.setResultId(resultSet.result.getId());
if (resultSet.testKit.getId() == null) {
resultInventoryDAO.insertData(resultSet.testKit);
} else {
resultInventoryDAO.updateData(resultSet.testKit);
}
}
if (resultSet.note != null) {
resultSet.note.setReferenceId(resultSet.result.getId());
if (resultSet.note.getId() == null) {
noteDAO.insertData(resultSet.note);
} else {
noteDAO.updateData(resultSet.note);
}
}
if (resultSet.newReferral != null) {
// we can't just create a referral with a blank result,
// because referral page assumes a referralResult and a
// result.
insertNewReferralAndReferralResult(resultSet);
}
if (resultSet.existingReferral != null) {
referralDAO.updateData(resultSet.existingReferral);
}
}
for (Analysis analysis : modifiedAnalysis) {
analysisDAO.updateData(analysis);
}
removeDeletedResults();
setTestReflexes();
setSampleStatus();
for (IResultUpdate updater : updaters) {
updater.transactionalUpdate(this);
}
tx.commit();
} catch (LIMSRuntimeException lre) {
logger.error("Could not update Results", lre);
tx.rollback();
ActionError error = null;
if (lre instanceof LIMSDuplicateRecordException) {
//error = new ActionError("errors.StaleViewException", ((LIMSDuplicateRecordException) lre).getObjectDescription(), "http://google.com?q=mujir", null);
error = new ActionError("errors.StaleViewException", null, null);
}
if (lre.getException() instanceof StaleObjectStateException) {
error = new ActionError("errors.OptimisticLockException", null, null);
}
if (error == null) {
lre.printStackTrace();
error = new ActionError("errors.UpdateException", null, null);
}
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward("error");
}
for (IResultUpdate updater : updaters) {
updater.postTransactionalCommitUpdate(this);
}
setSuccessFlag(request, forward);
if(referer != null && referer.matches("LabDashboard")) {
return mapping.findForward(FWD_DASHBOARD);
}
if (GenericValidator.isBlankOrNull(dynaForm.getString("logbookType"))) {
return mapping.findForward(forward);
} else {
Map<String, String> params = new HashMap<String, String>();
params.put("type", dynaForm.getString("logbookType"));
params.put("forward", forward);
return getForwardWithParameters(mapping.findForward(forward), params);
}
}
|
diff --git a/src/java/org/onesocialweb/openfire/handler/activity/ActivityPublishHandler.java b/src/java/org/onesocialweb/openfire/handler/activity/ActivityPublishHandler.java
index 12ad64e..307e0b2 100644
--- a/src/java/org/onesocialweb/openfire/handler/activity/ActivityPublishHandler.java
+++ b/src/java/org/onesocialweb/openfire/handler/activity/ActivityPublishHandler.java
@@ -1,145 +1,145 @@
/*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.openfire.handler.activity;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Element;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.openfire.handler.pep.PEPCommandHandler;
import org.onesocialweb.openfire.manager.ActivityManager;
import org.onesocialweb.openfire.model.activity.PersistentActivityDomReader;
import org.onesocialweb.xml.dom.ActivityDomReader;
import org.onesocialweb.xml.dom4j.ElementAdapter;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
public class ActivityPublishHandler extends PEPCommandHandler {
public static final String COMMAND = "publish";
private UserManager userManager;
private ActivityManager activityManager;
public ActivityPublishHandler() {
super("OneSocialWeb - Publish activity handler");
}
@Override
public String getCommand() {
return COMMAND;
}
@SuppressWarnings( { "deprecation", "unchecked" })
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException {
final JID sender = packet.getFrom();
final JID recipient = packet.getTo();
// Process the request inside a try/catch so that unhandled exceptions
// (oufofbounds etc...) can trigger a server error and we can send a
// error result packet
try {
// A valid request is an IQ of type set,
if (!packet.getType().equals(IQ.Type.set)) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.bad_request);
return result;
}
// If a recipient is specified, it must be equal to the sender
// bareJID
- if (recipient != null && !recipient.equals(sender.toBareJID())) {
+ if (recipient != null && !recipient.toString().equals(sender.toBareJID())) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.not_authorized);
return result;
}
// Only a local user can publish an activity to his stream
if (!userManager.isRegisteredUser(sender.getNode())) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.not_authorized);
return result;
}
// A valid submit request must contain at least one entry
Element pubsubElement = packet.getChildElement();
Element publishElement = pubsubElement.element("publish");
List<Element> items = publishElement.elements("item");
if (items == null || items.size() == 0) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.bad_request);
return result;
}
// Parse the activities
ActivityDomReader reader = new PersistentActivityDomReader();
List<String> itemIds = new ArrayList<String>(items.size());
for (Element item : items) {
Element entry = item.element("entry");
if (entry != null) {
ActivityEntry activity = reader.readEntry(new ElementAdapter(entry));
Log.debug("ActivityPublishHandler received activity: " + activity);
try {
activityManager.publishActivity(sender.toBareJID(), activity);
itemIds.add(activity.getId());
} catch (UserNotFoundException e) {}
}
}
// Send a success result
IQ result = IQ.createResultIQ(packet);
Element resultPubsubElement = result.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");
Element resultPublishElement = resultPubsubElement.addElement("publish", "http://jabber.org/protocol/pubsub");
resultPublishElement.addAttribute("node", PEPActivityHandler.NODE);
for (String itemId : itemIds) {
Element itemElement = resultPublishElement.addElement("item");
itemElement.addAttribute("id", itemId);
}
return result;
} catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.internal_server_error);
return result;
}
}
@Override
public void initialize(XMPPServer server) {
super.initialize(server);
userManager = server.getUserManager();
activityManager = ActivityManager.getInstance();
}
}
| true | true | public IQ handleIQ(IQ packet) throws UnauthorizedException {
final JID sender = packet.getFrom();
final JID recipient = packet.getTo();
// Process the request inside a try/catch so that unhandled exceptions
// (oufofbounds etc...) can trigger a server error and we can send a
// error result packet
try {
// A valid request is an IQ of type set,
if (!packet.getType().equals(IQ.Type.set)) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.bad_request);
return result;
}
// If a recipient is specified, it must be equal to the sender
// bareJID
if (recipient != null && !recipient.equals(sender.toBareJID())) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.not_authorized);
return result;
}
// Only a local user can publish an activity to his stream
if (!userManager.isRegisteredUser(sender.getNode())) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.not_authorized);
return result;
}
// A valid submit request must contain at least one entry
Element pubsubElement = packet.getChildElement();
Element publishElement = pubsubElement.element("publish");
List<Element> items = publishElement.elements("item");
if (items == null || items.size() == 0) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.bad_request);
return result;
}
// Parse the activities
ActivityDomReader reader = new PersistentActivityDomReader();
List<String> itemIds = new ArrayList<String>(items.size());
for (Element item : items) {
Element entry = item.element("entry");
if (entry != null) {
ActivityEntry activity = reader.readEntry(new ElementAdapter(entry));
Log.debug("ActivityPublishHandler received activity: " + activity);
try {
activityManager.publishActivity(sender.toBareJID(), activity);
itemIds.add(activity.getId());
} catch (UserNotFoundException e) {}
}
}
// Send a success result
IQ result = IQ.createResultIQ(packet);
Element resultPubsubElement = result.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");
Element resultPublishElement = resultPubsubElement.addElement("publish", "http://jabber.org/protocol/pubsub");
resultPublishElement.addAttribute("node", PEPActivityHandler.NODE);
for (String itemId : itemIds) {
Element itemElement = resultPublishElement.addElement("item");
itemElement.addAttribute("id", itemId);
}
return result;
} catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.internal_server_error);
return result;
}
}
| public IQ handleIQ(IQ packet) throws UnauthorizedException {
final JID sender = packet.getFrom();
final JID recipient = packet.getTo();
// Process the request inside a try/catch so that unhandled exceptions
// (oufofbounds etc...) can trigger a server error and we can send a
// error result packet
try {
// A valid request is an IQ of type set,
if (!packet.getType().equals(IQ.Type.set)) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.bad_request);
return result;
}
// If a recipient is specified, it must be equal to the sender
// bareJID
if (recipient != null && !recipient.toString().equals(sender.toBareJID())) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.not_authorized);
return result;
}
// Only a local user can publish an activity to his stream
if (!userManager.isRegisteredUser(sender.getNode())) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.not_authorized);
return result;
}
// A valid submit request must contain at least one entry
Element pubsubElement = packet.getChildElement();
Element publishElement = pubsubElement.element("publish");
List<Element> items = publishElement.elements("item");
if (items == null || items.size() == 0) {
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.bad_request);
return result;
}
// Parse the activities
ActivityDomReader reader = new PersistentActivityDomReader();
List<String> itemIds = new ArrayList<String>(items.size());
for (Element item : items) {
Element entry = item.element("entry");
if (entry != null) {
ActivityEntry activity = reader.readEntry(new ElementAdapter(entry));
Log.debug("ActivityPublishHandler received activity: " + activity);
try {
activityManager.publishActivity(sender.toBareJID(), activity);
itemIds.add(activity.getId());
} catch (UserNotFoundException e) {}
}
}
// Send a success result
IQ result = IQ.createResultIQ(packet);
Element resultPubsubElement = result.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");
Element resultPublishElement = resultPubsubElement.addElement("publish", "http://jabber.org/protocol/pubsub");
resultPublishElement.addAttribute("node", PEPActivityHandler.NODE);
for (String itemId : itemIds) {
Element itemElement = resultPublishElement.addElement("item");
itemElement.addAttribute("id", itemId);
}
return result;
} catch (Exception e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
IQ result = IQ.createResultIQ(packet);
result.setChildElement(packet.getChildElement().createCopy());
result.setError(PacketError.Condition.internal_server_error);
return result;
}
}
|
diff --git a/syncronizer/src/org/sync/GitImporter.java b/syncronizer/src/org/sync/GitImporter.java
index 74cac74..348c8c8 100644
--- a/syncronizer/src/org/sync/GitImporter.java
+++ b/syncronizer/src/org/sync/GitImporter.java
@@ -1,487 +1,487 @@
/*****************************************************************************
This file is part of Git-Starteam.
Git-Starteam 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.
Git-Starteam 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 Git-Starteam. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.sync;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.ossnoize.git.fastimport.Blob;
import org.ossnoize.git.fastimport.Commit;
import org.ossnoize.git.fastimport.Data;
import org.ossnoize.git.fastimport.FileDelete;
import org.ossnoize.git.fastimport.FileModification;
import org.ossnoize.git.fastimport.FileOperation;
import org.ossnoize.git.fastimport.enumeration.GitFileType;
import org.ossnoize.git.fastimport.exception.InvalidPathException;
import org.sync.util.CommitInformation;
import org.sync.util.TempFileManager;
import com.starbase.starteam.Folder;
import com.starbase.starteam.Item;
import com.starbase.starteam.Project;
import com.starbase.starteam.RecycleBin;
import com.starbase.starteam.Server;
import com.starbase.starteam.Status;
import com.starbase.starteam.Type;
import com.starbase.starteam.View;
import com.starbase.starteam.File;
import com.starbase.starteam.CheckoutManager;
import com.starbase.starteam.ViewConfiguration;
import com.starbase.util.OLEDate;
public class GitImporter {
private Server server;
private Project project;
private Folder folder;
private int folderNameLength;
private long lastModifiedTime = 0;
private Map<CommitInformation, File> sortedFileList = new TreeMap<CommitInformation, File>();
private Map<CommitInformation, File> AddedSortedFileList = new TreeMap<CommitInformation, File>();
private Map<CommitInformation, File> lastSortedFileList = new TreeMap<CommitInformation, File>();
private Commit lastCommit;
// get the really old time as base information;
private CommitInformation lastInformation = null;
private OutputStream exportStream;
private String alternateHead = null;
private boolean isResume = false;
private RepositoryHelper helper;
// Use these sets to find all the deleted files.
private Set<String> files = new HashSet<String>();
private Set<String> deletedFiles = new HashSet<String>();
private Set<String> lastFiles = new HashSet<String>();
public GitImporter(Server s, Project p) {
server = s;
project = p;
helper = RepositoryHelperFactory.getFactory().createHelper();
}
public long getLastModifiedTime() {
return lastModifiedTime;
}
public void setFolder(View view, String folderPath) {
if(null != folderPath) {
recursiveFolderPopulation(view.getRootFolder(), folderPath);
folderNameLength = folderPath.length();
} else {
folder = view.getRootFolder();
folderNameLength = 0;
}
}
public Folder getFolder() {
return folder;
}
public void recursiveLastModifiedTime(Folder f) {
for(Item i : f.getItems(f.getTypeNames().FILE)) {
if(i instanceof File) {
long modifiedTime = i.getModifiedTime().getLongValue();
if(modifiedTime > lastModifiedTime) {
lastModifiedTime = modifiedTime;
}
i.discard();
}
}
for(Folder subfolder : f.getSubFolders()) {
recursiveLastModifiedTime(subfolder);
}
f.discard();
}
public void setLastFilesLastSortedFileList(View view, String folderPath) {
folder = null;
setFolder(view, folderPath);
if(null == folder) {
return;
}
files.clear();
deletedFiles.clear();
deletedFiles.addAll(lastFiles);
sortedFileList.clear();
recursiveFilePopulation(folder);
lastFiles.clear();
lastFiles.addAll(files);
lastSortedFileList.clear();
lastSortedFileList.putAll(sortedFileList);
AddedSortedFileList.clear();
}
public void generateFastImportStream(View view, String folderPath, String domain) {
// http://techpubs.borland.com/starteam/2009/en/sdk_documentation/api/com/starbase/starteam/CheckoutManager.html
// said old version (passed in /opt/StarTeamCP_2005r2/lib/starteam80.jar) "Deprecated. Use View.createCheckoutManager() instead."
CheckoutManager cm = new CheckoutManager(view);
cm.getOptions().setEOLConversionEnabled(false);
lastInformation = new CommitInformation(Long.MIN_VALUE, Integer.MIN_VALUE, "", "");
folder = null;
setFolder(view, folderPath);
if(null == folder) {
return;
}
String head = view.getName();
if(null != alternateHead) {
head = alternateHead;
}
files.clear();
deletedFiles.clear();
deletedFiles.addAll(lastFiles);
sortedFileList.clear();
recursiveFilePopulation(folder);
lastFiles.clear();
lastFiles.addAll(files);
lastSortedFileList.clear();
lastSortedFileList.putAll(sortedFileList);
recoverDeleteInformation(deletedFiles, head, view);
exportStream = helper.getFastImportStream();
for(Map.Entry<CommitInformation, File> e : AddedSortedFileList.entrySet()) {
File f = e.getValue();
CommitInformation current = e.getKey();
String userName = server.getUser(current.getUid()).getName();
String userEmail = userName.replaceAll(" ", ".") + "@" + domain;
String path = f.getParentFolderHierarchy() + f.getName();
path = path.replace('\\', '/');
// Strip the view name from the path
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1 + folderNameLength);
try {
if(f.getStatus() == Status.CURRENT) {
f.discard();
continue;
}
if(f.getStatusByMD5(helper.getMD5Of(path, head)) == Status.CURRENT) {
f.discard();
continue;
}
FileOperation fo = null;
java.io.File aFile = null;
if(f.isDeleted() || current.isFileMove()) {
fo = new FileDelete();
fo.setPath(current.getPath());
helper.unregisterFileId(head, path);
} else {
aFile = TempFileManager.getInstance().createTempFile("StarteamFile", ".tmp");
cm.checkoutTo(f, aFile);
Integer fileid = helper.getRegisteredFileId(head, path);
if(null == fileid) {
helper.registerFileId(head, path, f.getItemID(), f.getRevisionNumber());
} else {
helper.updateFileVersion(head, path, f.getRevisionNumber());
}
Blob fileToStage = new Blob(new Data(aFile));
helper.writeBlob(fileToStage);
FileModification fm = new FileModification(fileToStage);
if(aFile.canExecute()) {
fm.setFileType(GitFileType.Executable);
} else {
fm.setFileType(GitFileType.Normal);
}
fm.setPath(path);
fo = fm;
}
if(null != lastCommit && lastInformation.equivalent(current)) {
if(lastInformation.getComment().trim().length() == 0 && current.getComment().trim().length() > 0) {
lastInformation = current;
lastCommit.setComment(current.getComment());
}
lastCommit.addFileOperation(fo);
} else {
Commit commit = new Commit(userName, userEmail, current.getComment(), head, new java.util.Date(current.getTime()));
commit.addFileOperation(fo);
if(null == lastCommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
helper.writeCommit(lastCommit);
TempFileManager.getInstance().deleteTempFiles();
commit.setFromCommit(lastCommit);
}
/** Keep last for information **/
lastCommit = commit;
lastInformation = current;
}
} catch (IOException io) {
io.printStackTrace();
System.err.println("Git outputstream just crash unexpectedly. Stopping process");
System.exit(-1);
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
f.discard();
}
// TODO: Simple hack to make deletion of diapered files. Since starteam does not carry some kind of
// TODO: delete event. (as known from now)
if(deletedFiles.size() > 0) {
try {
System.err.println("Janitor was needed for cleanup");
java.util.Date janitorTime;
if(view.getConfiguration().isTimeBased()) {
janitorTime = new java.util.Date(view.getConfiguration().getTime().getLongValue());
} else {
janitorTime = new java.util.Date(lastModifiedTime);
}
Commit commit = new Commit("File Janitor",
"janitor@" + domain,
"Cleaning files move along",
head,
janitorTime);
if(null == lastCommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
helper.writeCommit(lastCommit);
commit.setFromCommit(lastCommit);
TempFileManager.getInstance().deleteTempFiles();
}
for(String path : deletedFiles) {
if(!helper.isSpecialFile(path)) {
FileOperation fileDelete = new FileDelete();
try {
fileDelete.setPath(path);
commit.addFileOperation(fileDelete);
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
}
}
lastCommit = commit;
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(null != lastCommit) {
try {
helper.writeCommit(lastCommit);
TempFileManager.getInstance().deleteTempFiles();
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
if(AddedSortedFileList.size() > 0) {
System.err.println("There was no new revision in the starteam view.");
- System.err.println("All the files in the repository are at theire lastest version");
+ System.err.println("All the files in the repository are at their latest version");
} else {
// System.err.println("The starteam view specified was empty.");
}
}
AddedSortedFileList.clear();
cm = null;
System.gc();
}
@Override
protected void finalize() throws Throwable {
exportStream.close();
while(helper.isFastImportRunning()) {
Thread.sleep(500); // active wait but leave him a chance to actually finish.
}
super.finalize();
}
private void recoverDeleteInformation(Set<String> listOfFiles, String head, View view) {
RecycleBin recycleBin = view.getRecycleBin();
recycleBin.setIncludeDeletedItems(true);
Type fileType = server.typeForName(recycleBin.getTypeNames().FILE);
for(Iterator<String> ith = listOfFiles.iterator(); ith.hasNext(); ) {
String path = ith.next();
Integer fileID = helper.getRegisteredFileId(head, path);
if(null != fileID) {
CommitInformation info = null;
Item item = recycleBin.findItem(fileType, fileID);
if(null != item && item.isDeleted()) {
info = new CommitInformation(item.getDeletedTime().getLongValue(),
item.getDeletedUserID(),
"",
path);
item.discard();
} else {
item = view.findItem(fileType, fileID);
if(null != item) {
info = new CommitInformation(item.getModifiedTime().getLongValue(),
item.getModifiedBy(),
"",
path);
info.setFileMove(true);
item.discard();
}
}
if(info != null) {
ith.remove();
sortedFileList.put(info, (File)item);
AddedSortedFileList.put(info, (File)item);
}
} else {
System.err.println("Never seen the file " + path + " in " + head);
}
}
}
public void setResume(boolean b) {
isResume = b;
}
private void recursiveFolderPopulation(Folder f, String folderPath) {
for(Folder subfolder : f.getSubFolders()) {
if(null != folder) {
subfolder.discard();
f.discard();
break;
}
String path = subfolder.getFolderHierarchy();
path = path.replace('\\', '/');
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1);
if(folderPath.equalsIgnoreCase(path)) {
folder = subfolder;
break;
}
recursiveFolderPopulation(subfolder, folderPath);
}
f.discard();
}
private void recursiveFilePopulation(Folder f) {
for(Item i : f.getItems(f.getTypeNames().FILE)) {
if(i instanceof File) {
File historyFile = (File) i;
String path = i.getParentFolderHierarchy() + historyFile.getName();
path = path.replace('\\', '/');
//path = path.substring(1);
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1 + folderNameLength);
if(deletedFiles.contains(path)) {
deletedFiles.remove(path);
}
files.add(path);
CommitInformation info = new CommitInformation(i.getModifiedTime().getLongValue(), i.getModifiedBy(), i.getComment(), path);
if(! lastSortedFileList.containsKey(info)) {
AddedSortedFileList.put(info, historyFile);
// System.err.println("Found file marked as: " + key);
}
sortedFileList.put(info, historyFile);
}
i.discard();
}
for(Folder subfolder : f.getSubFolders()) {
recursiveFilePopulation(subfolder);
}
f.discard();
}
public void setHeadName(String head) {
alternateHead = head;
}
public void setDumpFile(java.io.File file) {
if(null != helper) {
helper.setFastExportDumpFile(file);
} else {
throw new NullPointerException("Ensure that the helper is correctly started.");
}
}
public void generateDayByDayImport(View view, Date date, String baseFolder, String domain) {
View vc;
long hour = 3600000L; // mSec
long day = 24 * hour; // 86400000 mSec
long firstTime = 0;
if(isResume) {
String head = view.getName();
if(null != alternateHead) {
head = alternateHead;
}
java.util.Date lastCommit = helper.getLastCommitOfBranch(head);
if(null != lastCommit) {
firstTime = lastCommit.getTime();
} else {
System.err.println("Cannot resume an import in a non existing branch");
return;
}
}
if(firstTime < view.getCreatedTime().getLongValue()) {
firstTime = view.getCreatedTime().getLongValue();
}
System.err.println("View Created Time: " + new java.util.Date(firstTime));
if (null == date){
if(isResume) {
// -R is for branch view
// 2000 mSec here is to avoid side effect in StarTeam View Configuration
vc = new View(view, ViewConfiguration.createFromTime(new OLEDate(firstTime + 2000)));
setLastFilesLastSortedFileList(vc, baseFolder);
vc.discard();
}
Calendar time = Calendar.getInstance();
time.setTimeInMillis(firstTime);
time.set(Calendar.HOUR_OF_DAY, 23);
time.set(Calendar.MINUTE, 59);
time.set(Calendar.SECOND, 59);
date = time.getTime();
}
firstTime = date.getTime();
// get the most recent commit
// could we just get the current date ? like (now)
setFolder(view, baseFolder);
recursiveLastModifiedTime(getFolder());
long lastTime = getLastModifiedTime();
// in case View life less than 24 hours
if(firstTime > lastTime) {
firstTime = view.getCreatedTime().getLongValue();
}
System.err.println("Commit from " + new java.util.Date(firstTime) + " to " + new java.util.Date(lastTime));
Calendar timeIncrement = Calendar.getInstance();
timeIncrement.setTimeInMillis(firstTime);
for(;timeIncrement.getTimeInMillis() < lastTime; timeIncrement.add(Calendar.DAY_OF_YEAR, 1)) {
if(lastTime - timeIncrement.getTimeInMillis() <= day) {
vc = view;
} else {
vc = new View(view, ViewConfiguration.createFromTime(new OLEDate(timeIncrement.getTimeInMillis())));
}
System.err.println("View Configuration Time: " + timeIncrement.getTime());
generateFastImportStream(vc, baseFolder, domain);
vc.discard();
vc = null;
}
helper.gc();
}
public void dispose() {
helper.dispose();
}
}
| true | true | public void generateFastImportStream(View view, String folderPath, String domain) {
// http://techpubs.borland.com/starteam/2009/en/sdk_documentation/api/com/starbase/starteam/CheckoutManager.html
// said old version (passed in /opt/StarTeamCP_2005r2/lib/starteam80.jar) "Deprecated. Use View.createCheckoutManager() instead."
CheckoutManager cm = new CheckoutManager(view);
cm.getOptions().setEOLConversionEnabled(false);
lastInformation = new CommitInformation(Long.MIN_VALUE, Integer.MIN_VALUE, "", "");
folder = null;
setFolder(view, folderPath);
if(null == folder) {
return;
}
String head = view.getName();
if(null != alternateHead) {
head = alternateHead;
}
files.clear();
deletedFiles.clear();
deletedFiles.addAll(lastFiles);
sortedFileList.clear();
recursiveFilePopulation(folder);
lastFiles.clear();
lastFiles.addAll(files);
lastSortedFileList.clear();
lastSortedFileList.putAll(sortedFileList);
recoverDeleteInformation(deletedFiles, head, view);
exportStream = helper.getFastImportStream();
for(Map.Entry<CommitInformation, File> e : AddedSortedFileList.entrySet()) {
File f = e.getValue();
CommitInformation current = e.getKey();
String userName = server.getUser(current.getUid()).getName();
String userEmail = userName.replaceAll(" ", ".") + "@" + domain;
String path = f.getParentFolderHierarchy() + f.getName();
path = path.replace('\\', '/');
// Strip the view name from the path
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1 + folderNameLength);
try {
if(f.getStatus() == Status.CURRENT) {
f.discard();
continue;
}
if(f.getStatusByMD5(helper.getMD5Of(path, head)) == Status.CURRENT) {
f.discard();
continue;
}
FileOperation fo = null;
java.io.File aFile = null;
if(f.isDeleted() || current.isFileMove()) {
fo = new FileDelete();
fo.setPath(current.getPath());
helper.unregisterFileId(head, path);
} else {
aFile = TempFileManager.getInstance().createTempFile("StarteamFile", ".tmp");
cm.checkoutTo(f, aFile);
Integer fileid = helper.getRegisteredFileId(head, path);
if(null == fileid) {
helper.registerFileId(head, path, f.getItemID(), f.getRevisionNumber());
} else {
helper.updateFileVersion(head, path, f.getRevisionNumber());
}
Blob fileToStage = new Blob(new Data(aFile));
helper.writeBlob(fileToStage);
FileModification fm = new FileModification(fileToStage);
if(aFile.canExecute()) {
fm.setFileType(GitFileType.Executable);
} else {
fm.setFileType(GitFileType.Normal);
}
fm.setPath(path);
fo = fm;
}
if(null != lastCommit && lastInformation.equivalent(current)) {
if(lastInformation.getComment().trim().length() == 0 && current.getComment().trim().length() > 0) {
lastInformation = current;
lastCommit.setComment(current.getComment());
}
lastCommit.addFileOperation(fo);
} else {
Commit commit = new Commit(userName, userEmail, current.getComment(), head, new java.util.Date(current.getTime()));
commit.addFileOperation(fo);
if(null == lastCommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
helper.writeCommit(lastCommit);
TempFileManager.getInstance().deleteTempFiles();
commit.setFromCommit(lastCommit);
}
/** Keep last for information **/
lastCommit = commit;
lastInformation = current;
}
} catch (IOException io) {
io.printStackTrace();
System.err.println("Git outputstream just crash unexpectedly. Stopping process");
System.exit(-1);
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
f.discard();
}
// TODO: Simple hack to make deletion of diapered files. Since starteam does not carry some kind of
// TODO: delete event. (as known from now)
if(deletedFiles.size() > 0) {
try {
System.err.println("Janitor was needed for cleanup");
java.util.Date janitorTime;
if(view.getConfiguration().isTimeBased()) {
janitorTime = new java.util.Date(view.getConfiguration().getTime().getLongValue());
} else {
janitorTime = new java.util.Date(lastModifiedTime);
}
Commit commit = new Commit("File Janitor",
"janitor@" + domain,
"Cleaning files move along",
head,
janitorTime);
if(null == lastCommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
helper.writeCommit(lastCommit);
commit.setFromCommit(lastCommit);
TempFileManager.getInstance().deleteTempFiles();
}
for(String path : deletedFiles) {
if(!helper.isSpecialFile(path)) {
FileOperation fileDelete = new FileDelete();
try {
fileDelete.setPath(path);
commit.addFileOperation(fileDelete);
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
}
}
lastCommit = commit;
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(null != lastCommit) {
try {
helper.writeCommit(lastCommit);
TempFileManager.getInstance().deleteTempFiles();
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
if(AddedSortedFileList.size() > 0) {
System.err.println("There was no new revision in the starteam view.");
System.err.println("All the files in the repository are at theire lastest version");
} else {
// System.err.println("The starteam view specified was empty.");
}
}
AddedSortedFileList.clear();
cm = null;
System.gc();
}
| public void generateFastImportStream(View view, String folderPath, String domain) {
// http://techpubs.borland.com/starteam/2009/en/sdk_documentation/api/com/starbase/starteam/CheckoutManager.html
// said old version (passed in /opt/StarTeamCP_2005r2/lib/starteam80.jar) "Deprecated. Use View.createCheckoutManager() instead."
CheckoutManager cm = new CheckoutManager(view);
cm.getOptions().setEOLConversionEnabled(false);
lastInformation = new CommitInformation(Long.MIN_VALUE, Integer.MIN_VALUE, "", "");
folder = null;
setFolder(view, folderPath);
if(null == folder) {
return;
}
String head = view.getName();
if(null != alternateHead) {
head = alternateHead;
}
files.clear();
deletedFiles.clear();
deletedFiles.addAll(lastFiles);
sortedFileList.clear();
recursiveFilePopulation(folder);
lastFiles.clear();
lastFiles.addAll(files);
lastSortedFileList.clear();
lastSortedFileList.putAll(sortedFileList);
recoverDeleteInformation(deletedFiles, head, view);
exportStream = helper.getFastImportStream();
for(Map.Entry<CommitInformation, File> e : AddedSortedFileList.entrySet()) {
File f = e.getValue();
CommitInformation current = e.getKey();
String userName = server.getUser(current.getUid()).getName();
String userEmail = userName.replaceAll(" ", ".") + "@" + domain;
String path = f.getParentFolderHierarchy() + f.getName();
path = path.replace('\\', '/');
// Strip the view name from the path
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1 + folderNameLength);
try {
if(f.getStatus() == Status.CURRENT) {
f.discard();
continue;
}
if(f.getStatusByMD5(helper.getMD5Of(path, head)) == Status.CURRENT) {
f.discard();
continue;
}
FileOperation fo = null;
java.io.File aFile = null;
if(f.isDeleted() || current.isFileMove()) {
fo = new FileDelete();
fo.setPath(current.getPath());
helper.unregisterFileId(head, path);
} else {
aFile = TempFileManager.getInstance().createTempFile("StarteamFile", ".tmp");
cm.checkoutTo(f, aFile);
Integer fileid = helper.getRegisteredFileId(head, path);
if(null == fileid) {
helper.registerFileId(head, path, f.getItemID(), f.getRevisionNumber());
} else {
helper.updateFileVersion(head, path, f.getRevisionNumber());
}
Blob fileToStage = new Blob(new Data(aFile));
helper.writeBlob(fileToStage);
FileModification fm = new FileModification(fileToStage);
if(aFile.canExecute()) {
fm.setFileType(GitFileType.Executable);
} else {
fm.setFileType(GitFileType.Normal);
}
fm.setPath(path);
fo = fm;
}
if(null != lastCommit && lastInformation.equivalent(current)) {
if(lastInformation.getComment().trim().length() == 0 && current.getComment().trim().length() > 0) {
lastInformation = current;
lastCommit.setComment(current.getComment());
}
lastCommit.addFileOperation(fo);
} else {
Commit commit = new Commit(userName, userEmail, current.getComment(), head, new java.util.Date(current.getTime()));
commit.addFileOperation(fo);
if(null == lastCommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
helper.writeCommit(lastCommit);
TempFileManager.getInstance().deleteTempFiles();
commit.setFromCommit(lastCommit);
}
/** Keep last for information **/
lastCommit = commit;
lastInformation = current;
}
} catch (IOException io) {
io.printStackTrace();
System.err.println("Git outputstream just crash unexpectedly. Stopping process");
System.exit(-1);
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
f.discard();
}
// TODO: Simple hack to make deletion of diapered files. Since starteam does not carry some kind of
// TODO: delete event. (as known from now)
if(deletedFiles.size() > 0) {
try {
System.err.println("Janitor was needed for cleanup");
java.util.Date janitorTime;
if(view.getConfiguration().isTimeBased()) {
janitorTime = new java.util.Date(view.getConfiguration().getTime().getLongValue());
} else {
janitorTime = new java.util.Date(lastModifiedTime);
}
Commit commit = new Commit("File Janitor",
"janitor@" + domain,
"Cleaning files move along",
head,
janitorTime);
if(null == lastCommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
helper.writeCommit(lastCommit);
commit.setFromCommit(lastCommit);
TempFileManager.getInstance().deleteTempFiles();
}
for(String path : deletedFiles) {
if(!helper.isSpecialFile(path)) {
FileOperation fileDelete = new FileDelete();
try {
fileDelete.setPath(path);
commit.addFileOperation(fileDelete);
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
}
}
lastCommit = commit;
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(null != lastCommit) {
try {
helper.writeCommit(lastCommit);
TempFileManager.getInstance().deleteTempFiles();
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
if(AddedSortedFileList.size() > 0) {
System.err.println("There was no new revision in the starteam view.");
System.err.println("All the files in the repository are at their latest version");
} else {
// System.err.println("The starteam view specified was empty.");
}
}
AddedSortedFileList.clear();
cm = null;
System.gc();
}
|
diff --git a/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/query/form/AnnotationDefinitionList.java b/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/query/form/AnnotationDefinitionList.java
index 213cff451..e86adc202 100644
--- a/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/query/form/AnnotationDefinitionList.java
+++ b/caintegrator2-war/src/gov/nih/nci/caintegrator2/web/action/query/form/AnnotationDefinitionList.java
@@ -1,141 +1,142 @@
/**
* The software subject to this notice and license includes both human readable
* source code form and machine readable, binary, object code form. The caIntegrator2
* Software was developed in conjunction with the National Cancer Institute
* (NCI) by NCI employees, 5AM Solutions, Inc. (5AM), ScenPro, Inc. (ScenPro)
* and Science Applications International Corporation (SAIC). To the extent
* government employees are authors, any rights in such works shall be subject
* to Title 17 of the United States Code, section 105.
*
* This caIntegrator2 Software License (the License) is between NCI 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.
*
* This License is granted provided that You agree to the conditions described
* below. NCI 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 caIntegrator2 Software to (i) use, install, access, operate,
* execute, copy, modify, translate, market, publicly display, publicly perform,
* and prepare derivative works of the caIntegrator2 Software; (ii) distribute and
* have distributed to and by third parties the caIntegrator2 Software and any
* modifications and derivative works thereof; and (iii) sublicense the
* foregoing rights set out in (i) and (ii) to third parties, including the
* right to license such rights to further third parties. For sake of clarity,
* and not by way of limitation, NCI shall have no right of accounting or right
* of payment from You or Your sub-licensees for the rights granted under this
* License. This License is granted at no charge to You.
*
* Your redistributions of the source code for the 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.
*
* Your end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: This product includes software
* developed by 5AM, ScenPro, SAIC and the National Cancer Institute. If You do
* not include such end-user documentation, You shall include this acknowledgment
* in the Software itself, wherever such third-party acknowledgments normally
* appear.
*
* You may not use the names "The National Cancer Institute", "NCI", "ScenPro",
* "SAIC" or "5AM" to endorse or promote products derived from this Software.
* This License does not authorize You to use any trademarks, service marks,
* trade names, logos or product names of either NCI, ScenPro, SAID or 5AM,
* except as required to comply with the terms of this License.
*
* For sake of clarity, and not by way of limitation, You may incorporate this
* Software into Your proprietary programs and into any third party proprietary
* programs. However, if You incorporate the 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 Software
* into such third party proprietary programs and for informing Your a
* sub-licensees, including without limitation Your end-users, of their
* obligation to secure any required permissions from such third parties before
* incorporating the Software into such third party proprietary software
* programs. In the event that You fail to obtain such permissions, You agree
* to indemnify NCI for any claims against NCI by such third parties, except to
* the extent prohibited by law, resulting from Your failure to obtain such
* permissions.
*
* 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 Software, or any derivative works of the
* Software as a whole, provided Your use, reproduction, and distribution of the
* Work otherwise complies with the conditions stated in this License.
*
* THIS 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 NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC., SCENPRO, INC.,
* SCIENCE APPLICATIONS INTERNATIONAL CORPORATION OR THEIR
* AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.nih.nci.caintegrator2.web.action.query.form;
import gov.nih.nci.caintegrator2.application.study.AnnotationTypeEnum;
import gov.nih.nci.caintegrator2.common.Cai2Util;
import gov.nih.nci.caintegrator2.domain.annotation.AnnotationDefinition;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Contains an ordered list of definition names and allows retrieval of the associated definition by name.
*/
class AnnotationDefinitionList {
private final List<String> names = new ArrayList<String>();
private final List<String> noDateNames = new ArrayList<String>();
private final Map<String, AnnotationDefinition> nameToDefinitionMap = new HashMap<String, AnnotationDefinition>();
AnnotationDefinitionList(Collection<AnnotationDefinition> definitions, boolean addIdentifierToList) {
if (definitions == null) {
throw new IllegalArgumentException("Argument definitions was null.");
}
if (addIdentifierToList) {
names.add(IdentifierCriterionWrapper.IDENTIFIER_FIELD_NAME);
+ noDateNames.add(IdentifierCriterionWrapper.IDENTIFIER_FIELD_NAME);
nameToDefinitionMap.put(IdentifierCriterionWrapper.IDENTIFIER_FIELD_NAME, null);
}
for (AnnotationDefinition definition : definitions) {
// TODO Need to implement the date type operator then will put it back in the query mechanism.
if (!AnnotationTypeEnum.DATE.getValue().equalsIgnoreCase(definition.getType())) {
noDateNames.add(definition.getDisplayName());
}
names.add(definition.getDisplayName());
nameToDefinitionMap.put(definition.getDisplayName(), definition);
Cai2Util.loadCollection(definition.getPermissibleValueCollection());
}
Collections.sort(names);
Collections.sort(noDateNames);
}
List<String> getNames() {
return names;
}
List<String> getNoDateNames() {
return noDateNames;
}
AnnotationDefinition getDefinition(String name) {
return nameToDefinitionMap.get(name);
}
}
| true | true | AnnotationDefinitionList(Collection<AnnotationDefinition> definitions, boolean addIdentifierToList) {
if (definitions == null) {
throw new IllegalArgumentException("Argument definitions was null.");
}
if (addIdentifierToList) {
names.add(IdentifierCriterionWrapper.IDENTIFIER_FIELD_NAME);
nameToDefinitionMap.put(IdentifierCriterionWrapper.IDENTIFIER_FIELD_NAME, null);
}
for (AnnotationDefinition definition : definitions) {
// TODO Need to implement the date type operator then will put it back in the query mechanism.
if (!AnnotationTypeEnum.DATE.getValue().equalsIgnoreCase(definition.getType())) {
noDateNames.add(definition.getDisplayName());
}
names.add(definition.getDisplayName());
nameToDefinitionMap.put(definition.getDisplayName(), definition);
Cai2Util.loadCollection(definition.getPermissibleValueCollection());
}
Collections.sort(names);
Collections.sort(noDateNames);
}
| AnnotationDefinitionList(Collection<AnnotationDefinition> definitions, boolean addIdentifierToList) {
if (definitions == null) {
throw new IllegalArgumentException("Argument definitions was null.");
}
if (addIdentifierToList) {
names.add(IdentifierCriterionWrapper.IDENTIFIER_FIELD_NAME);
noDateNames.add(IdentifierCriterionWrapper.IDENTIFIER_FIELD_NAME);
nameToDefinitionMap.put(IdentifierCriterionWrapper.IDENTIFIER_FIELD_NAME, null);
}
for (AnnotationDefinition definition : definitions) {
// TODO Need to implement the date type operator then will put it back in the query mechanism.
if (!AnnotationTypeEnum.DATE.getValue().equalsIgnoreCase(definition.getType())) {
noDateNames.add(definition.getDisplayName());
}
names.add(definition.getDisplayName());
nameToDefinitionMap.put(definition.getDisplayName(), definition);
Cai2Util.loadCollection(definition.getPermissibleValueCollection());
}
Collections.sort(names);
Collections.sort(noDateNames);
}
|
diff --git a/ServerOfEbag/src/org/ebag/web/ProblemHelper.java b/ServerOfEbag/src/org/ebag/web/ProblemHelper.java
index c262cc7..ab0080a 100644
--- a/ServerOfEbag/src/org/ebag/web/ProblemHelper.java
+++ b/ServerOfEbag/src/org/ebag/web/ProblemHelper.java
@@ -1,35 +1,35 @@
package org.ebag.web;
import org.ebag.net.obj.I;
import ebag.pojo.Eproblem;
import ebag.pojo.EproblemDAO;
public class ProblemHelper {
public static String getHtml(String pid,String type){
String res="";
try{
EproblemDAO epdao=new EproblemDAO();
Eproblem p=epdao.findById(Integer.parseInt(pid.trim()));
if(I.url.analysis.equals(type)){
res=p.getAnalysis();
}else if(I.url.ans.equals(type)){
res=p.getAns();
}else if(I.url.aspect.equals(type)){
res=p.getAspect();
}else if(I.url.difficulty.equals(type)){
res=p.getDifficulty();
}else if(I.url.hint.equals(type)){
res=p.getHint();
}else if(I.url.problem.equals(type)){
res=p.getProblem();
}else if(I.url.request.equals(type)){
res=p.getRequests();
}}catch (Exception e) {
return "";
}
- System.out.println(res);
+ //System.out.println(res);
return res;
}
}
| true | true | public static String getHtml(String pid,String type){
String res="";
try{
EproblemDAO epdao=new EproblemDAO();
Eproblem p=epdao.findById(Integer.parseInt(pid.trim()));
if(I.url.analysis.equals(type)){
res=p.getAnalysis();
}else if(I.url.ans.equals(type)){
res=p.getAns();
}else if(I.url.aspect.equals(type)){
res=p.getAspect();
}else if(I.url.difficulty.equals(type)){
res=p.getDifficulty();
}else if(I.url.hint.equals(type)){
res=p.getHint();
}else if(I.url.problem.equals(type)){
res=p.getProblem();
}else if(I.url.request.equals(type)){
res=p.getRequests();
}}catch (Exception e) {
return "";
}
System.out.println(res);
return res;
}
| public static String getHtml(String pid,String type){
String res="";
try{
EproblemDAO epdao=new EproblemDAO();
Eproblem p=epdao.findById(Integer.parseInt(pid.trim()));
if(I.url.analysis.equals(type)){
res=p.getAnalysis();
}else if(I.url.ans.equals(type)){
res=p.getAns();
}else if(I.url.aspect.equals(type)){
res=p.getAspect();
}else if(I.url.difficulty.equals(type)){
res=p.getDifficulty();
}else if(I.url.hint.equals(type)){
res=p.getHint();
}else if(I.url.problem.equals(type)){
res=p.getProblem();
}else if(I.url.request.equals(type)){
res=p.getRequests();
}}catch (Exception e) {
return "";
}
//System.out.println(res);
return res;
}
|
diff --git a/core/src/java/liquibase/migrator/parser/BaseChangeLogHandler.java b/core/src/java/liquibase/migrator/parser/BaseChangeLogHandler.java
index 2765abe9..fdea7e79 100644
--- a/core/src/java/liquibase/migrator/parser/BaseChangeLogHandler.java
+++ b/core/src/java/liquibase/migrator/parser/BaseChangeLogHandler.java
@@ -1,270 +1,271 @@
package liquibase.migrator.parser;
import liquibase.migrator.*;
import liquibase.migrator.change.*;
import liquibase.migrator.exception.DatabaseHistoryException;
import liquibase.migrator.exception.JDBCException;
import liquibase.migrator.exception.MigrationFailedException;
import liquibase.migrator.preconditions.*;
import liquibase.util.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.List;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Base SAX Handler for all modes of reading change logs. This class is subclassed depending on
* how the change log should be read (for migration, for rollback, etc).
*/
@SuppressWarnings({"AbstractClassExtendsConcreteClass"})
public abstract class BaseChangeLogHandler extends DefaultHandler {
protected Migrator migrator;
protected Logger log;
private DatabaseChangeLog changeLog;
private Change change;
private StringBuffer text;
private PreconditionSet precondition;
private ChangeSet changeSet;
private OrPrecondition orprecondition;
private NotPrecondition notprecondition;
private RunningAsPrecondition runningAs;
private String physicalChangeLogLocation;
private FileOpener fileOpener;
protected BaseChangeLogHandler(Migrator migrator, String physicalChangeLogLocation,FileOpener fileOpener) {
this.migrator = migrator;
this.physicalChangeLogLocation = physicalChangeLogLocation;
log = Logger.getLogger(Migrator.DEFAULT_LOG_NAME);
this.fileOpener = fileOpener;
}
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
try {
if ("comment".equals(qName)) {
text = new StringBuffer();
} else if ("databaseChangeLog".equals(qName)) {
changeLog = new DatabaseChangeLog(migrator, physicalChangeLogLocation);
changeLog.setLogicalFilePath(atts.getValue("logicalFilePath"));
} else if ("include".equals(qName)) {
String fileName = atts.getValue("file");
handleIncludedChangeLog(fileName);
} else if (changeSet == null && "changeSet".equals(qName)) {
boolean alwaysRun = false;
boolean runOnChange = false;
if ("true".equalsIgnoreCase(atts.getValue("runAlways"))) {
alwaysRun = true;
}
if ("true".equalsIgnoreCase(atts.getValue("runOnChange"))) {
runOnChange = true;
}
changeSet = new ChangeSet(atts.getValue("id"), atts.getValue("author"), alwaysRun, runOnChange, changeLog, atts.getValue("context"), atts.getValue("dbms"));
} else if (changeSet != null && "rollback".equals(qName)) {
text = new StringBuffer();
} else if (changeSet != null && change == null) {
change = migrator.getChangeFactory().create(qName);
text = new StringBuffer();
if (change == null) {
throw new MigrationFailedException("Unknown change: " + qName);
}
change.setFileOpener(fileOpener);
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(change, attributeName, attributeValue);
}
+ change.setUp();
} else if (change != null && "column".equals(qName)) {
ColumnConfig column = new ColumnConfig();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(column, attributeName, attributeValue);
}
if (change instanceof AddColumnChange) {
((AddColumnChange) change).setColumn(column);
} else if (change instanceof CreateTableChange) {
((CreateTableChange) change).addColumn(column);
} else if (change instanceof InsertDataChange) {
((InsertDataChange) change).addColumn(column);
} else if (change instanceof CreateIndexChange) {
((CreateIndexChange) change).addColumn(column);
} else if (change instanceof ModifyColumnChange) {
((ModifyColumnChange) change).setColumn(column);
} else {
throw new RuntimeException("Unexpected column tag for " + change.getClass().getName());
}
} else if (change != null && "constraints".equals(qName)) {
ConstraintsConfig constraints = new ConstraintsConfig();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(constraints, attributeName, attributeValue);
}
ColumnConfig lastColumn;
if (change instanceof AddColumnChange) {
lastColumn = ((AddColumnChange) change).getColumn();
} else if (change instanceof CreateTableChange) {
lastColumn = ((CreateTableChange) change).getColumns().get(((CreateTableChange) change).getColumns().size() - 1);
} else {
throw new RuntimeException("Unexpected change: " + change.getClass().getName());
}
lastColumn.setConstraints(constraints);
} else if ("preConditions".equals(qName)) {
// System.out.println(migrator);
precondition = new PreconditionSet(migrator, changeLog);
//System.out.println("pre condition is true");
} else if ("dbms".equals(qName)) {
if (precondition != null) {
DBMSPrecondition dbmsPrecondition = new DBMSPrecondition();
// System.out.println("dbms is true");
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(dbmsPrecondition, attributeName, attributeValue);
}
// System.out.println("attributes added");
if (orprecondition != null) {
// System.out.println("orrprecondition");
orprecondition.addDbms(dbmsPrecondition);
} else if (notprecondition != null) {
notprecondition.addDbms(dbmsPrecondition);
} else {
precondition.addDbms(dbmsPrecondition);
}
} else {
throw new RuntimeException("Unexpected Dbms tag");
}
} else if ("or".equals(qName)) {
if (precondition != null) {
orprecondition = new OrPrecondition();
if (notprecondition != null) {
notprecondition.setOrprecondition(orprecondition);
}
} else {
throw new RuntimeException("Unexpected Or tag");
}
} else if ("not".equals(qName)) {
if (precondition != null) {
notprecondition = new NotPrecondition();
} else {
throw new RuntimeException("Unexpected Or tag");
}
} else if ("runningAs".equals(qName)) {
if (precondition != null) {
runningAs = new RunningAsPrecondition();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(runningAs, attributeName, attributeValue);
}
} else {
throw new RuntimeException("Unexpected Or tag");
}
} else {
throw new MigrationFailedException("Unexpected tag: " + qName);
}
} catch (Exception e) {
throw new SAXException(e);
}
}
protected void handleIncludedChangeLog(String fileName) throws MigrationFailedException, IOException, JDBCException {
new IncludeMigrator(fileName, migrator).migrate();
}
private void setProperty(Object object, String attributeName, String attributeValue) throws IllegalAccessException, InvocationTargetException {
String methodName = "set" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
Method[] methods = object.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (method.getName().equals(methodName)) {
if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(Boolean.class)) {
method.invoke(object, Boolean.valueOf(attributeValue));
return;
} else
if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(String.class)) {
method.invoke(object, attributeValue);
return;
} else
if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0].equals(Integer.class)) {
method.invoke(object, Integer.valueOf(attributeValue));
return;
}
}
}
throw new RuntimeException("Property not found: " + attributeName);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
String textString = null;
if (text != null && text.length() > 0) {
textString = StringUtils.trimToNull(text.toString());
}
try {
if (precondition != null && "preConditions".equals(qName)) {
changeLog.setPreconditions(precondition);
handlePreCondition(precondition);
} else if (precondition != null && "or".equals(qName) && notprecondition == null) {
precondition.setOrPreCondition(orprecondition);
} else if (precondition != null && "not".equals(qName)) {
precondition.setNotPreCondition(notprecondition);
} else if (precondition != null && "runningAs".equals(qName)) {
precondition.setRunningAs(runningAs);
} else if (changeSet != null && "rollback".equals(qName)) {
changeSet.setRollBackSQL(textString);
} else if (changeSet != null && "comment".equals(qName)) {
changeSet.setComments(textString);
} else if (changeSet != null && "changeSet".equals(qName)) {
handleChangeSet(changeSet);
changeSet = null;
} else if (change != null && qName.equals(change.getTagName())) {
if (textString != null) {
if (change instanceof RawSQLChange) {
((RawSQLChange) change).setSql(textString);
} else if (change instanceof CreateViewChange) {
((CreateViewChange) change).setSelectQuery(textString);
} else if (change instanceof InsertDataChange) {
List<ColumnConfig> columns = ((InsertDataChange) change).getColumns();
columns.get(columns.size()-1).setValue(textString);
} else {
throw new RuntimeException("Unexpected text in " + change.getTagName());
}
}
text = null;
changeSet.addChange(change);
change = null;
}
} catch (Exception e) {
log.log(Level.SEVERE, "Error thrown as a SAXException: " + e.getMessage(), e);
throw new SAXException(changeLog.getPhysicalFilePath()+": "+e.getMessage(), e);
}
}
/**
* By defaultd does nothing. Overridden in ValidatChangeLogHandler and anywhere else that is interested in them.
*/
protected void handlePreCondition(PreconditionSet preconditions) {
;
}
protected abstract void handleChangeSet(ChangeSet changeSet) throws JDBCException, DatabaseHistoryException, MigrationFailedException, IOException;
public void characters(char ch[], int start, int length) throws SAXException {
if (text != null) {
text.append(new String(ch, start, length));
}
}
}
| true | true | public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
try {
if ("comment".equals(qName)) {
text = new StringBuffer();
} else if ("databaseChangeLog".equals(qName)) {
changeLog = new DatabaseChangeLog(migrator, physicalChangeLogLocation);
changeLog.setLogicalFilePath(atts.getValue("logicalFilePath"));
} else if ("include".equals(qName)) {
String fileName = atts.getValue("file");
handleIncludedChangeLog(fileName);
} else if (changeSet == null && "changeSet".equals(qName)) {
boolean alwaysRun = false;
boolean runOnChange = false;
if ("true".equalsIgnoreCase(atts.getValue("runAlways"))) {
alwaysRun = true;
}
if ("true".equalsIgnoreCase(atts.getValue("runOnChange"))) {
runOnChange = true;
}
changeSet = new ChangeSet(atts.getValue("id"), atts.getValue("author"), alwaysRun, runOnChange, changeLog, atts.getValue("context"), atts.getValue("dbms"));
} else if (changeSet != null && "rollback".equals(qName)) {
text = new StringBuffer();
} else if (changeSet != null && change == null) {
change = migrator.getChangeFactory().create(qName);
text = new StringBuffer();
if (change == null) {
throw new MigrationFailedException("Unknown change: " + qName);
}
change.setFileOpener(fileOpener);
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(change, attributeName, attributeValue);
}
} else if (change != null && "column".equals(qName)) {
ColumnConfig column = new ColumnConfig();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(column, attributeName, attributeValue);
}
if (change instanceof AddColumnChange) {
((AddColumnChange) change).setColumn(column);
} else if (change instanceof CreateTableChange) {
((CreateTableChange) change).addColumn(column);
} else if (change instanceof InsertDataChange) {
((InsertDataChange) change).addColumn(column);
} else if (change instanceof CreateIndexChange) {
((CreateIndexChange) change).addColumn(column);
} else if (change instanceof ModifyColumnChange) {
((ModifyColumnChange) change).setColumn(column);
} else {
throw new RuntimeException("Unexpected column tag for " + change.getClass().getName());
}
} else if (change != null && "constraints".equals(qName)) {
ConstraintsConfig constraints = new ConstraintsConfig();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(constraints, attributeName, attributeValue);
}
ColumnConfig lastColumn;
if (change instanceof AddColumnChange) {
lastColumn = ((AddColumnChange) change).getColumn();
} else if (change instanceof CreateTableChange) {
lastColumn = ((CreateTableChange) change).getColumns().get(((CreateTableChange) change).getColumns().size() - 1);
} else {
throw new RuntimeException("Unexpected change: " + change.getClass().getName());
}
lastColumn.setConstraints(constraints);
} else if ("preConditions".equals(qName)) {
// System.out.println(migrator);
precondition = new PreconditionSet(migrator, changeLog);
//System.out.println("pre condition is true");
} else if ("dbms".equals(qName)) {
if (precondition != null) {
DBMSPrecondition dbmsPrecondition = new DBMSPrecondition();
// System.out.println("dbms is true");
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(dbmsPrecondition, attributeName, attributeValue);
}
// System.out.println("attributes added");
if (orprecondition != null) {
// System.out.println("orrprecondition");
orprecondition.addDbms(dbmsPrecondition);
} else if (notprecondition != null) {
notprecondition.addDbms(dbmsPrecondition);
} else {
precondition.addDbms(dbmsPrecondition);
}
} else {
throw new RuntimeException("Unexpected Dbms tag");
}
} else if ("or".equals(qName)) {
if (precondition != null) {
orprecondition = new OrPrecondition();
if (notprecondition != null) {
notprecondition.setOrprecondition(orprecondition);
}
} else {
throw new RuntimeException("Unexpected Or tag");
}
} else if ("not".equals(qName)) {
if (precondition != null) {
notprecondition = new NotPrecondition();
} else {
throw new RuntimeException("Unexpected Or tag");
}
} else if ("runningAs".equals(qName)) {
if (precondition != null) {
runningAs = new RunningAsPrecondition();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(runningAs, attributeName, attributeValue);
}
} else {
throw new RuntimeException("Unexpected Or tag");
}
} else {
throw new MigrationFailedException("Unexpected tag: " + qName);
}
} catch (Exception e) {
throw new SAXException(e);
}
}
| public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
try {
if ("comment".equals(qName)) {
text = new StringBuffer();
} else if ("databaseChangeLog".equals(qName)) {
changeLog = new DatabaseChangeLog(migrator, physicalChangeLogLocation);
changeLog.setLogicalFilePath(atts.getValue("logicalFilePath"));
} else if ("include".equals(qName)) {
String fileName = atts.getValue("file");
handleIncludedChangeLog(fileName);
} else if (changeSet == null && "changeSet".equals(qName)) {
boolean alwaysRun = false;
boolean runOnChange = false;
if ("true".equalsIgnoreCase(atts.getValue("runAlways"))) {
alwaysRun = true;
}
if ("true".equalsIgnoreCase(atts.getValue("runOnChange"))) {
runOnChange = true;
}
changeSet = new ChangeSet(atts.getValue("id"), atts.getValue("author"), alwaysRun, runOnChange, changeLog, atts.getValue("context"), atts.getValue("dbms"));
} else if (changeSet != null && "rollback".equals(qName)) {
text = new StringBuffer();
} else if (changeSet != null && change == null) {
change = migrator.getChangeFactory().create(qName);
text = new StringBuffer();
if (change == null) {
throw new MigrationFailedException("Unknown change: " + qName);
}
change.setFileOpener(fileOpener);
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(change, attributeName, attributeValue);
}
change.setUp();
} else if (change != null && "column".equals(qName)) {
ColumnConfig column = new ColumnConfig();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(column, attributeName, attributeValue);
}
if (change instanceof AddColumnChange) {
((AddColumnChange) change).setColumn(column);
} else if (change instanceof CreateTableChange) {
((CreateTableChange) change).addColumn(column);
} else if (change instanceof InsertDataChange) {
((InsertDataChange) change).addColumn(column);
} else if (change instanceof CreateIndexChange) {
((CreateIndexChange) change).addColumn(column);
} else if (change instanceof ModifyColumnChange) {
((ModifyColumnChange) change).setColumn(column);
} else {
throw new RuntimeException("Unexpected column tag for " + change.getClass().getName());
}
} else if (change != null && "constraints".equals(qName)) {
ConstraintsConfig constraints = new ConstraintsConfig();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(constraints, attributeName, attributeValue);
}
ColumnConfig lastColumn;
if (change instanceof AddColumnChange) {
lastColumn = ((AddColumnChange) change).getColumn();
} else if (change instanceof CreateTableChange) {
lastColumn = ((CreateTableChange) change).getColumns().get(((CreateTableChange) change).getColumns().size() - 1);
} else {
throw new RuntimeException("Unexpected change: " + change.getClass().getName());
}
lastColumn.setConstraints(constraints);
} else if ("preConditions".equals(qName)) {
// System.out.println(migrator);
precondition = new PreconditionSet(migrator, changeLog);
//System.out.println("pre condition is true");
} else if ("dbms".equals(qName)) {
if (precondition != null) {
DBMSPrecondition dbmsPrecondition = new DBMSPrecondition();
// System.out.println("dbms is true");
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(dbmsPrecondition, attributeName, attributeValue);
}
// System.out.println("attributes added");
if (orprecondition != null) {
// System.out.println("orrprecondition");
orprecondition.addDbms(dbmsPrecondition);
} else if (notprecondition != null) {
notprecondition.addDbms(dbmsPrecondition);
} else {
precondition.addDbms(dbmsPrecondition);
}
} else {
throw new RuntimeException("Unexpected Dbms tag");
}
} else if ("or".equals(qName)) {
if (precondition != null) {
orprecondition = new OrPrecondition();
if (notprecondition != null) {
notprecondition.setOrprecondition(orprecondition);
}
} else {
throw new RuntimeException("Unexpected Or tag");
}
} else if ("not".equals(qName)) {
if (precondition != null) {
notprecondition = new NotPrecondition();
} else {
throw new RuntimeException("Unexpected Or tag");
}
} else if ("runningAs".equals(qName)) {
if (precondition != null) {
runningAs = new RunningAsPrecondition();
for (int i = 0; i < atts.getLength(); i++) {
String attributeName = atts.getQName(i);
String attributeValue = atts.getValue(i);
setProperty(runningAs, attributeName, attributeValue);
}
} else {
throw new RuntimeException("Unexpected Or tag");
}
} else {
throw new MigrationFailedException("Unexpected tag: " + qName);
}
} catch (Exception e) {
throw new SAXException(e);
}
}
|
diff --git a/src/cz/quinix/condroid/ui/AboutDialog.java b/src/cz/quinix/condroid/ui/AboutDialog.java
index f29af72..92e5c38 100644
--- a/src/cz/quinix/condroid/ui/AboutDialog.java
+++ b/src/cz/quinix/condroid/ui/AboutDialog.java
@@ -1,83 +1,83 @@
package cz.quinix.condroid.ui;
import cz.quinix.condroid.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
public class AboutDialog extends AlertDialog {
protected AboutDialog(Context context) {
super(context);
View v = LayoutInflater.from(context).inflate(R.layout.about_dialog, null);
- this.setTitle(R.string.appName);
+ this.setTitle(R.string.appNameAbout);
this.setView(v);
this.setButton(BUTTON1, "OK", new OkListener());
this.setButton(BUTTON2, "Přispět", new DonateListener());
this.setButton(BUTTON3, "Feedback", new FeedbackListener());
ImageView follow = ((ImageView) v.findViewById(R.id.iFollow));
follow.setOnClickListener(new FollowListener());
this.setIcon(R.drawable.icon);
}
class OkListener implements OnClickListener {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences pr = getContext().getSharedPreferences(WelcomeActivity.TAG, 0);
SharedPreferences.Editor e = pr.edit();
e.putBoolean("aboutShown", true);
e.commit();
}
}
class FeedbackListener implements OnClickListener {
public void onClick(DialogInterface dialog, int which) {
/* Create the Intent */
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
/* Fill it with Data */
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{getContext().getString(R.string.tAboutMail)});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "[Condroid] - Feedback");
//emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
/* Send it off to the Activity-Chooser */
getContext().startActivity(Intent.createChooser(emailIntent, "Poslat e-mail"));
}
}
class DonateListener implements OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_donations" +
"&business=2Z394R5DLKGU4&lc=CZ&item_name=Condroid¤cy_code=CZK" +
"&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHostedGuest"));
getContext().startActivity(intent);
}
}
class FollowListener implements android.view.View.OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://mobile.twitter.com/Condroid_CZ"));
getContext().startActivity(intent);
}
}
}
| true | true | protected AboutDialog(Context context) {
super(context);
View v = LayoutInflater.from(context).inflate(R.layout.about_dialog, null);
this.setTitle(R.string.appName);
this.setView(v);
this.setButton(BUTTON1, "OK", new OkListener());
this.setButton(BUTTON2, "Přispět", new DonateListener());
this.setButton(BUTTON3, "Feedback", new FeedbackListener());
ImageView follow = ((ImageView) v.findViewById(R.id.iFollow));
follow.setOnClickListener(new FollowListener());
this.setIcon(R.drawable.icon);
}
| protected AboutDialog(Context context) {
super(context);
View v = LayoutInflater.from(context).inflate(R.layout.about_dialog, null);
this.setTitle(R.string.appNameAbout);
this.setView(v);
this.setButton(BUTTON1, "OK", new OkListener());
this.setButton(BUTTON2, "Přispět", new DonateListener());
this.setButton(BUTTON3, "Feedback", new FeedbackListener());
ImageView follow = ((ImageView) v.findViewById(R.id.iFollow));
follow.setOnClickListener(new FollowListener());
this.setIcon(R.drawable.icon);
}
|
diff --git a/rvsn00p/src/rvsnoop/RvFieldTreeNode.java b/rvsn00p/src/rvsnoop/RvFieldTreeNode.java
index 5ff2c7b..444371d 100644
--- a/rvsn00p/src/rvsnoop/RvFieldTreeNode.java
+++ b/rvsn00p/src/rvsnoop/RvFieldTreeNode.java
@@ -1,243 +1,243 @@
//:File: RvFieldTreeNode.java
//:Created: Dec 12, 2005
//:Legal: Copyright © 2005-@year@ Apache Software Foundation.
//:Legal: Copyright © 2005-@year@ Ian Phillips.
//:License: Licensed under the Apache License, Version 2.0.
//:FileID: $Id$
package rvsnoop;
import com.tibco.tibrv.TibrvException;
import com.tibco.tibrv.TibrvIPAddr;
import com.tibco.tibrv.TibrvIPPort;
import com.tibco.tibrv.TibrvMsg;
import com.tibco.tibrv.TibrvMsgField;
import com.tibco.tibrv.TibrvXml;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Array;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.Icon;
import javax.swing.tree.TreeNode;
import org.apache.commons.io.IOUtils;
import nu.xom.Builder;
import nu.xom.Document;
import rvsnoop.ui.Icons;
/**
* A {@link TreeNode} that wraps a Rendezvous message field.
*
* @author <a href="mailto:[email protected]">Ian Phillips</a>
* @version $Revision$, $Date$
* @since 1.3
*/
final class RvFieldTreeNode extends LazyTreeNode {
private static Icon setIcon(TibrvMsgField field) {
switch (field.type) {
case TibrvMsg.ENCRYPTED:
return Icons.RV_FIELD;
case TibrvMsg.F32ARRAY:
return Icons.RV_FIELD;
case TibrvMsg.F64ARRAY:
return Icons.RV_FIELD;
case TibrvMsg.I8ARRAY:
return Icons.RV_FIELD;
case TibrvMsg.I16ARRAY:
return Icons.RV_FIELD;
case TibrvMsg.I32ARRAY:
return Icons.RV_FIELD;
case TibrvMsg.I64ARRAY:
return Icons.RV_FIELD;
case TibrvMsg.IPADDR32:
return Icons.RV_FIELD;
case TibrvMsg.IPPORT16:
return Icons.RV_FIELD;
case TibrvMsg.MSG:
return Icons.RV_MESSAGE;
case TibrvMsg.OPAQUE:
return Icons.RV_FIELD;
default:
return Icons.RV_FIELD;
}
}
static String getFieldDescription(TibrvMsgField field) {
final short type = field.type;
switch (type) {
case TibrvMsg.ENCRYPTED: return FD_ENCRYPTED.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.MSG: return FD_MSG.format(new Object[] {field.name, new Integer(((TibrvMsg) field.data).getNumFields())});
case TibrvMsg.OPAQUE: return FD_OPAQUE.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.BOOL: return FD_BOOL.format(new Object[] {field.name, field.data});
case TibrvMsg.DATETIME: return FD_DATETIME.format(new Object[] {field.name, field.data});
case TibrvMsg.IPADDR32: return FD_IPADDR32.format(new Object[] {field.name, ((TibrvIPAddr) field.data).getAsString()});
case TibrvMsg.IPPORT16: return FD_IPPORT16.format(new Object[] {field.name, new Integer(((TibrvIPPort) field.data).getPort())});
case TibrvMsg.F32ARRAY: return FD_F32ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.F64ARRAY: return FD_F64ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I8ARRAY: return FD_I8ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I16ARRAY: return FD_I16ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I32ARRAY: return FD_I32ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I64ARRAY: return FD_I64ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U8ARRAY: return FD_U8ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U16ARRAY: return FD_U16ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U32ARRAY: return FD_U32ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U64ARRAY: return FD_U64ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.F32: return FD_F32.format(new Object[] {field.name, field.data});
case TibrvMsg.F64: return FD_F64.format(new Object[] {field.name, field.data});
case TibrvMsg.I8: return FD_I8.format(new Object[] {field.name, field.data});
case TibrvMsg.I16: return FD_I16.format(new Object[] {field.name, field.data});
case TibrvMsg.I32: return FD_I32.format(new Object[] {field.name, field.data});
case TibrvMsg.I64: return FD_I64.format(new Object[] {field.name, field.data});
case TibrvMsg.U8: return FD_U8.format(new Object[] {field.name, field.data});
case TibrvMsg.U16: return FD_U16.format(new Object[] {field.name, field.data});
case TibrvMsg.U32: return FD_U32.format(new Object[] {field.name, field.data});
case TibrvMsg.U64: return FD_U64.format(new Object[] {field.name, field.data});
case TibrvMsg.XML:
return FD_XML.format(new Object[] {field.name, new Integer(((TibrvXml) field.data).getBytes().length)});
case TibrvMsg.STRING:
- final String s = new String(((TibrvXml) field.data).getBytes());
+ final String s = (String) field.data;
if (s.startsWith("<?xml ")) return FD_STRING_XML.format(new Object[] {field.name, new Integer(s.length())});
if (s.length() > 60) return FD_STRING_LONG.format(new Object[] {field.name, new Integer(s.length()), s.substring(0, 60)});
return FD_STRING.format(new Object[] {field.name, s});
default: return FD_USER.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
}
}
private static final MessageFormat FD_ENCRYPTED = new MessageFormat("{0} ({1} bytes of encrypted data)");
private static final MessageFormat FD_F32ARRAY = new MessageFormat("{0} ({1} single precision floating point {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_F64ARRAY = new MessageFormat("{0} ({1} double precision floating point {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_I8ARRAY = new MessageFormat("{0} ({1} 8-bit signed integer {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_I16ARRAY = new MessageFormat("{0} ({1} 16-bit signed integer {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_I32ARRAY = new MessageFormat("{0} ({1} 32-bit signed integer {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_I64ARRAY = new MessageFormat("{0} ({1} 64-bit signed integer {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_U8ARRAY = new MessageFormat("{0} ({1} 8-bit unsigned integer {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_U16ARRAY = new MessageFormat("{0} ({1} 16-bit unsigned integer {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_U32ARRAY = new MessageFormat("{0} ({1} 32-bit unsigned integer {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_U64ARRAY = new MessageFormat("{0} ({1} 64-bit unsigned integer {1,choice,0# values|1# value|1< values})");
private static final MessageFormat FD_IPADDR32 = new MessageFormat("{0} (IP Address: {1})");
private static final MessageFormat FD_IPPORT16 = new MessageFormat("{0} (IP Port Number: {1})");
private static final MessageFormat FD_F32 = new MessageFormat("{0} ({1}, with single/32-bit precision)");
private static final MessageFormat FD_F64 = new MessageFormat("{0} ({1}, with double/64-bit precision)");
private static final MessageFormat FD_I8 = new MessageFormat("{0} ({1}, as an 8-bit signed integer)");
private static final MessageFormat FD_I16 = new MessageFormat("{0} ({1}, as a 16-bit signed integer)");
private static final MessageFormat FD_I32 = new MessageFormat("{0} ({1}, as a 32-bit signed integer)");
private static final MessageFormat FD_I64 = new MessageFormat("{0} ({1}, as a 64-bit signed integer)");
private static final MessageFormat FD_U8 = new MessageFormat("{0} ({1}, as an 8-bit unsigned integer)");
private static final MessageFormat FD_U16 = new MessageFormat("{0} ({1}, as a 16-bit unsigned integer)");
private static final MessageFormat FD_U32 = new MessageFormat("{0} ({1}, as a 32-bit unsigned integer)");
private static final MessageFormat FD_U64 = new MessageFormat("{0} ({1}, as a 64-bit unsigned integer)");
private static final MessageFormat FD_MSG = new MessageFormat("{0} (Message with {1} {1,choice,0# fields|1# field|1< fields})");
private static final MessageFormat FD_OPAQUE = new MessageFormat("{0} ({1} bytes of opaque/binary data)");
private static final MessageFormat FD_BOOL = new MessageFormat("{0} ({1} as a boolean value)");
private static final MessageFormat FD_DATETIME = new MessageFormat("{0} ({1} as a Rendezvous time object)");
private static final MessageFormat FD_XML = new MessageFormat("{0} ({1} bytes of compressed XML data)");
private static final MessageFormat FD_STRING = new MessageFormat("{0} (\"{1}\")");
private static final MessageFormat FD_STRING_LONG = new MessageFormat("{0} ({1} characters of string data, starting with \"{2} ...\")");
private static final MessageFormat FD_STRING_XML = new MessageFormat("{0} ({1} characters of string encoded XML data)");
private static final MessageFormat FD_USER = new MessageFormat("{0} ({1} bytes of custom user data)");
private final boolean allowsChildren;
private final Icon icon;
private final String text;
private static final Logger logger = Logger.getLogger(RvFieldTreeNode.class);
private final TibrvMsgField field;
/**
* @param parent The parent of this node.
* @param field The field represented by this node.
* @param text A custom label to use when displaying this field.
* @param icon A custom icon to use when displaying this field.
*/
public RvFieldTreeNode(TreeNode parent, TibrvMsgField field, String text, Icon icon) {
super(parent);
this.icon = icon != null ? icon : setIcon(field);
this.text = text != null ? text : getFieldDescription(field);
this.field = field;
if (field.type == TibrvMsg.MSG) {
allowsChildren = true;
} else if (field.type == TibrvMsg.XML) {
allowsChildren = true;
} else {
allowsChildren = field.type == TibrvMsg.STRING && ((String) field.data).startsWith("<?xml ");
}
}
/**
* @param parent The parent of this node.
* @param field The field represented by this node.
*/
public RvFieldTreeNode(TreeNode parent, TibrvMsgField field) {
this(parent, field, null, null);
}
protected List createChildren() {
List children = null;
if (field.type == TibrvMsg.XML) {
final InputStream stream = new ByteArrayInputStream(((TibrvXml) field.data).getBytes());
children = createChildrenFromXML(new InputStreamReader(stream));
} else if (field.type == TibrvMsg.STRING && ((String) field.data).startsWith("<?xml ")) {
children = createChildrenFromXML(new StringReader((String) field.data));
} else if (field.type == TibrvMsg.MSG) {
final TibrvMsg msg = (TibrvMsg) field.data;
final int numChildren = msg.getNumFields();
children = new ArrayList(numChildren);
try {
for (int i = 0; i < numChildren; ++i)
children.add(new RvFieldTreeNode(this, msg.getFieldByIndex(i)));
} catch (TibrvException e) {
if (Logger.isErrorEnabled())
logger.error("Error reading field.", e);
}
}
return children != null ? children : Collections.EMPTY_LIST;
}
private List createChildrenFromXML(final Reader reader) {
List children = null;
final Builder builder = new Builder(false, new InterningTrimmingNodeFactory());
try {
final Document doc = builder.build(reader).getDocument();
final int numChildren = doc.getChildCount();
children = new ArrayList(numChildren);
for (int i = 0; i < numChildren; ++i)
children.add(new XMLTreeNode(this, doc.getChild(i)));
} catch (Exception e) {
logger.error("Error extracting XML.", e);
} finally {
IOUtils.closeQuietly(reader);
}
return children;
}
/* (non-Javadoc)
* @see javax.swing.tree.TreeNode#getAllowsChildren()
*/
public boolean getAllowsChildren() {
return allowsChildren;
}
public Icon getIcon() {
return icon;
}
public String getText() {
return text;
}
public String getTooltip() {
return TibrvMsg.getTypeName(field.type);
}
}
| true | true | static String getFieldDescription(TibrvMsgField field) {
final short type = field.type;
switch (type) {
case TibrvMsg.ENCRYPTED: return FD_ENCRYPTED.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.MSG: return FD_MSG.format(new Object[] {field.name, new Integer(((TibrvMsg) field.data).getNumFields())});
case TibrvMsg.OPAQUE: return FD_OPAQUE.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.BOOL: return FD_BOOL.format(new Object[] {field.name, field.data});
case TibrvMsg.DATETIME: return FD_DATETIME.format(new Object[] {field.name, field.data});
case TibrvMsg.IPADDR32: return FD_IPADDR32.format(new Object[] {field.name, ((TibrvIPAddr) field.data).getAsString()});
case TibrvMsg.IPPORT16: return FD_IPPORT16.format(new Object[] {field.name, new Integer(((TibrvIPPort) field.data).getPort())});
case TibrvMsg.F32ARRAY: return FD_F32ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.F64ARRAY: return FD_F64ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I8ARRAY: return FD_I8ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I16ARRAY: return FD_I16ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I32ARRAY: return FD_I32ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I64ARRAY: return FD_I64ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U8ARRAY: return FD_U8ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U16ARRAY: return FD_U16ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U32ARRAY: return FD_U32ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U64ARRAY: return FD_U64ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.F32: return FD_F32.format(new Object[] {field.name, field.data});
case TibrvMsg.F64: return FD_F64.format(new Object[] {field.name, field.data});
case TibrvMsg.I8: return FD_I8.format(new Object[] {field.name, field.data});
case TibrvMsg.I16: return FD_I16.format(new Object[] {field.name, field.data});
case TibrvMsg.I32: return FD_I32.format(new Object[] {field.name, field.data});
case TibrvMsg.I64: return FD_I64.format(new Object[] {field.name, field.data});
case TibrvMsg.U8: return FD_U8.format(new Object[] {field.name, field.data});
case TibrvMsg.U16: return FD_U16.format(new Object[] {field.name, field.data});
case TibrvMsg.U32: return FD_U32.format(new Object[] {field.name, field.data});
case TibrvMsg.U64: return FD_U64.format(new Object[] {field.name, field.data});
case TibrvMsg.XML:
return FD_XML.format(new Object[] {field.name, new Integer(((TibrvXml) field.data).getBytes().length)});
case TibrvMsg.STRING:
final String s = new String(((TibrvXml) field.data).getBytes());
if (s.startsWith("<?xml ")) return FD_STRING_XML.format(new Object[] {field.name, new Integer(s.length())});
if (s.length() > 60) return FD_STRING_LONG.format(new Object[] {field.name, new Integer(s.length()), s.substring(0, 60)});
return FD_STRING.format(new Object[] {field.name, s});
default: return FD_USER.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
}
}
| static String getFieldDescription(TibrvMsgField field) {
final short type = field.type;
switch (type) {
case TibrvMsg.ENCRYPTED: return FD_ENCRYPTED.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.MSG: return FD_MSG.format(new Object[] {field.name, new Integer(((TibrvMsg) field.data).getNumFields())});
case TibrvMsg.OPAQUE: return FD_OPAQUE.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.BOOL: return FD_BOOL.format(new Object[] {field.name, field.data});
case TibrvMsg.DATETIME: return FD_DATETIME.format(new Object[] {field.name, field.data});
case TibrvMsg.IPADDR32: return FD_IPADDR32.format(new Object[] {field.name, ((TibrvIPAddr) field.data).getAsString()});
case TibrvMsg.IPPORT16: return FD_IPPORT16.format(new Object[] {field.name, new Integer(((TibrvIPPort) field.data).getPort())});
case TibrvMsg.F32ARRAY: return FD_F32ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.F64ARRAY: return FD_F64ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I8ARRAY: return FD_I8ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I16ARRAY: return FD_I16ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I32ARRAY: return FD_I32ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.I64ARRAY: return FD_I64ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U8ARRAY: return FD_U8ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U16ARRAY: return FD_U16ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U32ARRAY: return FD_U32ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.U64ARRAY: return FD_U64ARRAY.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
case TibrvMsg.F32: return FD_F32.format(new Object[] {field.name, field.data});
case TibrvMsg.F64: return FD_F64.format(new Object[] {field.name, field.data});
case TibrvMsg.I8: return FD_I8.format(new Object[] {field.name, field.data});
case TibrvMsg.I16: return FD_I16.format(new Object[] {field.name, field.data});
case TibrvMsg.I32: return FD_I32.format(new Object[] {field.name, field.data});
case TibrvMsg.I64: return FD_I64.format(new Object[] {field.name, field.data});
case TibrvMsg.U8: return FD_U8.format(new Object[] {field.name, field.data});
case TibrvMsg.U16: return FD_U16.format(new Object[] {field.name, field.data});
case TibrvMsg.U32: return FD_U32.format(new Object[] {field.name, field.data});
case TibrvMsg.U64: return FD_U64.format(new Object[] {field.name, field.data});
case TibrvMsg.XML:
return FD_XML.format(new Object[] {field.name, new Integer(((TibrvXml) field.data).getBytes().length)});
case TibrvMsg.STRING:
final String s = (String) field.data;
if (s.startsWith("<?xml ")) return FD_STRING_XML.format(new Object[] {field.name, new Integer(s.length())});
if (s.length() > 60) return FD_STRING_LONG.format(new Object[] {field.name, new Integer(s.length()), s.substring(0, 60)});
return FD_STRING.format(new Object[] {field.name, s});
default: return FD_USER.format(new Object[] {field.name, new Integer(Array.getLength(field.data))});
}
}
|
diff --git a/sip-core/src/main/java/eu/delving/metadata/NodeMapping.java b/sip-core/src/main/java/eu/delving/metadata/NodeMapping.java
index a2620cde..908be069 100644
--- a/sip-core/src/main/java/eu/delving/metadata/NodeMapping.java
+++ b/sip-core/src/main/java/eu/delving/metadata/NodeMapping.java
@@ -1,391 +1,387 @@
/*
* Copyright 2011, 2012 Delving BV
*
* Licensed under the EUPL, Version 1.0 or? as soon they
* will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* you may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/
package eu.delving.metadata;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import java.util.*;
import static eu.delving.metadata.NodeMappingChange.CODE;
import static eu.delving.metadata.NodeMappingChange.DOCUMENTATION;
import static eu.delving.metadata.StringUtil.*;
/**
* This class describes how one node is transformed into another, which is part of mapping
* one hierarchy onto another. It can contain a dictionary, as well as a snippet
* of Groovy code.
* <p/>
* Instances of this class are placed in the RecDefNode elements of the record definition
* so that that data structure can be used as a scaffolding to recursively write the code
* for the Groovy builder.
* <p/>
* Instances are also stored in a list in the RecMapping, and upon reading a mapping they
* are distributed into the local prototype instance of the record definition data structure.
*
* @author Gerald de Jong <[email protected]>
*/
@XStreamAlias("node-mapping")
public class NodeMapping {
@XStreamAsAttribute
public Path inputPath;
@XStreamAsAttribute
public Path outputPath;
public List<Path> siblings;
@XStreamAsAttribute
public Operator operator;
public Map<String, String> dictionary;
@XStreamAlias("groovy-code")
public List<String> groovyCode;
public List<String> documentation;
@XStreamOmitField
public RecDefNode recDefNode;
@XStreamOmitField
public CodeOut codeOut;
@XStreamOmitField
private SortedSet sourceTreeNodes;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeMapping that = (NodeMapping) o;
if (inputPath != null ? !inputPath.equals(that.inputPath) : that.inputPath != null) return false;
if (outputPath != null ? !outputPath.equals(that.outputPath) : that.outputPath != null) return false;
return true;
}
@Override
public int hashCode() {
return inputPath.hashCode();
}
public String getDocumentation() {
return linesToString(documentation);
}
public void setDocumentation(String documentation) {
this.documentation = stringToLines(documentation);
notifyChanged(DOCUMENTATION);
}
public Operator getOperator() {
if (recDefNode.hasOperator()) return recDefNode.getOperator();
return operator == null ? Operator.ALL : operator;
}
public void clearStatsTreeNodes() {
sourceTreeNodes = null;
}
public boolean hasMap() {
return siblings != null;
}
public boolean hasSourceTreeNodes() {
return sourceTreeNodes != null;
}
public boolean hasOneSourceTreeNode() {
return hasSourceTreeNodes() && sourceTreeNodes.size() == 1;
}
public Object getSingleSourceTreeNode() {
Iterator walk = sourceTreeNodes.iterator();
return walk.hasNext() ? walk.next() : null;
}
public SortedSet getSourceTreeNodes() {
return sourceTreeNodes;
}
public void attachTo(RecDefNode recDefNode) {
this.recDefNode = recDefNode;
this.outputPath = recDefNode.getPath();
}
// this method should be called from exactly ONE place!
public NodeMapping setStatsTreeNodes(SortedSet statsTreeNodes, List<Path> inputPaths) {
if (statsTreeNodes.isEmpty()) throw new RuntimeException();
this.sourceTreeNodes = statsTreeNodes;
setInputPaths(inputPaths);
return this;
}
public NodeMapping setInputPath(Path inputPath) {
this.inputPath = inputPath;
return this;
}
public void notifyChanged(NodeMappingChange change) {
if (recDefNode != null) recDefNode.notifyNodeMappingChange(this, change);
}
public NodeMapping setInputPaths(Collection<Path> inputPaths) {
if (inputPaths.isEmpty()) throw new RuntimeException();
Path parent = null;
for (Path input : inputPaths) {
if (parent == null) {
parent = input.parent();
}
else if (!parent.equals(input.parent())) {
throw new RuntimeException(String.format("Input path %s should all be from the same parent %s", input, parent));
}
}
Iterator<Path> pathWalk = inputPaths.iterator();
this.inputPath = pathWalk.next();
if (pathWalk.hasNext()) {
siblings = new ArrayList<Path>();
while (pathWalk.hasNext()) siblings.add(pathWalk.next());
}
return this;
}
public List<Path> getInputPaths() {
List<Path> inputPaths = new ArrayList<Path>();
inputPaths.add(inputPath);
if (siblings != null) inputPaths.addAll(siblings);
Collections.sort(inputPaths);
return inputPaths;
}
public NodeMapping setOutputPath(Path outputPath) {
this.outputPath = outputPath;
return this;
}
public boolean generatedCodeLooksLike(String codeString, RecMapping recMapping) {
if (codeString == null) return false;
List<String> list = Arrays.asList(getCode(getGeneratorEditPath(), recMapping).split("\n"));
Iterator<String> walk = list.iterator();
return isSimilar(codeString, walk);
}
public boolean codeLooksLike(String codeString) {
return groovyCode == null || isSimilar(codeString, groovyCode.iterator());
}
public String getCode(EditPath editPath, RecMapping recMapping) {
recMapping.toCode(editPath);
return codeOut.toString();
}
public void revertToGenerated() {
setGroovyCode(null, null);
}
public void setGroovyCode(String codeString, RecMapping recMapping) {
if (codeString == null || generatedCodeLooksLike(codeString, recMapping)) {
if (groovyCode != null) {
groovyCode = null;
notifyChanged(CODE);
}
}
else if (groovyCode == null || !codeLooksLike(codeString)) {
groovyCode = stringToLines(codeString);
notifyChanged(CODE);
}
}
public void toAttributeCode(Stack<String> groovyParams, EditPath editPath) {
if (!recDefNode.isAttr()) return;
toUserCode(groovyParams, editPath);
}
public void toLeafElementCode(Stack<String> groovyParams, EditPath editPath) {
if (recDefNode.isAttr() || !recDefNode.isLeafElem()) return;
toUserCode(groovyParams, editPath);
}
public boolean isUserCodeEditable() {
return recDefNode.isAttr() || recDefNode.isLeafElem();
}
private boolean isSimilar(String codeString, Iterator<String> walk) {
for (String line : codeString.split("\n")) {
line = line.trim();
if (line.isEmpty()) continue;
if (!walk.hasNext()) return false;
while (walk.hasNext()) {
String otherLine = walk.next().trim();
if (otherLine.isEmpty()) continue;
if (!otherLine.equals(line)) return false;
break;
}
}
return !walk.hasNext();
}
private void toUserCode(Stack<String> groovyParams, EditPath editPath) {
if (editPath != null) {
String editedCode = editPath.getEditedCode(recDefNode.getPath());
if (editedCode != null) {
indentCode(editedCode, codeOut);
return;
}
else if (groovyCode != null) {
indentCode(groovyCode, codeOut);
return;
}
}
else if (groovyCode != null) {
indentCode(groovyCode, codeOut);
return;
}
toInnerLoop(getLocalPath(), groovyParams);
}
private void toInnerLoop(Path path, Stack<String> groovyParams) {
if (path.isEmpty()) throw new RuntimeException();
if (path.size() == 1) {
if (dictionary != null) {
codeOut.line("from%s(%s)", toDictionaryName(this), toLeafGroovyParam(path));
}
else if (hasMap()) {
codeOut.line(getMapUsage());
}
else {
+ String sanitize = recDefNode.getFieldType().equalsIgnoreCase("link") ? ".sanitizeURI()" : "";
if (path.peek().getLocalName().equals("constant")) {
codeOut.line("'CONSTANT'");
}
else if (recDefNode.hasFunction()) {
- if (recDefNode.getFieldType().equalsIgnoreCase("link")) {
- codeOut.line("\"${%s(%s).sanitizeURI()}\"", recDefNode.getFunction(), toLeafGroovyParam(path));
- }
- else {
- codeOut.line("\"${%s(%s)}\"", recDefNode.getFunction(), toLeafGroovyParam(path));
- }
+ codeOut.line("\"${%s(%s)%s}\"", recDefNode.getFunction(), toLeafGroovyParam(path), sanitize);
}
else {
- codeOut.line("\"${%s}\"", toLeafGroovyParam(path));
+ codeOut.line("\"${%s%s}\"", toLeafGroovyParam(path), sanitize);
}
}
}
else if (recDefNode.isLeafElem()) {
toInnerLoop(path.withRootRemoved(), groovyParams);
}
else {
boolean needLoop;
if (hasMap()) {
needLoop = !groovyParams.contains(getMapName());
if (needLoop) {
codeOut.line_(
"%s %s { %s ->",
toMapExpression(this), getOperator().getChar(), getMapName()
);
}
}
else {
String param = toLoopGroovyParam(path);
needLoop = !groovyParams.contains(param);
if (needLoop) {
codeOut.line_(
"%s %s { %s ->",
toLoopRef(path), getOperator().getChar(), param
);
}
}
toInnerLoop(path.withRootRemoved(), groovyParams);
if (needLoop) codeOut._line("}");
}
}
public Path getLocalPath() {
NodeMapping ancestor = getAncestorNodeMapping(inputPath);
if (ancestor.inputPath.isAncestorOf(inputPath)) {
return inputPath.extendAncestor(ancestor.inputPath);
}
else {
return inputPath;
}
}
private String getMapUsage() {
if (!hasMap()) return null;
StringBuilder usage = new StringBuilder("\"");
Iterator<Path> walk = getInputPaths().iterator();
while (walk.hasNext()) {
Path path = walk.next();
usage.append(String.format("${%s['%s']}", getMapName(), path.peek().toMapKey()));
if (walk.hasNext()) usage.append(" ");
}
usage.append("\"");
return usage.toString();
}
public String getMapName() {
return String.format("_M%d", inputPath.size());
}
public String toString() {
if (recDefNode == null) return "No RecDefNode";
String input = inputPath.getTail();
if (hasMap()) {
StringBuilder out = new StringBuilder();
Iterator<Path> walk = getInputPaths().iterator();
while (walk.hasNext()) {
out.append(walk.next().getTail());
if (walk.hasNext()) out.append(", ");
}
input = out.toString();
}
String wrap = groovyCode == null ? "p" : "b";
return String.format("<html><%s>%s → %s</%s>", wrap, input, recDefNode.toString(), wrap);
}
private NodeMapping getAncestorNodeMapping(Path path) {
for (RecDefNode ancestor = recDefNode.getParent(); ancestor != null; ancestor = ancestor.getParent()) {
for (NodeMapping nodeMapping : ancestor.getNodeMappings().values()) {
if (nodeMapping.inputPath.isAncestorOf(path)) return nodeMapping;
}
}
return new NodeMapping().setInputPath(Path.create("input")).setOutputPath(outputPath.takeFirst());
}
private EditPath getGeneratorEditPath() {
return new EditPath() {
@Override
public NodeMapping getNodeMapping() {
return NodeMapping.this;
}
@Override
public String getEditedCode(Path path) {
return null;
}
};
}
}
| false | true | private void toInnerLoop(Path path, Stack<String> groovyParams) {
if (path.isEmpty()) throw new RuntimeException();
if (path.size() == 1) {
if (dictionary != null) {
codeOut.line("from%s(%s)", toDictionaryName(this), toLeafGroovyParam(path));
}
else if (hasMap()) {
codeOut.line(getMapUsage());
}
else {
if (path.peek().getLocalName().equals("constant")) {
codeOut.line("'CONSTANT'");
}
else if (recDefNode.hasFunction()) {
if (recDefNode.getFieldType().equalsIgnoreCase("link")) {
codeOut.line("\"${%s(%s).sanitizeURI()}\"", recDefNode.getFunction(), toLeafGroovyParam(path));
}
else {
codeOut.line("\"${%s(%s)}\"", recDefNode.getFunction(), toLeafGroovyParam(path));
}
}
else {
codeOut.line("\"${%s}\"", toLeafGroovyParam(path));
}
}
}
else if (recDefNode.isLeafElem()) {
toInnerLoop(path.withRootRemoved(), groovyParams);
}
else {
boolean needLoop;
if (hasMap()) {
needLoop = !groovyParams.contains(getMapName());
if (needLoop) {
codeOut.line_(
"%s %s { %s ->",
toMapExpression(this), getOperator().getChar(), getMapName()
);
}
}
else {
String param = toLoopGroovyParam(path);
needLoop = !groovyParams.contains(param);
if (needLoop) {
codeOut.line_(
"%s %s { %s ->",
toLoopRef(path), getOperator().getChar(), param
);
}
}
toInnerLoop(path.withRootRemoved(), groovyParams);
if (needLoop) codeOut._line("}");
}
}
| private void toInnerLoop(Path path, Stack<String> groovyParams) {
if (path.isEmpty()) throw new RuntimeException();
if (path.size() == 1) {
if (dictionary != null) {
codeOut.line("from%s(%s)", toDictionaryName(this), toLeafGroovyParam(path));
}
else if (hasMap()) {
codeOut.line(getMapUsage());
}
else {
String sanitize = recDefNode.getFieldType().equalsIgnoreCase("link") ? ".sanitizeURI()" : "";
if (path.peek().getLocalName().equals("constant")) {
codeOut.line("'CONSTANT'");
}
else if (recDefNode.hasFunction()) {
codeOut.line("\"${%s(%s)%s}\"", recDefNode.getFunction(), toLeafGroovyParam(path), sanitize);
}
else {
codeOut.line("\"${%s%s}\"", toLeafGroovyParam(path), sanitize);
}
}
}
else if (recDefNode.isLeafElem()) {
toInnerLoop(path.withRootRemoved(), groovyParams);
}
else {
boolean needLoop;
if (hasMap()) {
needLoop = !groovyParams.contains(getMapName());
if (needLoop) {
codeOut.line_(
"%s %s { %s ->",
toMapExpression(this), getOperator().getChar(), getMapName()
);
}
}
else {
String param = toLoopGroovyParam(path);
needLoop = !groovyParams.contains(param);
if (needLoop) {
codeOut.line_(
"%s %s { %s ->",
toLoopRef(path), getOperator().getChar(), param
);
}
}
toInnerLoop(path.withRootRemoved(), groovyParams);
if (needLoop) codeOut._line("}");
}
}
|
diff --git a/src/org/fao/geonet/services/thumbnail/Set.java b/src/org/fao/geonet/services/thumbnail/Set.java
index 0dcdb262c0..7170a3318b 100644
--- a/src/org/fao/geonet/services/thumbnail/Set.java
+++ b/src/org/fao/geonet/services/thumbnail/Set.java
@@ -1,299 +1,299 @@
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 of the License, or (at
//=== your option) any later version.
//===
//=== This program is distributed in the hope that it will be useful, but
//=== WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.services.thumbnail;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import jeeves.interfaces.Service;
import jeeves.resources.dbms.Dbms;
import jeeves.server.ServiceConfig;
import jeeves.server.context.ServiceContext;
import jeeves.utils.Util;
import lizard.tiff.Tiff;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.constants.Params;
import org.fao.geonet.exceptions.ConcurrentUpdateEx;
import org.fao.geonet.kernel.AccessManager;
import org.fao.geonet.kernel.DataManager;
import org.fao.geonet.lib.Lib;
import org.jdom.Element;
//=============================================================================
public class Set implements Service
{
//--------------------------------------------------------------------------
//---
//--- Init
//---
//--------------------------------------------------------------------------
public void init(String appPath, ServiceConfig params) throws Exception {}
//--------------------------------------------------------------------------
//---
//--- Service
//---
//--------------------------------------------------------------------------
public Element exec(Element params, ServiceContext context) throws Exception
{
String id = Util.getParam (params, Params.ID);
String type = Util.getParam (params, Params.TYPE);
- String version = Util.getParam(params, Params.VERSION);
+ String version = Util.getParam (params, Params.VERSION);
String file = Util.getParam (params, Params.FNAME);
String scalingDir = Util.getParam (params, Params.SCALING_DIR);
int scalingFactor = Util.getParamInt (params, Params.SCALING_FACTOR);
boolean scaling = Util.getParamBool(params, Params.SCALING, false);
boolean createSmall = Util.getParamBool(params, Params.CREATE_SMALL, false);
String smallScalingDir = Util.getParam (params, Params.SMALL_SCALING_DIR, "");
int smallScalingFactor = Util.getParamInt (params, Params.SMALL_SCALING_FACTOR, 0);
Lib.resource.checkPrivilege(context, id, AccessManager.OPER_EDIT);
//-----------------------------------------------------------------------
//--- environment vars
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
DataManager dataMan = gc.getDataManager();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
//--- check if the metadata has been modified from last time
if (version != null && !dataMan.getVersion(id).equals(version))
throw new ConcurrentUpdateEx(id);
//-----------------------------------------------------------------------
//--- create destination directory
String dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id);
new File(dataDir).mkdirs();
//-----------------------------------------------------------------------
//--- create the small thumbnail, removing the old one
if (createSmall)
{
String smallFile = getFileName(file, true);
String inFile = context.getUploadDir() + file;
String outFile = dataDir + smallFile;
removeOldThumbnail(context, id, "small");
createThumbnail(inFile, outFile, smallScalingFactor, smallScalingDir);
dataMan.setThumbnail(dbms, id, true, smallFile);
}
//-----------------------------------------------------------------------
//--- create the requested thumbnail, removing the old one
removeOldThumbnail(context, id, type);
if (scaling)
{
String newFile = getFileName(file, type.equals("small"));
String inFile = context.getUploadDir() + file;
String outFile = dataDir + newFile;
createThumbnail(inFile, outFile, scalingFactor, scalingDir);
if (!new File(inFile).delete())
context.error("Error while deleting thumbnail : "+inFile);
dataMan.setThumbnail(dbms, id, type.equals("small"), newFile);
}
else
{
//--- move uploaded file to destination directory
File inFile = new File(context.getUploadDir(), file);
File outFile = new File(dataDir, file);
if (!inFile.renameTo(outFile))
{
inFile.delete();
throw new Exception("unable to move uploaded thumbnail to destination directory");
}
dataMan.setThumbnail(dbms, id, type.equals("small"), file);
}
//-----------------------------------------------------------------------
Element response = new Element("a");
response.addContent(new Element("id").setText(id));
response.addContent(new Element("version").setText(dataMan.getNewVersion(id)));
return response;
}
//--------------------------------------------------------------------------
//---
//--- Private methods
//---
//--------------------------------------------------------------------------
private void removeOldThumbnail(ServiceContext context, String id, String type) throws Exception
{
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
DataManager dataMan = gc.getDataManager();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
Element result = dataMan.getThumbnails(dbms, id);
if (result == null)
throw new IllegalArgumentException("Metadata not found --> " + id);
result = result.getChild(type);
//--- if there is no thumbnail, we return
if (result == null)
return;
//-----------------------------------------------------------------------
//--- remove thumbnail
dataMan.unsetThumbnail(dbms, id, type.equals("small"));
//--- remove file
String file = Lib.resource.getDir(context, Params.Access.PUBLIC, id) + result.getText();
if (!new File(file).delete())
context.error("Error while deleting thumbnail : "+file);
}
//--------------------------------------------------------------------------
private void createThumbnail(String inFile, String outFile, int scalingFactor,
String scalingDir) throws IOException
{
BufferedImage origImg = getImage(inFile);
int imgWidth = origImg.getWidth();
int imgHeight = origImg.getHeight();
int width;
int height;
if (scalingDir.equals("width"))
{
width = scalingFactor;
height = width * imgHeight / imgWidth;
}
else
{
height = scalingFactor;
width = height * imgWidth / imgHeight;
}
Image thumb = origImg.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = bimg.createGraphics();
g.drawImage(thumb, 0, 0, null);
g.dispose();
ImageIO.write(bimg, IMAGE_TYPE, new File(outFile));
}
//--------------------------------------------------------------------------
private String getFileName(String file, boolean small)
{
int pos = file.lastIndexOf(".");
if (pos != -1)
file = file.substring(0, pos);
return small ? file + SMALL_SUFFIX +"."+ IMAGE_TYPE
: file +"."+ IMAGE_TYPE;
}
//--------------------------------------------------------------------------
public BufferedImage getImage(String inFile) throws IOException
{
String lcFile = inFile.toLowerCase();
if (lcFile.endsWith(".tif") || lcFile.endsWith(".tiff"))
{
//--- load the TIFF/GEOTIFF file format
Image image = getTiffImage(inFile);
int width = image.getWidth(null);
int height= image.getHeight(null);
BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = bimg.createGraphics();
g.drawImage(image, 0,0, null);
g.dispose();
return bimg;
}
return ImageIO.read(new File(inFile));
}
//--------------------------------------------------------------------------
private Image getTiffImage(String inFile) throws IOException
{
Tiff t = new Tiff();
t.readInputStream(new FileInputStream(inFile));
if (t.getPageCount() == 0)
throw new IOException("No images inside TIFF file");
return t.getImage(0);
}
//--------------------------------------------------------------------------
//---
//--- Variables
//---
//--------------------------------------------------------------------------
private static final String IMAGE_TYPE = "png";
private static final String SMALL_SUFFIX = "_s";
}
//=============================================================================
| true | true | public Element exec(Element params, ServiceContext context) throws Exception
{
String id = Util.getParam (params, Params.ID);
String type = Util.getParam (params, Params.TYPE);
String version = Util.getParam(params, Params.VERSION);
String file = Util.getParam (params, Params.FNAME);
String scalingDir = Util.getParam (params, Params.SCALING_DIR);
int scalingFactor = Util.getParamInt (params, Params.SCALING_FACTOR);
boolean scaling = Util.getParamBool(params, Params.SCALING, false);
boolean createSmall = Util.getParamBool(params, Params.CREATE_SMALL, false);
String smallScalingDir = Util.getParam (params, Params.SMALL_SCALING_DIR, "");
int smallScalingFactor = Util.getParamInt (params, Params.SMALL_SCALING_FACTOR, 0);
Lib.resource.checkPrivilege(context, id, AccessManager.OPER_EDIT);
//-----------------------------------------------------------------------
//--- environment vars
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
DataManager dataMan = gc.getDataManager();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
//--- check if the metadata has been modified from last time
if (version != null && !dataMan.getVersion(id).equals(version))
throw new ConcurrentUpdateEx(id);
//-----------------------------------------------------------------------
//--- create destination directory
String dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id);
new File(dataDir).mkdirs();
//-----------------------------------------------------------------------
//--- create the small thumbnail, removing the old one
if (createSmall)
{
String smallFile = getFileName(file, true);
String inFile = context.getUploadDir() + file;
String outFile = dataDir + smallFile;
removeOldThumbnail(context, id, "small");
createThumbnail(inFile, outFile, smallScalingFactor, smallScalingDir);
dataMan.setThumbnail(dbms, id, true, smallFile);
}
//-----------------------------------------------------------------------
//--- create the requested thumbnail, removing the old one
removeOldThumbnail(context, id, type);
if (scaling)
{
String newFile = getFileName(file, type.equals("small"));
String inFile = context.getUploadDir() + file;
String outFile = dataDir + newFile;
createThumbnail(inFile, outFile, scalingFactor, scalingDir);
if (!new File(inFile).delete())
context.error("Error while deleting thumbnail : "+inFile);
dataMan.setThumbnail(dbms, id, type.equals("small"), newFile);
}
else
{
//--- move uploaded file to destination directory
File inFile = new File(context.getUploadDir(), file);
File outFile = new File(dataDir, file);
if (!inFile.renameTo(outFile))
{
inFile.delete();
throw new Exception("unable to move uploaded thumbnail to destination directory");
}
dataMan.setThumbnail(dbms, id, type.equals("small"), file);
}
//-----------------------------------------------------------------------
Element response = new Element("a");
response.addContent(new Element("id").setText(id));
response.addContent(new Element("version").setText(dataMan.getNewVersion(id)));
return response;
}
| public Element exec(Element params, ServiceContext context) throws Exception
{
String id = Util.getParam (params, Params.ID);
String type = Util.getParam (params, Params.TYPE);
String version = Util.getParam (params, Params.VERSION);
String file = Util.getParam (params, Params.FNAME);
String scalingDir = Util.getParam (params, Params.SCALING_DIR);
int scalingFactor = Util.getParamInt (params, Params.SCALING_FACTOR);
boolean scaling = Util.getParamBool(params, Params.SCALING, false);
boolean createSmall = Util.getParamBool(params, Params.CREATE_SMALL, false);
String smallScalingDir = Util.getParam (params, Params.SMALL_SCALING_DIR, "");
int smallScalingFactor = Util.getParamInt (params, Params.SMALL_SCALING_FACTOR, 0);
Lib.resource.checkPrivilege(context, id, AccessManager.OPER_EDIT);
//-----------------------------------------------------------------------
//--- environment vars
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
DataManager dataMan = gc.getDataManager();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
//--- check if the metadata has been modified from last time
if (version != null && !dataMan.getVersion(id).equals(version))
throw new ConcurrentUpdateEx(id);
//-----------------------------------------------------------------------
//--- create destination directory
String dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id);
new File(dataDir).mkdirs();
//-----------------------------------------------------------------------
//--- create the small thumbnail, removing the old one
if (createSmall)
{
String smallFile = getFileName(file, true);
String inFile = context.getUploadDir() + file;
String outFile = dataDir + smallFile;
removeOldThumbnail(context, id, "small");
createThumbnail(inFile, outFile, smallScalingFactor, smallScalingDir);
dataMan.setThumbnail(dbms, id, true, smallFile);
}
//-----------------------------------------------------------------------
//--- create the requested thumbnail, removing the old one
removeOldThumbnail(context, id, type);
if (scaling)
{
String newFile = getFileName(file, type.equals("small"));
String inFile = context.getUploadDir() + file;
String outFile = dataDir + newFile;
createThumbnail(inFile, outFile, scalingFactor, scalingDir);
if (!new File(inFile).delete())
context.error("Error while deleting thumbnail : "+inFile);
dataMan.setThumbnail(dbms, id, type.equals("small"), newFile);
}
else
{
//--- move uploaded file to destination directory
File inFile = new File(context.getUploadDir(), file);
File outFile = new File(dataDir, file);
if (!inFile.renameTo(outFile))
{
inFile.delete();
throw new Exception("unable to move uploaded thumbnail to destination directory");
}
dataMan.setThumbnail(dbms, id, type.equals("small"), file);
}
//-----------------------------------------------------------------------
Element response = new Element("a");
response.addContent(new Element("id").setText(id));
response.addContent(new Element("version").setText(dataMan.getNewVersion(id)));
return response;
}
|
diff --git a/caintegrator2-war/src/gov/nih/nci/caintegrator2/application/workspace/WorkspaceServiceImpl.java b/caintegrator2-war/src/gov/nih/nci/caintegrator2/application/workspace/WorkspaceServiceImpl.java
index 7794f561d..b91d69efb 100644
--- a/caintegrator2-war/src/gov/nih/nci/caintegrator2/application/workspace/WorkspaceServiceImpl.java
+++ b/caintegrator2-war/src/gov/nih/nci/caintegrator2/application/workspace/WorkspaceServiceImpl.java
@@ -1,184 +1,187 @@
/**
* The software subject to this notice and license includes both human readable
* source code form and machine readable, binary, object code form. The caIntegrator2
* Software was developed in conjunction with the National Cancer Institute
* (NCI) by NCI employees, 5AM Solutions, Inc. (5AM), ScenPro, Inc. (ScenPro)
* and Science Applications International Corporation (SAIC). To the extent
* government employees are authors, any rights in such works shall be subject
* to Title 17 of the United States Code, section 105.
*
* This caIntegrator2 Software License (the License) is between NCI 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.
*
* This License is granted provided that You agree to the conditions described
* below. NCI 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 caIntegrator2 Software to (i) use, install, access, operate,
* execute, copy, modify, translate, market, publicly display, publicly perform,
* and prepare derivative works of the caIntegrator2 Software; (ii) distribute and
* have distributed to and by third parties the caIntegrator2 Software and any
* modifications and derivative works thereof; and (iii) sublicense the
* foregoing rights set out in (i) and (ii) to third parties, including the
* right to license such rights to further third parties. For sake of clarity,
* and not by way of limitation, NCI shall have no right of accounting or right
* of payment from You or Your sub-licensees for the rights granted under this
* License. This License is granted at no charge to You.
*
* Your redistributions of the source code for the 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.
*
* Your end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: This product includes software
* developed by 5AM, ScenPro, SAIC and the National Cancer Institute. If You do
* not include such end-user documentation, You shall include this acknowledgment
* in the Software itself, wherever such third-party acknowledgments normally
* appear.
*
* You may not use the names "The National Cancer Institute", "NCI", "ScenPro",
* "SAIC" or "5AM" to endorse or promote products derived from this Software.
* This License does not authorize You to use any trademarks, service marks,
* trade names, logos or product names of either NCI, ScenPro, SAID or 5AM,
* except as required to comply with the terms of this License.
*
* For sake of clarity, and not by way of limitation, You may incorporate this
* Software into Your proprietary programs and into any third party proprietary
* programs. However, if You incorporate the 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 Software
* into such third party proprietary programs and for informing Your a
* sub-licensees, including without limitation Your end-users, of their
* obligation to secure any required permissions from such third parties before
* incorporating the Software into such third party proprietary software
* programs. In the event that You fail to obtain such permissions, You agree
* to indemnify NCI for any claims against NCI by such third parties, except to
* the extent prohibited by law, resulting from Your failure to obtain such
* permissions.
*
* 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 Software, or any derivative works of the
* Software as a whole, provided Your use, reproduction, and distribution of the
* Work otherwise complies with the conditions stated in this License.
*
* THIS 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 NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC., SCENPRO, INC.,
* SCIENCE APPLICATIONS INTERNATIONAL CORPORATION OR THEIR
* AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.nih.nci.caintegrator2.application.workspace;
import gov.nih.nci.caintegrator2.data.CaIntegrator2Dao;
import gov.nih.nci.caintegrator2.domain.application.StudySubscription;
import gov.nih.nci.caintegrator2.domain.application.UserWorkspace;
import gov.nih.nci.caintegrator2.domain.translational.Study;
import gov.nih.nci.caintegrator2.security.SecurityHelper;
import java.util.HashSet;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* Implementation entry point for the WorkspaceService subsystem.
*/
@Transactional(propagation = Propagation.REQUIRED)
public class WorkspaceServiceImpl implements WorkspaceService {
private CaIntegrator2Dao dao;
/**
* {@inheritDoc}
*/
public UserWorkspace getWorkspace() {
String username = SecurityHelper.getCurrentUsername();
UserWorkspace userWorkspace = dao.getWorkspace(username);
if (userWorkspace == null) {
userWorkspace = createUserWorkspace(username);
saveUserWorkspace(userWorkspace);
}
return userWorkspace;
}
private UserWorkspace createUserWorkspace(String username) {
UserWorkspace userWorkspace;
userWorkspace = new UserWorkspace();
userWorkspace.setUsername(username);
userWorkspace.setSubscriptionCollection(new HashSet<StudySubscription>());
return userWorkspace;
}
/**
* @return the dao
*/
public CaIntegrator2Dao getDao() {
return dao;
}
/**
* @param dao the dao to set
*/
public void setDao(CaIntegrator2Dao dao) {
this.dao = dao;
}
/**
* @param workspace saves workspace.
*/
public void saveUserWorkspace(UserWorkspace workspace) {
dao.save(workspace);
}
/**
* {@inheritDoc}
*/
public void subscribe(UserWorkspace workspace, Study study) {
if (!isSubscribed(workspace, study)) {
StudySubscription subscription = new StudySubscription();
subscription.setStudy(study);
workspace.getSubscriptionCollection().add(subscription);
saveUserWorkspace(workspace);
}
}
/**
* {@inheritDoc}
*/
public void unsubscribe(UserWorkspace workspace, Study study) {
for (StudySubscription subscription : workspace.getSubscriptionCollection()) {
if (subscription.getStudy().equals(study)) {
workspace.getSubscriptionCollection().remove(subscription);
+ if (workspace.getDefaultSubscription().equals(subscription)) {
+ workspace.setDefaultSubscription(null);
+ }
saveUserWorkspace(workspace);
dao.delete(subscription);
return;
}
}
}
private boolean isSubscribed(UserWorkspace workspace, Study study) {
for (StudySubscription subscription : workspace.getSubscriptionCollection()) {
if (subscription.getStudy().equals(study)) {
return true;
}
}
return false;
}
}
| true | true | public void unsubscribe(UserWorkspace workspace, Study study) {
for (StudySubscription subscription : workspace.getSubscriptionCollection()) {
if (subscription.getStudy().equals(study)) {
workspace.getSubscriptionCollection().remove(subscription);
saveUserWorkspace(workspace);
dao.delete(subscription);
return;
}
}
}
| public void unsubscribe(UserWorkspace workspace, Study study) {
for (StudySubscription subscription : workspace.getSubscriptionCollection()) {
if (subscription.getStudy().equals(study)) {
workspace.getSubscriptionCollection().remove(subscription);
if (workspace.getDefaultSubscription().equals(subscription)) {
workspace.setDefaultSubscription(null);
}
saveUserWorkspace(workspace);
dao.delete(subscription);
return;
}
}
}
|
diff --git a/src/main/java/org/atlasapi/media/util/Descriptions.java b/src/main/java/org/atlasapi/media/util/Descriptions.java
index dbd664fb..4f63cc86 100644
--- a/src/main/java/org/atlasapi/media/util/Descriptions.java
+++ b/src/main/java/org/atlasapi/media/util/Descriptions.java
@@ -1,68 +1,68 @@
package org.atlasapi.media.util;
import java.util.List;
import org.atlasapi.media.entity.simple.Description;
import org.atlasapi.media.entity.simple.Item;
import org.atlasapi.media.entity.simple.Playlist;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.ImmutableList.Builder;
public class Descriptions {
private Descriptions() {
}
public static List<Item> getItems(Iterable<? extends Description> descriptions) {
return ImmutableList.copyOf(Iterables.transform(Iterables.filter(descriptions, IS_ITEM), TO_ITEM));
}
public static List<Playlist> getPlaylists(Iterable<? extends Description> descriptions) {
return ImmutableList.copyOf(Iterables.transform(Iterables.filter(descriptions, IS_PLAYLIST), TO_PLAYLIST));
}
public static final Predicate<Description> IS_PLAYLIST = new Predicate<Description>() {
@Override
public boolean apply(Description input) {
return input instanceof Playlist;
}
};
public static final Predicate<Description> IS_ITEM = new Predicate<Description>() {
@Override
public boolean apply(Description input) {
return input instanceof Item;
}
};
public static final Function<Description, Playlist> TO_PLAYLIST = new Function<Description, Playlist>() {
@Override
public Playlist apply(Description input) {
return (Playlist) input;
}
};
public static final Function<Description, Item> TO_ITEM = new Function<Description, Item>() {
@Override
public Item apply(Description input) {
return (Item) input;
}
};
public static final Function<Playlist, Iterable<Description>> FLATTEN_PLAYLIST = new Function<Playlist, Iterable<Description>>() {
@Override
public Iterable<Description> apply(Playlist from) {
Builder<Description> flattened = ImmutableList.builder();
flattened.add(from);
- if (from.getItems() != null && ! from.getItems().isEmpty()) {
- flattened.addAll(from.getItems());
+ if (from.getContent() != null && ! from.getContent().isEmpty()) {
+ flattened.addAll(from.getContent());
}
return flattened.build();
}
};
}
| true | true | public Iterable<Description> apply(Playlist from) {
Builder<Description> flattened = ImmutableList.builder();
flattened.add(from);
if (from.getItems() != null && ! from.getItems().isEmpty()) {
flattened.addAll(from.getItems());
}
return flattened.build();
}
| public Iterable<Description> apply(Playlist from) {
Builder<Description> flattened = ImmutableList.builder();
flattened.add(from);
if (from.getContent() != null && ! from.getContent().isEmpty()) {
flattened.addAll(from.getContent());
}
return flattened.build();
}
|
diff --git a/liquibase-core/src/main/java/liquibase/sqlgenerator/core/RenameTableGenerator.java b/liquibase-core/src/main/java/liquibase/sqlgenerator/core/RenameTableGenerator.java
index c22035e2..c8f6216f 100644
--- a/liquibase-core/src/main/java/liquibase/sqlgenerator/core/RenameTableGenerator.java
+++ b/liquibase-core/src/main/java/liquibase/sqlgenerator/core/RenameTableGenerator.java
@@ -1,54 +1,54 @@
package liquibase.sqlgenerator.core;
import liquibase.database.Database;
import liquibase.database.core.*;
import liquibase.exception.ValidationErrors;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGenerator;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.core.RenameTableStatement;
public class RenameTableGenerator extends AbstractSqlGenerator<RenameTableStatement> {
@Override
public boolean supports(RenameTableStatement statement, Database database) {
return !(database instanceof CacheDatabase || database instanceof FirebirdDatabase);
}
public ValidationErrors validate(RenameTableStatement renameTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain) {
ValidationErrors validationErrors = new ValidationErrors();
validationErrors.checkRequiredField("newTableName", renameTableStatement.getNewTableName());
validationErrors.checkRequiredField("oldTableName", renameTableStatement.getOldTableName());
return validationErrors;
}
public Sql[] generateSql(RenameTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
String sql;
if (database instanceof MSSQLDatabase) {
sql = "exec sp_rename '" + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + "', '" + statement.getNewTableName() + '\'';
} else if (database instanceof MySQLDatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME " + database.escapeTableName(statement.getSchemaName(), statement.getNewTableName());
} else if (database instanceof PostgresDatabase) {
- sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeTableName(null, statement.getNewTableName());
+ sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else if (database instanceof SybaseASADatabase) {
- sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME " + database.escapeTableName(null, statement.getNewTableName());
+ sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME " + database.escapeDatabaseObject(statement.getNewTableName());
} else if ((database instanceof DerbyDatabase) || (database instanceof MaxDBDatabase) || (database instanceof InformixDatabase)) {
- sql = "RENAME TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeTableName(null, statement.getNewTableName());
+ sql = "RENAME TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else if (database instanceof HsqlDatabase || database instanceof H2Database) {
- sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeTableName(null, statement.getNewTableName());
+ sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else if (database instanceof OracleDatabase) {
- sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeTableName(null, statement.getNewTableName());
+ sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else if (database instanceof DB2Database) {
sql = "RENAME " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeDatabaseObject(statement.getNewTableName());//db2 doesn't allow specifying new schema name
} else if (database instanceof SQLiteDatabase) {
- sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeTableName(null, statement.getNewTableName());
+ sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else {
sql = "RENAME " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeTableName(statement.getSchemaName(), statement.getNewTableName());
}
return new Sql[] {
new UnparsedSql(sql)
}; //To change body of implemented methods use File | Settings | File Templates.
}
}
| false | true | public Sql[] generateSql(RenameTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
String sql;
if (database instanceof MSSQLDatabase) {
sql = "exec sp_rename '" + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + "', '" + statement.getNewTableName() + '\'';
} else if (database instanceof MySQLDatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME " + database.escapeTableName(statement.getSchemaName(), statement.getNewTableName());
} else if (database instanceof PostgresDatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeTableName(null, statement.getNewTableName());
} else if (database instanceof SybaseASADatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME " + database.escapeTableName(null, statement.getNewTableName());
} else if ((database instanceof DerbyDatabase) || (database instanceof MaxDBDatabase) || (database instanceof InformixDatabase)) {
sql = "RENAME TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeTableName(null, statement.getNewTableName());
} else if (database instanceof HsqlDatabase || database instanceof H2Database) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeTableName(null, statement.getNewTableName());
} else if (database instanceof OracleDatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeTableName(null, statement.getNewTableName());
} else if (database instanceof DB2Database) {
sql = "RENAME " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeDatabaseObject(statement.getNewTableName());//db2 doesn't allow specifying new schema name
} else if (database instanceof SQLiteDatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeTableName(null, statement.getNewTableName());
} else {
sql = "RENAME " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeTableName(statement.getSchemaName(), statement.getNewTableName());
}
return new Sql[] {
new UnparsedSql(sql)
}; //To change body of implemented methods use File | Settings | File Templates.
}
| public Sql[] generateSql(RenameTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
String sql;
if (database instanceof MSSQLDatabase) {
sql = "exec sp_rename '" + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + "', '" + statement.getNewTableName() + '\'';
} else if (database instanceof MySQLDatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME " + database.escapeTableName(statement.getSchemaName(), statement.getNewTableName());
} else if (database instanceof PostgresDatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else if (database instanceof SybaseASADatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME " + database.escapeDatabaseObject(statement.getNewTableName());
} else if ((database instanceof DerbyDatabase) || (database instanceof MaxDBDatabase) || (database instanceof InformixDatabase)) {
sql = "RENAME TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else if (database instanceof HsqlDatabase || database instanceof H2Database) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else if (database instanceof OracleDatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else if (database instanceof DB2Database) {
sql = "RENAME " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeDatabaseObject(statement.getNewTableName());//db2 doesn't allow specifying new schema name
} else if (database instanceof SQLiteDatabase) {
sql = "ALTER TABLE " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " RENAME TO " + database.escapeDatabaseObject(statement.getNewTableName());
} else {
sql = "RENAME " + database.escapeTableName(statement.getSchemaName(), statement.getOldTableName()) + " TO " + database.escapeTableName(statement.getSchemaName(), statement.getNewTableName());
}
return new Sql[] {
new UnparsedSql(sql)
}; //To change body of implemented methods use File | Settings | File Templates.
}
|
diff --git a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java
index a5b94f15e..cd5f918bd 100644
--- a/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java
+++ b/bundles/org.eclipse.equinox.p2.engine/src/org/eclipse/equinox/p2/engine/ProvisioningContext.java
@@ -1,370 +1,373 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 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
* WindRiver - https://bugs.eclipse.org/bugs/show_bug.cgi?id=227372
*******************************************************************************/
package org.eclipse.equinox.p2.engine;
import java.net.URI;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.engine.DebugHelper;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.core.ProvisionException;
import org.eclipse.equinox.p2.metadata.IArtifactKey;
import org.eclipse.equinox.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.query.*;
import org.eclipse.equinox.p2.repository.*;
import org.eclipse.equinox.p2.repository.artifact.*;
import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository;
import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager;
/**
* A provisioning context defines the scope in which a provisioning operation
* occurs. A context can be used to specify the set of repositories available
* to the planner and engine as they perform provisioning work.
* @since 2.0
*/
public class ProvisioningContext {
private IProvisioningAgent agent;
private URI[] artifactRepositories; //artifact repositories to consult
private final List<IInstallableUnit> extraIUs = Collections.synchronizedList(new ArrayList<IInstallableUnit>());
private URI[] metadataRepositories; //metadata repositories to consult
private final Map<String, String> properties = new HashMap<String, String>();
private Map<String, IArtifactRepository> referencedArtifactRepositories = null;
private static final String FILE_PROTOCOL = "file"; //$NON-NLS-1$
class ArtifactRepositoryQueryable implements IQueryable<IArtifactRepository> {
List<IArtifactRepository> repositories;
ArtifactRepositoryQueryable(List<IArtifactRepository> repositories) {
this.repositories = repositories;
}
public IQueryResult<IArtifactRepository> query(IQuery<IArtifactRepository> query, IProgressMonitor mon) {
return query.perform(repositories.listIterator());
}
}
/**
* This Comparator sorts the repositories such that local repositories are first
*/
private static final Comparator<URI> LOCAL_FIRST_COMPARATOR = new Comparator<URI>() {
public int compare(URI arg0, URI arg1) {
String protocol0 = arg0.getScheme();
String protocol1 = arg1.getScheme();
if (FILE_PROTOCOL.equals(protocol0) && !FILE_PROTOCOL.equals(protocol1))
return -1;
if (!FILE_PROTOCOL.equals(protocol0) && FILE_PROTOCOL.equals(protocol1))
return 1;
return 0;
}
};
/**
* Instructs the provisioning context to follow metadata repository references when
* providing queryables for obtaining metadata and artifacts. When this property is set to
* "true", then metadata repository references that are encountered while loading the
* specified metadata repositories will be included in the provisioning
* context.
*
* @see #getMetadata(IProgressMonitor)
* @see #setMetadataRepositories(URI[])
*/
public static final String FOLLOW_REPOSITORY_REFERENCES = "org.eclipse.equinox.p2.director.followRepositoryReferences"; //$NON-NLS-1$
/**
* Creates a new provisioning context that includes all available metadata and
* artifact repositories available to the specified provisioning agent.
*
* @param agent the provisioning agent from which to obtain any necessary services.
*/
public ProvisioningContext(IProvisioningAgent agent) {
this.agent = agent;
// null repos means look at them all
metadataRepositories = null;
artifactRepositories = null;
}
/**
* Returns a queryable that can be used to obtain any artifact keys that
* are needed for the provisioning operation.
*
* @param monitor a progress monitor to be used when creating the queryable
* @return a queryable that can be used to query available artifact keys.
*
* @see #setArtifactRepositories(URI[])
*/
public IQueryable<IArtifactKey> getArtifactKeys(IProgressMonitor monitor) {
return QueryUtil.compoundQueryable(getLoadedArtifactRepositories(monitor));
}
/**
* Returns a queryable that can be used to obtain any artifact descriptors that
* are needed for the provisioning operation.
*
* @param monitor a progress monitor to be used when creating the queryable
* @return a queryable that can be used to query available artifact descriptors.
*
* @see #setArtifactRepositories(URI[])
*/
public IQueryable<IArtifactDescriptor> getArtifactDescriptors(IProgressMonitor monitor) {
List<IArtifactRepository> repos = getLoadedArtifactRepositories(monitor);
List<IQueryable<IArtifactDescriptor>> descriptorQueryables = new ArrayList<IQueryable<IArtifactDescriptor>>();
for (IArtifactRepository repo : repos) {
descriptorQueryables.add(repo.descriptorQueryable());
}
return QueryUtil.compoundQueryable(descriptorQueryables);
}
/**
* Returns a queryable that can be used to obtain any artifact repositories that
* are needed for the provisioning operation.
*
* @param monitor a progress monitor to be used when creating the queryable
* @return a queryable that can be used to query available artifact repositories.
*
* @see #setArtifactRepositories(URI[])
*/
public IQueryable<IArtifactRepository> getArtifactRepositories(IProgressMonitor monitor) {
return new ArtifactRepositoryQueryable(getLoadedArtifactRepositories(monitor));
}
/**
* Return an array of loaded artifact repositories.
*/
private List<IArtifactRepository> getLoadedArtifactRepositories(IProgressMonitor monitor) {
IArtifactRepositoryManager repoManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
URI[] repositories = artifactRepositories == null ? repoManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL) : artifactRepositories;
Arrays.sort(repositories, LOCAL_FIRST_COMPARATOR);
List<IArtifactRepository> repos = new ArrayList<IArtifactRepository>();
SubMonitor sub = SubMonitor.convert(monitor, repositories.length * 100);
for (int i = 0; i < repositories.length; i++) {
if (sub.isCanceled())
throw new OperationCanceledException();
try {
repos.add(repoManager.loadRepository(repositories[i], sub.newChild(100)));
} catch (ProvisionException e) {
//skip unreadable repositories
}
}
if (referencedArtifactRepositories != null)
for (IArtifactRepository repo : referencedArtifactRepositories.values())
repos.add(repo);
return repos;
}
private Set<IMetadataRepository> getLoadedMetadataRepositories(IProgressMonitor monitor) {
IMetadataRepositoryManager repoManager = (IMetadataRepositoryManager) agent.getService(IMetadataRepositoryManager.SERVICE_NAME);
URI[] repositories = metadataRepositories == null ? repoManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL) : metadataRepositories;
HashMap<String, IMetadataRepository> repos = new HashMap<String, IMetadataRepository>();
SubMonitor sub = SubMonitor.convert(monitor, repositories.length * 100);
// Clear out the list of remembered artifact repositories
referencedArtifactRepositories = new HashMap<String, IArtifactRepository>();
for (int i = 0; i < repositories.length; i++) {
if (sub.isCanceled())
throw new OperationCanceledException();
loadMetadataRepository(repoManager, repositories[i], repos, shouldFollowReferences(), sub.newChild(100));
}
Set<IMetadataRepository> set = new HashSet<IMetadataRepository>();
set.addAll(repos.values());
return set;
}
private void loadMetadataRepository(IMetadataRepositoryManager manager, URI location, HashMap<String, IMetadataRepository> repos, boolean followMetadataRepoReferences, IProgressMonitor monitor) {
// if we've already processed this repo, don't do it again. This keeps us from getting
// caught up in circular references.
if (repos.containsKey(location.toString()))
return;
SubMonitor sub = SubMonitor.convert(monitor, 1000);
// First load the repository itself.
IMetadataRepository repository;
try {
repository = manager.loadRepository(location, sub.newChild(500));
} catch (ProvisionException e) {
// nothing more to do
return;
}
repos.put(location.toString(), repository);
Collection<IRepositoryReference> references = repository.getReferences();
// We always load artifact repositories referenced by this repository. We might load
// metadata repositories
if (references.size() > 0) {
IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
SubMonitor repoSubMon = SubMonitor.convert(sub.newChild(500), 100 * references.size());
for (IRepositoryReference ref : references) {
- if (ref.getType() == IRepository.TYPE_METADATA && followMetadataRepoReferences && isEnabled(manager, ref)) {
- loadMetadataRepository(manager, ref.getLocation(), repos, followMetadataRepoReferences, repoSubMon.newChild(100));
- } else if (ref.getType() == IRepository.TYPE_ARTIFACT) {
- // We want to remember all enabled artifact repository locations.
- if (isEnabled(artifactManager, ref))
- try {
+ try {
+ if (ref.getType() == IRepository.TYPE_METADATA && followMetadataRepoReferences && isEnabled(manager, ref)) {
+ loadMetadataRepository(manager, ref.getLocation(), repos, followMetadataRepoReferences, repoSubMon.newChild(100));
+ } else if (ref.getType() == IRepository.TYPE_ARTIFACT) {
+ // We want to remember all enabled artifact repository locations.
+ if (isEnabled(artifactManager, ref))
referencedArtifactRepositories.put(ref.getLocation().toString(), artifactManager.loadRepository(ref.getLocation(), repoSubMon.newChild(100)));
- } catch (ProvisionException e) {
- // ignore this one but keep looking at other references
- }
+ }
+ } catch (IllegalArgumentException e) {
+ // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=311338
+ // ignore invalid location and keep going
+ } catch (ProvisionException e) {
+ // ignore this one but keep looking at other references
}
}
} else {
sub.done();
}
}
// If the manager knows about the repo, consider its enablement state in the manager.
// If the manager does not know about the repo, consider the reference enablement state
@SuppressWarnings("rawtypes")
private boolean isEnabled(IRepositoryManager manager, IRepositoryReference reference) {
return (manager.contains(reference.getLocation()) && manager.isEnabled(reference.getLocation())) || ((!manager.contains(reference.getLocation())) && ((reference.getOptions() | IRepository.ENABLED) == IRepository.ENABLED));
}
private boolean shouldFollowReferences() {
return Boolean.valueOf(getProperty(FOLLOW_REPOSITORY_REFERENCES)).booleanValue();
}
/**
* Returns a queryable that can be used to obtain any metadata (installable units)
* that are needed for the provisioning operation.
*
* The provisioning context has a distinct lifecycle, whereby the metadata
* and artifact repositories to be used are determined when the client retrieves
* retrieves the metadata queryable. Clients should not reset the list of
* metadata repository locations or artifact repository locations once the
* metadata queryable has been retrieved.
*
* @param monitor a progress monitor to be used when creating the queryable
* @return a queryable that can be used to query available metadata.
*
* @see #setMetadataRepositories(URI[])
* @see #FOLLOW_REPOSITORY_REFERENCES
*/
public IQueryable<IInstallableUnit> getMetadata(IProgressMonitor monitor) {
return QueryUtil.compoundQueryable(getLoadedMetadataRepositories(monitor));
}
/**
* Returns the list of additional installable units that should be considered as
* available for installation by the planner. Returns an empty list if
* there are no extra installable units to consider. This method has no effect on the
* execution of the engine.
*
* @return The extra installable units that are available
*/
public List<IInstallableUnit> getExtraInstallableUnits() {
return extraIUs;
}
/**
* Returns the properties that are defined in this context. Context properties can
* be used to influence the behavior of either the planner or engine.
*
* @return the defined provisioning context properties
*/
public Map<String, String> getProperties() {
return properties;
}
/**
* Returns the value of the property with the given key, or <code>null</code>
* if no such property is defined
* @param key the property key
* @return the property value, or <code>null</code>
*/
public String getProperty(String key) {
return properties.get(key);
}
/**
* Sets the artifact repositories to consult when performing an operation.
* <p>
* The provisioning context has a distinct lifecycle, whereby the metadata
* and artifact repositories to be used are determined when the client
* retrieves the metadata queryable. Clients should not reset the list of
* artifact repository locations once the metadata queryable has been retrieved.
*
* @param artifactRepositories the artifact repository locations
*/
public void setArtifactRepositories(URI[] artifactRepositories) {
this.artifactRepositories = artifactRepositories;
}
/**
* Sets the metadata repositories to consult when performing an operation.
* <p>
* The provisioning context has a distinct lifecycle, whereby the metadata
* and artifact repositories to be used are determined when the client
* retrieves the metadata queryable. Clients should not reset the list of
* metadata repository locations once the metadata queryable has been retrieved.
* @param metadataRepositories the metadata repository locations
*/
public void setMetadataRepositories(URI[] metadataRepositories) {
this.metadataRepositories = metadataRepositories;
}
/**
* Sets the list of additional installable units that should be considered as
* available for installation by the planner. This method has no effect on the
* execution of the engine.
* @param extraIUs the extra installable units
*/
public void setExtraInstallableUnits(List<IInstallableUnit> extraIUs) {
this.extraIUs.clear();
//copy the list to prevent future client tampering
if (extraIUs != null)
this.extraIUs.addAll(extraIUs);
}
/**
* Sets a property on this provisioning context. Context properties can
* be used to influence the behavior of either the planner or engine.
* @param key the property key
* @param value the property value
*/
public void setProperty(String key, String value) {
properties.put(key, value);
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("{artifactRepos=" + DebugHelper.formatArray(null != artifactRepositories ? Arrays.asList(artifactRepositories) : null, true, false)); //$NON-NLS-1$
buffer.append(", metadataRepos=" + DebugHelper.formatArray(null != metadataRepositories ? Arrays.asList(metadataRepositories) : null, true, false)); //$NON-NLS-1$
buffer.append(", properties=" + getProperties() + "}"); //$NON-NLS-1$ //$NON-NLS-2$
return buffer.toString();
}
/**
* Return the array of repository locations for artifact repositories.
* @return an array of repository locations. This is never <code>null</code>.
*
* @deprecated This method will be removed in the next release. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=305086
* @noreference This method will be removed in the next release.
*
* @see #getArtifactRepositories()
* @see #getArtifactDescriptors(IProgressMonitor)
* @see #getArtifactKeys(IProgressMonitor)
*/
public URI[] getArtifactRepositories() {
IArtifactRepositoryManager repoManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
URI[] repositories = artifactRepositories == null ? repoManager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL) : artifactRepositories;
Arrays.sort(repositories, LOCAL_FIRST_COMPARATOR);
return repositories;
}
}
| false | true | private void loadMetadataRepository(IMetadataRepositoryManager manager, URI location, HashMap<String, IMetadataRepository> repos, boolean followMetadataRepoReferences, IProgressMonitor monitor) {
// if we've already processed this repo, don't do it again. This keeps us from getting
// caught up in circular references.
if (repos.containsKey(location.toString()))
return;
SubMonitor sub = SubMonitor.convert(monitor, 1000);
// First load the repository itself.
IMetadataRepository repository;
try {
repository = manager.loadRepository(location, sub.newChild(500));
} catch (ProvisionException e) {
// nothing more to do
return;
}
repos.put(location.toString(), repository);
Collection<IRepositoryReference> references = repository.getReferences();
// We always load artifact repositories referenced by this repository. We might load
// metadata repositories
if (references.size() > 0) {
IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
SubMonitor repoSubMon = SubMonitor.convert(sub.newChild(500), 100 * references.size());
for (IRepositoryReference ref : references) {
if (ref.getType() == IRepository.TYPE_METADATA && followMetadataRepoReferences && isEnabled(manager, ref)) {
loadMetadataRepository(manager, ref.getLocation(), repos, followMetadataRepoReferences, repoSubMon.newChild(100));
} else if (ref.getType() == IRepository.TYPE_ARTIFACT) {
// We want to remember all enabled artifact repository locations.
if (isEnabled(artifactManager, ref))
try {
referencedArtifactRepositories.put(ref.getLocation().toString(), artifactManager.loadRepository(ref.getLocation(), repoSubMon.newChild(100)));
} catch (ProvisionException e) {
// ignore this one but keep looking at other references
}
}
}
} else {
sub.done();
}
}
| private void loadMetadataRepository(IMetadataRepositoryManager manager, URI location, HashMap<String, IMetadataRepository> repos, boolean followMetadataRepoReferences, IProgressMonitor monitor) {
// if we've already processed this repo, don't do it again. This keeps us from getting
// caught up in circular references.
if (repos.containsKey(location.toString()))
return;
SubMonitor sub = SubMonitor.convert(monitor, 1000);
// First load the repository itself.
IMetadataRepository repository;
try {
repository = manager.loadRepository(location, sub.newChild(500));
} catch (ProvisionException e) {
// nothing more to do
return;
}
repos.put(location.toString(), repository);
Collection<IRepositoryReference> references = repository.getReferences();
// We always load artifact repositories referenced by this repository. We might load
// metadata repositories
if (references.size() > 0) {
IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
SubMonitor repoSubMon = SubMonitor.convert(sub.newChild(500), 100 * references.size());
for (IRepositoryReference ref : references) {
try {
if (ref.getType() == IRepository.TYPE_METADATA && followMetadataRepoReferences && isEnabled(manager, ref)) {
loadMetadataRepository(manager, ref.getLocation(), repos, followMetadataRepoReferences, repoSubMon.newChild(100));
} else if (ref.getType() == IRepository.TYPE_ARTIFACT) {
// We want to remember all enabled artifact repository locations.
if (isEnabled(artifactManager, ref))
referencedArtifactRepositories.put(ref.getLocation().toString(), artifactManager.loadRepository(ref.getLocation(), repoSubMon.newChild(100)));
}
} catch (IllegalArgumentException e) {
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=311338
// ignore invalid location and keep going
} catch (ProvisionException e) {
// ignore this one but keep looking at other references
}
}
} else {
sub.done();
}
}
|
diff --git a/src/java/org/apache/commons/jxpath/JXPathException.java b/src/java/org/apache/commons/jxpath/JXPathException.java
index d752b6d..9e45e04 100644
--- a/src/java/org/apache/commons/jxpath/JXPathException.java
+++ b/src/java/org/apache/commons/jxpath/JXPathException.java
@@ -1,118 +1,118 @@
/*
* 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.commons.jxpath;
/**
* Thrown in various situations by JXPath; may contain a nested exception.
*
* @author Dmitri Plotnikov
* @version $Revision$ $Date$
*/
public class JXPathException extends RuntimeException {
private static final long serialVersionUID = 4306409701468017766L;
/** @serial */
private Throwable exception;
/**
* Create a new <code>JXPathException</code> with no
* detail mesage.
*/
public JXPathException() {
super();
this.exception = null;
}
/**
* Create a new <code>JXPathException</code> with
* the <code>String </code> specified as an error message.
*
* @param msg The error message for the exception.
*/
public JXPathException(String msg) {
super(msg);
this.exception = null;
}
/**
* Create a new <code>JXPathException</code> with a
* given <code>Throwable</code> base cause of the error.
*
* @param e The exception to be encapsulated in a
* JXPathException.
*/
public JXPathException(Throwable e) {
super(e.toString());
this.exception = e;
}
/**
* Create a new <code>JXPathException</code> with the
* given <code>Exception</code> base cause and detail message.
*
* @param e The exception to be encapsulated in a
* JXPathException
* @param msg The detail message.
*/
public JXPathException(String msg, Throwable e) {
super(msg);
this.exception = e;
}
/**
* Return the message (if any) for this error . If there is no
* message for the exception and there is an encapsulated
* exception then the message of that exception will be returned.
*
* @return The error message.
*/
public String getMessage() {
String message = super.getMessage();
if (exception == null) {
return message;
}
StringBuffer buf = new StringBuffer();
- if (message == null) {
+ if (message != null) {
buf.append(message).append("; ");
}
String eMsg = exception.getMessage();
buf.append(eMsg == null ? exception.getClass().getName() : eMsg);
return buf.toString();
}
/**
* Return the actual exception (if any) that caused this exception to
* be raised.
*
* @return The encapsulated exception, or null if there is none.
*/
public Throwable getException() {
return exception;
}
/**
* Same as {@link #getException() getException()}
*/
public Throwable getCause() {
return exception;
}
}
| true | true | public String getMessage() {
String message = super.getMessage();
if (exception == null) {
return message;
}
StringBuffer buf = new StringBuffer();
if (message == null) {
buf.append(message).append("; ");
}
String eMsg = exception.getMessage();
buf.append(eMsg == null ? exception.getClass().getName() : eMsg);
return buf.toString();
}
| public String getMessage() {
String message = super.getMessage();
if (exception == null) {
return message;
}
StringBuffer buf = new StringBuffer();
if (message != null) {
buf.append(message).append("; ");
}
String eMsg = exception.getMessage();
buf.append(eMsg == null ? exception.getClass().getName() : eMsg);
return buf.toString();
}
|
diff --git a/src/com/fsck/k9/controller/MessagingController.java b/src/com/fsck/k9/controller/MessagingController.java
index 68776ae0..6860e188 100644
--- a/src/com/fsck/k9/controller/MessagingController.java
+++ b/src/com/fsck/k9/controller/MessagingController.java
@@ -1,5361 +1,5361 @@
package com.fsck.k9.controller;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import com.fsck.k9.Account;
import com.fsck.k9.AccountStats;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.SearchSpecification;
import com.fsck.k9.activity.FolderList;
import com.fsck.k9.activity.MessageList;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.helper.power.TracingPowerManager;
import com.fsck.k9.helper.power.TracingPowerManager.TracingWakeLock;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.FetchProfile;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.PushReceiver;
import com.fsck.k9.mail.Pusher;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.Transport;
import com.fsck.k9.mail.Folder.FolderType;
import com.fsck.k9.mail.Folder.OpenMode;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import com.fsck.k9.mail.store.LocalStore.LocalMessage;
import com.fsck.k9.mail.store.LocalStore.PendingCommand;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable
{
/**
* The maximum message size that we'll consider to be "small". A small message is downloaded
* in full immediately instead of in pieces. Anything over this size will be downloaded in
* pieces with attachments being left off completely and downloaded on demand.
*
*
* 25k for a "small" message was picked by educated trial and error.
* http://answers.google.com/answers/threadview?id=312463 claims that the
* average size of an email is 59k, which I feel is too large for our
* blind download. The following tests were performed on a download of
* 25 random messages.
* <pre>
* 5k - 61 seconds,
* 25k - 51 seconds,
* 55k - 53 seconds,
* </pre>
* So 25k gives good performance and a reasonable data footprint. Sounds good to me.
*/
private static final int MAX_SMALL_MESSAGE_SIZE = Store.FETCH_BODY_SANE_SUGGESTED_SIZE;
private static final String PENDING_COMMAND_MOVE_OR_COPY = "com.fsck.k9.MessagingController.moveOrCopy";
private static final String PENDING_COMMAND_MOVE_OR_COPY_BULK = "com.fsck.k9.MessagingController.moveOrCopyBulk";
private static final String PENDING_COMMAND_EMPTY_TRASH = "com.fsck.k9.MessagingController.emptyTrash";
private static final String PENDING_COMMAND_SET_FLAG_BULK = "com.fsck.k9.MessagingController.setFlagBulk";
private static final String PENDING_COMMAND_SET_FLAG = "com.fsck.k9.MessagingController.setFlag";
private static final String PENDING_COMMAND_APPEND = "com.fsck.k9.MessagingController.append";
private static final String PENDING_COMMAND_MARK_ALL_AS_READ = "com.fsck.k9.MessagingController.markAllAsRead";
private static final String PENDING_COMMAND_EXPUNGE = "com.fsck.k9.MessagingController.expunge";
private static MessagingController inst = null;
private BlockingQueue<Command> mCommands = new PriorityBlockingQueue<Command>();
private Thread mThread;
private Set<MessagingListener> mListeners = new CopyOnWriteArraySet<MessagingListener>();
private HashMap<SORT_TYPE, Boolean> sortAscending = new HashMap<SORT_TYPE, Boolean>();
private ConcurrentHashMap<String, AtomicInteger> sendCount = new ConcurrentHashMap<String, AtomicInteger>();
ConcurrentHashMap<Account, Pusher> pushers = new ConcurrentHashMap<Account, Pusher>();
private final ExecutorService threadPool = Executors.newFixedThreadPool(5);
public enum SORT_TYPE
{
SORT_DATE(R.string.sort_earliest_first, R.string.sort_latest_first, false),
SORT_SUBJECT(R.string.sort_subject_alpha, R.string.sort_subject_re_alpha, true),
SORT_SENDER(R.string.sort_sender_alpha, R.string.sort_sender_re_alpha, true),
SORT_UNREAD(R.string.sort_unread_first, R.string.sort_unread_last, true),
SORT_FLAGGED(R.string.sort_flagged_first, R.string.sort_flagged_last, true),
SORT_ATTACHMENT(R.string.sort_attach_first, R.string.sort_unattached_first, true);
private int ascendingToast;
private int descendingToast;
private boolean defaultAscending;
SORT_TYPE(int ascending, int descending, boolean ndefaultAscending)
{
ascendingToast = ascending;
descendingToast = descending;
defaultAscending = ndefaultAscending;
}
public int getToast(boolean ascending)
{
if (ascending)
{
return ascendingToast;
}
else
{
return descendingToast;
}
}
public boolean isDefaultAscending()
{
return defaultAscending;
}
};
private SORT_TYPE sortType = SORT_TYPE.SORT_DATE;
private MessagingListener checkMailListener = null;
private MemorizingListener memorizingListener = new MemorizingListener();
private boolean mBusy;
private Application mApplication;
// Key is accountUuid:folderName:messageUid , value is unimportant
private ConcurrentHashMap<String, String> deletedUids = new ConcurrentHashMap<String, String>();
private String createMessageKey(Account account, String folder, Message message)
{
return createMessageKey(account, folder, message.getUid());
}
private String createMessageKey(Account account, String folder, String uid)
{
return account.getUuid() + ":" + folder + ":" + uid;
}
private void suppressMessage(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return;
}
String messKey = createMessageKey(account, folder, message);
deletedUids.put(messKey, "true");
}
private void unsuppressMessage(Account account, String folder, String uid)
{
if (account == null || folder == null || uid == null)
{
return;
}
String messKey = createMessageKey(account, folder, uid);
deletedUids.remove(messKey);
}
private boolean isMessageSuppressed(Account account, String folder, Message message)
{
if (account == null || folder == null || message == null)
{
return false;
}
String messKey = createMessageKey(account, folder, message);
if (deletedUids.containsKey(messKey))
{
return true;
}
return false;
}
private MessagingController(Application application)
{
mApplication = application;
mThread = new Thread(this);
mThread.start();
if (memorizingListener != null)
{
addListener(memorizingListener);
}
}
/**
* Gets or creates the singleton instance of MessagingController. Application is used to
* provide a Context to classes that need it.
* @param application
* @return
*/
public synchronized static MessagingController getInstance(Application application)
{
if (inst == null)
{
inst = new MessagingController(application);
}
return inst;
}
public boolean isBusy()
{
return mBusy;
}
public void run()
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
while (true)
{
String commandDescription = null;
try
{
Command command = mCommands.take();
if (command != null)
{
commandDescription = command.description;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Running " + (command.isForeground ? "Foreground" : "Background") + " command '" + command.description + "', seq = " + command.sequence);
mBusy = true;
command.runnable.run();
if (K9.DEBUG)
Log.i(K9.LOG_TAG, (command.isForeground ? "Foreground" : "Background") +
" Command '" + command.description + "' completed");
for (MessagingListener l : getListeners())
{
l.controllerCommandCompleted(mCommands.size() > 0);
}
if (command.listener != null && !getListeners().contains(command.listener))
{
command.listener.controllerCommandCompleted(mCommands.size() > 0);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error running command '" + commandDescription + "'", e);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable)
{
putCommand(mCommands, description, listener, runnable, true);
}
private void putBackground(String description, MessagingListener listener, Runnable runnable)
{
putCommand(mCommands, description, listener, runnable, false);
}
private void putCommand(BlockingQueue<Command> queue, String description, MessagingListener listener, Runnable runnable, boolean isForeground)
{
int retries = 10;
Exception e = null;
while (retries-- > 0)
{
try
{
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
command.isForeground = isForeground;
queue.put(command);
return;
}
catch (InterruptedException ie)
{
try
{
Thread.sleep(200);
}
catch (InterruptedException ne)
{
}
e = ie;
}
}
throw new Error(e);
}
public void addListener(MessagingListener listener)
{
mListeners.add(listener);
refreshListener(listener);
}
public void refreshListener(MessagingListener listener)
{
if (memorizingListener != null && listener != null)
{
memorizingListener.refreshOther(listener);
}
}
public void removeListener(MessagingListener listener)
{
mListeners.remove(listener);
}
public Set<MessagingListener> getListeners()
{
return mListeners;
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
* TODO this needs to cache the remote folder list
*
* @param account
* @param includeRemote
* @param listener
* @throws MessagingException
*/
public void listFolders(final Account account, final boolean refreshRemote, final MessagingListener listener)
{
threadPool.execute(new Runnable()
{
public void run()
{
for (MessagingListener l : getListeners())
{
l.listFoldersStarted(account);
}
if (listener != null)
{
listener.listFoldersStarted(account);
}
List<? extends Folder> localFolders = null;
try
{
Store localStore = account.getLocalStore();
localFolders = localStore.getPersonalNamespaces(false);
Folder[] folderArray = localFolders.toArray(new Folder[0]);
if (refreshRemote || localFolders == null || localFolders.size() == 0)
{
doRefreshRemote(account, listener);
return;
}
for (MessagingListener l : getListeners())
{
l.listFolders(account, folderArray);
}
if (listener != null)
{
listener.listFolders(account, folderArray);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listFoldersFailed(account, e.getMessage());
}
if (listener != null)
{
listener.listFoldersFailed(account, e.getMessage());
}
addErrorMessage(account, null, e);
return;
}
finally
{
if (localFolders != null)
{
for (Folder localFolder : localFolders)
{
if (localFolder != null)
{
localFolder.close();
}
}
}
}
for (MessagingListener l : getListeners())
{
l.listFoldersFinished(account);
}
if (listener != null)
{
listener.listFoldersFinished(account);
}
}
});
}
private void doRefreshRemote(final Account account, MessagingListener listener)
{
put("doRefreshRemote", listener, new Runnable()
{
public void run()
{
List<? extends Folder> localFolders = null;
try
{
Store store = account.getRemoteStore();
List<? extends Folder> remoteFolders = store.getPersonalNamespaces(false);
LocalStore localStore = account.getLocalStore();
HashSet<String> remoteFolderNames = new HashSet<String>();
for (int i = 0, count = remoteFolders.size(); i < count; i++)
{
LocalFolder localFolder = localStore.getFolder(remoteFolders.get(i).getName());
if (!localFolder.exists())
{
localFolder.create(FolderType.HOLDS_MESSAGES, account.getDisplayCount());
}
remoteFolderNames.add(remoteFolders.get(i).getName());
}
localFolders = localStore.getPersonalNamespaces(false);
/*
* Clear out any folders that are no longer on the remote store.
*/
for (Folder localFolder : localFolders)
{
String localFolderName = localFolder.getName();
if (localFolderName.equalsIgnoreCase(K9.INBOX) ||
localFolderName.equals(account.getTrashFolderName()) ||
localFolderName.equals(account.getOutboxFolderName()) ||
localFolderName.equals(account.getDraftsFolderName()) ||
localFolderName.equals(account.getSentFolderName()) ||
localFolderName.equals(account.getErrorFolderName()))
{
continue;
}
if (!remoteFolderNames.contains(localFolder.getName()))
{
localFolder.delete(false);
}
}
localFolders = localStore.getPersonalNamespaces(false);
Folder[] folderArray = localFolders.toArray(new Folder[0]);
for (MessagingListener l : getListeners())
{
l.listFolders(account, folderArray);
}
for (MessagingListener l : getListeners())
{
l.listFoldersFinished(account);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listFoldersFailed(account, "");
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolders != null)
{
for (Folder localFolder : localFolders)
{
if (localFolder != null)
{
localFolder.close();
}
}
}
}
}
});
}
/**
* List the messages in the local message store for the given folder asynchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessages(final Account account, final String folder, final MessagingListener listener)
{
threadPool.execute(new Runnable()
{
public void run()
{
listLocalMessagesSynchronous(account, folder, listener);
}
});
}
/**
* List the messages in the local message store for the given folder synchronously.
*
* @param account
* @param folder
* @param listener
* @throws MessagingException
*/
public void listLocalMessagesSynchronous(final Account account, final String folder, final MessagingListener listener)
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesStarted(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesStarted(account, folder);
}
Folder localFolder = null;
MessageRetrievalListener retrievalListener =
new MessageRetrievalListener()
{
List<Message> pendingMessages = new ArrayList<Message>();
int totalDone = 0;
public void messageStarted(String message, int number, int ofTotal) {}
public void messageFinished(Message message, int number, int ofTotal)
{
if (isMessageSuppressed(account, folder, message) == false)
{
pendingMessages.add(message);
totalDone++;
if (pendingMessages.size() > 10)
{
addPendingMessages();
}
}
else
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesRemoveMessage(account, folder, message);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesRemoveMessage(account, folder, message);
}
}
}
public void messagesFinished(int number)
{
addPendingMessages();
}
private void addPendingMessages()
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesAddMessages(account, folder, pendingMessages);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesAddMessages(account, folder, pendingMessages);
}
pendingMessages.clear();
}
};
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
localFolder.getMessages(
retrievalListener,
false // Skip deleted messages
);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Got ack that callbackRunner finished");
for (MessagingListener l : getListeners())
{
l.listLocalMessagesFinished(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesFinished(account, folder);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.listLocalMessagesFailed(account, folder, e.getMessage());
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.listLocalMessagesFailed(account, folder, e.getMessage());
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}
public void searchLocalMessages(SearchSpecification searchSpecification, final Message[] messages, final MessagingListener listener)
{
searchLocalMessages(searchSpecification.getAccountUuids(), searchSpecification.getFolderNames(), messages,
searchSpecification.getQuery(), searchSpecification.isIntegrate(), searchSpecification.getRequiredFlags(), searchSpecification.getForbiddenFlags(), listener);
}
/**
* Find all messages in any local account which match the query 'query'
* @param folderNames TODO
* @param query
* @param listener
* @param searchAccounts TODO
* @param account TODO
* @param account
* @throws MessagingException
*/
public void searchLocalMessages(final String[] accountUuids, final String[] folderNames, final Message[] messages, final String query, final boolean integrate,
final Flag[] requiredFlags, final Flag[] forbiddenFlags, final MessagingListener listener)
{
if (K9.DEBUG)
{
Log.i(K9.LOG_TAG, "searchLocalMessages ("
+ "accountUuids=" + Utility.combine(accountUuids, ',')
+ ", folderNames = " + Utility.combine(folderNames, ',')
+ ", messages.size() = " + (messages != null ? messages.length : null)
+ ", query = " + query
+ ", integrate = " + integrate
+ ", requiredFlags = " + Utility.combine(requiredFlags, ',')
+ ", forbiddenFlags = " + Utility.combine(forbiddenFlags, ',')
+ ")");
}
threadPool.execute(new Runnable()
{
public void run()
{
final AccountStats stats = new AccountStats();
final Set<String> accountUuidsSet = new HashSet<String>();
if (accountUuids != null)
{
for (String accountUuid : accountUuids)
{
accountUuidsSet.add(accountUuid);
}
}
final Preferences prefs = Preferences.getPreferences(mApplication.getApplicationContext());
Account[] accounts = prefs.getAccounts();
List<LocalFolder> foldersToSearch = null;
boolean displayableOnly = false;
boolean noSpecialFolders = true;
for (final Account account : accounts)
{
if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == false)
{
continue;
}
if (accountUuids != null && accountUuidsSet.contains(account.getUuid()) == true)
{
displayableOnly = true;
noSpecialFolders = true;
}
else if (integrate == false && folderNames == null)
{
Account.Searchable searchableFolders = account.getSearchableFolders();
switch (searchableFolders)
{
case NONE:
continue;
case DISPLAYABLE:
displayableOnly = true;
break;
}
}
List<Message> messagesToSearch = null;
if (messages != null)
{
messagesToSearch = new LinkedList<Message>();
for (Message message : messages)
{
if (message.getFolder().getAccount().getUuid().equals(account.getUuid()))
{
messagesToSearch.add(message);
}
}
if (messagesToSearch.isEmpty())
{
continue;
}
}
if (listener != null)
{
listener.listLocalMessagesStarted(account, null);
}
if (integrate || displayableOnly || folderNames != null || noSpecialFolders)
{
List<LocalFolder> tmpFoldersToSearch = new LinkedList<LocalFolder>();
try
{
LocalStore store = account.getLocalStore();
List<? extends Folder> folders = store.getPersonalNamespaces(false);
Set<String> folderNameSet = null;
if (folderNames != null)
{
folderNameSet = new HashSet<String>();
for (String folderName : folderNames)
{
folderNameSet.add(folderName);
}
}
for (Folder folder : folders)
{
LocalFolder localFolder = (LocalFolder)folder;
boolean include = true;
folder.refresh(prefs);
String localFolderName = localFolder.getName();
if (integrate)
{
include = localFolder.isIntegrate();
}
else
{
if (folderNameSet != null)
{
if (folderNameSet.contains(localFolderName) == false)
{
include = false;
}
}
// Never exclude the INBOX (see issue 1817)
else if (noSpecialFolders && !localFolderName.equals(K9.INBOX) && (
localFolderName.equals(account.getTrashFolderName()) ||
localFolderName.equals(account.getOutboxFolderName()) ||
localFolderName.equals(account.getDraftsFolderName()) ||
localFolderName.equals(account.getSentFolderName()) ||
localFolderName.equals(account.getErrorFolderName())))
{
include = false;
}
else if (displayableOnly && modeMismatch(account.getFolderDisplayMode(), folder.getDisplayClass()))
{
include = false;
}
}
if (include)
{
tmpFoldersToSearch.add(localFolder);
}
}
if (tmpFoldersToSearch.size() < 1)
{
continue;
}
foldersToSearch = tmpFoldersToSearch;
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to restrict search folders in Account " + account.getDescription() + ", searching all", me);
addErrorMessage(account, null, me);
}
}
MessageRetrievalListener retrievalListener = new MessageRetrievalListener()
{
public void messageStarted(String message, int number, int ofTotal) {}
public void messageFinished(Message message, int number, int ofTotal)
{
if (isMessageSuppressed(message.getFolder().getAccount(), message.getFolder().getName(), message) == false)
{
List<Message> messages = new ArrayList<Message>();
messages.add(message);
stats.unreadMessageCount += (message.isSet(Flag.SEEN) == false) ? 1 : 0;
stats.flaggedMessageCount += (message.isSet(Flag.FLAGGED)) ? 1 : 0;
if (listener != null)
{
listener.listLocalMessagesAddMessages(account, null, messages);
}
}
}
public void messagesFinished(int number)
{
}
};
try
{
String[] queryFields = {"html_content","subject","sender_list"};
LocalStore localStore = account.getLocalStore();
localStore.searchForMessages(retrievalListener, queryFields
, query, foldersToSearch,
messagesToSearch == null ? null : messagesToSearch.toArray(new Message[0]),
requiredFlags, forbiddenFlags);
}
catch (Exception e)
{
if (listener != null)
{
listener.listLocalMessagesFailed(account, null, e.getMessage());
}
addErrorMessage(account, null, e);
}
finally
{
if (listener != null)
{
listener.listLocalMessagesFinished(account, null);
}
}
}
if (listener != null)
{
listener.searchStats(stats);
}
}
});
}
public void loadMoreMessages(Account account, String folder, MessagingListener listener)
{
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
localFolder.setVisibleLimit(localFolder.getVisibleLimit() + account.getDisplayCount());
synchronizeMailbox(account, folder, listener, null);
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException("Unable to set visible limit on folder", me);
}
}
public void resetVisibleLimits(Account[] accounts)
{
for (Account account : accounts)
{
try
{
LocalStore localStore = account.getLocalStore();
localStore.resetVisibleLimits(account.getDisplayCount());
}
catch (MessagingException e)
{
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Unable to reset visible limits", e);
}
}
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
* @param providedRemoteFolder TODO
*/
public void synchronizeMailbox(final Account account, final String folder, final MessagingListener listener, final Folder providedRemoteFolder)
{
putBackground("synchronizeMailbox", listener, new Runnable()
{
public void run()
{
synchronizeMailboxSynchronous(account, folder, listener, providedRemoteFolder);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is generally only called
* by synchronizeMailbox.
* @param account
* @param folder
*
* TODO Break this method up into smaller chunks.
* @param providedRemoteFolder TODO
*/
private void synchronizeMailboxSynchronous(final Account account, final String folder, final MessagingListener listener, Folder providedRemoteFolder)
{
Folder remoteFolder = null;
LocalFolder tLocalFolder = null;
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing folder " + account.getDescription() + ":" + folder);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxStarted(account, folder);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxStarted(account, folder);
}
/*
* We don't ever sync the Outbox or errors folder
*/
if (folder.equals(account.getOutboxFolderName()) || folder.equals(account.getErrorFolderName()))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFinished(account, folder, 0, 0);
}
return;
}
Exception commandException = null;
try
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to process pending commands for account " +
account.getDescription());
try
{
processPendingCommandsSynchronous(account);
}
catch (Exception e)
{
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failure processing command, but allow message sync attempt", e);
commandException = e;
}
/*
* Get the message list from the local store and create an index of
* the uids within the list.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get local folder " + folder);
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder);
final LocalFolder localFolder = tLocalFolder;
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
HashMap<String, Message> localUidMap = new HashMap<String, Message>();
for (Message message : localMessages)
{
localUidMap.put(message.getUid(), message);
}
if (providedRemoteFolder != null)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: using providedRemoteFolder " + folder);
remoteFolder = providedRemoteFolder;
}
else
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get remote store for " + folder);
Store remoteStore = account.getRemoteStore();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get remote folder " + folder);
remoteFolder = remoteStore.getFolder(folder);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.equals(account.getTrashFolderName()) ||
folder.equals(account.getSentFolderName()) ||
folder.equals(account.getDraftsFolderName()))
{
if (!remoteFolder.exists())
{
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFinished(account, folder, 0, 0);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + folder);
return;
}
}
}
/*
* Synchronization process:
Open the folder
Upload any local messages that are marked as PENDING_UPLOAD (Drafts, Sent, Trash)
Get the message count
Get the list of the newest K9.DEFAULT_VISIBLE_LIMIT messages
getMessages(messageCount - K9.DEFAULT_VISIBLE_LIMIT, messageCount)
See if we have each message locally, if not fetch it's flags and envelope
Get and update the unread count for the folder
Update the remote flags of any messages we have locally with an internal date
newer than the remote message.
Get the current flags for any messages we have locally but did not just download
Update local flags
For any message we have locally but not remotely, delete the local message to keep
cache clean.
Download larger parts of any new messages.
(Optional) Download small attachments in the background.
*/
/*
* Open the remote folder. This pre-loads certain metadata like message count.
*/
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to open remote folder " + folder);
remoteFolder.open(OpenMode.READ_WRITE);
if (Account.EXPUNGE_ON_POLL.equals(account.getExpungePolicy()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Expunging folder " + account.getDescription() + ":" + folder);
remoteFolder.expunge();
}
}
/*
* Get the remote message count.
*/
int remoteMessageCount = remoteFolder.getMessageCount();
int visibleLimit = localFolder.getVisibleLimit();
if (visibleLimit < 1)
{
visibleLimit = K9.DEFAULT_VISIBLE_LIMIT;
}
Message[] remoteMessageArray = new Message[0];
final ArrayList<Message> remoteMessages = new ArrayList<Message>();
// final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Remote message count for folder " + folder + " is " + remoteMessageCount);
final Date earliestDate = account.getEarliestPollDate();
if (remoteMessageCount > 0)
{
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: About to get messages " + remoteStart + " through " + remoteEnd + " for folder " + folder);
remoteMessageArray = remoteFolder.getMessages(remoteStart, remoteEnd, earliestDate, null);
for (Message thisMess : remoteMessageArray)
{
Message localMessage = localUidMap.get(thisMess.getUid());
if (localMessage == null || localMessage.olderThan(earliestDate) == false)
{
remoteMessages.add(thisMess);
remoteUidMap.put(thisMess.getUid(), thisMess);
}
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "SYNC: Got " + remoteUidMap.size() + " messages for folder " + folder);
remoteMessageArray = null;
}
else if (remoteMessageCount < 0)
{
throw new Exception("Message count " + remoteMessageCount + " for folder " + folder);
}
/*
* Remove any messages that are in the local store but no longer on the remote store or are too old
*/
if (account.syncRemoteDeletions())
{
for (Message localMessage : localMessages)
{
if (remoteUidMap.get(localMessage.getUid()) == null && !localMessage.isSet(Flag.DELETED))
{
localMessage.setFlag(Flag.X_DESTROYED, true);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
}
}
localMessages = null;
/*
* Now we download the actual content of messages.
*/
int newMessages = downloadMessages(account, remoteFolder, localFolder, remoteMessages, false);
int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, newMessages);
setLocalFlaggedCountToRemote(localFolder, remoteFolder);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, unreadMessageCount);
}
/*
* Notify listeners that we're finally done.
*/
localFolder.setLastChecked(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date() +
" with " + newMessages + " new messages");
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFinished(account, folder, remoteMessageCount, newMessages);
}
if (commandException != null)
{
String rootMessage = getRootCauseMessage(commandException);
Log.e(K9.LOG_TAG, "Root cause failure in " + account.getDescription() + ":" +
tLocalFolder.getName() + " was '" + rootMessage + "'");
localFolder.setStatus(rootMessage);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(account, folder, rootMessage);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFailed(account, folder, rootMessage);
}
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Done synchronizing folder " + account.getDescription() + ":" + folder);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "synchronizeMailbox", e);
// If we don't set the last checked, it can try too often during
// failure conditions
String rootMessage = getRootCauseMessage(e);
if (tLocalFolder != null)
{
try
{
tLocalFolder.setStatus(rootMessage);
tLocalFolder.setLastChecked(System.currentTimeMillis());
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Could not set last checked on folder " + account.getDescription() + ":" +
tLocalFolder.getName(), e);
}
}
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
if (listener != null && getListeners().contains(listener) == false)
{
listener.synchronizeMailboxFailed(
account,
folder,
rootMessage);
}
addErrorMessage(account, null, e);
Log.e(K9.LOG_TAG, "Failed synchronizing folder " +
account.getDescription() + ":" + folder + " @ " + new Date());
}
finally
{
if (providedRemoteFolder == null && remoteFolder != null)
{
remoteFolder.close();
}
if (tLocalFolder != null)
{
tLocalFolder.close();
}
}
}
private int setLocalUnreadCountToRemote(LocalFolder localFolder, Folder remoteFolder, int newMessageCount) throws MessagingException
{
int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
if (remoteUnreadMessageCount != -1)
{
localFolder.setUnreadMessageCount(remoteUnreadMessageCount);
}
else
{
int unreadCount = 0;
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false && message.isSet(Flag.DELETED) == false)
{
unreadCount++;
}
}
localFolder.setUnreadMessageCount(unreadCount);
}
return localFolder.getUnreadMessageCount();
}
private void setLocalFlaggedCountToRemote(LocalFolder localFolder, Folder remoteFolder) throws MessagingException
{
int remoteFlaggedMessageCount = remoteFolder.getFlaggedMessageCount();
if (remoteFlaggedMessageCount != -1)
{
localFolder.setFlaggedMessageCount(remoteFlaggedMessageCount);
}
else
{
int flaggedCount = 0;
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.FLAGGED) == true && message.isSet(Flag.DELETED) == false)
{
flaggedCount++;
}
}
localFolder.setFlaggedMessageCount(flaggedCount);
}
}
private int downloadMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException
{
final Date earliestDate = account.getEarliestPollDate();
if (earliestDate != null)
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate);
}
}
final String folder = remoteFolder.getName();
ArrayList<Message> syncFlagMessages = new ArrayList<Message>();
List<Message> unsyncedMessages = new ArrayList<Message>();
final AtomicInteger newMessages = new AtomicInteger(0);
List<Message> messages = new ArrayList<Message>(inputMessages);
for (Message message : messages)
{
if (message.isSet(Flag.DELETED))
{
syncFlagMessages.add(message);
}
else if (isMessageSuppressed(account, folder, message) == false)
{
Message localMessage = localFolder.getMessage(message.getUid());
if (localMessage == null)
{
if (!flagSyncOnly)
{
if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
- Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded at all");
+ Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded");
unsyncedMessages.add(message);
}
else
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded");
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL));
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL));
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
}
else if (localMessage.isSet(Flag.DELETED) == false)
{
if (K9.DEBUG)
- Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is already locally present");
+ Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store");
if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid()
+ " is not downloaded, even partially; trying again");
unsyncedMessages.add(message);
}
else
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
syncFlagMessages.add(message);
}
}
}
}
final AtomicInteger progress = new AtomicInteger(0);
final int todo = unsyncedMessages.size() + syncFlagMessages.size();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages");
messages.clear();
final ArrayList<Message> largeMessages = new ArrayList<Message>();
final ArrayList<Message> smallMessages = new ArrayList<Message>();
if (unsyncedMessages.size() > 0)
{
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
int visibleLimit = localFolder.getVisibleLimit();
int listSize = unsyncedMessages.size();
if (listSize > visibleLimit)
{
unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize);
}
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags())
{
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
- Log.d(K9.LOG_TAG, "SYNC: About to sync " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
+ Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
if (message.isSet(Flag.DELETED))
{
Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid()
- + " was already deleted on server, skipping");
+ + " was marked deleted on server, skipping");
}
else
{
Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than "
+ earliestDate + ", skipping");
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
return;
}
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE))
{
largeMessages.add(message);
}
else
{
smallMessages.add(message);
}
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null)
{
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false)
{
// Store the new message locally
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
syncFlags(localMessage, message);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message "
+ account + ":" + folder + ":" + message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, null, e);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
// If a message didn't exist, messageFinished won't be called, but we shouldn't try again
// If we got here, nothing failed
for (Message message : unsyncedMessages)
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have "
+ largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages out of "
+ unsyncedMessages.size() + " unsynced messages");
unsyncedMessages.clear();
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
// fp.add(FetchProfile.Item.FLAGS);
// fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
if (isMessageSuppressed(account, folder, message ))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " was suppressed "+
"but just downloaded. "+
"The race condition means we wasted some bandwidth. Oh well.");
}
progress.incrementAndGet();
return;
}
if (message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
progress.incrementAndGet();
return;
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
progress.incrementAndGet();
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
if (!localMessage.isSet(Flag.SEEN))
{
// Send a notification of this message
if (notifyAccount(mApplication, account, message) == true)
{
newMessages.incrementAndGet();
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
smallMessages.clear();
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages)
{
if (message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
progress.incrementAndGet();
continue;
}
if (message.getBody() == null)
{
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Certain (POP3) servers give you the whole message even when you ask for only the first x Kb
if (!message.isSet(Flag.X_DOWNLOADED_FULL))
{
/*
* Mark the message as fully downloaded if the message size is smaller than
* the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE)
{
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
else
{
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
}
}
else
{
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables)
{
remoteFolder.fetchPart(message, part, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
progress.incrementAndGet();
Message localMessage = localFolder.getMessage(message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
if (!localMessage.isSet(Flag.SEEN))
{
// Send a notification of this message
if (notifyAccount(mApplication, account, message) == true)
{
newMessages.incrementAndGet();
}
}
}//for large messsages
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
largeMessages.clear();
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
if (remoteFolder.supportsFetchingFlags())
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to sync flags for "
+ syncFlagMessages.size() + " remote messages for folder " + folder);
fp.clear();
fp.add(FetchProfile.Item.FLAGS);
List<Message> undeletedMessages = new LinkedList<Message>();
for (Message message : syncFlagMessages)
{
if (message.isSet(Flag.DELETED) == false)
{
undeletedMessages.add(message);
}
}
remoteFolder.fetch(undeletedMessages.toArray(new Message[0]), fp, null);
for (Message remoteMessage : syncFlagMessages)
{
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
boolean messageChanged = syncFlags(localMessage, remoteMessage);
if (messageChanged)
{
if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
else
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages");
localFolder.purgeToVisibleLimit(new MessageRemovalListener()
{
public void messageRemoved(Message message)
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, message);
}
}
});
return newMessages.get();
}
private boolean syncFlags(Message localMessage, Message remoteMessage) throws MessagingException
{
boolean messageChanged = false;
if (localMessage == null || localMessage.isSet(Flag.DELETED))
{
return false;
}
if (remoteMessage.isSet(Flag.DELETED))
{
if (localMessage.getFolder().getAccount().syncRemoteDeletions())
{
localMessage.setFlag(Flag.DELETED, true);
messageChanged = true;
}
}
else
{
for (Flag flag : new Flag[] { Flag.SEEN, Flag.FLAGGED, Flag.ANSWERED })
{
if (remoteMessage.isSet(flag) != localMessage.isSet(flag))
{
localMessage.setFlag(flag, remoteMessage.isSet(flag));
messageChanged = true;
}
}
}
return messageChanged;
}
private String getRootCauseMessage(Throwable t)
{
Throwable rootCause = t;
Throwable nextCause = rootCause;
do
{
nextCause = rootCause.getCause();
if (nextCause != null)
{
rootCause = nextCause;
}
}
while (nextCause != null);
return rootCause.getMessage();
}
private void queuePendingCommand(Account account, PendingCommand command)
{
try
{
LocalStore localStore = account.getLocalStore();
localStore.addPendingCommand(command);
}
catch (Exception e)
{
addErrorMessage(account, null, e);
throw new RuntimeException("Unable to enqueue pending command", e);
}
}
private void processPendingCommands(final Account account)
{
putBackground("processPendingCommands", null, new Runnable()
{
public void run()
{
try
{
processPendingCommandsSynchronous(account);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "processPendingCommands", me);
addErrorMessage(account, null, me);
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
private void processPendingCommandsSynchronous(Account account) throws MessagingException
{
LocalStore localStore = account.getLocalStore();
ArrayList<PendingCommand> commands = localStore.getPendingCommands();
int progress = 0;
int todo = commands.size();
if (todo == 0)
{
return;
}
for (MessagingListener l : getListeners())
{
l.pendingCommandsProcessing(account);
l.synchronizeMailboxProgress(account, null, progress, todo);
}
PendingCommand processingCommand = null;
try
{
for (PendingCommand command : commands)
{
processingCommand = command;
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Processing pending command '" + command + "'");
String[] components = command.command.split("\\.");
String commandTitle = components[components.length - 1];
for (MessagingListener l : getListeners())
{
l.pendingCommandStarted(account, commandTitle);
}
/*
* We specifically do not catch any exceptions here. If a command fails it is
* most likely due to a server or IO error and it must be retried before any
* other command processes. This maintains the order of the commands.
*/
try
{
if (PENDING_COMMAND_APPEND.equals(command.command))
{
processPendingAppend(command, account);
}
else if (PENDING_COMMAND_SET_FLAG_BULK.equals(command.command))
{
processPendingSetFlag(command, account);
}
else if (PENDING_COMMAND_SET_FLAG.equals(command.command))
{
processPendingSetFlagOld(command, account);
}
else if (PENDING_COMMAND_MARK_ALL_AS_READ.equals(command.command))
{
processPendingMarkAllAsRead(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY_BULK.equals(command.command))
{
processPendingMoveOrCopy(command, account);
}
else if (PENDING_COMMAND_MOVE_OR_COPY.equals(command.command))
{
processPendingMoveOrCopyOld(command, account);
}
else if (PENDING_COMMAND_EMPTY_TRASH.equals(command.command))
{
processPendingEmptyTrash(command, account);
}
else if (PENDING_COMMAND_EXPUNGE.equals(command.command))
{
processPendingExpunge(command, account);
}
localStore.removePendingCommand(command);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Done processing pending command '" + command + "'");
}
catch (MessagingException me)
{
if (me.isPermanentFailure())
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Failure of command '" + command + "' was permanent, removing command from queue");
localStore.removePendingCommand(processingCommand);
}
else
{
throw me;
}
}
finally
{
progress++;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, null, progress, todo);
l.pendingCommandCompleted(account, commandTitle);
}
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "Could not process command '" + processingCommand + "'", me);
throw me;
}
finally
{
for (MessagingListener l : getListeners())
{
l.pendingCommandsFinished(account);
}
}
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message. Once the local message is successfully processed it is deleted so
* that the server message will be synchronized down without an additional copy being
* created.
* TODO update the local message UID instead of deleteing it
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingAppend(PendingCommand command, Account account)
throws MessagingException
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
LocalMessage localMessage = (LocalMessage) localFolder.getMessage(uid);
if (localMessage == null)
{
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES))
{
return;
}
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
Message remoteMessage = null;
if (!localMessage.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteFolder.getMessage(localMessage.getUid());
}
if (remoteMessage == null)
{
if (localMessage.isSet(Flag.X_REMOTE_COPY_STARTED))
{
Log.w(K9.LOG_TAG, "Local message with uid " + localMessage.getUid() +
" has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, checking for remote message with " +
" same message id");
String rUid = remoteFolder.getUidFromMessageId(localMessage);
if (rUid != null)
{
Log.w(K9.LOG_TAG, "Local message has flag " + Flag.X_REMOTE_COPY_STARTED + " already set, and there is a remote message with " +
" uid " + rUid + ", assuming message was already copied and aborting this copy");
String oldUid = localMessage.getUid();
localMessage.setUid(rUid);
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
return;
}
else
{
Log.w(K9.LOG_TAG, "No remote message with message-id found, proceeding with append");
}
}
/*
* If the message does not exist remotely we just upload it and then
* update our local copy with the new uid.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[]
{
localMessage
}
, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
}
else
{
/*
* If the remote message exists we need to determine which copy to keep.
*/
/*
* See if the remote message is newer than ours.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
Date localDate = localMessage.getInternalDate();
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate != null && remoteDate.compareTo(localDate) > 0)
{
/*
* If the remote message is newer than ours we'll just
* delete ours and move on. A sync will get the server message
* if we need to be able to see it.
*/
localMessage.setFlag(Flag.X_DESTROYED, true);
}
else
{
/*
* Otherwise we'll upload our message and then delete the remote message.
*/
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { localMessage }, fp, null);
String oldUid = localMessage.getUid();
localMessage.setFlag(Flag.X_REMOTE_COPY_STARTED, true);
remoteFolder.appendMessages(new Message[] { localMessage });
localFolder.changeUid(localMessage);
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, folder, oldUid, localMessage.getUid());
}
if (remoteDate != null)
{
remoteMessage.setFlag(Flag.DELETED, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
remoteFolder.expunge();
}
}
}
}
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
if (localFolder != null)
{
localFolder.close();
}
}
}
private void queueMoveOrCopy(Account account, String srcFolder, String destFolder, boolean isCopy, String uids[])
{
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MOVE_OR_COPY_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = srcFolder;
command.arguments[1] = destFolder;
command.arguments[2] = Boolean.toString(isCopy);
for (int i = 0; i < uids.length; i++)
{
command.arguments[3 + i] = uids[i];
}
queuePendingCommand(account, command);
}
/**
* Process a pending trash message command.
*
* @param command arguments = (String folder, String uid)
* @param account
* @throws MessagingException
*/
private void processPendingMoveOrCopy(PendingCommand command, Account account)
throws MessagingException
{
Folder remoteSrcFolder = null;
Folder remoteDestFolder = null;
try
{
String srcFolder = command.arguments[0];
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
String destFolder = command.arguments[1];
String isCopyS = command.arguments[2];
Store remoteStore = account.getRemoteStore();
remoteSrcFolder = remoteStore.getFolder(srcFolder);
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++)
{
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
messages.add(remoteSrcFolder.getMessage(uid));
}
}
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (!remoteSrcFolder.exists())
{
throw new MessagingException("processingPendingMoveOrCopy: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processingPendingMoveOrCopy: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy: source folder = " + srcFolder
+ ", " + messages.size() + " messages, destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processingPendingMoveOrCopy doing special case for deleting message");
String destFolderName = destFolder;
if (K9.FOLDER_NONE.equals(destFolderName))
{
destFolderName = null;
}
remoteSrcFolder.delete(messages.toArray(new Message[0]), destFolderName);
}
else
{
remoteDestFolder = remoteStore.getFolder(destFolder);
if (isCopy)
{
remoteSrcFolder.copyMessages(messages.toArray(new Message[0]), remoteDestFolder);
}
else
{
remoteSrcFolder.moveMessages(messages.toArray(new Message[0]), remoteDestFolder);
}
}
if (isCopy == false && Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "processingPendingMoveOrCopy expunging folder " + account.getDescription() + ":" + srcFolder);
remoteSrcFolder.expunge();
}
}
finally
{
if (remoteSrcFolder != null)
{
remoteSrcFolder.close();
}
if (remoteDestFolder != null)
{
remoteDestFolder.close();
}
}
}
private void queueSetFlag(final Account account, final String folderName, final String newState, final String flag, final String[] uids)
{
putBackground("queueSetFlag " + account.getDescription() + ":" + folderName, null, new Runnable()
{
public void run()
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_SET_FLAG_BULK;
int length = 3 + uids.length;
command.arguments = new String[length];
command.arguments[0] = folderName;
command.arguments[1] = newState;
command.arguments[2] = flag;
for (int i = 0; i < uids.length; i++)
{
command.arguments[3 + i] = uids[i];
}
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
/**
* Processes a pending mark read or unread command.
*
* @param command arguments = (String folder, String uid, boolean read)
* @param account
*/
private void processPendingSetFlag(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder))
{
return;
}
boolean newState = Boolean.parseBoolean(command.arguments[1]);
Flag flag = Flag.valueOf(command.arguments[2]);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
try
{
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
List<Message> messages = new ArrayList<Message>();
for (int i = 3; i < command.arguments.length; i++)
{
String uid = command.arguments[i];
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
messages.add(remoteFolder.getMessage(uid));
}
}
if (messages.size() == 0)
{
return;
}
remoteFolder.setFlags(messages.toArray(new Message[0]), new Flag[] { flag }, newState);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingSetFlagOld(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
String uid = command.arguments[1];
if (account.getErrorFolderName().equals(folder))
{
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingSetFlagOld: folder = " + folder + ", uid = " + uid);
boolean newState = Boolean.parseBoolean(command.arguments[2]);
Flag flag = Flag.valueOf(command.arguments[3]);
Folder remoteFolder = null;
try
{
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteFolder.getMessage(uid);
}
if (remoteMessage == null)
{
return;
}
remoteMessage.setFlag(flag, newState);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
private void queueExpunge(final Account account, final String folderName)
{
putBackground("queueExpunge " + account.getDescription() + ":" + folderName, null, new Runnable()
{
public void run()
{
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EXPUNGE;
command.arguments = new String[1];
command.arguments[0] = folderName;
queuePendingCommand(account, command);
processPendingCommands(account);
}
});
}
private void processPendingExpunge(PendingCommand command, Account account)
throws MessagingException
{
String folder = command.arguments[0];
if (account.getErrorFolderName().equals(folder))
{
return;
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: folder = " + folder);
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(folder);
try
{
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
remoteFolder.expunge();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingExpunge: complete for folder = " + folder);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
// TODO: This method is obsolete and is only for transition from K-9 2.0 to K-9 2.1
// Eventually, it should be removed
private void processPendingMoveOrCopyOld(PendingCommand command, Account account)
throws MessagingException
{
String srcFolder = command.arguments[0];
String uid = command.arguments[1];
String destFolder = command.arguments[2];
String isCopyS = command.arguments[3];
boolean isCopy = false;
if (isCopyS != null)
{
isCopy = Boolean.parseBoolean(isCopyS);
}
if (account.getErrorFolderName().equals(srcFolder))
{
return;
}
Store remoteStore = account.getRemoteStore();
Folder remoteSrcFolder = remoteStore.getFolder(srcFolder);
Folder remoteDestFolder = remoteStore.getFolder(destFolder);
if (!remoteSrcFolder.exists())
{
throw new MessagingException("processPendingMoveOrCopyOld: remoteFolder " + srcFolder + " does not exist", true);
}
remoteSrcFolder.open(OpenMode.READ_WRITE);
if (remoteSrcFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteSrcFolder " + srcFolder + " read/write", true);
}
Message remoteMessage = null;
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
remoteMessage = remoteSrcFolder.getMessage(uid);
}
if (remoteMessage == null)
{
throw new MessagingException("processPendingMoveOrCopyOld: remoteMessage " + uid + " does not exist", true);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld: source folder = " + srcFolder
+ ", uid = " + uid + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy == false && destFolder.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "processPendingMoveOrCopyOld doing special case for deleting message");
remoteMessage.delete(account.getTrashFolderName());
remoteSrcFolder.close();
return;
}
remoteDestFolder.open(OpenMode.READ_WRITE);
if (remoteDestFolder.getMode() != OpenMode.READ_WRITE)
{
throw new MessagingException("processPendingMoveOrCopyOld: could not open remoteDestFolder " + srcFolder + " read/write", true);
}
if (isCopy)
{
remoteSrcFolder.copyMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
else
{
remoteSrcFolder.moveMessages(new Message[] { remoteMessage }, remoteDestFolder);
}
remoteSrcFolder.close();
remoteDestFolder.close();
}
private void processPendingMarkAllAsRead(PendingCommand command, Account account) throws MessagingException
{
String folder = command.arguments[0];
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = (LocalFolder) localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message[] messages = localFolder.getMessages(null, false);
for (Message message : messages)
{
if (message.isSet(Flag.SEEN) == false)
{
message.setFlag(Flag.SEEN, true);
for (MessagingListener l : getListeners())
{
l.listLocalMessagesUpdateMessage(account, folder, message);
}
}
}
localFolder.setUnreadMessageCount(0);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, 0);
}
if (account.getErrorFolderName().equals(folder))
{
return;
}
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
if (!remoteFolder.exists())
{
return;
}
remoteFolder.open(OpenMode.READ_WRITE);
if (remoteFolder.getMode() != OpenMode.READ_WRITE)
{
return;
}
remoteFolder.setFlags(new Flag[] {Flag.SEEN}, true);
remoteFolder.close();
}
catch (UnsupportedOperationException uoe)
{
Log.w(K9.LOG_TAG, "Could not mark all server-side as read because store doesn't support operation", uoe);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
static long uidfill = 0;
static AtomicBoolean loopCatch = new AtomicBoolean();
public void addErrorMessage(Account account, String subject, Throwable t)
{
if (K9.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (t == null)
{
return;
}
String rootCauseMessage = getRootCauseMessage(t);
Log.e(K9.LOG_TAG, "Error " + "'" + rootCauseMessage + "'", t);
Store localStore = account.getLocalStore();
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
MimeMessage message = new MimeMessage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
t.printStackTrace(ps);
ps.close();
message.setBody(new TextBody(baos.toString()));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (subject != null)
{
message.setSubject(subject);
}
else
{
message.setSubject(rootCauseMessage);
}
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, localFolder.getName(), localFolder.getUnreadMessageCount());
}
}
catch (Throwable it)
{
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void addErrorMessage(Account account, String subject, String body)
{
if (K9.ENABLE_ERROR_FOLDER == false)
{
return;
}
if (loopCatch.compareAndSet(false, true) == false)
{
return;
}
try
{
if (body == null || body.length() < 1)
{
return;
}
Store localStore = account.getLocalStore();
LocalFolder localFolder = (LocalFolder)localStore.getFolder(account.getErrorFolderName());
Message[] messages = new Message[1];
MimeMessage message = new MimeMessage();
message.setBody(new TextBody(body));
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
message.setSubject(subject);
long nowTime = System.currentTimeMillis();
Date nowDate = new Date(nowTime);
message.setInternalDate(nowDate);
message.addSentDate(nowDate);
message.setFrom(new Address(account.getEmail(), "K9mail internal"));
messages[0] = message;
localFolder.appendMessages(messages);
localFolder.deleteMessagesOlderThan(nowTime - (15 * 60 * 1000));
}
catch (Throwable it)
{
Log.e(K9.LOG_TAG, "Could not save error message to " + account.getErrorFolderName(), it);
}
finally
{
loopCatch.set(false);
}
}
public void markAllMessagesRead(final Account account, final String folder)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Marking all messages in " + account.getDescription() + ":" + folder + " as read");
List<String> args = new ArrayList<String>();
args.add(folder);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_MARK_ALL_AS_READ;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
public void setFlag(
final Message[] messages,
final Flag flag,
final boolean newState)
{
actOnMessages(messages, new MessageActor()
{
@Override
public void act(final Account account, final Folder folder,
final List<Message> messages)
{
String[] uids = new String[messages.size()];
for (int i = 0; i < messages.size(); i++)
{
uids[i] = messages.get(i).getUid();
}
setFlag(account, folder.getName(), uids, flag, newState);
}
});
}
public void setFlag(
final Account account,
final String folderName,
final String[] uids,
final Flag flag,
final boolean newState)
{
// TODO: put this into the background, but right now that causes odd behavior
// because the FolderMessageList doesn't have its own cache of the flag states
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folderName);
localFolder.open(OpenMode.READ_WRITE);
ArrayList<Message> messages = new ArrayList<Message>();
for (int i = 0; i < uids.length; i++)
{
String uid = uids[i];
// Allows for re-allowing sending of messages that could not be sent
if (flag == Flag.FLAGGED && newState == false
&& uid != null
&& account.getOutboxFolderName().equals(folderName))
{
sendCount.remove(uid);
}
Message msg = localFolder.getMessage(uid);
if (msg != null)
{
messages.add(msg);
}
}
localFolder.setFlags(messages.toArray(new Message[0]), new Flag[] {flag}, newState);
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folderName, localFolder.getUnreadMessageCount());
}
if (account.getErrorFolderName().equals(folderName))
{
return;
}
queueSetFlag(account, folderName, Boolean.toString(newState), flag.toString(), uids);
processPendingCommands(account);
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException(me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}//setMesssageFlag
public void clearAllPending(final Account account)
{
try
{
Log.w(K9.LOG_TAG, "Clearing pending commands!");
LocalStore localStore = account.getLocalStore();
localStore.removePendingCommands();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to clear pending command", me);
addErrorMessage(account, null, me);
}
}
private void loadMessageForViewRemote(final Account account, final String folder,
final String uid, final MessagingListener listener)
{
put("loadMessageForViewRemote", listener, new Runnable()
{
public void run()
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
if (message.isSet(Flag.X_DOWNLOADED_FULL))
{
/*
* If the message has been synchronized since we were called we'll
* just hand it back cause it's ready to go.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[] { message }, fp, null);
}
else
{
/*
* At this point the message is not available, so we need to download it
* fully if possible.
*/
Store remoteStore = account.getRemoteStore();
remoteFolder = remoteStore.getFolder(folder);
remoteFolder.open(OpenMode.READ_WRITE);
// Get the remote message and fully download it
Message remoteMessage = remoteFolder.getMessage(uid);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
// Store the message locally and load the stored message into memory
localFolder.appendMessages(new Message[] { remoteMessage });
message = localFolder.getMessage(uid);
localFolder.fetch(new Message[] { message }, fp, null);
// Mark that this message is now fully synched
message.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFinished(account, folder, uid, message);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFailed(account, folder, uid, e);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, null, e);
}
finally
{
if (remoteFolder!=null)
{
remoteFolder.close();
}
if (localFolder!=null)
{
localFolder.close();
}
}//finally
}//run
});
}
public void loadMessageForView(final Account account, final String folder, final String uid,
final MessagingListener listener)
{
for (MessagingListener l : getListeners())
{
l.loadMessageForViewStarted(account, folder, uid);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewStarted(account, folder, uid);
}
threadPool.execute(new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(folder);
localFolder.open(OpenMode.READ_WRITE);
LocalMessage message = (LocalMessage)localFolder.getMessage(uid);
if (message==null
|| message.getId()==0)
{
throw new IllegalArgumentException("Message not found: folder=" + folder + ", uid=" + uid);
}
if (!message.isSet(Flag.SEEN))
{
message.setFlag(Flag.SEEN, true);
setFlag(new Message[] { message }, Flag.SEEN, true);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewHeadersAvailable(account, folder, uid, message);
}
if (!message.isSet(Flag.X_DOWNLOADED_FULL))
{
loadMessageForViewRemote(account, folder, uid, listener);
if (!message.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
localFolder.close();
return;
}
}
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localFolder.fetch(new Message[]
{
message
}, fp, null);
localFolder.close();
for (MessagingListener l : getListeners())
{
l.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewBodyAvailable(account, folder, uid, message);
}
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFinished(account, folder, uid, message);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFinished(account, folder, uid, message);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.loadMessageForViewFailed(account, folder, uid, e);
}
if (listener != null && !getListeners().contains(listener))
{
listener.loadMessageForViewFailed(account, folder, uid, e);
}
addErrorMessage(account, null, e);
}
}
});
}
/**
* Attempts to load the attachment specified by part from the given account and message.
* @param account
* @param message
* @param part
* @param listener
*/
public void loadAttachment(
final Account account,
final Message message,
final Part part,
final Object tag,
final MessagingListener listener)
{
/*
* Check if the attachment has already been downloaded. If it has there's no reason to
* download it, so we just tell the listener that it's ready to go.
*/
try
{
if (part.getBody() != null)
{
for (MessagingListener l : getListeners())
{
l.loadAttachmentStarted(account, message, part, tag, false);
}
if (listener != null)
{
listener.loadAttachmentStarted(account, message, part, tag, false);
}
for (MessagingListener l : getListeners())
{
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null)
{
listener.loadAttachmentFinished(account, message, part, tag);
}
return;
}
}
catch (MessagingException me)
{
/*
* If the header isn't there the attachment isn't downloaded yet, so just continue
* on.
*/
}
for (MessagingListener l : getListeners())
{
l.loadAttachmentStarted(account, message, part, tag, true);
}
if (listener != null)
{
listener.loadAttachmentStarted(account, message, part, tag, false);
}
put("loadAttachment", listener, new Runnable()
{
public void run()
{
Folder remoteFolder = null;
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
/*
* We clear out any attachments already cached in the entire store and then
* we update the passed in message to reflect that there are no cached
* attachments. This is in support of limiting the account to having one
* attachment downloaded at a time.
*/
localStore.pruneCachedAttachments();
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
for (Part attachment : attachments)
{
attachment.setBody(null);
}
Store remoteStore = account.getRemoteStore();
localFolder = localStore.getFolder(message.getFolder().getName());
remoteFolder = remoteStore.getFolder(message.getFolder().getName());
remoteFolder.open(OpenMode.READ_WRITE);
//FIXME: This is an ugly hack that won't be needed once the Message objects have been united.
Message remoteMessage = remoteFolder.getMessage(message.getUid());
remoteMessage.setBody(message.getBody());
remoteFolder.fetchPart(remoteMessage, part, null);
localFolder.updateMessage((LocalMessage)message);
for (MessagingListener l : getListeners())
{
l.loadAttachmentFinished(account, message, part, tag);
}
if (listener != null)
{
listener.loadAttachmentFinished(account, message, part, tag);
}
}
catch (MessagingException me)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Exception loading attachment", me);
for (MessagingListener l : getListeners())
{
l.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
if (listener != null)
{
listener.loadAttachmentFailed(account, message, part, tag, me.getMessage());
}
addErrorMessage(account, null, me);
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
if (localFolder != null)
{
localFolder.close();
}
}
}
});
}
/**
* Stores the given message in the Outbox and starts a sendPendingMessages command to
* attempt to send the message.
* @param account
* @param message
* @param listener
*/
public void sendMessage(final Account account,
final Message message,
MessagingListener listener)
{
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getOutboxFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
localFolder.close();
sendPendingMessages(account, null);
}
catch (Exception e)
{
/*
for (MessagingListener l : getListeners())
{
// TODO general failed
}
*/
addErrorMessage(account, null, e);
}
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final Account account,
MessagingListener listener)
{
putBackground("sendPendingMessages", listener, new Runnable()
{
public void run()
{
sendPendingMessagesSynchronous(account);
}
});
}
public boolean messagesPendingSend(final Account account)
{
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists())
{
return false;
}
localFolder.open(OpenMode.READ_WRITE);
int localMessages = localFolder.getMessageCount();
if (localMessages > 0)
{
return true;
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while checking for unsent messages", e);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
return false;
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessagesSynchronous(final Account account)
{
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(
account.getOutboxFolderName());
if (!localFolder.exists())
{
return;
}
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesStarted(account);
}
localFolder.open(OpenMode.READ_WRITE);
Message[] localMessages = localFolder.getMessages(null);
boolean anyFlagged = false;
int progress = 0;
int todo = localMessages.length;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
/*
* The profile we will use to pull all of the content
* for a given local message into memory for sending.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Scanning folder '" + account.getOutboxFolderName() + "' (" + ((LocalFolder)localFolder).getId() + ") for messages to send");
Transport transport = Transport.getInstance(account);
for (Message message : localMessages)
{
if (message.isSet(Flag.DELETED))
{
message.setFlag(Flag.X_DESTROYED, true);
continue;
}
if (message.isSet(Flag.FLAGGED))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Skipping sending FLAGGED message " + message.getUid());
continue;
}
try
{
AtomicInteger count = new AtomicInteger(0);
AtomicInteger oldCount = sendCount.putIfAbsent(message.getUid(), count);
if (oldCount != null)
{
count = oldCount;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Send count for message " + message.getUid() + " is " + count.get());
if (count.incrementAndGet() > K9.MAX_SEND_ATTEMPTS)
{
Log.e(K9.LOG_TAG, "Send count for message " + message.getUid() + " has exceeded maximum attempt threshold, flagging");
message.setFlag(Flag.FLAGGED, true);
anyFlagged = true;
continue;
}
localFolder.fetch(new Message[] { message }, fp, null);
try
{
message.setFlag(Flag.X_SEND_IN_PROGRESS, true);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Sending message with UID " + message.getUid());
transport.sendMessage(message);
message.setFlag(Flag.X_SEND_IN_PROGRESS, false);
message.setFlag(Flag.SEEN, true);
progress++;
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, account.getSentFolderName(), progress, todo);
}
if (K9.FOLDER_NONE.equals(account.getSentFolderName()))
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Sent folder set to " + K9.FOLDER_NONE + ", deleting sent message");
message.setFlag(Flag.DELETED, true);
}
else
{
LocalFolder localSentFolder =
(LocalFolder) localStore.getFolder(
account.getSentFolderName());
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moving sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
localFolder.moveMessages(
new Message[] { message },
localSentFolder);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Moved sent message to folder '" + account.getSentFolderName() + "' (" + localSentFolder.getId() + ") ");
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[]
{
localSentFolder.getName(),
message.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
}
}
catch (Exception e)
{
if (e instanceof MessagingException)
{
MessagingException me = (MessagingException)e;
if (me.isPermanentFailure() == false)
{
// Decrement the counter if the message could not possibly have been sent
int newVal = count.decrementAndGet();
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Decremented send count for message " + message.getUid() + " to " + newVal
+ "; no possible send");
}
}
message.setFlag(Flag.X_SEND_FAILED, true);
Log.e(K9.LOG_TAG, "Failed to send message", e);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, null, e);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to fetch message for sending", e);
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(
account,
localFolder.getName(),
getRootCauseMessage(e));
}
addErrorMessage(account, null, e);
/*
* We ignore this exception because a future refresh will retry this
* message.
*/
}
}
if (localFolder.getMessageCount() == 0)
{
localFolder.delete(false);
}
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesCompleted(account);
}
if (anyFlagged)
{
addErrorMessage(account, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_fmt, K9.ERROR_FOLDER_NAME));
NotificationManager notifMgr =
(NotificationManager)mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.stat_notify_email_generic,
mApplication.getString(R.string.send_failure_subject), System.currentTimeMillis());
Intent i = MessageList.actionHandleFolderIntent(mApplication, account, account.getErrorFolderName());
PendingIntent pi = PendingIntent.getActivity(mApplication, 0, i, 0);
notif.setLatestEventInfo(mApplication, mApplication.getString(R.string.send_failure_subject),
mApplication.getString(R.string.send_failure_body_abbrev, K9.ERROR_FOLDER_NAME), pi);
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = K9.NOTIFICATION_LED_SENDING_FAILURE_COLOR;
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
notifMgr.notify(-1000 - account.getAccountNumber(), notif);
}
}
catch (Exception e)
{
for (MessagingListener l : getListeners())
{
l.sendPendingMessagesFailed(account);
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while closing folder", e);
}
}
}
}
public void getAccountStats(final Context context, final Account account,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable()
{
public void run()
{
try
{
AccountStats stats = account.getStats(context);
l.accountStatusChanged(account, stats);
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(),
me);
}
}
};
put("getAccountStats:" + account.getDescription(), l, unreadRunnable);
}
public void getFolderUnreadMessageCount(final Account account, final String folderName,
final MessagingListener l)
{
Runnable unreadRunnable = new Runnable()
{
public void run()
{
int unreadMessageCount = 0;
try
{
Folder localFolder = account.getLocalStore().getFolder(folderName);
unreadMessageCount = localFolder.getUnreadMessageCount();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Count not get unread count for account " + account.getDescription(), me);
}
l.folderStatusChanged(account, folderName, unreadMessageCount);
}
};
put("getFolderUnread:" + account.getDescription() + ":" + folderName, l, unreadRunnable);
}
public boolean isMoveCapable(Message message)
{
if (!message.getUid().startsWith(K9.LOCAL_UID_PREFIX))
{
return true;
}
else
{
return false;
}
}
public boolean isCopyCapable(Message message)
{
return isMoveCapable(message);
}
public boolean isMoveCapable(final Account account)
{
try
{
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isMoveCapable() && remoteStore.isMoveCapable();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Exception while ascertaining move capability", me);
return false;
}
}
public boolean isCopyCapable(final Account account)
{
try
{
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
return localStore.isCopyCapable() && remoteStore.isCopyCapable();
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Exception while ascertaining copy capability", me);
return false;
}
}
public void moveMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder,
final MessagingListener listener)
{
for (Message message : messages)
{
suppressMessage(account, srcFolder, message);
}
putBackground("moveMessages", null, new Runnable()
{
public void run()
{
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, false, listener);
}
});
}
public void moveMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
moveMessages(account, srcFolder, new Message[] { message }, destFolder, listener);
}
public void copyMessages(final Account account, final String srcFolder, final Message[] messages, final String destFolder,
final MessagingListener listener)
{
putBackground("copyMessages", null, new Runnable()
{
public void run()
{
moveOrCopyMessageSynchronous(account, srcFolder, messages, destFolder, true, listener);
}
});
}
public void copyMessage(final Account account, final String srcFolder, final Message message, final String destFolder,
final MessagingListener listener)
{
copyMessages(account, srcFolder, new Message[] { message }, destFolder, listener);
}
private void moveOrCopyMessageSynchronous(final Account account, final String srcFolder, final Message[] inMessages,
final String destFolder, final boolean isCopy, MessagingListener listener)
{
try
{
Store localStore = account.getLocalStore();
Store remoteStore = account.getRemoteStore();
if (isCopy == false && (remoteStore.isMoveCapable() == false || localStore.isMoveCapable() == false))
{
return;
}
if (isCopy == true && (remoteStore.isCopyCapable() == false || localStore.isCopyCapable() == false))
{
return;
}
Folder localSrcFolder = localStore.getFolder(srcFolder);
Folder localDestFolder = localStore.getFolder(destFolder);
List<String> uids = new LinkedList<String>();
for (Message message : inMessages)
{
String uid = message.getUid();
if (!uid.startsWith(K9.LOCAL_UID_PREFIX))
{
uids.add(uid);
}
}
Message[] messages = localSrcFolder.getMessages(uids.toArray(new String[0]), null);
if (messages.length > 0)
{
Map<String, Message> origUidMap = new HashMap<String, Message>();
for (Message message : messages)
{
origUidMap.put(message.getUid(), message);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "moveOrCopyMessageSynchronous: source folder = " + srcFolder
+ ", " + messages.length + " messages, " + ", destination folder = " + destFolder + ", isCopy = " + isCopy);
if (isCopy)
{
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.BODY);
localSrcFolder.fetch(messages, fp, null);
localSrcFolder.copyMessages(messages, localDestFolder);
}
else
{
localSrcFolder.moveMessages(messages, localDestFolder);
for (String origUid : origUidMap.keySet())
{
for (MessagingListener l : getListeners())
{
l.messageUidChanged(account, srcFolder, origUid, origUidMap.get(origUid).getUid());
}
unsuppressMessage(account, srcFolder, origUid);
}
}
queueMoveOrCopy(account, srcFolder, destFolder, isCopy, origUidMap.keySet().toArray(new String[0]));
}
processPendingCommands(account);
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException("Error moving message", me);
}
}
public void expunge(final Account account, final String folder, final MessagingListener listener)
{
putBackground("expunge", null, new Runnable()
{
public void run()
{
queueExpunge(account, folder);
}
});
}
public void deleteDraft(final Account account, String uid)
{
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(OpenMode.READ_WRITE);
Message message = localFolder.getMessage(uid);
if (message != null)
{
deleteMessages(new Message[] { message }, null);
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}
public void deleteMessages(final Message[] messages, final MessagingListener listener)
{
actOnMessages(messages, new MessageActor()
{
@Override
public void act(final Account account, final Folder folder,
final List<Message> messages)
{
for (Message message : messages)
{
suppressMessage(account, folder.getName(), message);
}
putBackground("deleteMessages", null, new Runnable()
{
public void run()
{
deleteMessagesSynchronous(account, folder.getName(), messages.toArray(new Message[0]), listener);
}
});
}
});
}
private void deleteMessagesSynchronous(final Account account, final String folder, final Message[] messages,
MessagingListener listener)
{
Folder localFolder = null;
Folder localTrashFolder = null;
String[] uids = getUidsFromMessages(messages);
try
{
//We need to make these callbacks before moving the messages to the trash
//as messages get a new UID after being moved
for (Message message : messages)
{
if (listener != null)
{
listener.messageDeleted(account, folder, message);
}
for (MessagingListener l : getListeners())
{
l.messageDeleted(account, folder, message);
}
}
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
if (folder.equals(account.getTrashFolderName()) || K9.FOLDER_NONE.equals(account.getTrashFolderName()))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in trash folder or trash set to -None-, not copying");
localFolder.setFlags(messages, new Flag[] { Flag.DELETED }, true);
}
else
{
localTrashFolder = localStore.getFolder(account.getTrashFolderName());
if (localTrashFolder.exists() == false)
{
localTrashFolder.create(Folder.FolderType.HOLDS_MESSAGES);
}
if (localTrashFolder.exists() == true)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Deleting messages in normal folder, moving");
localFolder.moveMessages(messages, localTrashFolder);
}
}
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, folder, localFolder.getUnreadMessageCount());
if (localTrashFolder != null)
{
l.folderStatusChanged(account, account.getTrashFolderName(), localTrashFolder.getUnreadMessageCount());
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy for account " + account.getDescription() + " is " + account.getDeletePolicy());
if (folder.equals(account.getOutboxFolderName()))
{
for (Message message : messages)
{
// If the message was in the Outbox, then it has been copied to local Trash, and has
// to be copied to remote trash
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments =
new String[]
{
account.getTrashFolderName(),
message.getUid()
};
queuePendingCommand(account, command);
}
processPendingCommands(account);
}
else if (folder.equals(account.getTrashFolderName()) && account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
queueSetFlag(account, folder, Boolean.toString(true), Flag.DELETED.toString(), uids);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_ON_DELETE)
{
queueMoveOrCopy(account, folder, account.getTrashFolderName(), false, uids);
processPendingCommands(account);
}
else if (account.getDeletePolicy() == Account.DELETE_POLICY_MARK_AS_READ)
{
queueSetFlag(account, folder, Boolean.toString(true), Flag.SEEN.toString(), uids);
processPendingCommands(account);
}
else
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Delete policy " + account.getDeletePolicy() + " prevents delete from server");
}
for (String uid : uids)
{
unsuppressMessage(account, folder, uid);
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
throw new RuntimeException("Error deleting message from local store.", me);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
if (localTrashFolder != null)
{
localTrashFolder.close();
}
}
}
private String[] getUidsFromMessages(Message[] messages)
{
String[] uids = new String[messages.length];
for (int i = 0; i < messages.length; i++)
{
uids[i] = messages[i].getUid();
}
return uids;
}
private void processPendingEmptyTrash(PendingCommand command, Account account) throws MessagingException
{
Store remoteStore = account.getRemoteStore();
Folder remoteFolder = remoteStore.getFolder(account.getTrashFolderName());
try
{
if (remoteFolder.exists())
{
remoteFolder.open(OpenMode.READ_WRITE);
remoteFolder.setFlags(new Flag [] { Flag.DELETED }, true);
if (Account.EXPUNGE_IMMEDIATELY.equals(account.getExpungePolicy()))
{
remoteFolder.expunge();
}
}
}
finally
{
if (remoteFolder != null)
{
remoteFolder.close();
}
}
}
public void emptyTrash(final Account account, MessagingListener listener)
{
putBackground("emptyTrash", listener, new Runnable()
{
public void run()
{
Folder localFolder = null;
try
{
Store localStore = account.getLocalStore();
localFolder = localStore.getFolder(account.getTrashFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.setFlags(new Flag[] { Flag.DELETED }, true);
for (MessagingListener l : getListeners())
{
l.emptyTrashCompleted(account);
}
List<String> args = new ArrayList<String>();
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_EMPTY_TRASH;
command.arguments = args.toArray(new String[0]);
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "emptyTrash failed", e);
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
localFolder.close();
}
}
}
});
}
public void sendAlternate(final Context context, Account account, Message message)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "About to load message " + account.getDescription() + ":" + message.getFolder().getName()
+ ":" + message.getUid() + " for sendAlternate");
loadMessageForView(account, message.getFolder().getName(),
message.getUid(), new MessagingListener()
{
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid,
Message message)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got message " + account.getDescription() + ":" + folder
+ ":" + message.getUid() + " for sendAlternate");
try
{
Intent msg=new Intent(Intent.ACTION_SEND);
String quotedText = null;
Part part = MimeUtility.findFirstPartByMimeType(message,
"text/plain");
if (part == null)
{
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null)
{
quotedText = MimeUtility.getTextFromPart(part);
}
if (quotedText != null)
{
msg.putExtra(Intent.EXTRA_TEXT, quotedText);
}
msg.putExtra(Intent.EXTRA_SUBJECT, "Fwd: " + message.getSubject());
msg.setType("text/plain");
context.startActivity(Intent.createChooser(msg, context.getString(R.string.send_alternate_chooser_title)));
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Unable to send email through alternate program", me);
}
}
});
}
/**
* Checks mail for one or multiple accounts. If account is null all accounts
* are checked.
*
* @param context
* @param account
* @param listener
*/
public void checkMail(final Context context, final Account account,
final boolean ignoreLastCheckedTime,
final boolean useManualWakeLock,
final MessagingListener listener)
{
TracingWakeLock twakeLock = null;
if (useManualWakeLock)
{
TracingPowerManager pm = TracingPowerManager.getPowerManager(context);
twakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9 MessagingController.checkMail");
twakeLock.setReferenceCounted(false);
twakeLock.acquire(K9.MANUAL_WAKE_LOCK_TIMEOUT);
}
final TracingWakeLock wakeLock = twakeLock;
for (MessagingListener l : getListeners())
{
l.checkMailStarted(context, account);
}
putBackground("checkMail", listener, new Runnable()
{
public void run()
{
final NotificationManager notifMgr = (NotificationManager)context
.getSystemService(Context.NOTIFICATION_SERVICE);
try
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting mail check");
Preferences prefs = Preferences.getPreferences(context);
Account[] accounts;
if (account != null)
{
accounts = new Account[]
{
account
};
}
else
{
accounts = prefs.getAccounts();
}
for (final Account account : accounts)
{
final long accountInterval = account.getAutomaticCheckIntervalMinutes() * 60 * 1000;
if (ignoreLastCheckedTime == false && accountInterval <= 0)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Skipping synchronizing account " + account.getDescription());
continue;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Synchronizing account " + account.getDescription());
account.setRingNotified(false);
putBackground("sendPending " + account.getDescription(), null, new Runnable()
{
public void run()
{
if (messagesPendingSend(account))
{
if (account.isShowOngoing())
{
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_send_ticker, account.getDescription()), System.currentTimeMillis());
Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_send_title),
account.getDescription() , pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (K9.NOTIFICATION_LED_WHILE_SYNCING)
{
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = account.getLedColor();
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif);
}
try
{
sendPendingMessagesSynchronous(account);
}
finally
{
if (account.isShowOngoing())
{
notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
}
}
}
);
try
{
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aSyncMode = account.getFolderSyncMode();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false))
{
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fSyncClass = folder.getSyncClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never sync a folder that isn't displayed
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in display mode " + fDisplayClass + " while account is in display mode " + aDisplayMode);
continue;
}
if (modeMismatch(aSyncMode, fSyncClass))
{
// Do not sync folders in the wrong class
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName() +
" which is in sync mode " + fSyncClass + " while account is in sync mode " + aSyncMode);
continue;
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Folder " + folder.getName() + " was last synced @ " +
new Date(folder.getLastChecked()));
if (ignoreLastCheckedTime == false && folder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not syncing folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
continue;
}
putBackground("sync" + folder.getName(), null, new Runnable()
{
public void run()
{
LocalFolder tLocalFolder = null;
try
{
// In case multiple Commands get enqueued, don't run more than
// once
final LocalStore localStore = account.getLocalStore();
tLocalFolder = localStore.getFolder(folder.getName());
tLocalFolder.open(Folder.OpenMode.READ_WRITE);
if (ignoreLastCheckedTime == false && tLocalFolder.getLastChecked() >
(System.currentTimeMillis() - accountInterval))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Not running Command for folder " + folder.getName()
+ ", previously synced @ " + new Date(folder.getLastChecked())
+ " which would be too recent for the account period");
return;
}
if (account.isShowOngoing())
{
Notification notif = new Notification(R.drawable.ic_menu_refresh,
context.getString(R.string.notification_bg_sync_ticker, account.getDescription(), folder.getName()),
System.currentTimeMillis());
Intent intent = MessageList.actionHandleFolderIntent(context, account, K9.INBOX);
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notif.setLatestEventInfo(context, context.getString(R.string.notification_bg_sync_title), account.getDescription()
+ context.getString(R.string.notification_bg_title_separator) + folder.getName(), pi);
notif.flags = Notification.FLAG_ONGOING_EVENT;
if (K9.NOTIFICATION_LED_WHILE_SYNCING)
{
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = account.getLedColor();
notif.ledOnMS = K9.NOTIFICATION_LED_FAST_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_FAST_OFF_TIME;
}
notifMgr.notify(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber(), notif);
}
try
{
synchronizeMailboxSynchronous(account, folder.getName(), listener, null);
}
finally
{
if (account.isShowOngoing())
{
notifMgr.cancel(K9.FETCHING_EMAIL_NOTIFICATION - account.getAccountNumber());
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Exception while processing folder " +
account.getDescription() + ":" + folder.getName(), e);
addErrorMessage(account, null, e);
}
finally
{
if (tLocalFolder != null)
{
tLocalFolder.close();
}
}
}
}
);
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to synchronize account " + account.getName(), e);
addErrorMessage(account, null, e);
}
finally
{
putBackground("clear notification flag for " + account.getDescription(), null, new Runnable()
{
public void run()
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Clearing notification flag for " + account.getDescription());
account.setRingNotified(false);
try
{
AccountStats stats = account.getStats(context);
int unreadMessageCount = stats.unreadMessageCount;
if (unreadMessageCount == 0)
{
notifyAccountCancel(context, account);
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
}
}
);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to synchronize mail", e);
addErrorMessage(account, null, e);
}
putBackground("finalize sync", null, new Runnable()
{
public void run()
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Finished mail sync");
if (wakeLock != null)
{
wakeLock.release();
}
for (MessagingListener l : getListeners())
{
l.checkMailFinished(context, account);
}
}
}
);
}
});
}
public void compact(final Account account, final MessagingListener ml)
{
putBackground("compact:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.compact();
long newSize = localStore.getSize();
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to compact account " + account.getDescription(), e);
}
}
});
}
public void clear(final Account account, final MessagingListener ml)
{
putBackground("clear:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.clear();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
ml.accountStatusChanged(account, stats);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to clear account " + account.getDescription(), e);
}
}
});
}
public void recreate(final Account account, final MessagingListener ml)
{
putBackground("recreate:" + account.getDescription(), ml, new Runnable()
{
public void run()
{
try
{
LocalStore localStore = account.getLocalStore();
long oldSize = localStore.getSize();
localStore.recreate();
localStore.resetVisibleLimits(account.getDisplayCount());
long newSize = localStore.getSize();
AccountStats stats = new AccountStats();
stats.size = newSize;
stats.unreadMessageCount = 0;
stats.flaggedMessageCount = 0;
if (ml != null)
{
ml.accountSizeChanged(account, oldSize, newSize);
ml.accountStatusChanged(account, stats);
}
for (MessagingListener l : getListeners())
{
l.accountSizeChanged(account, oldSize, newSize);
l.accountStatusChanged(account, stats);
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Failed to recreate account " + account.getDescription(), e);
}
}
});
}
/** Creates a notification of new email messages
* ringtone, lights, and vibration to be played
*/
private boolean notifyAccount(Context context, Account account, Message message)
{
int unreadMessageCount = 0;
try
{
AccountStats stats = account.getStats(context);
unreadMessageCount = stats.unreadMessageCount;
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to getUnreadMessageCount for account: " + account, e);
}
// Do not notify if the user does not have notifications
// enabled or if the message has been read
if (!account.isNotifyNewMail() || message.isSet(Flag.SEEN))
{
return false;
}
Folder folder = message.getFolder();
if (folder != null)
{
// No notification for new messages in Trash, Drafts, or Sent folder.
// But do notify if it's the INBOX (see issue 1817).
String folderName = folder.getName();
if (!K9.INBOX.equals(folderName) &&
(account.getTrashFolderName().equals(folderName)
|| account.getDraftsFolderName().equals(folderName)
|| account.getSentFolderName().equals(folderName)))
{
return false;
}
}
// If we have a message, set the notification to "<From>: <Subject>"
StringBuffer messageNotice = new StringBuffer();
try
{
if (message != null && message.getFrom() != null)
{
Address[] fromAddrs = message.getFrom();
String from = fromAddrs.length > 0 ? fromAddrs[0].toFriendly() : null;
String subject = message.getSubject();
if (subject == null)
{
subject = context.getString(R.string.general_no_subject);
}
if (from != null)
{
// Show From: address by default
if (account.isAnIdentity(fromAddrs) == false)
{
messageNotice.append(from + ": " + subject);
}
// show To: if the message was sent from me
else
{
// Do not notify of mail from self if !isNotifySelfNewMail
if (!account.isNotifySelfNewMail())
{
return false;
}
Address[] rcpts = message.getRecipients(Message.RecipientType.TO);
String to = rcpts.length > 0 ? rcpts[0].toFriendly() : null;
if (to != null)
{
messageNotice.append(String.format(context.getString(R.string.message_list_to_fmt), to) +": "+subject);
}
else
{
messageNotice.append(context.getString(R.string.general_no_sender) + ": "+subject);
}
}
}
}
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to get message information for notification.", e);
}
// If we could not set a per-message notification, revert to a default message
if (messageNotice.length() == 0)
{
messageNotice.append(context.getString(R.string.notification_new_title));
}
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.stat_notify_email_generic, messageNotice, System.currentTimeMillis());
notif.number = unreadMessageCount;
Intent i = FolderList.actionHandleNotification(context, account, account.getAutoExpandFolderName());
PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
String accountNotice = context.getString(R.string.notification_new_one_account_fmt, unreadMessageCount, account.getDescription());
notif.setLatestEventInfo(context, accountNotice, messageNotice, pi);
// Only ring or vibrate if we have not done so already on this
// account and fetch
if (!account.isRingNotified())
{
account.setRingNotified(true);
if (account.isRing())
{
String ringtone = account.getRingtone();
notif.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone);
}
if (account.isVibrate())
{
int times = account.getVibrateTimes();
long[] pattern1 = new long[] {100,200};
long[] pattern2 = new long[] {100,500};
long[] pattern3 = new long[] {200,200};
long[] pattern4 = new long[] {200,500};
long[] pattern5 = new long[] {500,500};
long[] src = null;
switch (account.getVibratePattern())
{
case 1:
src = pattern1;
break;
case 2:
src = pattern2;
break;
case 3:
src = pattern3;
break;
case 4:
src = pattern4;
break;
case 5:
src = pattern5;
break;
default:
notif.defaults |= Notification.DEFAULT_VIBRATE;
break;
}
if (src != null)
{
long[] dest = new long[src.length * times];
for (int n = 0; n < times; n++)
{
System.arraycopy(src, 0, dest, n * src.length, src.length);
}
notif.vibrate = dest;
}
}
}
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = account.getLedColor();
notif.ledOnMS = K9.NOTIFICATION_LED_ON_TIME;
notif.ledOffMS = K9.NOTIFICATION_LED_OFF_TIME;
notif.audioStreamType = AudioManager.STREAM_NOTIFICATION;
notifMgr.notify(account.getAccountNumber(), notif);
return true;
}
/** Cancel a notification of new email messages */
public void notifyAccountCancel(Context context, Account account)
{
NotificationManager notifMgr =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notifMgr.cancel(account.getAccountNumber());
notifMgr.cancel(-1000 - account.getAccountNumber());
}
public Message saveDraft(final Account account, final Message message)
{
Message localMessage = null;
try
{
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolder(account.getDraftsFolderName());
localFolder.open(OpenMode.READ_WRITE);
localFolder.appendMessages(new Message[]
{
message
});
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
PendingCommand command = new PendingCommand();
command.command = PENDING_COMMAND_APPEND;
command.arguments = new String[]
{
localFolder.getName(),
localMessage.getUid()
};
queuePendingCommand(account, command);
processPendingCommands(account);
}
catch (MessagingException e)
{
Log.e(K9.LOG_TAG, "Unable to save message as draft.", e);
addErrorMessage(account, null, e);
}
return localMessage;
}
public boolean modeMismatch(Account.FolderMode aMode, Folder.FolderClass fMode)
{
if (aMode == Account.FolderMode.NONE
|| (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
|| (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
|| (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS))
{
return true;
}
else
{
return false;
}
}
static AtomicInteger sequencing = new AtomicInteger(0);
class Command implements Comparable<Command>
{
public Runnable runnable;
public MessagingListener listener;
public String description;
boolean isForeground;
int sequence = sequencing.getAndIncrement();
@Override
public int compareTo(Command other)
{
if (other.isForeground == true && isForeground == false)
{
return 1;
}
else if (other.isForeground == false && isForeground == true)
{
return -1;
}
else
{
return (sequence - other.sequence);
}
}
}
public MessagingListener getCheckMailListener()
{
return checkMailListener;
}
public void setCheckMailListener(MessagingListener checkMailListener)
{
if (this.checkMailListener != null)
{
removeListener(this.checkMailListener);
}
this.checkMailListener = checkMailListener;
if (this.checkMailListener != null)
{
addListener(this.checkMailListener);
}
}
public SORT_TYPE getSortType()
{
return sortType;
}
public void setSortType(SORT_TYPE sortType)
{
this.sortType = sortType;
}
public boolean isSortAscending(SORT_TYPE sortType)
{
Boolean sortAsc = sortAscending.get(sortType);
if (sortAsc == null)
{
return sortType.isDefaultAscending();
}
else return sortAsc;
}
public void setSortAscending(SORT_TYPE sortType, boolean nsortAscending)
{
sortAscending.put(sortType, nsortAscending);
}
public Collection<Pusher> getPushers()
{
return pushers.values();
}
public boolean setupPushing(final Account account)
{
try
{
Pusher previousPusher = pushers.remove(account);
if (previousPusher != null)
{
previousPusher.stop();
}
Preferences prefs = Preferences.getPreferences(mApplication);
Account.FolderMode aDisplayMode = account.getFolderDisplayMode();
Account.FolderMode aPushMode = account.getFolderPushMode();
List<String> names = new ArrayList<String>();
Store localStore = account.getLocalStore();
for (final Folder folder : localStore.getPersonalNamespaces(false))
{
if (folder.getName().equals(account.getErrorFolderName())
|| folder.getName().equals(account.getOutboxFolderName()))
{
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which should never be pushed");
continue;
}
folder.open(Folder.OpenMode.READ_WRITE);
folder.refresh(prefs);
Folder.FolderClass fDisplayClass = folder.getDisplayClass();
Folder.FolderClass fPushClass = folder.getPushClass();
if (modeMismatch(aDisplayMode, fDisplayClass))
{
// Never push a folder that isn't displayed
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in display class " + fDisplayClass + " while account is in display mode " + aDisplayMode);
continue;
}
if (modeMismatch(aPushMode, fPushClass))
{
// Do not push folders in the wrong class
if (K9.DEBUG && false)
Log.v(K9.LOG_TAG, "Not pushing folder " + folder.getName() +
" which is in push mode " + fPushClass + " while account is in push mode " + aPushMode);
continue;
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Starting pusher for " + account.getDescription() + ":" + folder.getName());
names.add(folder.getName());
}
if (names.size() > 0)
{
PushReceiver receiver = new MessagingControllerPushReceiver(mApplication, account, this);
int maxPushFolders = account.getMaxPushFolders();
if (names.size() > maxPushFolders)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Count of folders to push for account " + account.getDescription() + " is " + names.size()
+ ", greater than limit of " + maxPushFolders + ", truncating");
names = names.subList(0, maxPushFolders);
}
try
{
Store store = account.getRemoteStore();
if (store.isPushCapable() == false)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Account " + account.getDescription() + " is not push capable, skipping");
return false;
}
Pusher pusher = store.getPusher(receiver);
if (pusher != null)
{
Pusher oldPusher = pushers.putIfAbsent(account, pusher);
if (oldPusher == null)
{
pusher.start(names);
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Could not get remote store", e);
return false;
}
return true;
}
else
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "No folders are configured for pushing in account " + account.getDescription());
return false;
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Got exception while setting up pushing", e);
}
return false;
}
public void stopAllPushing()
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Stopping all pushers");
Iterator<Pusher> iter = pushers.values().iterator();
while (iter.hasNext())
{
Pusher pusher = iter.next();
iter.remove();
pusher.stop();
}
}
public void messagesArrived(final Account account, final Folder remoteFolder, final List<Message> messages, final boolean flagSyncOnly)
{
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "Got new pushed email messages for account " + account.getDescription()
+ ", folder " + remoteFolder.getName());
final CountDownLatch latch = new CountDownLatch(1);
putBackground("Push messageArrived of account " + account.getDescription()
+ ", folder " + remoteFolder.getName(), null, new Runnable()
{
public void run()
{
LocalFolder localFolder = null;
try
{
LocalStore localStore = account.getLocalStore();
localFolder= localStore.getFolder(remoteFolder.getName());
localFolder.open(OpenMode.READ_WRITE);
account.setRingNotified(false);
int newCount = downloadMessages(account, remoteFolder, localFolder, messages, flagSyncOnly);
int unreadMessageCount = setLocalUnreadCountToRemote(localFolder, remoteFolder, messages.size());
setLocalFlaggedCountToRemote(localFolder, remoteFolder);
localFolder.setLastPush(System.currentTimeMillis());
localFolder.setStatus(null);
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "messagesArrived newCount = " + newCount + ", unread count = " + unreadMessageCount);
if (unreadMessageCount == 0)
{
notifyAccountCancel(mApplication, account);
}
for (MessagingListener l : getListeners())
{
l.folderStatusChanged(account, remoteFolder.getName(), unreadMessageCount);
}
}
catch (Exception e)
{
String rootMessage = getRootCauseMessage(e);
String errorMessage = "Push failed: " + rootMessage;
try
{
localFolder.setStatus(errorMessage);
}
catch (Exception se)
{
Log.e(K9.LOG_TAG, "Unable to set failed status on localFolder", se);
}
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxFailed(account, remoteFolder.getName(), errorMessage);
}
addErrorMessage(account, null, e);
}
finally
{
if (localFolder != null)
{
try
{
localFolder.close();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to close localFolder", e);
}
}
latch.countDown();
}
}
});
try
{
latch.await();
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Interrupted while awaiting latch release", e);
}
if (K9.DEBUG)
Log.i(K9.LOG_TAG, "MessagingController.messagesArrivedLatch released");
}
enum MemorizingState { STARTED, FINISHED, FAILED };
class Memory
{
Account account;
String folderName;
MemorizingState syncingState = null;
MemorizingState sendingState = null;
MemorizingState pushingState = null;
MemorizingState processingState = null;
String failureMessage = null;
int syncingTotalMessagesInMailbox;
int syncingNumNewMessages;
int folderCompleted = 0;
int folderTotal = 0;
String processingCommandTitle = null;
Memory(Account nAccount, String nFolderName)
{
account = nAccount;
folderName = nFolderName;
}
String getKey()
{
return getMemoryKey(account, folderName);
}
}
static String getMemoryKey(Account taccount, String tfolderName)
{
return taccount.getDescription() + ":" + tfolderName;
}
class MemorizingListener extends MessagingListener
{
HashMap<String, Memory> memories = new HashMap<String, Memory>(31);
Memory getMemory(Account account, String folderName)
{
Memory memory = memories.get(getMemoryKey(account, folderName));
if (memory == null)
{
memory = new Memory(account, folderName);
memories.put(memory.getKey(), memory);
}
return memory;
}
@Override
public synchronized void synchronizeMailboxStarted(Account account, String folder)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void synchronizeMailboxFinished(Account account, String folder,
int totalMessagesInMailbox, int numNewMessages)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FINISHED;
memory.syncingTotalMessagesInMailbox = totalMessagesInMailbox;
memory.syncingNumNewMessages = numNewMessages;
}
@Override
public synchronized void synchronizeMailboxFailed(Account account, String folder,
String message)
{
Memory memory = getMemory(account, folder);
memory.syncingState = MemorizingState.FAILED;
memory.failureMessage = message;
}
synchronized void refreshOther(MessagingListener other)
{
if (other != null)
{
Memory syncStarted = null;
Memory sendStarted = null;
Memory processingStarted = null;
for (Memory memory : memories.values())
{
if (memory.syncingState != null)
{
switch (memory.syncingState)
{
case STARTED:
syncStarted = memory;
break;
case FINISHED:
other.synchronizeMailboxFinished(memory.account, memory.folderName,
memory.syncingTotalMessagesInMailbox, memory.syncingNumNewMessages);
break;
case FAILED:
other.synchronizeMailboxFailed(memory.account, memory.folderName,
memory.failureMessage);
break;
}
}
if (memory.sendingState != null)
{
switch (memory.sendingState)
{
case STARTED:
sendStarted = memory;
break;
case FINISHED:
other.sendPendingMessagesCompleted(memory.account);
break;
case FAILED:
other.sendPendingMessagesFailed(memory.account);
break;
}
}
if (memory.pushingState != null)
{
switch (memory.pushingState)
{
case STARTED:
other.setPushActive(memory.account, memory.folderName, true);
break;
case FINISHED:
other.setPushActive(memory.account, memory.folderName, false);
break;
}
}
if (memory.processingState != null)
{
switch (memory.processingState)
{
case STARTED:
processingStarted = memory;
break;
case FINISHED:
case FAILED:
other.pendingCommandsFinished(memory.account);
break;
}
}
}
Memory somethingStarted = null;
if (syncStarted != null)
{
other.synchronizeMailboxStarted(syncStarted.account, syncStarted.folderName);
somethingStarted = syncStarted;
}
if (sendStarted != null)
{
other.sendPendingMessagesStarted(sendStarted.account);
somethingStarted = sendStarted;
}
if (processingStarted != null)
{
other.pendingCommandsProcessing(processingStarted.account);
if (processingStarted.processingCommandTitle != null)
{
other.pendingCommandStarted(processingStarted.account, processingStarted.processingCommandTitle);
}
else
{
other.pendingCommandCompleted(processingStarted.account, processingStarted.processingCommandTitle);
}
somethingStarted = processingStarted;
}
if (somethingStarted != null && somethingStarted.folderTotal > 0)
{
other.synchronizeMailboxProgress(somethingStarted.account, somethingStarted.folderName, somethingStarted.folderCompleted, somethingStarted.folderTotal);
}
}
}
@Override
public synchronized void setPushActive(Account account, String folderName, boolean active)
{
Memory memory = getMemory(account, folderName);
memory.pushingState = (active ? MemorizingState.STARTED : MemorizingState.FINISHED);
}
@Override
public synchronized void sendPendingMessagesStarted(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void sendPendingMessagesCompleted(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FINISHED;
}
@Override
public synchronized void sendPendingMessagesFailed(Account account)
{
Memory memory = getMemory(account, null);
memory.sendingState = MemorizingState.FAILED;
}
@Override
public synchronized void synchronizeMailboxProgress(Account account, String folderName, int completed, int total)
{
Memory memory = getMemory(account, folderName);
memory.folderCompleted = completed;
memory.folderTotal = total;
}
@Override
public synchronized void pendingCommandsProcessing(Account account)
{
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.STARTED;
memory.folderCompleted = 0;
memory.folderTotal = 0;
}
@Override
public synchronized void pendingCommandsFinished(Account account)
{
Memory memory = getMemory(account, null);
memory.processingState = MemorizingState.FINISHED;
}
@Override
public synchronized void pendingCommandStarted(Account account, String commandTitle)
{
Memory memory = getMemory(account, null);
memory.processingCommandTitle = commandTitle;
}
@Override
public synchronized void pendingCommandCompleted(Account account, String commandTitle)
{
Memory memory = getMemory(account, null);
memory.processingCommandTitle = null;
}
}
private void actOnMessages(Message[] messages, MessageActor actor)
{
Map<Account, Map<Folder, List<Message>>> accountMap = new HashMap<Account, Map<Folder, List<Message>>>();
for (Message message : messages)
{
Folder folder = message.getFolder();
Account account = folder.getAccount();
Map<Folder, List<Message>> folderMap = accountMap.get(account);
if (folderMap == null)
{
folderMap = new HashMap<Folder, List<Message>>();
accountMap.put(account, folderMap);
}
List<Message> messageList = folderMap.get(folder);
if (messageList == null)
{
messageList = new LinkedList<Message>();
folderMap.put(folder, messageList);
}
messageList.add(message);
}
for (Map.Entry<Account, Map<Folder, List<Message>>> entry : accountMap.entrySet())
{
Account account = entry.getKey();
//account.refresh(Preferences.getPreferences(K9.app));
Map<Folder, List<Message>> folderMap = entry.getValue();
for (Map.Entry<Folder, List<Message>> folderEntry : folderMap.entrySet())
{
Folder folder = folderEntry.getKey();
List<Message> messageList = folderEntry.getValue();
actor.act(account, folder, messageList);
}
}
}
interface MessageActor
{
public void act(final Account account, final Folder folder, final List<Message> messages);
}
}
| false | true | private int downloadMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException
{
final Date earliestDate = account.getEarliestPollDate();
if (earliestDate != null)
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate);
}
}
final String folder = remoteFolder.getName();
ArrayList<Message> syncFlagMessages = new ArrayList<Message>();
List<Message> unsyncedMessages = new ArrayList<Message>();
final AtomicInteger newMessages = new AtomicInteger(0);
List<Message> messages = new ArrayList<Message>(inputMessages);
for (Message message : messages)
{
if (message.isSet(Flag.DELETED))
{
syncFlagMessages.add(message);
}
else if (isMessageSuppressed(account, folder, message) == false)
{
Message localMessage = localFolder.getMessage(message.getUid());
if (localMessage == null)
{
if (!flagSyncOnly)
{
if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is not downloaded at all");
unsyncedMessages.add(message);
}
else
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded");
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL));
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL));
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
}
else if (localMessage.isSet(Flag.DELETED) == false)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is already locally present");
if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid()
+ " is not downloaded, even partially; trying again");
unsyncedMessages.add(message);
}
else
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
syncFlagMessages.add(message);
}
}
}
}
final AtomicInteger progress = new AtomicInteger(0);
final int todo = unsyncedMessages.size() + syncFlagMessages.size();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages");
messages.clear();
final ArrayList<Message> largeMessages = new ArrayList<Message>();
final ArrayList<Message> smallMessages = new ArrayList<Message>();
if (unsyncedMessages.size() > 0)
{
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
int visibleLimit = localFolder.getVisibleLimit();
int listSize = unsyncedMessages.size();
if (listSize > visibleLimit)
{
unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize);
}
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags())
{
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to sync " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
if (message.isSet(Flag.DELETED))
{
Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid()
+ " was already deleted on server, skipping");
}
else
{
Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than "
+ earliestDate + ", skipping");
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
return;
}
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE))
{
largeMessages.add(message);
}
else
{
smallMessages.add(message);
}
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null)
{
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false)
{
// Store the new message locally
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
syncFlags(localMessage, message);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message "
+ account + ":" + folder + ":" + message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, null, e);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
// If a message didn't exist, messageFinished won't be called, but we shouldn't try again
// If we got here, nothing failed
for (Message message : unsyncedMessages)
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have "
+ largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages out of "
+ unsyncedMessages.size() + " unsynced messages");
unsyncedMessages.clear();
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
// fp.add(FetchProfile.Item.FLAGS);
// fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
if (isMessageSuppressed(account, folder, message ))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " was suppressed "+
"but just downloaded. "+
"The race condition means we wasted some bandwidth. Oh well.");
}
progress.incrementAndGet();
return;
}
if (message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
progress.incrementAndGet();
return;
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
progress.incrementAndGet();
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
if (!localMessage.isSet(Flag.SEEN))
{
// Send a notification of this message
if (notifyAccount(mApplication, account, message) == true)
{
newMessages.incrementAndGet();
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
smallMessages.clear();
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages)
{
if (message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
progress.incrementAndGet();
continue;
}
if (message.getBody() == null)
{
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Certain (POP3) servers give you the whole message even when you ask for only the first x Kb
if (!message.isSet(Flag.X_DOWNLOADED_FULL))
{
/*
* Mark the message as fully downloaded if the message size is smaller than
* the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE)
{
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
else
{
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
}
}
else
{
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables)
{
remoteFolder.fetchPart(message, part, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
progress.incrementAndGet();
Message localMessage = localFolder.getMessage(message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
if (!localMessage.isSet(Flag.SEEN))
{
// Send a notification of this message
if (notifyAccount(mApplication, account, message) == true)
{
newMessages.incrementAndGet();
}
}
}//for large messsages
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
largeMessages.clear();
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
if (remoteFolder.supportsFetchingFlags())
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to sync flags for "
+ syncFlagMessages.size() + " remote messages for folder " + folder);
fp.clear();
fp.add(FetchProfile.Item.FLAGS);
List<Message> undeletedMessages = new LinkedList<Message>();
for (Message message : syncFlagMessages)
{
if (message.isSet(Flag.DELETED) == false)
{
undeletedMessages.add(message);
}
}
remoteFolder.fetch(undeletedMessages.toArray(new Message[0]), fp, null);
for (Message remoteMessage : syncFlagMessages)
{
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
boolean messageChanged = syncFlags(localMessage, remoteMessage);
if (messageChanged)
{
if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
else
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages");
localFolder.purgeToVisibleLimit(new MessageRemovalListener()
{
public void messageRemoved(Message message)
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, message);
}
}
});
return newMessages.get();
}
| private int downloadMessages(final Account account, final Folder remoteFolder,
final LocalFolder localFolder, List<Message> inputMessages, boolean flagSyncOnly) throws MessagingException
{
final Date earliestDate = account.getEarliestPollDate();
if (earliestDate != null)
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Only syncing messages after " + earliestDate);
}
}
final String folder = remoteFolder.getName();
ArrayList<Message> syncFlagMessages = new ArrayList<Message>();
List<Message> unsyncedMessages = new ArrayList<Message>();
final AtomicInteger newMessages = new AtomicInteger(0);
List<Message> messages = new ArrayList<Message>(inputMessages);
for (Message message : messages)
{
if (message.isSet(Flag.DELETED))
{
syncFlagMessages.add(message);
}
else if (isMessageSuppressed(account, folder, message) == false)
{
Message localMessage = localFolder.getMessage(message.getUid());
if (localMessage == null)
{
if (!flagSyncOnly)
{
if (!message.isSet(Flag.X_DOWNLOADED_FULL) && !message.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " has not yet been downloaded");
unsyncedMessages.add(message);
}
else
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is partially or fully downloaded");
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
localMessage = localFolder.getMessage(message.getUid());
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, message.isSet(Flag.X_DOWNLOADED_FULL));
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, message.isSet(Flag.X_DOWNLOADED_PARTIAL));
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
}
}
}
else if (localMessage.isSet(Flag.DELETED) == false)
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid() + " is present in the local store");
if (!localMessage.isSet(Flag.X_DOWNLOADED_FULL) && !localMessage.isSet(Flag.X_DOWNLOADED_PARTIAL))
{
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "Message with uid " + message.getUid()
+ " is not downloaded, even partially; trying again");
unsyncedMessages.add(message);
}
else
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
syncFlagMessages.add(message);
}
}
}
}
final AtomicInteger progress = new AtomicInteger(0);
final int todo = unsyncedMessages.size() + syncFlagMessages.size();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have " + unsyncedMessages.size() + " unsynced messages");
messages.clear();
final ArrayList<Message> largeMessages = new ArrayList<Message>();
final ArrayList<Message> smallMessages = new ArrayList<Message>();
if (unsyncedMessages.size() > 0)
{
/*
* Reverse the order of the messages. Depending on the server this may get us
* fetch results for newest to oldest. If not, no harm done.
*/
Collections.reverse(unsyncedMessages);
int visibleLimit = localFolder.getVisibleLimit();
int listSize = unsyncedMessages.size();
if (listSize > visibleLimit)
{
unsyncedMessages = unsyncedMessages.subList(listSize - visibleLimit, listSize);
}
FetchProfile fp = new FetchProfile();
if (remoteFolder.supportsFetchingFlags())
{
fp.add(FetchProfile.Item.FLAGS);
}
fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to fetch " + unsyncedMessages.size() + " unsynced messages for folder " + folder);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
if (message.isSet(Flag.DELETED))
{
Log.v(K9.LOG_TAG, "Newly downloaded message " + account + ":" + folder + ":" + message.getUid()
+ " was marked deleted on server, skipping");
}
else
{
Log.d(K9.LOG_TAG, "Newly downloaded message " + message.getUid() + " is older than "
+ earliestDate + ", skipping");
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
return;
}
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE))
{
largeMessages.add(message);
}
else
{
smallMessages.add(message);
}
// And include it in the view
if (message.getSubject() != null &&
message.getFrom() != null)
{
/*
* We check to make sure that we got something worth
* showing (subject and from) because some protocols
* (POP) may not be able to give us headers for
* ENVELOPE, only size.
*/
if (isMessageSuppressed(account, folder, message) == false)
{
// Store the new message locally
localFolder.appendMessages(new Message[]
{
message
});
Message localMessage = localFolder.getMessage(message.getUid());
syncFlags(localMessage, message);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new unsynced message "
+ account + ":" + folder + ":" + message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Error while storing downloaded message.", e);
addErrorMessage(account, null, e);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
// If a message didn't exist, messageFinished won't be called, but we shouldn't try again
// If we got here, nothing failed
for (Message message : unsyncedMessages)
{
String newPushState = remoteFolder.getNewPushState(localFolder.getPushState(), message);
if (newPushState != null)
{
localFolder.setPushState(newPushState);
}
}
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "SYNC: Synced unsynced messages for folder " + folder);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Have "
+ largeMessages.size() + " large messages and "
+ smallMessages.size() + " small messages out of "
+ unsyncedMessages.size() + " unsynced messages");
unsyncedMessages.clear();
/*
* Grab the content of the small messages first. This is going to
* be very fast and at very worst will be a single up of a few bytes and a single
* download of 625k.
*/
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
// fp.add(FetchProfile.Item.FLAGS);
// fp.add(FetchProfile.Item.ENVELOPE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching small messages for folder " + folder);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]),
fp, new MessageRetrievalListener()
{
public void messageFinished(Message message, int number, int ofTotal)
{
try
{
if (isMessageSuppressed(account, folder, message ))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " was suppressed "+
"but just downloaded. "+
"The race condition means we wasted some bandwidth. Oh well.");
}
progress.incrementAndGet();
return;
}
if (message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
progress.incrementAndGet();
return;
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
progress.incrementAndGet();
// Set a flag indicating this message has now be fully downloaded
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new small message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
if (!localMessage.isSet(Flag.SEEN))
{
// Send a notification of this message
if (notifyAccount(mApplication, account, message) == true)
{
newMessages.incrementAndGet();
}
}
}
catch (MessagingException me)
{
addErrorMessage(account, null, me);
Log.e(K9.LOG_TAG, "SYNC: fetch small messages", me);
}
}
public void messageStarted(String uid, int number, int ofTotal)
{
}
public void messagesFinished(int total) {}
});
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching small messages for folder " + folder);
smallMessages.clear();
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Fetching large messages for folder " + folder);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages)
{
if (message.olderThan(earliestDate))
{
if (K9.DEBUG)
{
Log.d(K9.LOG_TAG, "Message " + message.getUid() + " is older than "
+ earliestDate + ", hence not saving");
}
progress.incrementAndGet();
continue;
}
if (message.getBody() == null)
{
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Certain (POP3) servers give you the whole message even when you ask for only the first x Kb
if (!message.isSet(Flag.X_DOWNLOADED_FULL))
{
/*
* Mark the message as fully downloaded if the message size is smaller than
* the FETCH_BODY_SANE_SUGGESTED_SIZE, otherwise mark as only a partial
* download. This will prevent the system from downloading the same message
* twice.
*/
if (message.getSize() < Store.FETCH_BODY_SANE_SUGGESTED_SIZE)
{
localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
else
{
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
}
}
else
{
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables)
{
remoteFolder.fetchPart(message, part, null);
}
// Store the updated message locally
localFolder.appendMessages(new Message[] { message });
Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
}
if (K9.DEBUG)
Log.v(K9.LOG_TAG, "About to notify listeners that we got a new large message "
+ account + ":" + folder + ":" + message.getUid());
// Update the listener with what we've found
progress.incrementAndGet();
Message localMessage = localFolder.getMessage(message.getUid());
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
if (!localMessage.isSet(Flag.SEEN))
{
l.synchronizeMailboxNewMessage(account, folder, localMessage);
}
}
if (!localMessage.isSet(Flag.SEEN))
{
// Send a notification of this message
if (notifyAccount(mApplication, account, message) == true)
{
newMessages.incrementAndGet();
}
}
}//for large messsages
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Done fetching large messages for folder " + folder);
largeMessages.clear();
/*
* Refresh the flags for any messages in the local store that we didn't just
* download.
*/
if (remoteFolder.supportsFetchingFlags())
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: About to sync flags for "
+ syncFlagMessages.size() + " remote messages for folder " + folder);
fp.clear();
fp.add(FetchProfile.Item.FLAGS);
List<Message> undeletedMessages = new LinkedList<Message>();
for (Message message : syncFlagMessages)
{
if (message.isSet(Flag.DELETED) == false)
{
undeletedMessages.add(message);
}
}
remoteFolder.fetch(undeletedMessages.toArray(new Message[0]), fp, null);
for (Message remoteMessage : syncFlagMessages)
{
Message localMessage = localFolder.getMessage(remoteMessage.getUid());
boolean messageChanged = syncFlags(localMessage, remoteMessage);
if (messageChanged)
{
if (localMessage.isSet(Flag.DELETED) || isMessageSuppressed(account, folder, localMessage))
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, localMessage);
}
}
else
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxAddOrUpdateMessage(account, folder, localMessage);
}
}
}
progress.incrementAndGet();
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxProgress(account, folder, progress.get(), todo);
}
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "SYNC: Synced remote messages for folder " + folder + ", " + newMessages.get() + " new messages");
localFolder.purgeToVisibleLimit(new MessageRemovalListener()
{
public void messageRemoved(Message message)
{
for (MessagingListener l : getListeners())
{
l.synchronizeMailboxRemovedMessage(account, folder, message);
}
}
});
return newMessages.get();
}
|
diff --git a/jlv-eclipse-plugin/jlv-plugin/src/com/rdiachenko/jlv/model/LogField.java b/jlv-eclipse-plugin/jlv-plugin/src/com/rdiachenko/jlv/model/LogField.java
index 8847f35..165286a 100644
--- a/jlv-eclipse-plugin/jlv-plugin/src/com/rdiachenko/jlv/model/LogField.java
+++ b/jlv-eclipse-plugin/jlv-plugin/src/com/rdiachenko/jlv/model/LogField.java
@@ -1,52 +1,52 @@
package com.rdiachenko.jlv.model;
import com.rdiachenko.jlv.log4j.domain.Log;
public enum LogField {
LEVEL("Level"),
CATEGORY("Category"),
MESSAGE("Message"),
LINE("Line"),
DATE("Date"),
THROWABLE("Throwable");
private String name;
private LogField(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getValue(Log log) {
String value = "";
switch (this) {
case LEVEL:
value = log.getLevel();
break;
case CATEGORY:
value = log.getCategoryName();
break;
case MESSAGE:
value = log.getMessage();
break;
case LINE:
value = log.getLineNumber();
break;
case DATE:
value = log.getDate();
break;
case THROWABLE:
value = log.getThrowable();
break;
default:
- throw new IllegalStateException("Only [LEVEL,CATEGORY,MESSAGE,LINE,DATE] log fields are available. "
+ throw new IllegalStateException("Only [LEVEL,CATEGORY,MESSAGE,LINE,DATE,THROWABLE] log fields are available. "
+ "Current value: " + this);
}
return value;
}
}
| true | true | public String getValue(Log log) {
String value = "";
switch (this) {
case LEVEL:
value = log.getLevel();
break;
case CATEGORY:
value = log.getCategoryName();
break;
case MESSAGE:
value = log.getMessage();
break;
case LINE:
value = log.getLineNumber();
break;
case DATE:
value = log.getDate();
break;
case THROWABLE:
value = log.getThrowable();
break;
default:
throw new IllegalStateException("Only [LEVEL,CATEGORY,MESSAGE,LINE,DATE] log fields are available. "
+ "Current value: " + this);
}
return value;
}
| public String getValue(Log log) {
String value = "";
switch (this) {
case LEVEL:
value = log.getLevel();
break;
case CATEGORY:
value = log.getCategoryName();
break;
case MESSAGE:
value = log.getMessage();
break;
case LINE:
value = log.getLineNumber();
break;
case DATE:
value = log.getDate();
break;
case THROWABLE:
value = log.getThrowable();
break;
default:
throw new IllegalStateException("Only [LEVEL,CATEGORY,MESSAGE,LINE,DATE,THROWABLE] log fields are available. "
+ "Current value: " + this);
}
return value;
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/handler/ContentMRUContribution.java b/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/handler/ContentMRUContribution.java
index 3ce54a9b0..f44552d42 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/handler/ContentMRUContribution.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/handler/ContentMRUContribution.java
@@ -1,97 +1,99 @@
/*******************************************************************************
* Copyright (c) 2012 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.tcf.te.ui.views.handler;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.tcf.te.ui.views.ViewsUtil;
import org.eclipse.tcf.te.ui.views.interfaces.IUIConstants;
import org.eclipse.tcf.te.ui.views.internal.preferences.IPreferenceKeys;
import org.eclipse.ui.actions.CompoundContributionItem;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.INavigatorContentDescriptor;
import org.eclipse.ui.navigator.INavigatorContentService;
/**
* The dynamic contribution of content extension MRU menu list.
*/
public class ContentMRUContribution extends CompoundContributionItem {
/**
* A MRU item action to enable or disable specified content extension.
*/
static class ContentMRUAction extends Action {
// The content service of the navigator.
private INavigatorContentService contentService;
// The content extension descriptor to be configured by this action.
private INavigatorContentDescriptor contentDescriptor;
// The common viewer of the navigator.
private CommonViewer commonViewer;
/**
* Constructor
*/
public ContentMRUAction(int order, INavigatorContentDescriptor contentDescriptor, INavigatorContentService contentService, CommonViewer commonViewer) {
super("" + order + " " + contentDescriptor.getName(), AS_CHECK_BOX); //$NON-NLS-1$//$NON-NLS-2$
this.contentDescriptor = contentDescriptor;
this.contentService = contentService;
this.commonViewer = commonViewer;
setChecked(contentService.isActive(contentDescriptor.getId()));
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
Set<String> activeIds = new HashSet<String>();
String[] visibleIds = contentService.getVisibleExtensionIds();
if (visibleIds != null) {
for (String visibleId : visibleIds) {
if (contentService.isActive(visibleId)) activeIds.add(visibleId);
}
}
if (isChecked()) activeIds.add(contentDescriptor.getId());
else activeIds.remove(contentDescriptor.getId());
String[] idsToActivate = activeIds.toArray(new String[activeIds.size()]);
UpdateActiveExtensionsOperation updateExtensions = new UpdateActiveExtensionsOperation(commonViewer, idsToActivate);
updateExtensions.execute(null, null);
}
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.actions.CompoundContributionItem#getContributionItems()
*/
@Override
protected IContributionItem[] getContributionItems() {
CommonNavigator navigator = (CommonNavigator) ViewsUtil.getPart(IUIConstants.ID_EXPLORER);
if (navigator == null) return new IContributionItem[0];
INavigatorContentService contentService = navigator.getNavigatorContentService();
List<IContributionItem> items = new ArrayList<IContributionItem>();
List<String> extensionSet = new MRUList(IPreferenceKeys.PREF_CONTENT_MRU_LIST);
CommonViewer commonViewer = navigator.getCommonViewer();
for (int i = 0; i < extensionSet.size(); i++) {
String extensionId = extensionSet.get(i);
INavigatorContentDescriptor contentDescriptor = contentService.getContentDescriptorById(extensionId);
- items.add(new ActionContributionItem(new ContentMRUAction((i + 1), contentDescriptor, contentService, commonViewer)));
+ if (contentDescriptor != null) {
+ items.add(new ActionContributionItem(new ContentMRUAction((i + 1), contentDescriptor, contentService, commonViewer)));
+ }
}
return items.toArray(new IContributionItem[items.size()]);
}
}
| true | true | protected IContributionItem[] getContributionItems() {
CommonNavigator navigator = (CommonNavigator) ViewsUtil.getPart(IUIConstants.ID_EXPLORER);
if (navigator == null) return new IContributionItem[0];
INavigatorContentService contentService = navigator.getNavigatorContentService();
List<IContributionItem> items = new ArrayList<IContributionItem>();
List<String> extensionSet = new MRUList(IPreferenceKeys.PREF_CONTENT_MRU_LIST);
CommonViewer commonViewer = navigator.getCommonViewer();
for (int i = 0; i < extensionSet.size(); i++) {
String extensionId = extensionSet.get(i);
INavigatorContentDescriptor contentDescriptor = contentService.getContentDescriptorById(extensionId);
items.add(new ActionContributionItem(new ContentMRUAction((i + 1), contentDescriptor, contentService, commonViewer)));
}
return items.toArray(new IContributionItem[items.size()]);
}
| protected IContributionItem[] getContributionItems() {
CommonNavigator navigator = (CommonNavigator) ViewsUtil.getPart(IUIConstants.ID_EXPLORER);
if (navigator == null) return new IContributionItem[0];
INavigatorContentService contentService = navigator.getNavigatorContentService();
List<IContributionItem> items = new ArrayList<IContributionItem>();
List<String> extensionSet = new MRUList(IPreferenceKeys.PREF_CONTENT_MRU_LIST);
CommonViewer commonViewer = navigator.getCommonViewer();
for (int i = 0; i < extensionSet.size(); i++) {
String extensionId = extensionSet.get(i);
INavigatorContentDescriptor contentDescriptor = contentService.getContentDescriptorById(extensionId);
if (contentDescriptor != null) {
items.add(new ActionContributionItem(new ContentMRUAction((i + 1), contentDescriptor, contentService, commonViewer)));
}
}
return items.toArray(new IContributionItem[items.size()]);
}
|
diff --git a/src/main/java/de/cismet/tools/gui/downloadmanager/AbstractDownload.java b/src/main/java/de/cismet/tools/gui/downloadmanager/AbstractDownload.java
index 1a4932d..05fa80f 100644
--- a/src/main/java/de/cismet/tools/gui/downloadmanager/AbstractDownload.java
+++ b/src/main/java/de/cismet/tools/gui/downloadmanager/AbstractDownload.java
@@ -1,279 +1,279 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* Copyright (C) 2011 jweintraut
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.cismet.tools.gui.downloadmanager;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Observable;
import javax.swing.JPanel;
import de.cismet.tools.CismetThreadPool;
/**
* The objects of this class represent downloads. This class encompasses several default methods which should be the
* same for most download which care about single files.
*
* @author jweintraut
* @version $Revision$, $Date$
*/
public abstract class AbstractDownload extends Observable implements Download, Runnable, Comparable {
//~ Instance fields --------------------------------------------------------
protected String directory;
protected File fileToSaveTo;
protected State status;
protected String title;
protected boolean started = false;
protected Exception caughtException;
protected final Logger log = Logger.getLogger(this.getClass());
//~ Methods ----------------------------------------------------------------
/**
* Returns the title of the download.
*
* @return The title.
*/
@Override
public String getTitle() {
return title;
}
/**
* Returns a file object pointing to the download location of this download.
*
* @return A file object pointing to the download location.
*/
@Override
public File getFileToSaveTo() {
return fileToSaveTo;
}
/**
* Returns the status of this download.
*
* @return The status of this download.
*/
@Override
public State getStatus() {
return status;
}
/**
* Returns the exception which is caught during the download. If an exception occurs the download is aborted.
*
* @return The caught exception.
*/
@Override
public Exception getCaughtException() {
return caughtException;
}
@Override
public int getDownloadsTotal() {
return 1;
}
@Override
public int getDownloadsCompleted() {
if (status == State.RUNNING) {
return 0;
}
return 1;
}
@Override
public int getDownloadsErroneous() {
if (status == State.COMPLETED_WITH_ERROR) {
return 1;
}
return 0;
}
/**
* Logs a caught exception and sets some members accordingly.
*
* @param exception The caught exception.
*/
protected void error(final Exception exception) {
log.error("Exception occurred while downloading '" + fileToSaveTo + "'.", exception);
fileToSaveTo.deleteOnExit();
caughtException = exception;
status = State.COMPLETED_WITH_ERROR;
stateChanged();
}
/**
* Starts a thread which starts the download by starting this Runnable.
*/
@Override
public void startDownload() {
if (!started) {
started = true;
CismetThreadPool.execute(this);
}
}
@Override
public JPanel getExceptionPanel(final Exception exception) {
return null;
}
@Override
public abstract void run();
/**
* Determines the destination file for this download. There exist given parameters like a download destination and a
* pattern for the file name. It's possible that a previous download with equal parameters still exists physically,
* therefore this method adds a counter (2..999) which is appended to the filename.
*
* @param filename The file name for this download.
* @param extension The extension for the downloaded file.
*/
protected void determineDestinationFile(final String filename,
final String extension) {
final File directoryToSaveTo;
if ((directory != null) && (directory.trim().length() > 0)) {
directoryToSaveTo = new File(DownloadManager.instance().getDestinationDirectory(), directory);
} else {
directoryToSaveTo = DownloadManager.instance().getDestinationDirectory();
}
if (log.isDebugEnabled()) {
log.debug("Determined path '" + directoryToSaveTo + "' for file '" + filename + extension + "'.");
}
if (!directoryToSaveTo.exists()) {
if (!directoryToSaveTo.mkdirs()) {
log.error("Couldn't create destination directory '"
+ directoryToSaveTo.getAbsolutePath()
+ "'. Cancelling download.");
error(new Exception(
"Couldn't create destination directory '"
+ directoryToSaveTo.getAbsolutePath()
+ "'. Cancelling download."));
return;
}
}
fileToSaveTo = new File(directoryToSaveTo, filename + extension);
boolean fileFound = false;
int counter = 2;
while (!fileFound) {
while (fileToSaveTo.exists() && (counter < 1000)) {
- fileToSaveTo = new File(directoryToSaveTo, filename + counter + extension);
+ fileToSaveTo = new File(directoryToSaveTo, filename + "(" + counter + ")" + extension);
counter++;
}
try {
fileToSaveTo.createNewFile();
if (fileToSaveTo.exists() && fileToSaveTo.isFile() && fileToSaveTo.canWrite()) {
fileFound = true;
}
} catch (IOException ex) {
log.warn("IOEXception while trying to create destination file '" + fileToSaveTo.getAbsolutePath()
+ "'.",
ex);
fileToSaveTo.deleteOnExit();
}
if ((counter >= 1000) && !fileFound) {
log.error("Could not create a file for the download. The tested path is '"
+ directoryToSaveTo.getAbsolutePath()
+ File.separatorChar
+ filename
+ "<1.."
+ 999
+ ">."
+ extension
+ ".");
error(new FileNotFoundException(
"Could not create a file for the download. The tested path is '"
+ directoryToSaveTo.getAbsolutePath()
+ File.separatorChar
+ filename
+ "<1.."
+ 999
+ ">."
+ extension
+ "."));
return;
}
}
}
/**
* Marks this observable as changed and notifies observers.
*/
protected void stateChanged() {
setChanged();
notifyObservers();
}
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof AbstractDownload)) {
return false;
}
final AbstractDownload other = (AbstractDownload)obj;
boolean result = true;
if ((this.fileToSaveTo == null) ? (other.fileToSaveTo != null)
: (!this.fileToSaveTo.equals(other.fileToSaveTo))) {
result &= false;
}
return result;
}
@Override
public int hashCode() {
int hash = 7;
hash = (43 * hash) + ((this.fileToSaveTo != null) ? this.fileToSaveTo.hashCode() : 0);
return hash;
}
@Override
public int compareTo(final Object o) {
if (!(o instanceof AbstractDownload)) {
return 1;
}
final AbstractDownload other = (AbstractDownload)o;
return this.title.compareTo(other.title);
}
}
| true | true | protected void determineDestinationFile(final String filename,
final String extension) {
final File directoryToSaveTo;
if ((directory != null) && (directory.trim().length() > 0)) {
directoryToSaveTo = new File(DownloadManager.instance().getDestinationDirectory(), directory);
} else {
directoryToSaveTo = DownloadManager.instance().getDestinationDirectory();
}
if (log.isDebugEnabled()) {
log.debug("Determined path '" + directoryToSaveTo + "' for file '" + filename + extension + "'.");
}
if (!directoryToSaveTo.exists()) {
if (!directoryToSaveTo.mkdirs()) {
log.error("Couldn't create destination directory '"
+ directoryToSaveTo.getAbsolutePath()
+ "'. Cancelling download.");
error(new Exception(
"Couldn't create destination directory '"
+ directoryToSaveTo.getAbsolutePath()
+ "'. Cancelling download."));
return;
}
}
fileToSaveTo = new File(directoryToSaveTo, filename + extension);
boolean fileFound = false;
int counter = 2;
while (!fileFound) {
while (fileToSaveTo.exists() && (counter < 1000)) {
fileToSaveTo = new File(directoryToSaveTo, filename + counter + extension);
counter++;
}
try {
fileToSaveTo.createNewFile();
if (fileToSaveTo.exists() && fileToSaveTo.isFile() && fileToSaveTo.canWrite()) {
fileFound = true;
}
} catch (IOException ex) {
log.warn("IOEXception while trying to create destination file '" + fileToSaveTo.getAbsolutePath()
+ "'.",
ex);
fileToSaveTo.deleteOnExit();
}
if ((counter >= 1000) && !fileFound) {
log.error("Could not create a file for the download. The tested path is '"
+ directoryToSaveTo.getAbsolutePath()
+ File.separatorChar
+ filename
+ "<1.."
+ 999
+ ">."
+ extension
+ ".");
error(new FileNotFoundException(
"Could not create a file for the download. The tested path is '"
+ directoryToSaveTo.getAbsolutePath()
+ File.separatorChar
+ filename
+ "<1.."
+ 999
+ ">."
+ extension
+ "."));
return;
}
}
}
| protected void determineDestinationFile(final String filename,
final String extension) {
final File directoryToSaveTo;
if ((directory != null) && (directory.trim().length() > 0)) {
directoryToSaveTo = new File(DownloadManager.instance().getDestinationDirectory(), directory);
} else {
directoryToSaveTo = DownloadManager.instance().getDestinationDirectory();
}
if (log.isDebugEnabled()) {
log.debug("Determined path '" + directoryToSaveTo + "' for file '" + filename + extension + "'.");
}
if (!directoryToSaveTo.exists()) {
if (!directoryToSaveTo.mkdirs()) {
log.error("Couldn't create destination directory '"
+ directoryToSaveTo.getAbsolutePath()
+ "'. Cancelling download.");
error(new Exception(
"Couldn't create destination directory '"
+ directoryToSaveTo.getAbsolutePath()
+ "'. Cancelling download."));
return;
}
}
fileToSaveTo = new File(directoryToSaveTo, filename + extension);
boolean fileFound = false;
int counter = 2;
while (!fileFound) {
while (fileToSaveTo.exists() && (counter < 1000)) {
fileToSaveTo = new File(directoryToSaveTo, filename + "(" + counter + ")" + extension);
counter++;
}
try {
fileToSaveTo.createNewFile();
if (fileToSaveTo.exists() && fileToSaveTo.isFile() && fileToSaveTo.canWrite()) {
fileFound = true;
}
} catch (IOException ex) {
log.warn("IOEXception while trying to create destination file '" + fileToSaveTo.getAbsolutePath()
+ "'.",
ex);
fileToSaveTo.deleteOnExit();
}
if ((counter >= 1000) && !fileFound) {
log.error("Could not create a file for the download. The tested path is '"
+ directoryToSaveTo.getAbsolutePath()
+ File.separatorChar
+ filename
+ "<1.."
+ 999
+ ">."
+ extension
+ ".");
error(new FileNotFoundException(
"Could not create a file for the download. The tested path is '"
+ directoryToSaveTo.getAbsolutePath()
+ File.separatorChar
+ filename
+ "<1.."
+ 999
+ ">."
+ extension
+ "."));
return;
}
}
}
|
diff --git a/geoserver/wms/src/main/java/org/geoserver/wms/kvp/LayersKvpParser.java b/geoserver/wms/src/main/java/org/geoserver/wms/kvp/LayersKvpParser.java
index 43e5c290b5..adde57595a 100644
--- a/geoserver/wms/src/main/java/org/geoserver/wms/kvp/LayersKvpParser.java
+++ b/geoserver/wms/src/main/java/org/geoserver/wms/kvp/LayersKvpParser.java
@@ -1,159 +1,165 @@
/* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.geoserver.wms.kvp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.geoserver.ows.FlatKvpParser;
import org.vfny.geoserver.global.CoverageInfo;
import org.vfny.geoserver.global.Data;
import org.vfny.geoserver.global.FeatureTypeInfo;
import org.vfny.geoserver.global.MapLayerInfo;
import org.vfny.geoserver.global.WMS;
import org.vfny.geoserver.wms.WmsException;
public class LayersKvpParser extends FlatKvpParser {
Data catalog;
private WMS wms;
public LayersKvpParser(WMS wms) {
super("layers", MapLayerInfo.class);
this.wms = wms;
this.catalog = wms.getData();
}
protected Object parse(List values) throws Exception {
MapLayerInfo[] layers;
List layerNames = values;
List realLayerNames = new ArrayList();
String layerName = null;
int l_counter = 0;
////
// Expand the eventually WMS grouped layers into the same WMS Path element
////
for (Iterator it = layerNames.iterator(); it.hasNext();) {
layerName = (String) it.next();
Integer layerType = catalog.getLayerType(layerName);
if (layerType == null) {
+ boolean found = false;
if(wms.getBaseMapLayers().containsKey(layerName)) {
realLayerNames.add(layerName);
+ found = true;
l_counter++;
} else {
////
// Search for grouped layers (attention: heavy process)
////
String catalogLayerName = null;
for (Iterator c_keys = catalog.getLayerNames().iterator(); c_keys.hasNext();) {
catalogLayerName = (String) c_keys.next();
try {
FeatureTypeInfo ftype = findFeatureLayer(catalogLayerName);
String wmsPath = ftype.getWmsPath();
if ((wmsPath != null) && wmsPath.matches(".*/" + layerName)) {
realLayerNames.add(catalogLayerName);
+ found = true;
l_counter++;
}
- } catch (WmsException e_1) {
+ } catch (Exception e_1) {
try {
CoverageInfo cv = findCoverageLayer(catalogLayerName);
String wmsPath = cv.getWmsPath();
if ((wmsPath != null) && wmsPath.matches(".*/" + layerName)) {
realLayerNames.add(catalogLayerName);
+ found = true;
l_counter++;
}
- } catch (WmsException e_2) {
+ } catch (Exception e_2) {
}
}
}
}
+ if(!found)
+ throw new WmsException("Could not find layer " + layerName);
} else {
realLayerNames.add(layerName);
l_counter++;
}
}
int layerCount = realLayerNames.size();
if (layerCount == 0) {
throw new WmsException("No LAYERS has been requested", getClass().getName());
}
layers = new MapLayerInfo[layerCount];
for (int i = 0; i < layerCount; i++) {
layerName = (String) layerNames.get(i);
layers[i] = buildMapLayerInfo(layerName);
}
return layers;
}
private MapLayerInfo buildMapLayerInfo(String layerName) throws Exception {
MapLayerInfo li = new MapLayerInfo();
FeatureTypeInfo ftype = findFeatureLayer(layerName);
if (ftype != null) {
li.setFeature(ftype);
} else {
CoverageInfo cv = findCoverageLayer(layerName);
if (cv != null) {
li.setCoverage(cv);
} else {
if (wms.getBaseMapLayers().containsKey(layerName)) {
String styleCsl = (String) wms.getBaseMapStyles().get(layerName);
String layerCsl = (String) wms.getBaseMapLayers().get(layerName);
LayersKvpParser lparser = new LayersKvpParser(wms);
StylesKvpParser sparser = new StylesKvpParser(wms.getData());
MapLayerInfo[] layerArray = (MapLayerInfo[]) lparser.parse(layerCsl);
List styleList = (List) sparser.parse(styleCsl);
li.setBase(layerName, new ArrayList(Arrays.asList(layerArray)), styleList);
} else {
throw new WmsException("Layer " + layerName + " could not be found");
}
}
}
return li;
}
FeatureTypeInfo findFeatureLayer(String layerName)
throws WmsException {
FeatureTypeInfo ftype = null;
Integer layerType = catalog.getLayerType(layerName);
if (Data.TYPE_VECTOR != layerType) {
return null;
} else {
ftype = catalog.getFeatureTypeInfo(layerName);
}
return ftype;
}
CoverageInfo findCoverageLayer(String layerName) throws WmsException {
CoverageInfo cv = null;
Integer layerType = catalog.getLayerType(layerName);
if (Data.TYPE_RASTER != layerType) {
return null;
} else {
cv = catalog.getCoverageInfo(layerName);
}
return cv;
}
}
| false | true | protected Object parse(List values) throws Exception {
MapLayerInfo[] layers;
List layerNames = values;
List realLayerNames = new ArrayList();
String layerName = null;
int l_counter = 0;
////
// Expand the eventually WMS grouped layers into the same WMS Path element
////
for (Iterator it = layerNames.iterator(); it.hasNext();) {
layerName = (String) it.next();
Integer layerType = catalog.getLayerType(layerName);
if (layerType == null) {
if(wms.getBaseMapLayers().containsKey(layerName)) {
realLayerNames.add(layerName);
l_counter++;
} else {
////
// Search for grouped layers (attention: heavy process)
////
String catalogLayerName = null;
for (Iterator c_keys = catalog.getLayerNames().iterator(); c_keys.hasNext();) {
catalogLayerName = (String) c_keys.next();
try {
FeatureTypeInfo ftype = findFeatureLayer(catalogLayerName);
String wmsPath = ftype.getWmsPath();
if ((wmsPath != null) && wmsPath.matches(".*/" + layerName)) {
realLayerNames.add(catalogLayerName);
l_counter++;
}
} catch (WmsException e_1) {
try {
CoverageInfo cv = findCoverageLayer(catalogLayerName);
String wmsPath = cv.getWmsPath();
if ((wmsPath != null) && wmsPath.matches(".*/" + layerName)) {
realLayerNames.add(catalogLayerName);
l_counter++;
}
} catch (WmsException e_2) {
}
}
}
}
} else {
realLayerNames.add(layerName);
l_counter++;
}
}
int layerCount = realLayerNames.size();
if (layerCount == 0) {
throw new WmsException("No LAYERS has been requested", getClass().getName());
}
layers = new MapLayerInfo[layerCount];
for (int i = 0; i < layerCount; i++) {
layerName = (String) layerNames.get(i);
layers[i] = buildMapLayerInfo(layerName);
}
return layers;
}
| protected Object parse(List values) throws Exception {
MapLayerInfo[] layers;
List layerNames = values;
List realLayerNames = new ArrayList();
String layerName = null;
int l_counter = 0;
////
// Expand the eventually WMS grouped layers into the same WMS Path element
////
for (Iterator it = layerNames.iterator(); it.hasNext();) {
layerName = (String) it.next();
Integer layerType = catalog.getLayerType(layerName);
if (layerType == null) {
boolean found = false;
if(wms.getBaseMapLayers().containsKey(layerName)) {
realLayerNames.add(layerName);
found = true;
l_counter++;
} else {
////
// Search for grouped layers (attention: heavy process)
////
String catalogLayerName = null;
for (Iterator c_keys = catalog.getLayerNames().iterator(); c_keys.hasNext();) {
catalogLayerName = (String) c_keys.next();
try {
FeatureTypeInfo ftype = findFeatureLayer(catalogLayerName);
String wmsPath = ftype.getWmsPath();
if ((wmsPath != null) && wmsPath.matches(".*/" + layerName)) {
realLayerNames.add(catalogLayerName);
found = true;
l_counter++;
}
} catch (Exception e_1) {
try {
CoverageInfo cv = findCoverageLayer(catalogLayerName);
String wmsPath = cv.getWmsPath();
if ((wmsPath != null) && wmsPath.matches(".*/" + layerName)) {
realLayerNames.add(catalogLayerName);
found = true;
l_counter++;
}
} catch (Exception e_2) {
}
}
}
}
if(!found)
throw new WmsException("Could not find layer " + layerName);
} else {
realLayerNames.add(layerName);
l_counter++;
}
}
int layerCount = realLayerNames.size();
if (layerCount == 0) {
throw new WmsException("No LAYERS has been requested", getClass().getName());
}
layers = new MapLayerInfo[layerCount];
for (int i = 0; i < layerCount; i++) {
layerName = (String) layerNames.get(i);
layers[i] = buildMapLayerInfo(layerName);
}
return layers;
}
|
diff --git a/src/mulan/transformations/RemoveAllLabels.java b/src/mulan/transformations/RemoveAllLabels.java
index faa8801..f142d5c 100644
--- a/src/mulan/transformations/RemoveAllLabels.java
+++ b/src/mulan/transformations/RemoveAllLabels.java
@@ -1,79 +1,77 @@
/*
* 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.
*/
/*
* RemoveAllLabels.java
* Copyright (C) 2009-2010 Aristotle University of Thessaloniki, Thessaloniki, Greece
*/
package mulan.transformations;
import mulan.data.MultiLabelInstances;
import mulan.data.DataUtils;
import weka.core.Instance;
import weka.core.Instances;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Remove;
/**
*
* @author Stavros Mpakirtzoglou
* @author Grigorios Tsoumakas
*/
public class RemoveAllLabels {
public static Instances transformInstances(MultiLabelInstances mlData) throws Exception {
Instances result;
result = transformInstances(mlData.getDataSet(), mlData.getLabelIndices());
return result;
}
public static Instances transformInstances(Instances dataSet, int[] labelIndices) throws Exception {
Remove remove = new Remove();
remove.setAttributeIndicesArray(labelIndices);
remove.setInputFormat(dataSet);
Instances result = Filter.useFilter(dataSet, remove);
return result;
}
public static Instance transformInstance(Instance instance, int[] labelIndices) {
double[] oldValues = instance.toDoubleArray();
double[] newValues = new double[oldValues.length - labelIndices.length];
int counter1 = 0;
int counter2 = 0;
for (int i = 0; i < oldValues.length; i++) {
- if (i == labelIndices[counter1]) {
- counter1++;
- if (counter1 == labelIndices.length)
- break;
- else
+ if (counter1 < labelIndices.length)
+ if (i == labelIndices[counter1]) {
+ counter1++;
continue;
- }
+ }
newValues[counter2] = oldValues[i];
counter2++;
}
return DataUtils.createInstance(instance, instance.weight(), newValues);
}
/*
public static Instance transformInstance(Instance instance, int[] labelIndices) throws Exception
{
Remove remove = new Remove();
remove.setAttributeIndicesArray(labelIndices);
remove.setInputFormat(instance.dataset());
remove.input(instance);
remove.batchFinished();
return remove.output();
}*/
}
| false | true | public static Instance transformInstance(Instance instance, int[] labelIndices) {
double[] oldValues = instance.toDoubleArray();
double[] newValues = new double[oldValues.length - labelIndices.length];
int counter1 = 0;
int counter2 = 0;
for (int i = 0; i < oldValues.length; i++) {
if (i == labelIndices[counter1]) {
counter1++;
if (counter1 == labelIndices.length)
break;
else
continue;
}
newValues[counter2] = oldValues[i];
counter2++;
}
return DataUtils.createInstance(instance, instance.weight(), newValues);
}
| public static Instance transformInstance(Instance instance, int[] labelIndices) {
double[] oldValues = instance.toDoubleArray();
double[] newValues = new double[oldValues.length - labelIndices.length];
int counter1 = 0;
int counter2 = 0;
for (int i = 0; i < oldValues.length; i++) {
if (counter1 < labelIndices.length)
if (i == labelIndices[counter1]) {
counter1++;
continue;
}
newValues[counter2] = oldValues[i];
counter2++;
}
return DataUtils.createInstance(instance, instance.weight(), newValues);
}
|
diff --git a/src/test/hdfs/org/apache/hadoop/fs/TestHDFSFileContextMainOperations.java b/src/test/hdfs/org/apache/hadoop/fs/TestHDFSFileContextMainOperations.java
index e5281c3efe..ddedc61768 100644
--- a/src/test/hdfs/org/apache/hadoop/fs/TestHDFSFileContextMainOperations.java
+++ b/src/test/hdfs/org/apache/hadoop/fs/TestHDFSFileContextMainOperations.java
@@ -1,76 +1,76 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs;
import java.io.IOException;
import javax.security.auth.login.LoginException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.security.UnixUserGroupInformation;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestHDFSFileContextMainOperations extends
FileContextMainOperationsBaseTest {
private static MiniDFSCluster cluster;
private static Path defaultWorkingDirectory;
@BeforeClass
public static void clusterSetupAtBegining()
throws IOException, LoginException {
cluster = new MiniDFSCluster(new Configuration(), 2, true, null);
fc = FileContext.getFileContext(cluster.getFileSystem());
defaultWorkingDirectory = fc.makeQualified( new Path("/user/" +
UnixUserGroupInformation.login().getUserName()));
- fc.mkdirs(defaultWorkingDirectory, FileContext.DEFAULT_PERM);
+ fc.mkdir(defaultWorkingDirectory, FileContext.DEFAULT_PERM, true);
}
@AfterClass
public static void ClusterShutdownAtEnd() throws Exception {
cluster.shutdown();
}
@Before
public void setUp() throws Exception {
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Override
protected Path getDefaultWorkingDirectory() {
return defaultWorkingDirectory;
}
@Override
@Test
public void testRenameFileAsExistingFile() throws Exception {
// ignore base class test till hadoop-6240 is fixed
}
}
| true | true | public static void clusterSetupAtBegining()
throws IOException, LoginException {
cluster = new MiniDFSCluster(new Configuration(), 2, true, null);
fc = FileContext.getFileContext(cluster.getFileSystem());
defaultWorkingDirectory = fc.makeQualified( new Path("/user/" +
UnixUserGroupInformation.login().getUserName()));
fc.mkdirs(defaultWorkingDirectory, FileContext.DEFAULT_PERM);
}
| public static void clusterSetupAtBegining()
throws IOException, LoginException {
cluster = new MiniDFSCluster(new Configuration(), 2, true, null);
fc = FileContext.getFileContext(cluster.getFileSystem());
defaultWorkingDirectory = fc.makeQualified( new Path("/user/" +
UnixUserGroupInformation.login().getUserName()));
fc.mkdir(defaultWorkingDirectory, FileContext.DEFAULT_PERM, true);
}
|
diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java
index 1d40f44d..7531c03f 100644
--- a/Essentials/src/com/earth2me/essentials/Essentials.java
+++ b/Essentials/src/com/earth2me/essentials/Essentials.java
@@ -1,747 +1,747 @@
/*
* Essentials - a bukkit plugin
* Copyright (C) 2011 Essentials Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.earth2me.essentials;
import com.earth2me.essentials.commands.EssentialsCommand;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import org.bukkit.*;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import com.earth2me.essentials.register.payment.Methods;
import java.math.BigInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.craftbukkit.scheduler.CraftScheduler;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.event.server.ServerListener;
import org.bukkit.plugin.*;
import org.bukkit.plugin.java.*;
public class Essentials extends JavaPlugin implements IEssentials
{
public static final String AUTHORS = "Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans and Xeology";
public static final int minBukkitBuildVersion = 818;
private static final Logger logger = Logger.getLogger("Minecraft");
private Settings settings;
private EssentialsPlayerListener playerListener;
private EssentialsBlockListener blockListener;
private EssentialsEntityListener entityListener;
private JailPlayerListener jailPlayerListener;
private static Essentials instance = null;
private Spawn spawn;
private Jail jail;
private Warps warps;
private Worth worth;
private List<IConf> confList;
public ArrayList bans = new ArrayList();
public ArrayList bannedIps = new ArrayList();
private Backup backup;
private final Map<String, User> users = new HashMap<String, User>();
private EssentialsTimer timer;
private EssentialsUpdateTimer updateTimer;
private boolean registerFallback = true;
private final Methods paymentMethod = new Methods();
private final static boolean enableErrorLogging = false;
private final EssentialsErrorHandler errorHandler = new EssentialsErrorHandler();
public static IEssentials getStatic()
{
return instance;
}
public Settings getSettings()
{
return settings;
}
public void setupForTesting(Server server) throws IOException, InvalidDescriptionException
{
File dataFolder = File.createTempFile("essentialstest", "");
dataFolder.delete();
dataFolder.mkdir();
logger.log(Level.INFO, Util.i18n("usingTempFolderForTesting"));
logger.log(Level.INFO, dataFolder.toString());
this.initialize(null, server, new PluginDescriptionFile(new FileReader(new File("src" + File.separator + "plugin.yml"))), dataFolder, null, null);
settings = new Settings(dataFolder);
setStatic();
}
public void setStatic()
{
instance = this;
}
public void onEnable()
{
if (enableErrorLogging)
{
logger.addHandler(errorHandler);
}
setStatic();
EssentialsUpgrade upgrade = new EssentialsUpgrade(this.getDescription().getVersion(), this);
upgrade.beforeSettings();
confList = new ArrayList<IConf>();
settings = new Settings(this.getDataFolder());
confList.add(settings);
upgrade.afterSettings();
Util.updateLocale(settings.getLocale(), this.getDataFolder());
spawn = new Spawn(getServer(), this.getDataFolder());
confList.add(spawn);
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
worth = new Worth(this.getDataFolder());
confList.add(worth);
reload();
backup = new Backup(this);
PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins())
{
if (plugin.getDescription().getName().startsWith("Essentials"))
{
if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion()))
{
logger.log(Level.WARNING, Util.format("versionMismatch", plugin.getDescription().getName()));
}
}
}
Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(getServer().getVersion());
if (versionMatch.matches())
{
int versionNumber = Integer.parseInt(versionMatch.group(4));
if (versionNumber < minBukkitBuildVersion)
{
logger.log(Level.WARNING, Util.i18n("notRecommendedBukkit"));
}
}
else
{
logger.log(Level.INFO, Util.i18n("bukkitFormatChanged"));
}
ServerListener serverListener = new EssentialsPluginListener(paymentMethod);
pm.registerEvent(Type.PLUGIN_ENABLE, serverListener, Priority.Low, this);
pm.registerEvent(Type.PLUGIN_DISABLE, serverListener, Priority.Low, this);
playerListener = new EssentialsPlayerListener(this);
pm.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Monitor, this);
pm.registerEvent(Type.PLAYER_QUIT, playerListener, Priority.Monitor, this);
pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Lowest, this);
if (getSettings().getNetherPortalsEnabled())
{
pm.registerEvent(Type.PLAYER_MOVE, playerListener, Priority.High, this);
}
pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_EGG_THROW, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_BUCKET_EMPTY, playerListener, Priority.High, this);
pm.registerEvent(Type.PLAYER_ANIMATION, playerListener, Priority.High, this);
blockListener = new EssentialsBlockListener(this);
pm.registerEvent(Type.SIGN_CHANGE, blockListener, Priority.Low, this);
pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Lowest, this);
pm.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Lowest, this);
entityListener = new EssentialsEntityListener(this);
pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.Lowest, this);
pm.registerEvent(Type.ENTITY_COMBUST, entityListener, Priority.Lowest, this);
pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Lowest, this);
jail = new Jail(this);
jailPlayerListener = new JailPlayerListener(this);
confList.add(jail);
pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.High, this);
pm.registerEvent(Type.BLOCK_DAMAGE, jail, Priority.High, this);
pm.registerEvent(Type.BLOCK_PLACE, jail, Priority.High, this);
pm.registerEvent(Type.PLAYER_INTERACT, jailPlayerListener, Priority.High, this);
attachEcoListeners();
if (settings.isNetherEnabled() && getServer().getWorlds().size() < 2)
{
logger.log(Level.WARNING, "Old nether is disabled until multiworld support in bukkit is fixed.");
getServer().createWorld(settings.getNetherName(), World.Environment.NETHER);
}
timer = new EssentialsTimer(this);
getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 50);
if (enableErrorLogging)
{
updateTimer = new EssentialsUpdateTimer(this);
getScheduler().scheduleAsyncRepeatingTask(this, updateTimer, 50, 50 * 60 * (this.getDescription().getVersion().startsWith("Dev") ? 60 : 360));
}
logger.info(Util.format("loadinfo", this.getDescription().getName(), this.getDescription().getVersion(), AUTHORS));
}
public void onDisable()
{
instance = null;
logger.removeHandler(errorHandler);
}
public void reload()
{
loadBanList();
for (IConf iConf : confList)
{
iConf.reloadConfig();
}
Util.updateLocale(settings.getLocale(), this.getDataFolder());
for (User user : users.values())
{
user.reloadConfig();
}
// for motd
getConfiguration().load();
try
{
ItemDb.load(getDataFolder(), "items.csv");
}
catch (Exception ex)
{
logger.log(Level.WARNING, Util.i18n("itemsCsvNotLoaded"), ex);
}
}
public String[] getMotd(CommandSender sender, String def)
{
return getLines(sender, "motd", def);
}
public String[] getLines(CommandSender sender, String node, String def)
{
List<String> lines = (List<String>)getConfiguration().getProperty(node);
if (lines == null)
{
return new String[0];
}
String[] retval = new String[lines.size()];
if (lines == null || lines.isEmpty() || lines.get(0) == null)
{
try
{
lines = new ArrayList<String>();
// "[]" in YaML indicates empty array, so respect that
if (!getConfiguration().getString(node, def).equals("[]"))
{
lines.add(getConfiguration().getString(node, def));
retval = new String[lines.size()];
}
}
catch (Throwable ex2)
{
logger.log(Level.WARNING, Util.format("corruptNodeInConfig", node));
return new String[0];
}
}
// if still empty, call it a day
if (lines == null || lines.isEmpty() || lines.get(0) == null)
{
return new String[0];
}
for (int i = 0; i < lines.size(); i++)
{
String m = lines.get(i);
if (m == null)
{
continue;
}
m = m.replace('&', '§').replace("§§", "&");
if (sender instanceof User || sender instanceof Player)
{
User user = getUser(sender);
m = m.replace("{PLAYER}", user.getDisplayName());
m = m.replace("{IP}", user.getAddress().toString());
m = m.replace("{BALANCE}", Double.toString(user.getMoney()));
m = m.replace("{MAILS}", Integer.toString(user.getMails().size()));
}
m = m.replace("{ONLINE}", Integer.toString(getServer().getOnlinePlayers().length));
if (m.matches(".*\\{PLAYERLIST\\}.*"))
{
StringBuilder online = new StringBuilder();
for (Player p : getServer().getOnlinePlayers())
{
if (online.length() > 0)
{
online.append(", ");
}
online.append(p.getDisplayName());
}
m = m.replace("{PLAYERLIST}", online.toString());
}
if (sender instanceof Player)
{
try
{
Class User = getClassLoader().loadClass("bukkit.Vandolis.User");
Object vuser = User.getConstructor(User.class).newInstance((Player)sender);
m = m.replace("{RED:BALANCE}", User.getMethod("getMoney").invoke(vuser).toString());
m = m.replace("{RED:BUYS}", User.getMethod("getNumTransactionsBuy").invoke(vuser).toString());
m = m.replace("{RED:SELLS}", User.getMethod("getNumTransactionsSell").invoke(vuser).toString());
}
catch (Throwable ex)
{
m = m.replace("{RED:BALANCE}", "N/A");
m = m.replace("{RED:BUYS}", "N/A");
m = m.replace("{RED:SELLS}", "N/A");
}
}
retval[i] = m + " ";
}
return retval;
}
@SuppressWarnings("LoggerStringConcat")
public static void previewCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
if (sender instanceof Player)
{
logger.info(ChatColor.BLUE + "[PLAYER_COMMAND] " + ((Player)sender).getName() + ": /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0));
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command");
}
public boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath)
{
- if ("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase()) && sender instanceof CraftPlayer)
+ if (("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase())) && sender instanceof Player)
{
StringBuilder str = new StringBuilder();
str.append(commandLabel).append(" ");
for (String a : args)
{
str.append(a).append(" ");
}
for (Player player : getServer().getOnlinePlayers())
{
if (getUser(player).isSocialSpyEnabled())
{
player.sendMessage(getUser(sender).getDisplayName() + " : " + str);
}
}
}
// Allow plugins to override the command via onCommand
if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e"))
{
for (Plugin p : getServer().getPluginManager().getPlugins())
{
if (p.getDescription().getMain().contains("com.earth2me.essentials"))
{
continue;
}
PluginDescriptionFile desc = p.getDescription();
if (desc == null)
{
continue;
}
if (desc.getName() == null)
{
continue;
}
if (!(desc.getCommands() instanceof Map))
{
continue;
}
Map<String, Object> cmds = (Map<String, Object>)desc.getCommands();
if (!cmds.containsKey(command.getName()))
{
continue;
}
return p.onCommand(sender, command, commandLabel, args);
}
}
try
{
previewCommand(sender, command, commandLabel, args);
User user = sender instanceof Player ? getUser(sender) : null;
// New mail notification
if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail"))
{
final List<String> mail = user.getMails();
if (mail != null && !mail.isEmpty())
{
user.sendMessage(Util.format("youHaveNewMail", mail.size()));
}
}
// Check for disabled commands
if (getSettings().isCommandDisabled(commandLabel))
{
return true;
}
IEssentialsCommand cmd;
try
{
cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance();
cmd.setEssentials(this);
}
catch (Exception ex)
{
sender.sendMessage(Util.format("commandNotLoaded", commandLabel));
logger.log(Level.SEVERE, Util.format("commandNotLoaded", commandLabel), ex);
return true;
}
// Check authorization
if (user != null && !user.isAuthorized(cmd))
{
logger.log(Level.WARNING, Util.format("deniedAccessCommand", user.getName()));
user.sendMessage(Util.i18n("noAccessCommand"));
return true;
}
// Run the command
try
{
if (user == null)
{
cmd.run(getServer(), sender, commandLabel, command, args);
}
else
{
cmd.run(getServer(), user, commandLabel, command, args);
}
return true;
}
catch (NotEnoughArgumentsException ex)
{
sender.sendMessage(command.getDescription());
sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel));
return true;
}
catch (Throwable ex)
{
sender.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
LogRecord lr = new LogRecord(Level.WARNING, Util.format("errorCallingCommand", commandLabel));
lr.setThrown(ex);
if (getSettings().isDebug())
{
logger.log(lr);
}
else
{
if (enableErrorLogging)
{
errorHandler.publish(lr);
errorHandler.flush();
}
}
return true;
}
}
catch (Throwable ex)
{
logger.log(Level.SEVERE, Util.format("commandFailed", commandLabel), ex);
return true;
}
}
public void loadBanList()
{
//I don't like this but it needs to be done until CB fixors
File file = new File("banned-players.txt");
File ipFile = new File("banned-ips.txt");
try
{
if (!file.exists())
{
throw new FileNotFoundException(Util.i18n("bannedPlayersFileNotFound"));
}
final BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try
{
bans.clear();
while (bufferedReader.ready())
{
final String line = bufferedReader.readLine().trim().toLowerCase();
if (line.length() > 0 && line.charAt(0) == '#')
{
continue;
}
bans.add(line);
}
}
catch (IOException io)
{
logger.log(Level.SEVERE, Util.i18n("bannedPlayersFileError"), io);
}
finally
{
try
{
bufferedReader.close();
}
catch (IOException ex)
{
logger.log(Level.SEVERE, Util.i18n("bannedPlayersFileError"), ex);
}
}
}
catch (FileNotFoundException ex)
{
logger.log(Level.SEVERE, Util.i18n("bannedPlayersFileError"), ex);
}
try
{
if (!ipFile.exists())
{
throw new FileNotFoundException(Util.i18n("bannedIpsFileNotFound"));
}
final BufferedReader bufferedReader = new BufferedReader(new FileReader(ipFile));
try
{
bannedIps.clear();
while (bufferedReader.ready())
{
final String line = bufferedReader.readLine().trim().toLowerCase();
if (line.length() > 0 && line.charAt(0) == '#')
{
continue;
}
bannedIps.add(line);
}
}
catch (IOException io)
{
logger.log(Level.SEVERE, Util.i18n("bannedIpsFileError"), io);
}
finally
{
try
{
bufferedReader.close();
}
catch (IOException ex)
{
logger.log(Level.SEVERE, Util.i18n("bannedIpsFileError"), ex);
}
}
}
catch (FileNotFoundException ex)
{
logger.log(Level.SEVERE, Util.i18n("bannedIpsFileError"), ex);
}
}
private void attachEcoListeners()
{
PluginManager pm = getServer().getPluginManager();
EssentialsEcoBlockListener ecoBlockListener = new EssentialsEcoBlockListener(this);
EssentialsEcoPlayerListener ecoPlayerListener = new EssentialsEcoPlayerListener(this);
pm.registerEvent(Type.PLAYER_INTERACT, ecoPlayerListener, Priority.High, this);
pm.registerEvent(Type.BLOCK_BREAK, ecoBlockListener, Priority.High, this);
pm.registerEvent(Type.SIGN_CHANGE, ecoBlockListener, Priority.Monitor, this);
}
public CraftScheduler getScheduler()
{
return (CraftScheduler)this.getServer().getScheduler();
}
public Jail getJail()
{
return jail;
}
public Warps getWarps()
{
return warps;
}
public Worth getWorth()
{
return worth;
}
public Backup getBackup()
{
return backup;
}
public Spawn getSpawn()
{
return spawn;
}
public User getUser(Object base)
{
if (base instanceof Player)
{
return getUser((Player)base);
}
return null;
}
private <T extends Player> User getUser(T base)
{
if (base == null)
{
return null;
}
if (base instanceof User)
{
return (User)base;
}
if (users.containsKey(base.getName().toLowerCase()))
{
return users.get(base.getName().toLowerCase()).update(base);
}
User u = new User(base, this);
users.put(u.getName().toLowerCase(), u);
return u;
}
public User getOfflineUser(String name)
{
File userFolder = new File(getDataFolder(), "userdata");
File userFile = new File(userFolder, Util.sanitizeFileName(name) + ".yml");
if (userFile.exists())
{ //Users do not get offline changes saved without being reproccessed as Users! ~ Xeology :)
return getUser((Player)new OfflinePlayer(name));
}
return null;
}
public World getWorld(String name)
{
if (name.matches("[0-9]+"))
{
int id = Integer.parseInt(name);
if (id < getServer().getWorlds().size())
{
return getServer().getWorlds().get(id);
}
}
World w = getServer().getWorld(name);
if (w != null)
{
return w;
}
return null;
}
public void setRegisterFallback(boolean registerFallback)
{
this.registerFallback = registerFallback;
}
public boolean isRegisterFallbackEnabled()
{
return registerFallback;
}
public void addReloadListener(IConf listener)
{
confList.add(listener);
}
public Methods getPaymentMethod()
{
return paymentMethod;
}
public int broadcastMessage(String name, String message)
{
Player[] players = getServer().getOnlinePlayers();
for (Player player : players)
{
User u = getUser(player);
if (!u.isIgnoredPlayer(name))
{
player.sendMessage(message);
}
}
return players.length;
}
public Map<BigInteger, String> getErrors()
{
return errorHandler.getErrors();
}
public int scheduleAsyncDelayedTask(final Runnable run)
{
return this.getScheduler().scheduleAsyncDelayedTask(this, run);
}
public int scheduleSyncDelayedTask(final Runnable run)
{
return this.getScheduler().scheduleSyncDelayedTask(this, run);
}
public int scheduleSyncRepeatingTask(final Runnable run, long delay, long period)
{
return this.getScheduler().scheduleSyncRepeatingTask(this, run, delay, period);
}
public List<String> getBans()
{
return bans;
}
public List<String> getBannedIps()
{
return bannedIps;
}
}
| true | true | public boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath)
{
if ("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase()) && sender instanceof CraftPlayer)
{
StringBuilder str = new StringBuilder();
str.append(commandLabel).append(" ");
for (String a : args)
{
str.append(a).append(" ");
}
for (Player player : getServer().getOnlinePlayers())
{
if (getUser(player).isSocialSpyEnabled())
{
player.sendMessage(getUser(sender).getDisplayName() + " : " + str);
}
}
}
// Allow plugins to override the command via onCommand
if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e"))
{
for (Plugin p : getServer().getPluginManager().getPlugins())
{
if (p.getDescription().getMain().contains("com.earth2me.essentials"))
{
continue;
}
PluginDescriptionFile desc = p.getDescription();
if (desc == null)
{
continue;
}
if (desc.getName() == null)
{
continue;
}
if (!(desc.getCommands() instanceof Map))
{
continue;
}
Map<String, Object> cmds = (Map<String, Object>)desc.getCommands();
if (!cmds.containsKey(command.getName()))
{
continue;
}
return p.onCommand(sender, command, commandLabel, args);
}
}
try
{
previewCommand(sender, command, commandLabel, args);
User user = sender instanceof Player ? getUser(sender) : null;
// New mail notification
if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail"))
{
final List<String> mail = user.getMails();
if (mail != null && !mail.isEmpty())
{
user.sendMessage(Util.format("youHaveNewMail", mail.size()));
}
}
// Check for disabled commands
if (getSettings().isCommandDisabled(commandLabel))
{
return true;
}
IEssentialsCommand cmd;
try
{
cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance();
cmd.setEssentials(this);
}
catch (Exception ex)
{
sender.sendMessage(Util.format("commandNotLoaded", commandLabel));
logger.log(Level.SEVERE, Util.format("commandNotLoaded", commandLabel), ex);
return true;
}
// Check authorization
if (user != null && !user.isAuthorized(cmd))
{
logger.log(Level.WARNING, Util.format("deniedAccessCommand", user.getName()));
user.sendMessage(Util.i18n("noAccessCommand"));
return true;
}
// Run the command
try
{
if (user == null)
{
cmd.run(getServer(), sender, commandLabel, command, args);
}
else
{
cmd.run(getServer(), user, commandLabel, command, args);
}
return true;
}
catch (NotEnoughArgumentsException ex)
{
sender.sendMessage(command.getDescription());
sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel));
return true;
}
catch (Throwable ex)
{
sender.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
LogRecord lr = new LogRecord(Level.WARNING, Util.format("errorCallingCommand", commandLabel));
lr.setThrown(ex);
if (getSettings().isDebug())
{
logger.log(lr);
}
else
{
if (enableErrorLogging)
{
errorHandler.publish(lr);
errorHandler.flush();
}
}
return true;
}
}
catch (Throwable ex)
{
logger.log(Level.SEVERE, Util.format("commandFailed", commandLabel), ex);
return true;
}
}
| public boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath)
{
if (("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase())) && sender instanceof Player)
{
StringBuilder str = new StringBuilder();
str.append(commandLabel).append(" ");
for (String a : args)
{
str.append(a).append(" ");
}
for (Player player : getServer().getOnlinePlayers())
{
if (getUser(player).isSocialSpyEnabled())
{
player.sendMessage(getUser(sender).getDisplayName() + " : " + str);
}
}
}
// Allow plugins to override the command via onCommand
if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e"))
{
for (Plugin p : getServer().getPluginManager().getPlugins())
{
if (p.getDescription().getMain().contains("com.earth2me.essentials"))
{
continue;
}
PluginDescriptionFile desc = p.getDescription();
if (desc == null)
{
continue;
}
if (desc.getName() == null)
{
continue;
}
if (!(desc.getCommands() instanceof Map))
{
continue;
}
Map<String, Object> cmds = (Map<String, Object>)desc.getCommands();
if (!cmds.containsKey(command.getName()))
{
continue;
}
return p.onCommand(sender, command, commandLabel, args);
}
}
try
{
previewCommand(sender, command, commandLabel, args);
User user = sender instanceof Player ? getUser(sender) : null;
// New mail notification
if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail"))
{
final List<String> mail = user.getMails();
if (mail != null && !mail.isEmpty())
{
user.sendMessage(Util.format("youHaveNewMail", mail.size()));
}
}
// Check for disabled commands
if (getSettings().isCommandDisabled(commandLabel))
{
return true;
}
IEssentialsCommand cmd;
try
{
cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance();
cmd.setEssentials(this);
}
catch (Exception ex)
{
sender.sendMessage(Util.format("commandNotLoaded", commandLabel));
logger.log(Level.SEVERE, Util.format("commandNotLoaded", commandLabel), ex);
return true;
}
// Check authorization
if (user != null && !user.isAuthorized(cmd))
{
logger.log(Level.WARNING, Util.format("deniedAccessCommand", user.getName()));
user.sendMessage(Util.i18n("noAccessCommand"));
return true;
}
// Run the command
try
{
if (user == null)
{
cmd.run(getServer(), sender, commandLabel, command, args);
}
else
{
cmd.run(getServer(), user, commandLabel, command, args);
}
return true;
}
catch (NotEnoughArgumentsException ex)
{
sender.sendMessage(command.getDescription());
sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel));
return true;
}
catch (Throwable ex)
{
sender.sendMessage(Util.format("errorWithMessage", ex.getMessage()));
LogRecord lr = new LogRecord(Level.WARNING, Util.format("errorCallingCommand", commandLabel));
lr.setThrown(ex);
if (getSettings().isDebug())
{
logger.log(lr);
}
else
{
if (enableErrorLogging)
{
errorHandler.publish(lr);
errorHandler.flush();
}
}
return true;
}
}
catch (Throwable ex)
{
logger.log(Level.SEVERE, Util.format("commandFailed", commandLabel), ex);
return true;
}
}
|
diff --git a/src/com/vloxlands/game/world/Island.java b/src/com/vloxlands/game/world/Island.java
index 116dc0f..85bbc8a 100644
--- a/src/com/vloxlands/game/world/Island.java
+++ b/src/com/vloxlands/game/world/Island.java
@@ -1,199 +1,199 @@
package com.vloxlands.game.world;
import static org.lwjgl.opengl.GL11.glTranslatef;
import java.util.ArrayList;
import org.lwjgl.util.vector.Vector3f;
import com.vloxlands.game.Game;
import com.vloxlands.game.voxel.Voxel;
import com.vloxlands.render.VoxelFace;
public class Island
{
public static final int MAXSIZE = 256;
byte[][][] voxels = new byte[MAXSIZE][MAXSIZE][MAXSIZE];
byte[][][] voxelMetadata = new byte[MAXSIZE][MAXSIZE][MAXSIZE];
public ArrayList<VoxelFace> faces = new ArrayList<>();
public ArrayList<VoxelFace> transparentFaces = new ArrayList<>();
Vector3f pos;
public float weight, uplift;
public Island()
{
pos = new Vector3f(0, 0, 0);
for (int i = 0; i < MAXSIZE; i++)
{
for (int j = 0; j < MAXSIZE; j++)
{
for (int k = 0; k < MAXSIZE; k++)
{
voxels[i][j][k] = Voxel.AIR.getId();
voxelMetadata[i][j][k] = -128;
}
}
}
}
public void onTick()
{
pos.translate(0, (uplift * Game.currentMap.calculateUplift(pos.y) - weight) / 100000f, 0);
}
public void calculateWeight()
{
weight = 0;
for (int x = 0; x < 256; x++)
{
for (int y = 0; y < 256; y++)
{
for (int z = 0; z < 256; z++)
{
if (getVoxelId(x, y, z) == 0) continue;
weight += Voxel.getVoxelForId(getVoxelId(x, y, z)).getWeight();
}
}
}
}
public void calculateUplift()
{
uplift = 0;
for (int x = 0; x < 256; x++)
{
for (int y = 0; y < 256; y++)
{
for (int z = 0; z < 256; z++)
{
if (getVoxelId(x, y, z) == 0) continue;
uplift += Voxel.getVoxelForId(getVoxelId(x, y, z)).getUplift();
}
}
}
}
public void placeVoxel(int x, int y, int z, byte id)
{
placeVoxel(x, y, z, id, (byte) 0);
}
public void placeVoxel(int x, int y, int z, byte id, byte metadata)
{
voxels[x][y][z] = id;
voxelMetadata[x][y][z] = metadata;
Voxel.getVoxelForId(id).onPlaced(x, y, z);
weight += Voxel.getVoxelForId(id).getWeight();
uplift += Voxel.getVoxelForId(id).getUplift();
}
public void removeVoxel(int x, int y, int z)
{
Voxel v = Voxel.getVoxelForId(getVoxelId(x, y, z));
setVoxel(x, y, z, Voxel.AIR.getId());
weight -= v.getWeight();
uplift -= v.getUplift();
}
public byte getVoxelId(int x, int y, int z)
{
if (x >= Island.MAXSIZE || y >= Island.MAXSIZE || z >= Island.MAXSIZE || x < 0 || y < 0 || z < 0) return 0;
return voxels[x][y][z];
}
public byte getMetadata(int x, int y, int z)
{
return voxelMetadata[x][y][z];
}
public void setVoxel(int x, int y, int z, byte id)
{
voxels[x][y][z] = id;
}
public void setVoxel(int x, int y, int z, byte id, byte metadata)
{
voxels[x][y][z] = id;
voxelMetadata[x][y][z] = metadata;
}
public void setVoxelMetadata(int x, int y, int z, byte metadata)
{
voxelMetadata[x][y][z] = metadata;
}
public byte[] getVoxels()
{
byte[] bytes = new byte[(int) Math.pow(MAXSIZE, 3)];
for (int i = 0; i < MAXSIZE; i++)
{
for (int j = 0; j < MAXSIZE; j++)
{
for (int k = 0; k < MAXSIZE; k++)
{
bytes[(i * MAXSIZE + j) * MAXSIZE + k] = voxels[i][j][k];
}
}
}
return bytes;
}
public byte[] getVoxelMetadatas()
{
byte[] bytes = new byte[(int) Math.pow(MAXSIZE, 3)];
for (int i = 0; i < MAXSIZE; i++)
{
for (int j = 0; j < MAXSIZE; j++)
{
for (int k = 0; k < MAXSIZE; k++)
{
bytes[(i * MAXSIZE + j) * MAXSIZE + k] = voxelMetadata[i][j][k];
}
}
}
return bytes;
}
public void render()
{
glTranslatef(pos.x, pos.y, pos.z);
for (VoxelFace f : faces)
f.render();
for (VoxelFace f : transparentFaces)
f.render();
}
public Vector3f getPos()
{
return pos;
}
public void setPos(Vector3f pos)
{
this.pos = pos;
}
public void grassify()
{
for (int i = 0; i < Island.MAXSIZE; i++)
{
for (int j = 0; j < Island.MAXSIZE; j++)
{
for (int k = 0; k < Island.MAXSIZE; k++)
{
if (getVoxelId(i, j, k) == Voxel.DIRT.getId())
{
- if (getVoxelId(i, j - 1, k) == Voxel.AIR.getId())
+ if (getVoxelId(i, j + 1, k) == Voxel.AIR.getId())
{
setVoxel(i, j, k, Voxel.GRASS.getId());
}
}
}
}
}
}
}
| true | true | public void grassify()
{
for (int i = 0; i < Island.MAXSIZE; i++)
{
for (int j = 0; j < Island.MAXSIZE; j++)
{
for (int k = 0; k < Island.MAXSIZE; k++)
{
if (getVoxelId(i, j, k) == Voxel.DIRT.getId())
{
if (getVoxelId(i, j - 1, k) == Voxel.AIR.getId())
{
setVoxel(i, j, k, Voxel.GRASS.getId());
}
}
}
}
}
}
| public void grassify()
{
for (int i = 0; i < Island.MAXSIZE; i++)
{
for (int j = 0; j < Island.MAXSIZE; j++)
{
for (int k = 0; k < Island.MAXSIZE; k++)
{
if (getVoxelId(i, j, k) == Voxel.DIRT.getId())
{
if (getVoxelId(i, j + 1, k) == Voxel.AIR.getId())
{
setVoxel(i, j, k, Voxel.GRASS.getId());
}
}
}
}
}
}
|
diff --git a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java
index 518323e..44933f5 100644
--- a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java
+++ b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java
@@ -1,29 +1,30 @@
package com.github.kpacha.jkata.tennis;
public class Tennis {
private int playerOneScored = 0;
private int playerTwoScored = 0;
public String getScore() {
if (isDeuce())
return "Deuce";
- if (playerOneScored == 4 && playerTwoScored == 3)
+ if (playerOneScored == 4 && playerTwoScored == 3
+ || playerOneScored == 5 && playerTwoScored == 4)
return "Advantage Player 1";
if (playerOneScored == 4)
return "Player 1 wins";
return (15 * playerOneScored) + " - " + (15 * playerTwoScored);
}
private boolean isDeuce() {
return playerOneScored == playerTwoScored && playerTwoScored > 2;
}
public void playerOneScores() {
playerOneScored++;
}
public void playerTwoScores() {
playerTwoScored++;
}
}
| true | true | public String getScore() {
if (isDeuce())
return "Deuce";
if (playerOneScored == 4 && playerTwoScored == 3)
return "Advantage Player 1";
if (playerOneScored == 4)
return "Player 1 wins";
return (15 * playerOneScored) + " - " + (15 * playerTwoScored);
}
| public String getScore() {
if (isDeuce())
return "Deuce";
if (playerOneScored == 4 && playerTwoScored == 3
|| playerOneScored == 5 && playerTwoScored == 4)
return "Advantage Player 1";
if (playerOneScored == 4)
return "Player 1 wins";
return (15 * playerOneScored) + " - " + (15 * playerTwoScored);
}
|
diff --git a/kernel/src/main/java/com/qspin/qtaste/addon/ConfigurationTree.java b/kernel/src/main/java/com/qspin/qtaste/addon/ConfigurationTree.java
index 26e0e2f7..1509bd94 100644
--- a/kernel/src/main/java/com/qspin/qtaste/addon/ConfigurationTree.java
+++ b/kernel/src/main/java/com/qspin/qtaste/addon/ConfigurationTree.java
@@ -1,50 +1,54 @@
package com.qspin.qtaste.addon;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class ConfigurationTree extends JTree {
public ConfigurationTree(DefaultMutableTreeNode pRootNode, final JPanel pConfigurationPane)
{
super(pRootNode);
mModel = (DefaultTreeModel)getModel();
mRoot = (DefaultMutableTreeNode) mModel.getRoot();
setRootVisible(true);
getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
+ if ( e.getNewLeadSelectionPath() == null)
+ {
+ return;
+ }
String componentName = e.getNewLeadSelectionPath().getLastPathComponent().toString();
CardLayout rcl = (CardLayout) pConfigurationPane.getLayout();
rcl.show(pConfigurationPane, componentName);
}
});
}
public synchronized void addConfiguration(DefaultMutableTreeNode pConfigNode) {
mRoot.add(pConfigNode);
pConfigNode.setParent(mRoot);
mModel.reload();
}
public synchronized void removeConfiguration(DefaultMutableTreeNode pConfigNode) {
for ( int i = 0; i< mRoot.getChildCount(); ++i)
{
if ( ((DefaultMutableTreeNode)mRoot.getChildAt(i)).getUserObject().equals(pConfigNode.getUserObject()))
{
mRoot.remove(i);
break;
}
}
mModel.reload();
}
protected DefaultMutableTreeNode mRoot;
protected DefaultTreeModel mModel;
}
| true | true | public ConfigurationTree(DefaultMutableTreeNode pRootNode, final JPanel pConfigurationPane)
{
super(pRootNode);
mModel = (DefaultTreeModel)getModel();
mRoot = (DefaultMutableTreeNode) mModel.getRoot();
setRootVisible(true);
getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
String componentName = e.getNewLeadSelectionPath().getLastPathComponent().toString();
CardLayout rcl = (CardLayout) pConfigurationPane.getLayout();
rcl.show(pConfigurationPane, componentName);
}
});
}
| public ConfigurationTree(DefaultMutableTreeNode pRootNode, final JPanel pConfigurationPane)
{
super(pRootNode);
mModel = (DefaultTreeModel)getModel();
mRoot = (DefaultMutableTreeNode) mModel.getRoot();
setRootVisible(true);
getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
if ( e.getNewLeadSelectionPath() == null)
{
return;
}
String componentName = e.getNewLeadSelectionPath().getLastPathComponent().toString();
CardLayout rcl = (CardLayout) pConfigurationPane.getLayout();
rcl.show(pConfigurationPane, componentName);
}
});
}
|
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/change/PatchSetInserter.java b/gerrit-server/src/main/java/com/google/gerrit/server/change/PatchSetInserter.java
index f0458a682..7156cc658 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/change/PatchSetInserter.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/change/PatchSetInserter.java
@@ -1,270 +1,270 @@
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.change;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.gerrit.common.ChangeHooks;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.ChangeMessage;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.RevId;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ApprovalsUtil;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.config.TrackingFooters;
import com.google.gerrit.server.events.CommitReceivedEvent;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.validators.CommitValidationException;
import com.google.gerrit.server.git.validators.CommitValidators;
import com.google.gerrit.server.index.ChangeIndexer;
import com.google.gerrit.server.patch.PatchSetInfoFactory;
import com.google.gerrit.server.project.InvalidChangeOperationException;
import com.google.gerrit.server.project.RefControl;
import com.google.gerrit.server.ssh.NoSshInfo;
import com.google.gerrit.server.ssh.SshInfo;
import com.google.gwtorm.server.AtomicUpdate;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.FooterLine;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.ReceiveCommand;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.List;
public class PatchSetInserter {
public static interface Factory {
PatchSetInserter create(Repository git, RevWalk revWalk, RefControl refControl,
Change change, RevCommit commit);
}
private final ChangeHooks hooks;
private final TrackingFooters trackingFooters;
private final PatchSetInfoFactory patchSetInfoFactory;
private final ReviewDb db;
private final IdentifiedUser user;
private final GitReferenceUpdated gitRefUpdated;
private final CommitValidators.Factory commitValidatorsFactory;
private final ChangeIndexer indexer;
private boolean validateForReceiveCommits;
private final Repository git;
private final RevWalk revWalk;
private final RevCommit commit;
private final Change change;
private final RefControl refControl;
private PatchSet patchSet;
private ChangeMessage changeMessage;
private boolean copyLabels;
private SshInfo sshInfo;
@Inject
public PatchSetInserter(ChangeHooks hooks,
TrackingFooters trackingFooters,
ReviewDb db,
PatchSetInfoFactory patchSetInfoFactory,
IdentifiedUser user,
GitReferenceUpdated gitRefUpdated,
CommitValidators.Factory commitValidatorsFactory,
ChangeIndexer indexer,
@Assisted Repository git,
@Assisted RevWalk revWalk,
@Assisted RefControl refControl,
@Assisted Change change,
@Assisted RevCommit commit) {
this.hooks = hooks;
this.trackingFooters = trackingFooters;
this.db = db;
this.patchSetInfoFactory = patchSetInfoFactory;
this.user = user;
this.gitRefUpdated = gitRefUpdated;
this.commitValidatorsFactory = commitValidatorsFactory;
this.indexer = indexer;
this.git = git;
this.revWalk = revWalk;
this.refControl = refControl;
this.change = change;
this.commit = commit;
}
public PatchSetInserter setPatchSet(PatchSet patchSet) {
PatchSet.Id psid = patchSet.getId();
checkArgument(psid.getParentKey().equals(change.getId()),
"patch set %s not for change %s", psid, change.getId());
checkArgument(psid.get() > change.currentPatchSetId().get(),
"new patch set ID %s is not greater than current patch set ID %s",
psid.get(), change.currentPatchSetId().get());
this.patchSet = patchSet;
return this;
}
public PatchSetInserter setMessage(String message) throws OrmException {
changeMessage = new ChangeMessage(new ChangeMessage.Key(change.getId(),
ChangeUtil.messageUUID(db)), user.getAccountId(), patchSet.getId());
changeMessage.setMessage(message);
return this;
}
public PatchSetInserter setMessage(ChangeMessage changeMessage) throws OrmException {
this.changeMessage = changeMessage;
return this;
}
public PatchSetInserter setCopyLabels(boolean copyLabels) {
this.copyLabels = copyLabels;
return this;
}
public PatchSetInserter setSshInfo(SshInfo sshInfo) {
this.sshInfo = sshInfo;
return this;
}
public PatchSetInserter setValidateForReceiveCommits(boolean validate) {
this.validateForReceiveCommits = validate;
return this;
}
public Change insert() throws InvalidChangeOperationException, OrmException,
IOException {
init();
validate();
Change updatedChange;
RefUpdate ru = git.updateRef(patchSet.getRefName());
ru.setExpectedOldObjectId(ObjectId.zeroId());
ru.setNewObjectId(commit);
ru.disableRefLog();
if (ru.update(revWalk) != RefUpdate.Result.NEW) {
throw new IOException(String.format(
"Failed to create ref %s in %s: %s", patchSet.getRefName(),
change.getDest().getParentKey().get(), ru.getResult()));
}
gitRefUpdated.fire(change.getProject(), ru);
final PatchSet.Id currentPatchSetId = change.currentPatchSetId();
db.changes().beginTransaction(change.getId());
try {
if (!db.changes().get(change.getId()).getStatus().isOpen()) {
throw new InvalidChangeOperationException(String.format(
"Change %s is closed", change.getId()));
}
ChangeUtil.insertAncestors(db, patchSet.getId(), commit);
db.patchSets().insert(Collections.singleton(patchSet));
updatedChange =
db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
if (change.getStatus().isClosed()) {
return null;
}
if (!change.currentPatchSetId().equals(currentPatchSetId)) {
return null;
}
if (change.getStatus() != Change.Status.DRAFT) {
change.setStatus(Change.Status.NEW);
}
change.setLastSha1MergeTested(null);
change.setCurrentPatchSet(patchSetInfoFactory.get(commit,
patchSet.getId()));
ChangeUtil.updated(change);
return change;
}
});
if (updatedChange == null) {
throw new ChangeModifiedException(String.format(
"Change %s was modified", change.getId()));
}
if (copyLabels) {
ApprovalsUtil.copyLabels(db, refControl.getProjectControl()
- .getLabelTypes(), currentPatchSetId, change.currentPatchSetId());
+ .getLabelTypes(), currentPatchSetId, updatedChange.currentPatchSetId());
}
final List<FooterLine> footerLines = commit.getFooterLines();
ChangeUtil.updateTrackingIds(db, change, trackingFooters, footerLines);
db.commit();
if (changeMessage != null) {
db.changeMessages().insert(Collections.singleton(changeMessage));
}
indexer.index(change);
hooks.doPatchsetCreatedHook(change, patchSet, db);
} finally {
db.rollback();
}
return updatedChange;
}
private void init() {
if (sshInfo == null) {
sshInfo = new NoSshInfo();
}
if (patchSet == null) {
patchSet = new PatchSet(
ChangeUtil.nextPatchSetId(git, change.currentPatchSetId()));
patchSet.setCreatedOn(new Timestamp(System.currentTimeMillis()));
patchSet.setUploader(change.getOwner());
patchSet.setRevision(new RevId(commit.name()));
}
}
private void validate() throws InvalidChangeOperationException {
CommitValidators cv = commitValidatorsFactory.create(refControl, sshInfo, git);
String refName = patchSet.getRefName();
CommitReceivedEvent event = new CommitReceivedEvent(
new ReceiveCommand(
ObjectId.zeroId(),
commit.getId(),
refName.substring(0, refName.lastIndexOf('/') + 1) + "new"),
refControl.getProjectControl().getProject(), refControl.getRefName(),
commit, user);
try {
if (validateForReceiveCommits) {
cv.validateForReceiveCommits(event);
} else {
cv.validateForGerritCommits(event);
}
} catch (CommitValidationException e) {
throw new InvalidChangeOperationException(e.getMessage());
}
}
public class ChangeModifiedException extends InvalidChangeOperationException {
private static final long serialVersionUID = 1L;
public ChangeModifiedException(String msg) {
super(msg);
}
}
}
| true | true | public Change insert() throws InvalidChangeOperationException, OrmException,
IOException {
init();
validate();
Change updatedChange;
RefUpdate ru = git.updateRef(patchSet.getRefName());
ru.setExpectedOldObjectId(ObjectId.zeroId());
ru.setNewObjectId(commit);
ru.disableRefLog();
if (ru.update(revWalk) != RefUpdate.Result.NEW) {
throw new IOException(String.format(
"Failed to create ref %s in %s: %s", patchSet.getRefName(),
change.getDest().getParentKey().get(), ru.getResult()));
}
gitRefUpdated.fire(change.getProject(), ru);
final PatchSet.Id currentPatchSetId = change.currentPatchSetId();
db.changes().beginTransaction(change.getId());
try {
if (!db.changes().get(change.getId()).getStatus().isOpen()) {
throw new InvalidChangeOperationException(String.format(
"Change %s is closed", change.getId()));
}
ChangeUtil.insertAncestors(db, patchSet.getId(), commit);
db.patchSets().insert(Collections.singleton(patchSet));
updatedChange =
db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
if (change.getStatus().isClosed()) {
return null;
}
if (!change.currentPatchSetId().equals(currentPatchSetId)) {
return null;
}
if (change.getStatus() != Change.Status.DRAFT) {
change.setStatus(Change.Status.NEW);
}
change.setLastSha1MergeTested(null);
change.setCurrentPatchSet(patchSetInfoFactory.get(commit,
patchSet.getId()));
ChangeUtil.updated(change);
return change;
}
});
if (updatedChange == null) {
throw new ChangeModifiedException(String.format(
"Change %s was modified", change.getId()));
}
if (copyLabels) {
ApprovalsUtil.copyLabels(db, refControl.getProjectControl()
.getLabelTypes(), currentPatchSetId, change.currentPatchSetId());
}
final List<FooterLine> footerLines = commit.getFooterLines();
ChangeUtil.updateTrackingIds(db, change, trackingFooters, footerLines);
db.commit();
if (changeMessage != null) {
db.changeMessages().insert(Collections.singleton(changeMessage));
}
indexer.index(change);
hooks.doPatchsetCreatedHook(change, patchSet, db);
} finally {
db.rollback();
}
return updatedChange;
}
| public Change insert() throws InvalidChangeOperationException, OrmException,
IOException {
init();
validate();
Change updatedChange;
RefUpdate ru = git.updateRef(patchSet.getRefName());
ru.setExpectedOldObjectId(ObjectId.zeroId());
ru.setNewObjectId(commit);
ru.disableRefLog();
if (ru.update(revWalk) != RefUpdate.Result.NEW) {
throw new IOException(String.format(
"Failed to create ref %s in %s: %s", patchSet.getRefName(),
change.getDest().getParentKey().get(), ru.getResult()));
}
gitRefUpdated.fire(change.getProject(), ru);
final PatchSet.Id currentPatchSetId = change.currentPatchSetId();
db.changes().beginTransaction(change.getId());
try {
if (!db.changes().get(change.getId()).getStatus().isOpen()) {
throw new InvalidChangeOperationException(String.format(
"Change %s is closed", change.getId()));
}
ChangeUtil.insertAncestors(db, patchSet.getId(), commit);
db.patchSets().insert(Collections.singleton(patchSet));
updatedChange =
db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
if (change.getStatus().isClosed()) {
return null;
}
if (!change.currentPatchSetId().equals(currentPatchSetId)) {
return null;
}
if (change.getStatus() != Change.Status.DRAFT) {
change.setStatus(Change.Status.NEW);
}
change.setLastSha1MergeTested(null);
change.setCurrentPatchSet(patchSetInfoFactory.get(commit,
patchSet.getId()));
ChangeUtil.updated(change);
return change;
}
});
if (updatedChange == null) {
throw new ChangeModifiedException(String.format(
"Change %s was modified", change.getId()));
}
if (copyLabels) {
ApprovalsUtil.copyLabels(db, refControl.getProjectControl()
.getLabelTypes(), currentPatchSetId, updatedChange.currentPatchSetId());
}
final List<FooterLine> footerLines = commit.getFooterLines();
ChangeUtil.updateTrackingIds(db, change, trackingFooters, footerLines);
db.commit();
if (changeMessage != null) {
db.changeMessages().insert(Collections.singleton(changeMessage));
}
indexer.index(change);
hooks.doPatchsetCreatedHook(change, patchSet, db);
} finally {
db.rollback();
}
return updatedChange;
}
|
diff --git a/src/turtle/behavior/turtle/Goalkeeper.java b/src/turtle/behavior/turtle/Goalkeeper.java
index e779175..e246d30 100644
--- a/src/turtle/behavior/turtle/Goalkeeper.java
+++ b/src/turtle/behavior/turtle/Goalkeeper.java
@@ -1,72 +1,72 @@
/*
* This file is part of the Turtle project
*
* (c) 2011 Julien Brochet <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package turtle.behavior.turtle;
import java.awt.geom.Point2D;
import turtle.entity.field.Ball;
import turtle.entity.field.Field;
import turtle.entity.field.Goal;
import turtle.util.Random;
import turtle.util.Vector2D;
/**
* Comportement d'un gardien de but
*
* @author Julien Brochet <[email protected]>
* @since 1.0
*/
public class Goalkeeper extends AbstractTurtleBehavior
{
public Goalkeeper(Field field)
{
super(field);
}
@Override
public void apply(Vector2D vector, long elapsedTime)
{
double width = mField.getDimension().getWidth();
double height = mField.getDimension().getHeight();
double maxDistance = width * 0.15;
Ball ball = mField.getBall();
Point2D turtlePosition = mTurtle.getPosition();
//TODO Il ne faut pas regarder en fonction du joueur mais du goal
if (mTurtle.isAround(ball, maxDistance)) {
if (mTurtle.isAround(ball)) {
// Le goal est juste a coté du ballon
// Il le tire alors à l'autre bout du terrain
Vector2D speed = new Vector2D();
Goal goal = mField.getOtherGoal(mTurtle.getTeam().getGoal());
- speed.set(goal.getRectangle().getCenterX(), Random.between(0, height));
+ speed.set(goal.getRectangle().getCenterX() - turtlePosition.getX(), Random.between(0, height) - turtlePosition.getY());
speed.setLength(Random.between(0.15, 0.30));
ball.shoot(mTurtle, speed);
} else {
// Le ballon est proche mais pas encore assez donc
// le goal doit avancer vers lui
Point2D ballPosition = ball.getPosition();
vector.set(ballPosition.getX() - turtlePosition.getX(), ballPosition.getY() - turtlePosition.getY());
vector.setLength(Random.between(0.01, 0.03));
}
} else {
Point2D initialPosition = mTurtle.getInitialPosition();
if (turtlePosition.distance(initialPosition) > 0.1) {
// Le goal n'est pas à sa place de départ
vector.set(initialPosition.getX() - turtlePosition.getX(), initialPosition.getY() - turtlePosition.getY());
vector.setLength(Random.between(0.01, 0.03));
}
}
}
}
| true | true | public void apply(Vector2D vector, long elapsedTime)
{
double width = mField.getDimension().getWidth();
double height = mField.getDimension().getHeight();
double maxDistance = width * 0.15;
Ball ball = mField.getBall();
Point2D turtlePosition = mTurtle.getPosition();
//TODO Il ne faut pas regarder en fonction du joueur mais du goal
if (mTurtle.isAround(ball, maxDistance)) {
if (mTurtle.isAround(ball)) {
// Le goal est juste a coté du ballon
// Il le tire alors à l'autre bout du terrain
Vector2D speed = new Vector2D();
Goal goal = mField.getOtherGoal(mTurtle.getTeam().getGoal());
speed.set(goal.getRectangle().getCenterX(), Random.between(0, height));
speed.setLength(Random.between(0.15, 0.30));
ball.shoot(mTurtle, speed);
} else {
// Le ballon est proche mais pas encore assez donc
// le goal doit avancer vers lui
Point2D ballPosition = ball.getPosition();
vector.set(ballPosition.getX() - turtlePosition.getX(), ballPosition.getY() - turtlePosition.getY());
vector.setLength(Random.between(0.01, 0.03));
}
} else {
Point2D initialPosition = mTurtle.getInitialPosition();
if (turtlePosition.distance(initialPosition) > 0.1) {
// Le goal n'est pas à sa place de départ
vector.set(initialPosition.getX() - turtlePosition.getX(), initialPosition.getY() - turtlePosition.getY());
vector.setLength(Random.between(0.01, 0.03));
}
}
}
| public void apply(Vector2D vector, long elapsedTime)
{
double width = mField.getDimension().getWidth();
double height = mField.getDimension().getHeight();
double maxDistance = width * 0.15;
Ball ball = mField.getBall();
Point2D turtlePosition = mTurtle.getPosition();
//TODO Il ne faut pas regarder en fonction du joueur mais du goal
if (mTurtle.isAround(ball, maxDistance)) {
if (mTurtle.isAround(ball)) {
// Le goal est juste a coté du ballon
// Il le tire alors à l'autre bout du terrain
Vector2D speed = new Vector2D();
Goal goal = mField.getOtherGoal(mTurtle.getTeam().getGoal());
speed.set(goal.getRectangle().getCenterX() - turtlePosition.getX(), Random.between(0, height) - turtlePosition.getY());
speed.setLength(Random.between(0.15, 0.30));
ball.shoot(mTurtle, speed);
} else {
// Le ballon est proche mais pas encore assez donc
// le goal doit avancer vers lui
Point2D ballPosition = ball.getPosition();
vector.set(ballPosition.getX() - turtlePosition.getX(), ballPosition.getY() - turtlePosition.getY());
vector.setLength(Random.between(0.01, 0.03));
}
} else {
Point2D initialPosition = mTurtle.getInitialPosition();
if (turtlePosition.distance(initialPosition) > 0.1) {
// Le goal n'est pas à sa place de départ
vector.set(initialPosition.getX() - turtlePosition.getX(), initialPosition.getY() - turtlePosition.getY());
vector.setLength(Random.between(0.01, 0.03));
}
}
}
|
diff --git a/JAVA/psd/src/ch/epfl/bbcf/psd/Main.java b/JAVA/psd/src/ch/epfl/bbcf/psd/Main.java
index 3a70e1e..5b3c2c3 100644
--- a/JAVA/psd/src/ch/epfl/bbcf/psd/Main.java
+++ b/JAVA/psd/src/ch/epfl/bbcf/psd/Main.java
@@ -1,167 +1,169 @@
package ch.epfl.bbcf.psd;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.zip.DataFormatException;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
public class Main {
private static final int[] zooms = {1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000};
public static final int TAB_WIDTH = 100;
public static final int LIMIT_QUERY_SIZE = 1000000;
public static final String decimals = "%.2f";
public static Level loglevel = Level.INFO;
public static Logger logger;
public static void usage(){
String usage = "USAGE\n" +
"\targs[0] database : the sqlite file\n" +
"\targs[1] sah1 : the sha1 of this database\n" +
"\targs[2] output_dir : the output directory\n" +
"\targs[3] loglevel : (optionnal) can be TRACE, DEBUG, INFO, OFF, WARN, ERROR, FATAL. Default is INFO";
logger.warn(usage);
}
public static void main (String[] args) {
if(args.length < 3){
logger = initLogger("psd", Level.ERROR);
logger.error("no enought args");
usage();
} else {
File database = new File(args[0]);
String sha1 = args[1];
String outputDir = args[2];
if (args.length == 4){
loglevel = Level.toLevel(args[3]);
};
logger = initLogger("psd", loglevel);
try {
logger.info("processing " + database + " with sha1(" + sha1 + ") on directory : " + outputDir);
long start = System.currentTimeMillis();
process(database, sha1, outputDir);
long end = System.currentTimeMillis();
logger.debug("Execution time was ~"+(int)((end-start) / 1000) +"s.");
} catch (ClassNotFoundException e) {
logger.error(e);
for (StackTraceElement el : e.getStackTrace()){
logger.debug(el.getFileName() + " .. " +
el.getClassName() + "::" + el.getMethodName()
+" at line " + el.getLineNumber());
}
System.err.println("Class not found Exception");
System.exit(1);
} catch (SQLException e) {
logger.error(e);
for (StackTraceElement el : e.getStackTrace()){
logger.debug(el.getFileName() + " .. " +
el.getClassName() + "::" + el.getMethodName()
+" at line " + el.getLineNumber());
+ System.err.println("SQLException : " + e.getMessage());
+ System.exit(1);
}
System.err.println("Java.sql.SQLException " + e.getMessage());
} catch (DataFormatException e) {
for (StackTraceElement el : e.getStackTrace()){
logger.debug(el.getFileName() + " .. " +
el.getClassName() + "::" + el.getMethodName()
+" at line " + el.getLineNumber());
}
System.err.println("DataFormatException " + e.getMessage());
System.exit(1);
}
}
}
/**
* Calculate scores at different zoom level for an sqlite database and create one database for each.
* @param database : the sqlite file
* @param sha1 : the sha1 of this database
* @param outputDir : the output directory
* @throws SQLException
* @throws ClassNotFoundException
* @throws DataFormatException
*/
private static void process(File database, String sha1, String outputDir) throws ClassNotFoundException, SQLException, DataFormatException {
Map<String, Integer> chromosomes; // contains all chromosomes and length in the database
Connection principal; // the connection to the main database
principal = SQLiteConnector.getConnection(database.getAbsolutePath());
chromosomes = SQLiteConnector.getChromosomesAndLength(principal);
File output = new File(outputDir + File.separator + sha1);
output.mkdir();
logger.trace("output is " + output);
for(Map.Entry<String, Integer> entry : chromosomes.entrySet()){
String chromosome = entry.getKey();
logger.debug("doing chromosome " + chromosome);
ConnectionStore connectionStore = SQLiteConnector.createOutputDatabases(output.getAbsolutePath(), chromosome, zooms);
ResultSet scores = SQLiteConnector.getScores(principal, chromosome);
Tree tree = new Tree(connectionStore, chromosome, output.getAbsolutePath() );
tree.process(scores);
scores.close();
connectionStore.destruct();
}
principal.close();
}
public static boolean floatEquals(float a,float b){
float epsilon = 0.0001f;
boolean z = (Math.abs(a-b)<epsilon);
return z;
}
public static Logger initLogger(String name, Level level) {
Logger out = Logger.getLogger(name);
out.setAdditivity(false);
out.setLevel(level);
PatternLayout layout = new PatternLayout("%d [%t] %-5p %c - %m%n");
ConsoleAppender appender = new ConsoleAppender(layout);
out.addAppender(appender);
return out;
}
}
| true | true | public static void main (String[] args) {
if(args.length < 3){
logger = initLogger("psd", Level.ERROR);
logger.error("no enought args");
usage();
} else {
File database = new File(args[0]);
String sha1 = args[1];
String outputDir = args[2];
if (args.length == 4){
loglevel = Level.toLevel(args[3]);
};
logger = initLogger("psd", loglevel);
try {
logger.info("processing " + database + " with sha1(" + sha1 + ") on directory : " + outputDir);
long start = System.currentTimeMillis();
process(database, sha1, outputDir);
long end = System.currentTimeMillis();
logger.debug("Execution time was ~"+(int)((end-start) / 1000) +"s.");
} catch (ClassNotFoundException e) {
logger.error(e);
for (StackTraceElement el : e.getStackTrace()){
logger.debug(el.getFileName() + " .. " +
el.getClassName() + "::" + el.getMethodName()
+" at line " + el.getLineNumber());
}
System.err.println("Class not found Exception");
System.exit(1);
} catch (SQLException e) {
logger.error(e);
for (StackTraceElement el : e.getStackTrace()){
logger.debug(el.getFileName() + " .. " +
el.getClassName() + "::" + el.getMethodName()
+" at line " + el.getLineNumber());
}
System.err.println("Java.sql.SQLException " + e.getMessage());
} catch (DataFormatException e) {
for (StackTraceElement el : e.getStackTrace()){
logger.debug(el.getFileName() + " .. " +
el.getClassName() + "::" + el.getMethodName()
+" at line " + el.getLineNumber());
}
System.err.println("DataFormatException " + e.getMessage());
System.exit(1);
}
}
}
| public static void main (String[] args) {
if(args.length < 3){
logger = initLogger("psd", Level.ERROR);
logger.error("no enought args");
usage();
} else {
File database = new File(args[0]);
String sha1 = args[1];
String outputDir = args[2];
if (args.length == 4){
loglevel = Level.toLevel(args[3]);
};
logger = initLogger("psd", loglevel);
try {
logger.info("processing " + database + " with sha1(" + sha1 + ") on directory : " + outputDir);
long start = System.currentTimeMillis();
process(database, sha1, outputDir);
long end = System.currentTimeMillis();
logger.debug("Execution time was ~"+(int)((end-start) / 1000) +"s.");
} catch (ClassNotFoundException e) {
logger.error(e);
for (StackTraceElement el : e.getStackTrace()){
logger.debug(el.getFileName() + " .. " +
el.getClassName() + "::" + el.getMethodName()
+" at line " + el.getLineNumber());
}
System.err.println("Class not found Exception");
System.exit(1);
} catch (SQLException e) {
logger.error(e);
for (StackTraceElement el : e.getStackTrace()){
logger.debug(el.getFileName() + " .. " +
el.getClassName() + "::" + el.getMethodName()
+" at line " + el.getLineNumber());
System.err.println("SQLException : " + e.getMessage());
System.exit(1);
}
System.err.println("Java.sql.SQLException " + e.getMessage());
} catch (DataFormatException e) {
for (StackTraceElement el : e.getStackTrace()){
logger.debug(el.getFileName() + " .. " +
el.getClassName() + "::" + el.getMethodName()
+" at line " + el.getLineNumber());
}
System.err.println("DataFormatException " + e.getMessage());
System.exit(1);
}
}
}
|
diff --git a/src/main/java/org/spiffyui/mvsb/samples/client/LocalSuggestBox.java b/src/main/java/org/spiffyui/mvsb/samples/client/LocalSuggestBox.java
index 704b296..917b812 100644
--- a/src/main/java/org/spiffyui/mvsb/samples/client/LocalSuggestBox.java
+++ b/src/main/java/org/spiffyui/mvsb/samples/client/LocalSuggestBox.java
@@ -1,83 +1,79 @@
/*
* ========================================================================
*
* Copyright (c) 2005 Unpublished Work of Novell, Inc. All Rights Reserved.
*
* THIS WORK IS AN UNPUBLISHED WORK AND CONTAINS CONFIDENTIAL,
* PROPRIETARY AND TRADE SECRET INFORMATION OF NOVELL, INC. ACCESS TO
* THIS WORK IS RESTRICTED TO (I) NOVELL, INC. EMPLOYEES WHO HAVE A NEED
* TO KNOW HOW TO PERFORM TASKS WITHIN THE SCOPE OF THEIR ASSIGNMENTS AND
* (II) ENTITIES OTHER THAN NOVELL, INC. WHO HAVE ENTERED INTO
* APPROPRIATE LICENSE AGREEMENTS. NO PART OF THIS WORK MAY BE USED,
* PRACTICED, PERFORMED, COPIED, DISTRIBUTED, REVISED, MODIFIED,
* TRANSLATED, ABRIDGED, CONDENSED, EXPANDED, COLLECTED, COMPILED,
* LINKED, RECAST, TRANSFORMED OR ADAPTED WITHOUT THE PRIOR WRITTEN
* CONSENT OF NOVELL, INC. ANY USE OR EXPLOITATION OF THIS WORK WITHOUT
* AUTHORIZATION COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND CIVIL
* LIABILITY.
*
* ========================================================================
*/
package org.spiffyui.mvsb.samples.client;
import java.util.ArrayList;
import java.util.List;
import org.spiffyui.client.rest.RESTObjectCallBack;
import org.spiffyui.client.widgets.multivaluesuggest.MultivalueSuggestBoxBase;
public class LocalSuggestBox extends MultivalueSuggestBoxBase
{
private static final List<String> BASIC_COLORS;
static {
BASIC_COLORS = new ArrayList<String>();
BASIC_COLORS.add("Red");
BASIC_COLORS.add("Orange");
BASIC_COLORS.add("Yellow");
BASIC_COLORS.add("Green");
BASIC_COLORS.add("Blue");
BASIC_COLORS.add("Purple");
BASIC_COLORS.add("White");
BASIC_COLORS.add("Brown");
BASIC_COLORS.add("Black");
}
/**
* Constructor
* @param isMultivalued - whether or not to allow multiple values
*/
public LocalSuggestBox(boolean isMultivalued)
{
super(null, isMultivalued);
}
@Override
protected void queryOptions(String query, int from, int to, RESTObjectCallBack<OptionResultSet> callback)
{
- /*
- * We are just going to hard-code 10 shapes,
- * if the query is included
- */
OptionResultSet options = new OptionResultSet(BASIC_COLORS.size()); // this size isn't correct
int totalSize = 0;
for (String color : BASIC_COLORS) {
if (color.toLowerCase().indexOf(query.toLowerCase()) >= 0 || query.equals("*")) {
Option option = createOption(color);
options.addOption(option);
totalSize++;
}
}
options.setTotalSize(totalSize);
callback.success(options);
}
private Option createOption(String color)
{
Option option = new Option();
option.setName(color);
option.setValue(color);
return option;
}
}
| true | true | protected void queryOptions(String query, int from, int to, RESTObjectCallBack<OptionResultSet> callback)
{
/*
* We are just going to hard-code 10 shapes,
* if the query is included
*/
OptionResultSet options = new OptionResultSet(BASIC_COLORS.size()); // this size isn't correct
int totalSize = 0;
for (String color : BASIC_COLORS) {
if (color.toLowerCase().indexOf(query.toLowerCase()) >= 0 || query.equals("*")) {
Option option = createOption(color);
options.addOption(option);
totalSize++;
}
}
options.setTotalSize(totalSize);
callback.success(options);
}
| protected void queryOptions(String query, int from, int to, RESTObjectCallBack<OptionResultSet> callback)
{
OptionResultSet options = new OptionResultSet(BASIC_COLORS.size()); // this size isn't correct
int totalSize = 0;
for (String color : BASIC_COLORS) {
if (color.toLowerCase().indexOf(query.toLowerCase()) >= 0 || query.equals("*")) {
Option option = createOption(color);
options.addOption(option);
totalSize++;
}
}
options.setTotalSize(totalSize);
callback.success(options);
}
|
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/SecureStoreUtils.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/SecureStoreUtils.java
index 9717d166..5580bf2f 100644
--- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/SecureStoreUtils.java
+++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/SecureStoreUtils.java
@@ -1,51 +1,51 @@
/*******************************************************************************
* Copyright (C) 2010, Jens Baumgart <[email protected]>
* Copyright (C) 2010, Philipp Thun <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.ui.internal;
import java.io.IOException;
import org.eclipse.egit.core.securestorage.UserPasswordCredentials;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIText;
import org.eclipse.equinox.security.storage.StorageException;
import org.eclipse.jgit.transport.URIish;
/**
* Utilities for EGit secure store
*/
public class SecureStoreUtils {
/**
* Store credentials for the given uri
*
* @param credentials
* @param uri
* @return true if successful
*/
public static boolean storeCredentials(UserPasswordCredentials credentials,
URIish uri) {
- if (credentials != null) {
+ if (credentials != null && uri != null) {
try {
org.eclipse.egit.core.Activator.getDefault().getSecureStore()
.putCredentials(uri, credentials);
} catch (StorageException e) {
Activator.handleError(
UIText.SecureStoreUtils_writingCredentialsFailed, e,
true);
return false;
} catch (IOException e) {
Activator.handleError(
UIText.SecureStoreUtils_writingCredentialsFailed, e,
true);
return false;
}
}
return true;
}
}
| true | true | public static boolean storeCredentials(UserPasswordCredentials credentials,
URIish uri) {
if (credentials != null) {
try {
org.eclipse.egit.core.Activator.getDefault().getSecureStore()
.putCredentials(uri, credentials);
} catch (StorageException e) {
Activator.handleError(
UIText.SecureStoreUtils_writingCredentialsFailed, e,
true);
return false;
} catch (IOException e) {
Activator.handleError(
UIText.SecureStoreUtils_writingCredentialsFailed, e,
true);
return false;
}
}
return true;
}
| public static boolean storeCredentials(UserPasswordCredentials credentials,
URIish uri) {
if (credentials != null && uri != null) {
try {
org.eclipse.egit.core.Activator.getDefault().getSecureStore()
.putCredentials(uri, credentials);
} catch (StorageException e) {
Activator.handleError(
UIText.SecureStoreUtils_writingCredentialsFailed, e,
true);
return false;
} catch (IOException e) {
Activator.handleError(
UIText.SecureStoreUtils_writingCredentialsFailed, e,
true);
return false;
}
}
return true;
}
|
diff --git a/h2/src/main/org/h2/util/HashBase.java b/h2/src/main/org/h2/util/HashBase.java
index 2fab26a64..5a89b70c6 100644
--- a/h2/src/main/org/h2/util/HashBase.java
+++ b/h2/src/main/org/h2/util/HashBase.java
@@ -1,119 +1,123 @@
/*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.util;
/**
* The base for other hash classes.
*/
public abstract class HashBase {
private static final int MAX_LOAD = 90;
/**
* The bit mask to get the index from the hash code.
*/
protected int mask;
/**
* The number of slots in the table.
*/
protected int len;
/**
* The number of occupied slots, excluding the zero key (if any).
*/
protected int size;
/**
* The number of deleted slots.
*/
protected int deletedCount;
/**
* The level. The number of slots is 2 ^ level.
*/
protected int level;
/**
* Whether the zero key is used.
*/
protected boolean zeroKey;
private int maxSize, minSize, maxDeleted;
public HashBase() {
reset(2);
}
/**
* Increase the size of the underlying table and re-distribute the elements.
*
* @param newLevel the new level
*/
protected abstract void rehash(int newLevel);
/**
* Get the size of the map.
*
* @return the size
*/
public int size() {
return size + (zeroKey ? 1 : 0);
}
/**
* Check the size before adding an entry. This method resizes the map if
* required.
*/
void checkSizePut() {
if (deletedCount > size) {
rehash(level);
}
if (size + deletedCount >= maxSize) {
rehash(level + 1);
}
}
/**
* Check the size before removing an entry. This method resizes the map if
* required.
*/
protected void checkSizeRemove() {
if (size < minSize && level > 0) {
rehash(level - 1);
} else if (deletedCount > maxDeleted) {
rehash(level);
}
}
/**
* Clear the map and reset the level to the specified value.
*
* @param newLevel the new level
*/
protected void reset(int newLevel) {
+ // can't exceed 30 or we will generate a negative value for the "len" field
+ if (newLevel > 30) {
+ newLevel = 30;
+ }
minSize = size * 3 / 4;
size = 0;
level = newLevel;
len = 2 << level;
mask = len - 1;
maxSize = (int) (len * MAX_LOAD / 100L);
deletedCount = 0;
maxDeleted = 20 + len / 2;
}
/**
* Calculate the index for this hash code.
*
* @param hash the hash code
* @return the index
*/
protected int getIndex(int hash) {
return hash & mask;
}
}
| true | true | protected void reset(int newLevel) {
minSize = size * 3 / 4;
size = 0;
level = newLevel;
len = 2 << level;
mask = len - 1;
maxSize = (int) (len * MAX_LOAD / 100L);
deletedCount = 0;
maxDeleted = 20 + len / 2;
}
| protected void reset(int newLevel) {
// can't exceed 30 or we will generate a negative value for the "len" field
if (newLevel > 30) {
newLevel = 30;
}
minSize = size * 3 / 4;
size = 0;
level = newLevel;
len = 2 << level;
mask = len - 1;
maxSize = (int) (len * MAX_LOAD / 100L);
deletedCount = 0;
maxDeleted = 20 + len / 2;
}
|
diff --git a/tests/src/com/android/email/UtilityMediumTests.java b/tests/src/com/android/email/UtilityMediumTests.java
index 0c33391d..9b95fddc 100644
--- a/tests/src/com/android/email/UtilityMediumTests.java
+++ b/tests/src/com/android/email/UtilityMediumTests.java
@@ -1,275 +1,275 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email;
import com.android.email.provider.EmailContent;
import com.android.email.provider.EmailContent.Account;
import com.android.email.provider.EmailContent.Attachment;
import com.android.email.provider.EmailContent.Mailbox;
import com.android.email.provider.EmailContent.Message;
import com.android.email.provider.EmailContent.MessageColumns;
import com.android.email.provider.EmailProvider;
import com.android.email.provider.ProviderTestUtils;
import android.content.Context;
import android.test.ProviderTestCase2;
import android.test.suitebuilder.annotation.MediumTest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* This is a series of medium tests for the Utility class. These tests must be locally
* complete - no server(s) required.
*
* You can run this entire test case with:
* runtest -c com.android.email.UtilityMediumTests email
*/
@MediumTest
public class UtilityMediumTests extends ProviderTestCase2<EmailProvider> {
EmailProvider mProvider;
Context mMockContext;
public UtilityMediumTests() {
super(EmailProvider.class, EmailProvider.EMAIL_AUTHORITY);
}
@Override
public void setUp() throws Exception {
super.setUp();
mMockContext = getMockContext();
}
public void testFindExistingAccount() {
// Create two accounts
Account account1 = ProviderTestUtils.setupAccount("account1", false, mMockContext);
account1.mHostAuthRecv = ProviderTestUtils.setupHostAuth("ha1", -1, false, mMockContext);
account1.mHostAuthSend = ProviderTestUtils.setupHostAuth("ha1", -1, false, mMockContext);
account1.save(mMockContext);
Account account2 = ProviderTestUtils.setupAccount("account2", false, mMockContext);
account2.mHostAuthRecv = ProviderTestUtils.setupHostAuth("ha2", -1, false, mMockContext);
account2.mHostAuthSend = ProviderTestUtils.setupHostAuth("ha2", -1, false, mMockContext);
account2.save(mMockContext);
// Make sure we can find them
Account acct = Utility.findExistingAccount(mMockContext, -1, "address-ha1", "login-ha1");
assertNotNull(acct);
assertEquals("account1", acct.mDisplayName);
acct = Utility.findExistingAccount(mMockContext, -1, "address-ha2", "login-ha2");
assertNotNull(acct);
assertEquals("account2", acct.mDisplayName);
// We shouldn't find account
acct = Utility.findExistingAccount(mMockContext, -1, "address-ha3", "login-ha3");
assertNull(acct);
// Try to find account1, excluding account1
acct = Utility.findExistingAccount(mMockContext, account1.mId, "address-ha1", "login-ha1");
assertNull(acct);
}
public void testAttachmentExists() throws IOException {
Account account = ProviderTestUtils.setupAccount("account", true, mMockContext);
// We return false with null attachment
assertFalse(Utility.attachmentExists(mMockContext, null));
Mailbox mailbox =
ProviderTestUtils.setupMailbox("mailbox", account.mId, true, mMockContext);
Message message = ProviderTestUtils.setupMessage("foo", account.mId, mailbox.mId, false,
true, mMockContext);
Attachment attachment = ProviderTestUtils.setupAttachment(message.mId, "filename.ext",
69105, true, mMockContext);
attachment.mContentBytes = null;
// With no contentUri, we should return false
assertFalse(Utility.attachmentExists(mMockContext, attachment));
attachment.mContentBytes = new byte[0];
// With contentBytes set, we should return true
assertTrue(Utility.attachmentExists(mMockContext, attachment));
attachment.mContentBytes = null;
// Generate a file name in our data directory, and use that for contentUri
File file = mMockContext.getFileStreamPath("test.att");
// Delete the file if it already exists
if (file.exists()) {
assertTrue(file.delete());
}
// Should return false, because the file doesn't exist
assertFalse(Utility.attachmentExists(mMockContext, attachment));
assertTrue(file.createNewFile());
// Put something in the file
FileWriter writer = new FileWriter(file);
writer.write("Foo");
writer.flush();
writer.close();
attachment.mContentUri = "file://" + file.getAbsolutePath();
// Now, this should return true
assertTrue(Utility.attachmentExists(mMockContext, attachment));
}
public void testGetFirstRowLong() {
Account account1 = ProviderTestUtils.setupAccount("1", true, mMockContext);
Account account2 = ProviderTestUtils.setupAccount("X1", true, mMockContext);
Account account3 = ProviderTestUtils.setupAccount("X2", true, mMockContext);
// case 1. Account found
assertEquals((Long) account2.mId, Utility.getFirstRowLong(
mMockContext, Account.CONTENT_URI, EmailContent.ID_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"X%"},
Account.DISPLAY_NAME,
EmailContent.ID_PROJECTION_COLUMN));
// different sort order
assertEquals((Long) account3.mId, Utility.getFirstRowLong(
mMockContext, Account.CONTENT_URI, EmailContent.ID_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"X%"},
Account.DISPLAY_NAME + " desc",
EmailContent.ID_PROJECTION_COLUMN));
// case 2. no row found
assertEquals(null, Utility.getFirstRowLong(
mMockContext, Account.CONTENT_URI, EmailContent.ID_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"NO SUCH ACCOUNT"},
null,
EmailContent.ID_PROJECTION_COLUMN));
// case 3. no row found with default value
assertEquals((Long) (-1L), Utility.getFirstRowLong(
mMockContext, Account.CONTENT_URI, EmailContent.ID_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"NO SUCH ACCOUNT"},
null,
EmailContent.ID_PROJECTION_COLUMN, -1L));
}
public void testGetFirstRowInt() {
Account account1 = ProviderTestUtils.setupAccount("1", true, mMockContext);
Account account2 = ProviderTestUtils.setupAccount("X1", true, mMockContext);
Account account3 = ProviderTestUtils.setupAccount("X2", true, mMockContext);
// case 1. Account found
assertEquals((Integer)(int) account2.mId, Utility.getFirstRowInt(
mMockContext, Account.CONTENT_URI, EmailContent.ID_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"X%"},
Account.DISPLAY_NAME,
EmailContent.ID_PROJECTION_COLUMN));
// different sort order
assertEquals((Integer)(int) account3.mId, Utility.getFirstRowInt(
mMockContext, Account.CONTENT_URI, EmailContent.ID_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"X%"},
Account.DISPLAY_NAME + " desc",
EmailContent.ID_PROJECTION_COLUMN));
// case 2. no row found
assertEquals(null, Utility.getFirstRowInt(
mMockContext, Account.CONTENT_URI, EmailContent.ID_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"NO SUCH ACCOUNT"},
null,
EmailContent.ID_PROJECTION_COLUMN));
// case 3. no row found with default value
assertEquals((Integer) (-1), Utility.getFirstRowInt(
mMockContext, Account.CONTENT_URI, EmailContent.ID_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"NO SUCH ACCOUNT"},
null,
EmailContent.ID_PROJECTION_COLUMN, -1));
}
public void testGetFirstRowString() {
final String[] DISPLAY_NAME_PROJECTION = new String[] {Account.DISPLAY_NAME};
Account account1 = ProviderTestUtils.setupAccount("1", true, mMockContext);
Account account2 = ProviderTestUtils.setupAccount("X1", true, mMockContext);
Account account3 = ProviderTestUtils.setupAccount("X2", true, mMockContext);
// case 1. Account found
assertEquals(account2.mDisplayName, Utility.getFirstRowString(
mMockContext, Account.CONTENT_URI, DISPLAY_NAME_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"X%"},
Account.DISPLAY_NAME, 0));
// different sort order
assertEquals(account3.mDisplayName, Utility.getFirstRowString(
mMockContext, Account.CONTENT_URI, DISPLAY_NAME_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"X%"},
Account.DISPLAY_NAME + " desc", 0));
// case 2. no row found
assertEquals(null, Utility.getFirstRowString(
mMockContext, Account.CONTENT_URI, DISPLAY_NAME_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"NO SUCH ACCOUNT"},
null, 0));
// case 3. no row found with default value
assertEquals("-", Utility.getFirstRowString(
mMockContext, Account.CONTENT_URI, DISPLAY_NAME_PROJECTION,
Account.DISPLAY_NAME + " like :1", new String[] {"NO SUCH ACCOUNT"},
null, 0, "-"));
}
public void testBuildMailboxIdSelection() {
// Create dummy data...
Context c = mMockContext;
Account account1 = ProviderTestUtils.setupAccount("1", true, mMockContext);
Account account2 = ProviderTestUtils.setupAccount("X1", true, mMockContext);
Mailbox box1in = ProviderTestUtils.setupMailbox("m", account1.mId, true, c,
Mailbox.TYPE_INBOX);
Mailbox box1out = ProviderTestUtils.setupMailbox("m", account1.mId, true, c,
Mailbox.TYPE_OUTBOX);
Mailbox box1d = ProviderTestUtils.setupMailbox("m", account1.mId, true, c,
Mailbox.TYPE_DRAFTS);
Mailbox box2in = ProviderTestUtils.setupMailbox("m", account2.mId, true, c,
Mailbox.TYPE_INBOX);
Mailbox box2out = ProviderTestUtils.setupMailbox("m", account2.mId, true, c,
Mailbox.TYPE_OUTBOX);
Mailbox box2d = ProviderTestUtils.setupMailbox("m", account2.mId, true, c,
Mailbox.TYPE_DRAFTS);
final String FLAG_LOADED_TEST =
" AND ("
+ MessageColumns.FLAG_LOADED + " IN ("
+ Message.FLAG_LOADED_PARTIAL + "," + Message.FLAG_LOADED_COMPLETE
+ "))";
// Test!
// Normal mailbox
assertEquals(MessageColumns.MAILBOX_KEY + "=" + box1in.mId + FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, box1in.mId));
// Outbox query doesn't have FLAG_LOADED_TEST
assertEquals(MessageColumns.MAILBOX_KEY + "=" + box1out.mId,
Utility.buildMailboxIdSelection(mMockContext, box1out.mId));
// Combined mailboxes
assertEquals(Message.FLAG_READ + "=0" + FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_UNREAD));
- assertEquals(Message.FLAG_FAVORITE + "=1" + FLAG_LOADED_TEST,
+ assertEquals(Message.ALL_FAVORITE_SELECTION + FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_FAVORITES));
assertEquals(MessageColumns.MAILBOX_KEY + " IN (" + box1in.mId + "," + box2in.mId + ")"
+ FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_INBOXES));
assertEquals(MessageColumns.MAILBOX_KEY + " IN (" + box1d.mId + "," + box2d.mId + ")"
+ FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_DRAFTS));
assertEquals(MessageColumns.MAILBOX_KEY + " IN (" + box1out.mId + "," + box2out.mId + ")",
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_OUTBOX));
}
}
| true | true | public void testBuildMailboxIdSelection() {
// Create dummy data...
Context c = mMockContext;
Account account1 = ProviderTestUtils.setupAccount("1", true, mMockContext);
Account account2 = ProviderTestUtils.setupAccount("X1", true, mMockContext);
Mailbox box1in = ProviderTestUtils.setupMailbox("m", account1.mId, true, c,
Mailbox.TYPE_INBOX);
Mailbox box1out = ProviderTestUtils.setupMailbox("m", account1.mId, true, c,
Mailbox.TYPE_OUTBOX);
Mailbox box1d = ProviderTestUtils.setupMailbox("m", account1.mId, true, c,
Mailbox.TYPE_DRAFTS);
Mailbox box2in = ProviderTestUtils.setupMailbox("m", account2.mId, true, c,
Mailbox.TYPE_INBOX);
Mailbox box2out = ProviderTestUtils.setupMailbox("m", account2.mId, true, c,
Mailbox.TYPE_OUTBOX);
Mailbox box2d = ProviderTestUtils.setupMailbox("m", account2.mId, true, c,
Mailbox.TYPE_DRAFTS);
final String FLAG_LOADED_TEST =
" AND ("
+ MessageColumns.FLAG_LOADED + " IN ("
+ Message.FLAG_LOADED_PARTIAL + "," + Message.FLAG_LOADED_COMPLETE
+ "))";
// Test!
// Normal mailbox
assertEquals(MessageColumns.MAILBOX_KEY + "=" + box1in.mId + FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, box1in.mId));
// Outbox query doesn't have FLAG_LOADED_TEST
assertEquals(MessageColumns.MAILBOX_KEY + "=" + box1out.mId,
Utility.buildMailboxIdSelection(mMockContext, box1out.mId));
// Combined mailboxes
assertEquals(Message.FLAG_READ + "=0" + FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_UNREAD));
assertEquals(Message.FLAG_FAVORITE + "=1" + FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_FAVORITES));
assertEquals(MessageColumns.MAILBOX_KEY + " IN (" + box1in.mId + "," + box2in.mId + ")"
+ FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_INBOXES));
assertEquals(MessageColumns.MAILBOX_KEY + " IN (" + box1d.mId + "," + box2d.mId + ")"
+ FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_DRAFTS));
assertEquals(MessageColumns.MAILBOX_KEY + " IN (" + box1out.mId + "," + box2out.mId + ")",
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_OUTBOX));
}
| public void testBuildMailboxIdSelection() {
// Create dummy data...
Context c = mMockContext;
Account account1 = ProviderTestUtils.setupAccount("1", true, mMockContext);
Account account2 = ProviderTestUtils.setupAccount("X1", true, mMockContext);
Mailbox box1in = ProviderTestUtils.setupMailbox("m", account1.mId, true, c,
Mailbox.TYPE_INBOX);
Mailbox box1out = ProviderTestUtils.setupMailbox("m", account1.mId, true, c,
Mailbox.TYPE_OUTBOX);
Mailbox box1d = ProviderTestUtils.setupMailbox("m", account1.mId, true, c,
Mailbox.TYPE_DRAFTS);
Mailbox box2in = ProviderTestUtils.setupMailbox("m", account2.mId, true, c,
Mailbox.TYPE_INBOX);
Mailbox box2out = ProviderTestUtils.setupMailbox("m", account2.mId, true, c,
Mailbox.TYPE_OUTBOX);
Mailbox box2d = ProviderTestUtils.setupMailbox("m", account2.mId, true, c,
Mailbox.TYPE_DRAFTS);
final String FLAG_LOADED_TEST =
" AND ("
+ MessageColumns.FLAG_LOADED + " IN ("
+ Message.FLAG_LOADED_PARTIAL + "," + Message.FLAG_LOADED_COMPLETE
+ "))";
// Test!
// Normal mailbox
assertEquals(MessageColumns.MAILBOX_KEY + "=" + box1in.mId + FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, box1in.mId));
// Outbox query doesn't have FLAG_LOADED_TEST
assertEquals(MessageColumns.MAILBOX_KEY + "=" + box1out.mId,
Utility.buildMailboxIdSelection(mMockContext, box1out.mId));
// Combined mailboxes
assertEquals(Message.FLAG_READ + "=0" + FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_UNREAD));
assertEquals(Message.ALL_FAVORITE_SELECTION + FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_FAVORITES));
assertEquals(MessageColumns.MAILBOX_KEY + " IN (" + box1in.mId + "," + box2in.mId + ")"
+ FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_INBOXES));
assertEquals(MessageColumns.MAILBOX_KEY + " IN (" + box1d.mId + "," + box2d.mId + ")"
+ FLAG_LOADED_TEST,
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_DRAFTS));
assertEquals(MessageColumns.MAILBOX_KEY + " IN (" + box1out.mId + "," + box2out.mId + ")",
Utility.buildMailboxIdSelection(mMockContext, Mailbox.QUERY_ALL_OUTBOX));
}
|
diff --git a/adore-djatoka-1.1-corisco-1/src/java/gov/lanl/adore/djatoka/openurl/OpenURLJP2KMetadata.java b/adore-djatoka-1.1-corisco-1/src/java/gov/lanl/adore/djatoka/openurl/OpenURLJP2KMetadata.java
index 0238295..fa72113 100644
--- a/adore-djatoka-1.1-corisco-1/src/java/gov/lanl/adore/djatoka/openurl/OpenURLJP2KMetadata.java
+++ b/adore-djatoka-1.1-corisco-1/src/java/gov/lanl/adore/djatoka/openurl/OpenURLJP2KMetadata.java
@@ -1,167 +1,167 @@
/*
* Copyright (c) 2008 Los Alamos National Security, LLC.
* With modifications by Brasiliana Digital Library (http://brasiliana.usp.br), 2010.
*
* Los Alamos National Laboratory
* Research Library
* Digital Library Research & Prototyping Team
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package gov.lanl.adore.djatoka.openurl;
import gov.lanl.adore.djatoka.DjatokaException;
import gov.lanl.adore.djatoka.IExtract;
import gov.lanl.adore.djatoka.io.ExtractorFactory;
import gov.lanl.adore.djatoka.io.FormatConstants;
import gov.lanl.adore.djatoka.util.IOUtils;
import gov.lanl.adore.djatoka.util.ImageRecord;
import gov.lanl.util.HttpDate;
import info.openurl.oom.ContextObject;
import info.openurl.oom.OpenURLRequest;
import info.openurl.oom.OpenURLRequestProcessor;
import info.openurl.oom.OpenURLResponse;
import info.openurl.oom.Service;
import info.openurl.oom.config.ClassConfig;
import info.openurl.oom.config.OpenURLConfig;
import info.openurl.oom.entities.ServiceType;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/**
* The OpenURLJP2KMetadata OpenURL Service
*
* @author Ryan Chute
*/
public class OpenURLJP2KMetadata implements Service, FormatConstants {
static Logger logger = Logger.getLogger(OpenURLJP2KMetadata.class);
private static final String DEFAULT_IMPL_CLASS = SimpleListResolver.class.getCanonicalName();
private static final String PROPS_KEY_IMPL_CLASS = "OpenURLJP2KService.referentResolverImpl";
private static final String SVC_ID = "info:lanl-repo/svc/getMetadata";
private static final String RESPONSE_TYPE = "application/json";
private static String implClass = null;
private static Properties props = new Properties();
private static ExtractorFactory extractorFactory = new ExtractorFactory();
/**
* Construct an info:lanl-repo/svc/getMetadata web service class. Initializes
* Referent Resolver instance using OpenURLJP2KService.referentResolverImpl property.
*
* @param openURLConfig OOM Properties forwarded from OpenURLServlet
* @param classConfig Implementation Properties forwarded from OpenURLServlet
* @throws ResolverException
*/
public OpenURLJP2KMetadata(OpenURLConfig openURLConfig, ClassConfig classConfig) throws ResolverException {
try {
if (!ReferentManager.isInit()) {
props = IOUtils.loadConfigByCP(classConfig.getArg("props"));
implClass = props.getProperty(PROPS_KEY_IMPL_CLASS,DEFAULT_IMPL_CLASS);
ReferentManager.init((IReferentResolver) Class.forName(implClass).newInstance(), props);
}
} catch (IOException e) {
throw new ResolverException("Error attempting to open props file from classpath, disabling " + SVC_ID + " : " + e.getMessage());
} catch (Exception e) {
throw new ResolverException("Unable to inititalize implementation: " + props.getProperty(implClass) + " - " + e.getMessage());
}
}
/**
* Returns the OpenURL service identifier for this implementation of
* info.openurl.oom.Service
*/
public URI getServiceID() throws URISyntaxException {
return new URI(SVC_ID);
}
/**
* Returns the OpenURLResponse of a JSON object defining the core image
* properties. Having obtained a result, this method is then responsible for
* transforming it into an OpenURLResponse that acts as a proxy for
* HttpServletResponse.
*/
public OpenURLResponse resolve(ServiceType serviceType,
ContextObject contextObject, OpenURLRequest openURLRequest,
OpenURLRequestProcessor processor) {
String responseFormat = RESPONSE_TYPE;
int status = HttpServletResponse.SC_OK;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
baos = new ByteArrayOutputStream();
ImageRecord r = ReferentManager.getImageRecord(contextObject.getReferent());
IExtract jp2 = extractorFactory.getExtractorInstanceForFile(r.getImageFile());
r = jp2.getMetadata(r);
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\n\"identifier\": \"" + r.getIdentifier() + "\",");
sb.append("\n\"imagefile\": \"" + r.getImageFile() + "\",");
sb.append("\n\"width\": \"" + r.getWidth() + "\",");
sb.append("\n\"height\": \"" + r.getHeight() + "\",");
sb.append("\n\"dwtLevels\": \"" + r.getDWTLevels() + "\",");
sb.append("\n\"levels\": \"" + r.getLevels() + "\",");
sb.append("\n\"compositingLayerCount\": \"" + r.getCompositingLayerCount() + "\",");
if (r.getInstProps() != null) {
//HashMap<String, String> props = r.getInstProps();
sb.append("\n\"instProps\": {");
+ String separator = "";
for (Map.Entry<String, String> entry : r.getInstProps().entrySet()) {
- String key = entry.getKey();
- String value = entry.getValue();
- sb.append("\n\t\"" + key + "\": \"" + value + "\",");
+ sb.append(separator + "\n\t\"" + entry.getKey() + "\": \"" + entry.getValue() + "\"");
+ separator = ",";
}
sb.append("\n\t}");
}
sb.append("\n}");
baos.write(sb.toString().getBytes());
} catch (DjatokaException e) {
responseFormat = "text/plain";
status = HttpServletResponse.SC_NOT_FOUND;
} catch (Exception e) {
baos = new ByteArrayOutputStream();
try {
if (e.getMessage() != null)
baos.write(e.getMessage().getBytes("UTF-8"));
else {
logger.error(e,e);
baos.write("Internal Server Error: ".getBytes());
}
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
responseFormat = "text/plain";
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
HashMap<String, String> header_map = new HashMap<String, String>();
header_map.put("Content-Length", baos.size() + "");
header_map.put("Date", HttpDate.getHttpDate());
return new OpenURLResponse(status, responseFormat, baos.toByteArray(), header_map);
}
}
| false | true | public OpenURLResponse resolve(ServiceType serviceType,
ContextObject contextObject, OpenURLRequest openURLRequest,
OpenURLRequestProcessor processor) {
String responseFormat = RESPONSE_TYPE;
int status = HttpServletResponse.SC_OK;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
baos = new ByteArrayOutputStream();
ImageRecord r = ReferentManager.getImageRecord(contextObject.getReferent());
IExtract jp2 = extractorFactory.getExtractorInstanceForFile(r.getImageFile());
r = jp2.getMetadata(r);
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\n\"identifier\": \"" + r.getIdentifier() + "\",");
sb.append("\n\"imagefile\": \"" + r.getImageFile() + "\",");
sb.append("\n\"width\": \"" + r.getWidth() + "\",");
sb.append("\n\"height\": \"" + r.getHeight() + "\",");
sb.append("\n\"dwtLevels\": \"" + r.getDWTLevels() + "\",");
sb.append("\n\"levels\": \"" + r.getLevels() + "\",");
sb.append("\n\"compositingLayerCount\": \"" + r.getCompositingLayerCount() + "\",");
if (r.getInstProps() != null) {
//HashMap<String, String> props = r.getInstProps();
sb.append("\n\"instProps\": {");
for (Map.Entry<String, String> entry : r.getInstProps().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append("\n\t\"" + key + "\": \"" + value + "\",");
}
sb.append("\n\t}");
}
sb.append("\n}");
baos.write(sb.toString().getBytes());
} catch (DjatokaException e) {
responseFormat = "text/plain";
status = HttpServletResponse.SC_NOT_FOUND;
} catch (Exception e) {
baos = new ByteArrayOutputStream();
try {
if (e.getMessage() != null)
baos.write(e.getMessage().getBytes("UTF-8"));
else {
logger.error(e,e);
baos.write("Internal Server Error: ".getBytes());
}
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
responseFormat = "text/plain";
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
HashMap<String, String> header_map = new HashMap<String, String>();
header_map.put("Content-Length", baos.size() + "");
header_map.put("Date", HttpDate.getHttpDate());
return new OpenURLResponse(status, responseFormat, baos.toByteArray(), header_map);
}
| public OpenURLResponse resolve(ServiceType serviceType,
ContextObject contextObject, OpenURLRequest openURLRequest,
OpenURLRequestProcessor processor) {
String responseFormat = RESPONSE_TYPE;
int status = HttpServletResponse.SC_OK;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
baos = new ByteArrayOutputStream();
ImageRecord r = ReferentManager.getImageRecord(contextObject.getReferent());
IExtract jp2 = extractorFactory.getExtractorInstanceForFile(r.getImageFile());
r = jp2.getMetadata(r);
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append("\n\"identifier\": \"" + r.getIdentifier() + "\",");
sb.append("\n\"imagefile\": \"" + r.getImageFile() + "\",");
sb.append("\n\"width\": \"" + r.getWidth() + "\",");
sb.append("\n\"height\": \"" + r.getHeight() + "\",");
sb.append("\n\"dwtLevels\": \"" + r.getDWTLevels() + "\",");
sb.append("\n\"levels\": \"" + r.getLevels() + "\",");
sb.append("\n\"compositingLayerCount\": \"" + r.getCompositingLayerCount() + "\",");
if (r.getInstProps() != null) {
//HashMap<String, String> props = r.getInstProps();
sb.append("\n\"instProps\": {");
String separator = "";
for (Map.Entry<String, String> entry : r.getInstProps().entrySet()) {
sb.append(separator + "\n\t\"" + entry.getKey() + "\": \"" + entry.getValue() + "\"");
separator = ",";
}
sb.append("\n\t}");
}
sb.append("\n}");
baos.write(sb.toString().getBytes());
} catch (DjatokaException e) {
responseFormat = "text/plain";
status = HttpServletResponse.SC_NOT_FOUND;
} catch (Exception e) {
baos = new ByteArrayOutputStream();
try {
if (e.getMessage() != null)
baos.write(e.getMessage().getBytes("UTF-8"));
else {
logger.error(e,e);
baos.write("Internal Server Error: ".getBytes());
}
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
responseFormat = "text/plain";
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
HashMap<String, String> header_map = new HashMap<String, String>();
header_map.put("Content-Length", baos.size() + "");
header_map.put("Date", HttpDate.getHttpDate());
return new OpenURLResponse(status, responseFormat, baos.toByteArray(), header_map);
}
|
diff --git a/src/campyre/java/Room.java b/src/campyre/java/Room.java
index 2488433..e10d9d6 100644
--- a/src/campyre/java/Room.java
+++ b/src/campyre/java/Room.java
@@ -1,125 +1,125 @@
package campyre.java;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.impl.cookie.DateParseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Room implements Comparable<Room> {
public String id, name, topic;
public boolean full = false;
public Campfire campfire;
public ArrayList<User> initialUsers = null;
// For those times when you don't need a whole Room's details,
// You just have the ID and need a Room function (e.g. uploading a file)
public Room(Campfire campfire, String id) {
this.campfire = campfire;
this.id = id;
}
protected Room(Campfire campfire, JSONObject json) throws JSONException {
this.campfire = campfire;
this.id = json.getString("id");
this.name = json.getString("name");
this.topic = json.getString("topic");
if (json.has("full"))
this.full = json.getBoolean("full");
if (json.has("users")) {
initialUsers = new ArrayList<User>();
JSONArray users = json.getJSONArray("users");
int length = users.length();
for (int i=0; i<length; i++)
initialUsers.add(new User(campfire, users.getJSONObject(i)));
}
}
public static Room find(Campfire campfire, String id) throws CampfireException {
try {
return new Room(campfire, new CampfireRequest(campfire).getOne(Campfire.roomPath(id), "room"));
} catch(JSONException e) {
throw new CampfireException(e, "Problem loading room from the API.");
}
}
public static ArrayList<Room> all(Campfire campfire) throws CampfireException {
ArrayList<Room> rooms = new ArrayList<Room>();
try {
JSONArray roomList = new CampfireRequest(campfire).getList(Campfire.roomsPath(), "rooms");
int length = roomList.length();
for (int i=0; i<length; i++)
rooms.add(new Room(campfire, roomList.getJSONObject(i)));
Collections.sort(rooms);
} catch(JSONException e) {
throw new CampfireException(e, "Problem loading room list from the API.");
}
return rooms;
}
// convenience function
public void join() throws CampfireException {
joinRoom(campfire, id);
}
public static void joinRoom(Campfire campfire, String roomId) throws CampfireException {
String url = Campfire.joinPath(roomId);
HttpResponse response = new CampfireRequest(campfire).post(url);
int statusCode = response.getStatusLine().getStatusCode();
switch(statusCode) {
case HttpStatus.SC_OK:
return; // okay!
case HttpStatus.SC_MOVED_TEMPORARILY:
throw new CampfireException("Unknown room.");
default:
throw new CampfireException("Unknown error trying to join the room.");
}
}
public Message speak(String body) throws CampfireException {
String type = (body.contains("\n")) ? "PasteMessage" : "TextMessage";
String url = Campfire.speakPath(id);
try {
body = new String(body.getBytes("UTF-8"), "ISO-8859-1");
String request = new JSONObject().put("message", new JSONObject().put("type", type).put("body", body)).toString();
HttpResponse response = new CampfireRequest(campfire).post(url, request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_CREATED) {
String responseBody = CampfireRequest.responseBody(response);
return new Message(new JSONObject(responseBody).getJSONObject("message"));
} else
throw new CampfireException("Campfire error, message was not sent.");
} catch(JSONException e) {
throw new CampfireException(e, "Couldn't create JSON object while speaking.");
} catch (DateParseException e) {
throw new CampfireException(e, "Couldn't parse date from created message while speaking.");
} catch (UnsupportedEncodingException e) {
- throw new CampfireException(e, "Cannot convert from UTF-8 to ISO-8859-1");
+ throw new CampfireException(e, "Problem converting special characters for transmission.");
}
}
public void uploadImage(InputStream stream, String filename, String mimeType) throws CampfireException {
new CampfireRequest(campfire).uploadFile(Campfire.uploadPath(id), stream, filename, mimeType);
}
public String toString() {
return name;
}
@Override
public int compareTo(Room another) {
return name.compareTo(another.name);
}
}
| true | true | public Message speak(String body) throws CampfireException {
String type = (body.contains("\n")) ? "PasteMessage" : "TextMessage";
String url = Campfire.speakPath(id);
try {
body = new String(body.getBytes("UTF-8"), "ISO-8859-1");
String request = new JSONObject().put("message", new JSONObject().put("type", type).put("body", body)).toString();
HttpResponse response = new CampfireRequest(campfire).post(url, request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_CREATED) {
String responseBody = CampfireRequest.responseBody(response);
return new Message(new JSONObject(responseBody).getJSONObject("message"));
} else
throw new CampfireException("Campfire error, message was not sent.");
} catch(JSONException e) {
throw new CampfireException(e, "Couldn't create JSON object while speaking.");
} catch (DateParseException e) {
throw new CampfireException(e, "Couldn't parse date from created message while speaking.");
} catch (UnsupportedEncodingException e) {
throw new CampfireException(e, "Cannot convert from UTF-8 to ISO-8859-1");
}
}
| public Message speak(String body) throws CampfireException {
String type = (body.contains("\n")) ? "PasteMessage" : "TextMessage";
String url = Campfire.speakPath(id);
try {
body = new String(body.getBytes("UTF-8"), "ISO-8859-1");
String request = new JSONObject().put("message", new JSONObject().put("type", type).put("body", body)).toString();
HttpResponse response = new CampfireRequest(campfire).post(url, request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_CREATED) {
String responseBody = CampfireRequest.responseBody(response);
return new Message(new JSONObject(responseBody).getJSONObject("message"));
} else
throw new CampfireException("Campfire error, message was not sent.");
} catch(JSONException e) {
throw new CampfireException(e, "Couldn't create JSON object while speaking.");
} catch (DateParseException e) {
throw new CampfireException(e, "Couldn't parse date from created message while speaking.");
} catch (UnsupportedEncodingException e) {
throw new CampfireException(e, "Problem converting special characters for transmission.");
}
}
|
diff --git a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE2219Test.java b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE2219Test.java
index d7b490880..6967a889d 100644
--- a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE2219Test.java
+++ b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE2219Test.java
@@ -1,74 +1,76 @@
/*******************************************************************************
* Copyright (c) 2007 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.jsf.vpe.jsf.test.jbide;
import org.eclipse.core.resources.IFile;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import org.jboss.tools.jsf.vpe.jsf.test.JsfAllTests;
import org.jboss.tools.jst.jsp.jspeditor.JSPMultiPageEditor;
import org.jboss.tools.vpe.base.test.TestUtil;
import org.jboss.tools.vpe.base.test.VpeTest;
/**
* @author mareshkau
*
* Test case for JBIDE-2219
*/
public class JBIDE2219Test extends VpeTest {
public JBIDE2219Test(String name) {
super(name);
}
public void testJBIDE2219() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
// get test page path
IFile file = (IFile) TestUtil.getComponentPath("JBIDE/2219/testJBIDE2219.xhtml", //$NON-NLS-1$
JsfAllTests.IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file " + "JBIDE/2219/testJBIDE2219.xhtml", file); //$NON-NLS-1$ //$NON-NLS-2$
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input); //$NON-NLS-1$
// open and get editor
JSPMultiPageEditor part = openEditor(input);
TestUtil.waitForJobs();
StyledText styledText = part.getSourceEditor().getTextViewer()
.getTextWidget();
//sets caret in the begining of text
styledText.setCaretOffset(0);
assertTrue("Char count should be a 0", styledText.getCharCount()==0); //$NON-NLS-1$
+ assertFalse(part.isDirty());
styledText.insert("Test "); //$NON-NLS-1$
+ assertTrue(part.isDirty());
styledText.setSelection(0, 1);
assertTrue("Char count shouldn't be a 0",styledText.getCharCount()>2); //$NON-NLS-1$
TestUtil.delay();
TestUtil.waitForJobs();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(part, false);
TestUtil.waitForJobs();
//open again editor
part = openEditor(input);
TestUtil.waitForJobs();
styledText = part.getSourceEditor().getTextViewer().getTextWidget();
assertTrue("Number of chars should be a 0",styledText.getCharCount()==0); //$NON-NLS-1$
part.close(false);
}
}
| false | true | public void testJBIDE2219() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
// get test page path
IFile file = (IFile) TestUtil.getComponentPath("JBIDE/2219/testJBIDE2219.xhtml", //$NON-NLS-1$
JsfAllTests.IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file " + "JBIDE/2219/testJBIDE2219.xhtml", file); //$NON-NLS-1$ //$NON-NLS-2$
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input); //$NON-NLS-1$
// open and get editor
JSPMultiPageEditor part = openEditor(input);
TestUtil.waitForJobs();
StyledText styledText = part.getSourceEditor().getTextViewer()
.getTextWidget();
//sets caret in the begining of text
styledText.setCaretOffset(0);
assertTrue("Char count should be a 0", styledText.getCharCount()==0); //$NON-NLS-1$
styledText.insert("Test "); //$NON-NLS-1$
styledText.setSelection(0, 1);
assertTrue("Char count shouldn't be a 0",styledText.getCharCount()>2); //$NON-NLS-1$
TestUtil.delay();
TestUtil.waitForJobs();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(part, false);
TestUtil.waitForJobs();
//open again editor
part = openEditor(input);
TestUtil.waitForJobs();
styledText = part.getSourceEditor().getTextViewer().getTextWidget();
assertTrue("Number of chars should be a 0",styledText.getCharCount()==0); //$NON-NLS-1$
part.close(false);
}
| public void testJBIDE2219() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
// get test page path
IFile file = (IFile) TestUtil.getComponentPath("JBIDE/2219/testJBIDE2219.xhtml", //$NON-NLS-1$
JsfAllTests.IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file " + "JBIDE/2219/testJBIDE2219.xhtml", file); //$NON-NLS-1$ //$NON-NLS-2$
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input); //$NON-NLS-1$
// open and get editor
JSPMultiPageEditor part = openEditor(input);
TestUtil.waitForJobs();
StyledText styledText = part.getSourceEditor().getTextViewer()
.getTextWidget();
//sets caret in the begining of text
styledText.setCaretOffset(0);
assertTrue("Char count should be a 0", styledText.getCharCount()==0); //$NON-NLS-1$
assertFalse(part.isDirty());
styledText.insert("Test "); //$NON-NLS-1$
assertTrue(part.isDirty());
styledText.setSelection(0, 1);
assertTrue("Char count shouldn't be a 0",styledText.getCharCount()>2); //$NON-NLS-1$
TestUtil.delay();
TestUtil.waitForJobs();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeEditor(part, false);
TestUtil.waitForJobs();
//open again editor
part = openEditor(input);
TestUtil.waitForJobs();
styledText = part.getSourceEditor().getTextViewer().getTextWidget();
assertTrue("Number of chars should be a 0",styledText.getCharCount()==0); //$NON-NLS-1$
part.close(false);
}
|
diff --git a/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java b/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java
index 36a6ab5dc..dd1851597 100644
--- a/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java
+++ b/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java
@@ -1,520 +1,521 @@
//
// GACurveFitter.java
//
/*
SLIM Plotter application and curve fitting library for
combined spectral lifetime visualization and analysis.
Copyright (C) 2006-@year@ Curtis Rueden and Eric Kjellman.
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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.slim.fit;
import java.util.Random;
/**
* Genetic algorithm for exponential curve fitting.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/slim-plotter/src/loci/slim/fit/GACurveFitter.java">SVN</a></dd></dl>
*
* @author Eric Kjellman egkjellman at wisc.edu
*/
public class GACurveFitter extends CurveFitter {
// -- Fields --
protected int components;
protected double[][][] geneticData;
protected double[] fitness;
protected double currentRCSE;
protected int stallGenerations;
private double mutationFactor;
private static final boolean DEBUG = false;
private static final int STALL_GENERATIONS = 3;
private static final double STALLED_FACTOR = 2.0d;
private static final double MUTATION_CHANCE = .25d;
private static final int SPECIMENS = 25;
// Must be 0 < x < 1
private static final double INITIAL_MUTATION_FACTOR = .5;
// Must be 0 < x < 1
private static final double MUTATION_FACTOR_REDUCTION = .99;
// -- Constructor --
public GACurveFitter() {
initialize();
}
public void initialize() {
curveData = null;
components = 1;
curveEstimate = new double[components][3];
geneticData = null;
fitness = null;
currentRCSE = Double.MAX_VALUE;
stallGenerations = 0;
mutationFactor = INITIAL_MUTATION_FACTOR;
}
// -- CurveFitter methods --
/**
* iterate() runs through one iteration of whatever curve fitting
* technique this curve fitter uses. This will generally update the
* information returned by getCurve and getChiSquaredError
**/
public void iterate() {
if (currentRCSE == Double.MAX_VALUE) estimate();
// TODO: Move these out, reuse them. Synchronized?
double[][][] newGeneration = new double[SPECIMENS][components][3];
Random r = new Random();
// First make the new generation.
// If we don't have generation or fitness data, generate it from whatever
// the current estimate is.
// Additionally, if we haven't improved for a number of generations,
// shake things up.
if (geneticData == null || fitness == null ||
stallGenerations > STALL_GENERATIONS)
{
stallGenerations = 0;
mutationFactor *= MUTATION_FACTOR_REDUCTION;
for (int i = 1; i < newGeneration.length; i++) {
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
double factor = r.nextDouble() * STALLED_FACTOR;
newGeneration[i][j][k] = curveEstimate[j][k] * factor;
}
}
}
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
newGeneration[0][j][k] = curveEstimate[j][k];
}
}
}
else {
// The fitness array is determined in the previous generation. It is
// actually a marker for a range for a single random number, scaled to
// 0.0-1.0. For example, if the raw fitness was {4, 3, 2, 1}, the
// fitness array would contain {.4, .7, .9, 1.0}
for (int q = 0; q < newGeneration.length; q++) {
int mother = 0;
int father = 0;
double fchance = r.nextDouble();
double mchance = r.nextDouble();
for (int i = 0; i < fitness.length; i++) {
if (fitness[i] > fchance) {
father = i;
break;
}
}
for (int i = 0; i < fitness.length; i++) {
if (fitness[i] > mchance) {
mother = i;
break;
}
}
double minfluence = r.nextDouble();
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
newGeneration[q][j][k] =
geneticData[mother][j][k] * minfluence +
geneticData[father][j][k] * (1.0 - minfluence);
}
}
}
for (int i = 0; i < newGeneration.length; i++) {
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
// mutate, if necessary
if (r.nextDouble() < MUTATION_CHANCE) {
newGeneration[i][j][k] *= ((1.0 - mutationFactor) +
r.nextDouble() * (2.0 * mutationFactor));
}
}
}
}
}
geneticData = newGeneration;
double total = 0.0d;
double best = Double.MAX_VALUE;
int bestindex = -1;
stallGenerations++;
for (int i = 0; i < geneticData.length; i++) {
fitness = new double[geneticData.length];
fitness[i] = getReducedChiSquaredError(geneticData[i]);
if (fitness[i] < best) {
best = fitness[i];
bestindex = i;
}
fitness[i] = 1.0 / fitness[i];
total += fitness[i];
}
for (int i = 0; i < geneticData.length; i++) {
fitness[i] /= total;
}
if (best < currentRCSE) {
stallGenerations = 0;
currentRCSE = best;
for (int j = 0; j < components; j++) {
for (int k = 0; k < 3; k++) {
curveEstimate[j][k] = geneticData[bestindex][j][k];
}
}
}
/*
System.out.println("RCSE: " + currentRCSE);
for (int j = 0; j < components; j++) {
System.out.println("a: " + curveEstimate[j][0] + " b: " +
curveEstimate[j][1] + " c: " + curveEstimate[j][2]);
}
*/
}
/**
* Sets the data to be used to generate curve estimates.
* The array is expected to be of size datapoints
**/
public void setData(int[] data) {
curveData = data;
firstindex = 0;
lastindex = data.length - 1;
}
/**
* Returns a reference to the data array.
* Does not create a copy.
*/
public int[] getData() {
return curveData;
}
/**
* Sets how many exponentials are expected to be fitted.
* Currently, more than 2 is not supported.
**/
public void setComponentCount(int numExp) {
components = numExp;
curveEstimate = new double[numExp][3];
}
// Returns the number of exponentials to be fitted.
public int getComponentCount() {
return components;
}
// Initializes the curve fitter with a starting curve estimate.
public void estimate() {
/*
System.out.println("****** DATA ******");
for (int i = 0; i < curveData.length; i++) {
System.out.println("i: " + i + " data: " + curveData[i]);
}
*/
//try { Thread.sleep(1000); } catch(Exception e) {}
if (components >= 1) {
// TODO: Estimate c, factor it in below.
double guessC = Double.MAX_VALUE;
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
//double guessC = 0.0d;
// First, get a guess for the exponent.
// The exponent should be "constant", but we'd also like to weight
// the area at the beginning of the curve more heavily.
double num = 0.0;
double den = 0.0;
//for (int i = 1; i < curveData.length; i++) {
for (int i = firstindex + 1; i < curveData.length && i < lastindex; i++) {
if (curveData[i] > guessC && curveData[i-1] > guessC) {
//double time = curveData[i][0] - curveData[i-1][0];
double time = 1.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-1] - guessC);
double guess = 1.0 * -Math.log(factor);
if (DEBUG) {
System.out.println("Guess: " + guess + " Factor: " + factor);
}
num += (guess * (curveData[i] - guessC));
den += curveData[i] - guessC;
}
}
double exp = num/den;
if (DEBUG) System.out.println("Final exp guess: " + exp);
num = 0.0;
den = 0.0;
// Hacky... we would like to do this over the entire curve length,
// but the actual data is far too noisy to do this. Instead, we'll just
// do it for the first 5, which have the most data.
//for (int i = 0; i < curveData.length; i++)
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * exp);
// estimate a
double guessA = (curveData[i] - guessC) / value;
num += guessA * (curveData[i] - guessC);
den += curveData[i] - guessC;
if (DEBUG) {
System.out.println("Data: " + curveData[i] +
" Value: " + value + " guessA: " + guessA);
}
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
if (components == 2) {
double guessC = Double.MAX_VALUE;
//for (int i = 0; i < curveData.length; i++) {
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
curveEstimate[0][2] = guessC;
curveEstimate[1][2] = 0;
// First, get a guess for the exponents.
// To stabilize for error, do guesses over spans of 3 timepoints.
double high = 0.0d;
double low = Double.MAX_VALUE;
for (int i = firstindex + 3; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > guessC && curveData[i-3] > guessC + 10) {
//double time = curveData[i][0] - curveData[i-3][0];
double time = 3.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-3] - guessC);
double guess = (1.0 / 3.0) * -Math.log(factor);
if (guess > high) high = guess;
if (guess < low) low = guess;
}
}
curveEstimate[0][1] = high;
curveEstimate[1][1] = low;
double highA = 0.0d;
double lowA = Double.MAX_VALUE;
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC + 10) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * low);
// estimate a
double guessA = curveData[i] / value;
if (guessA > highA) highA = guessA;
if (guessA < lowA) lowA = guessA;
}
}
/*
if (10.0 > lowA) lowA = 10.0;
if (20.0 > highA) highA = 20.0;
*/
curveEstimate[0][0] = highA - lowA;
curveEstimate[1][0] = lowA;
// It seems like the low estimates are pretty good, usually.
// It may be possible to get a better high estimate by subtracting out
// the low estimate, and then recalculating as if it were single
// exponential.
double[][] lowEst = new double[1][3];
lowEst[0][0] = curveEstimate[1][0];
lowEst[0][1] = curveEstimate[1][1];
lowEst[0][2] = curveEstimate[1][2];
int[] cdata = new int[lastindex - firstindex + 1];
System.arraycopy(curveData, firstindex, cdata, 0, cdata.length);
double[] lowData = getEstimates(cdata, lowEst);
double[][] lowValues = new double[cdata.length][2];
for (int i = 0; i < lowValues.length; i++) {
lowValues[i][0] = i;
lowValues[i][1] = cdata[i] - lowData[i];
}
// now, treat lowValues as a single exponent.
double num = 0.0;
double den = 0.0;
for (int i = 1; i < lowValues.length; i++) {
if (lowValues[i][1] > guessC && lowValues[i-1][1] > guessC) {
double time = lowValues[i][0] - lowValues[i-1][0];
double factor =
(lowValues[i][1] - guessC) / (lowValues[i-1][1] - guessC);
double guess = (1.0 / time) * -Math.log(factor);
num += (guess * (lowValues[i][1] - guessC));
den += lowValues[i][1] - guessC;
}
}
double exp = num/den;
num = 0.0;
den = 0.0;
//for (int i = 0; i < lowValues.length; i++)
- for (int i = 0; i < 5; i++) {
+ int lowBound = lowValues.length < 5 ? lowValues.length : 5;
+ for (int i = 0; i < lowBound; i++) {
if (lowValues[i][1] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -lowValues[i][0] * exp);
// estimate a
double guessA = lowValues[i][1] / value;
num += guessA * (lowValues[i][1] - guessC);
den += lowValues[i][1] - guessC;
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
// Sometimes, if the curve looks strange, we'll get a negative estimate
// This will really have to be fixed in iteration, but until then we want
// to get a "reasonable" positive estimate.
// We'll take the high point of the curve, and then the farthest away
// low point of the curve, and naively fit a single exponential to those
// two points. In the case of a multiple exponential curve, we'll split the
// a factor unevenly among the two, and then sort it out in iteration.
// This is all very "last ditch effort" estimation.
boolean doNegativeEstimation = false;
for (int i = 0; i < curveEstimate.length; i++) {
if (curveEstimate[i][1] < 0) {
doNegativeEstimation = true;
//System.out.println("Negative factor " +
// curveEstimate[i][1] + " found.");
}
}
if (doNegativeEstimation) {
// Find highest point in the curve
int maxIndex = -1;
int maxData = -1;
for (int i = firstindex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > maxData) {
maxIndex = i;
maxData = curveData[i];
}
}
int minIndex = -1;
int minData = Integer.MAX_VALUE;
for (int i = maxIndex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] <= minData) {
minIndex = i;
minData = curveData[i];
}
}
//System.out.println("maxIndex: " + maxIndex + " minIndex: " + minIndex);
// If we have valid min and max data, perform the "estimate"
double expguess = -1;
// ae^-b(t0)+c = x
// ae^-b(t1)+c = y.
// if t0 = 0, and c is minData, then a = x - minData. (e^0 = 1)
// Then, (x-min)e^-b(t1) = y
// e^-b(t1) = y / (x-min)
// ln e^-b(t1) = ln (y / (x - min))
// -b(t1) = ln (y / (x - min))
// -b = (ln (y / (x - min)) / t1)
// b = -(ln (y / (x - min)) / t1)
// and c = minData
if (maxData != -1 && minData != -1) {
double a = maxData - minData;
// min value for many trouble cases is 0, which is problematic.
// As an estimate, if minData is 0, we'll scan back to see how far it
// until data, and use that distance as an estimate.
double y = 0;
int newmin = minIndex;
while (curveData[newmin] == minData) newmin--;
y = 1.0 / (minIndex - newmin);
expguess = -(Math.log(y / (maxData - minData)) / (minIndex - maxIndex));
}
if (expguess < 0) {
// If the guess is still somehow negative
// (example, ascending curve), punt;
expguess = 1;
}
//System.out.println("Estimating: " + expguess);
//System.out.println("maxData: " + maxData + " firstindex: " +
// firstindex + " data: " + curveData[firstindex]);
if (components == 1) {
curveEstimate[0][0] = maxData - minData;
curveEstimate[0][1] = expguess;
curveEstimate[0][2] = minData;
} else {
// 2 components
curveEstimate[0][0] = maxData * .8;
curveEstimate[0][1] = expguess;
curveEstimate[1][0] = maxData * .2;
curveEstimate[1][1] = expguess;
curveEstimate[0][2] = minData;
}
}
// To update currentRCSE.
currentRCSE = getReducedChiSquaredError();
}
/**
* Returns the current curve estimate.
* Return size is expected to be [components][3]
* For each exponential of the form ae^-bt+c,
* [][0] is a, [1] is b, [2] is c.
**/
public double[][] getCurve() {
if (components == 1) return curveEstimate;
// Otherwise, it's 2 exponential, and we want it in ascending order
if (components == 2) {
if (curveEstimate[0][1] > curveEstimate[1][1]) {
double[][] toreturn = new double[components][3];
toreturn[0] = curveEstimate[1];
toreturn[1] = curveEstimate[0];
return toreturn;
} else {
return curveEstimate;
}
}
return null;
}
/**
* Sets the current curve estimate, useful if information about the
* curve is already known.
* See getCurve for information about the array to pass.
**/
public void setCurve(double[][] curve) {
if (curve.length != components) {
throw new IllegalArgumentException("Incorrect number of components.");
}
if (curve[0].length != 3) {
throw new IllegalArgumentException(
"Incorrect number of elements per degree.");
}
curveEstimate = curve;
currentRCSE = getReducedChiSquaredError();
}
public void setFirst(int index) {
firstindex = index;
}
public void setLast(int index) {
lastindex = index;
}
}
| true | true | public void estimate() {
/*
System.out.println("****** DATA ******");
for (int i = 0; i < curveData.length; i++) {
System.out.println("i: " + i + " data: " + curveData[i]);
}
*/
//try { Thread.sleep(1000); } catch(Exception e) {}
if (components >= 1) {
// TODO: Estimate c, factor it in below.
double guessC = Double.MAX_VALUE;
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
//double guessC = 0.0d;
// First, get a guess for the exponent.
// The exponent should be "constant", but we'd also like to weight
// the area at the beginning of the curve more heavily.
double num = 0.0;
double den = 0.0;
//for (int i = 1; i < curveData.length; i++) {
for (int i = firstindex + 1; i < curveData.length && i < lastindex; i++) {
if (curveData[i] > guessC && curveData[i-1] > guessC) {
//double time = curveData[i][0] - curveData[i-1][0];
double time = 1.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-1] - guessC);
double guess = 1.0 * -Math.log(factor);
if (DEBUG) {
System.out.println("Guess: " + guess + " Factor: " + factor);
}
num += (guess * (curveData[i] - guessC));
den += curveData[i] - guessC;
}
}
double exp = num/den;
if (DEBUG) System.out.println("Final exp guess: " + exp);
num = 0.0;
den = 0.0;
// Hacky... we would like to do this over the entire curve length,
// but the actual data is far too noisy to do this. Instead, we'll just
// do it for the first 5, which have the most data.
//for (int i = 0; i < curveData.length; i++)
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * exp);
// estimate a
double guessA = (curveData[i] - guessC) / value;
num += guessA * (curveData[i] - guessC);
den += curveData[i] - guessC;
if (DEBUG) {
System.out.println("Data: " + curveData[i] +
" Value: " + value + " guessA: " + guessA);
}
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
if (components == 2) {
double guessC = Double.MAX_VALUE;
//for (int i = 0; i < curveData.length; i++) {
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
curveEstimate[0][2] = guessC;
curveEstimate[1][2] = 0;
// First, get a guess for the exponents.
// To stabilize for error, do guesses over spans of 3 timepoints.
double high = 0.0d;
double low = Double.MAX_VALUE;
for (int i = firstindex + 3; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > guessC && curveData[i-3] > guessC + 10) {
//double time = curveData[i][0] - curveData[i-3][0];
double time = 3.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-3] - guessC);
double guess = (1.0 / 3.0) * -Math.log(factor);
if (guess > high) high = guess;
if (guess < low) low = guess;
}
}
curveEstimate[0][1] = high;
curveEstimate[1][1] = low;
double highA = 0.0d;
double lowA = Double.MAX_VALUE;
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC + 10) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * low);
// estimate a
double guessA = curveData[i] / value;
if (guessA > highA) highA = guessA;
if (guessA < lowA) lowA = guessA;
}
}
/*
if (10.0 > lowA) lowA = 10.0;
if (20.0 > highA) highA = 20.0;
*/
curveEstimate[0][0] = highA - lowA;
curveEstimate[1][0] = lowA;
// It seems like the low estimates are pretty good, usually.
// It may be possible to get a better high estimate by subtracting out
// the low estimate, and then recalculating as if it were single
// exponential.
double[][] lowEst = new double[1][3];
lowEst[0][0] = curveEstimate[1][0];
lowEst[0][1] = curveEstimate[1][1];
lowEst[0][2] = curveEstimate[1][2];
int[] cdata = new int[lastindex - firstindex + 1];
System.arraycopy(curveData, firstindex, cdata, 0, cdata.length);
double[] lowData = getEstimates(cdata, lowEst);
double[][] lowValues = new double[cdata.length][2];
for (int i = 0; i < lowValues.length; i++) {
lowValues[i][0] = i;
lowValues[i][1] = cdata[i] - lowData[i];
}
// now, treat lowValues as a single exponent.
double num = 0.0;
double den = 0.0;
for (int i = 1; i < lowValues.length; i++) {
if (lowValues[i][1] > guessC && lowValues[i-1][1] > guessC) {
double time = lowValues[i][0] - lowValues[i-1][0];
double factor =
(lowValues[i][1] - guessC) / (lowValues[i-1][1] - guessC);
double guess = (1.0 / time) * -Math.log(factor);
num += (guess * (lowValues[i][1] - guessC));
den += lowValues[i][1] - guessC;
}
}
double exp = num/den;
num = 0.0;
den = 0.0;
//for (int i = 0; i < lowValues.length; i++)
for (int i = 0; i < 5; i++) {
if (lowValues[i][1] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -lowValues[i][0] * exp);
// estimate a
double guessA = lowValues[i][1] / value;
num += guessA * (lowValues[i][1] - guessC);
den += lowValues[i][1] - guessC;
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
// Sometimes, if the curve looks strange, we'll get a negative estimate
// This will really have to be fixed in iteration, but until then we want
// to get a "reasonable" positive estimate.
// We'll take the high point of the curve, and then the farthest away
// low point of the curve, and naively fit a single exponential to those
// two points. In the case of a multiple exponential curve, we'll split the
// a factor unevenly among the two, and then sort it out in iteration.
// This is all very "last ditch effort" estimation.
boolean doNegativeEstimation = false;
for (int i = 0; i < curveEstimate.length; i++) {
if (curveEstimate[i][1] < 0) {
doNegativeEstimation = true;
//System.out.println("Negative factor " +
// curveEstimate[i][1] + " found.");
}
}
if (doNegativeEstimation) {
// Find highest point in the curve
int maxIndex = -1;
int maxData = -1;
for (int i = firstindex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > maxData) {
maxIndex = i;
maxData = curveData[i];
}
}
int minIndex = -1;
int minData = Integer.MAX_VALUE;
for (int i = maxIndex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] <= minData) {
minIndex = i;
minData = curveData[i];
}
}
//System.out.println("maxIndex: " + maxIndex + " minIndex: " + minIndex);
// If we have valid min and max data, perform the "estimate"
double expguess = -1;
// ae^-b(t0)+c = x
// ae^-b(t1)+c = y.
// if t0 = 0, and c is minData, then a = x - minData. (e^0 = 1)
// Then, (x-min)e^-b(t1) = y
// e^-b(t1) = y / (x-min)
// ln e^-b(t1) = ln (y / (x - min))
// -b(t1) = ln (y / (x - min))
// -b = (ln (y / (x - min)) / t1)
// b = -(ln (y / (x - min)) / t1)
// and c = minData
if (maxData != -1 && minData != -1) {
double a = maxData - minData;
// min value for many trouble cases is 0, which is problematic.
// As an estimate, if minData is 0, we'll scan back to see how far it
// until data, and use that distance as an estimate.
double y = 0;
int newmin = minIndex;
while (curveData[newmin] == minData) newmin--;
y = 1.0 / (minIndex - newmin);
expguess = -(Math.log(y / (maxData - minData)) / (minIndex - maxIndex));
}
if (expguess < 0) {
// If the guess is still somehow negative
// (example, ascending curve), punt;
expguess = 1;
}
//System.out.println("Estimating: " + expguess);
//System.out.println("maxData: " + maxData + " firstindex: " +
// firstindex + " data: " + curveData[firstindex]);
if (components == 1) {
curveEstimate[0][0] = maxData - minData;
curveEstimate[0][1] = expguess;
curveEstimate[0][2] = minData;
} else {
// 2 components
curveEstimate[0][0] = maxData * .8;
curveEstimate[0][1] = expguess;
curveEstimate[1][0] = maxData * .2;
curveEstimate[1][1] = expguess;
curveEstimate[0][2] = minData;
}
}
// To update currentRCSE.
currentRCSE = getReducedChiSquaredError();
}
| public void estimate() {
/*
System.out.println("****** DATA ******");
for (int i = 0; i < curveData.length; i++) {
System.out.println("i: " + i + " data: " + curveData[i]);
}
*/
//try { Thread.sleep(1000); } catch(Exception e) {}
if (components >= 1) {
// TODO: Estimate c, factor it in below.
double guessC = Double.MAX_VALUE;
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
//double guessC = 0.0d;
// First, get a guess for the exponent.
// The exponent should be "constant", but we'd also like to weight
// the area at the beginning of the curve more heavily.
double num = 0.0;
double den = 0.0;
//for (int i = 1; i < curveData.length; i++) {
for (int i = firstindex + 1; i < curveData.length && i < lastindex; i++) {
if (curveData[i] > guessC && curveData[i-1] > guessC) {
//double time = curveData[i][0] - curveData[i-1][0];
double time = 1.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-1] - guessC);
double guess = 1.0 * -Math.log(factor);
if (DEBUG) {
System.out.println("Guess: " + guess + " Factor: " + factor);
}
num += (guess * (curveData[i] - guessC));
den += curveData[i] - guessC;
}
}
double exp = num/den;
if (DEBUG) System.out.println("Final exp guess: " + exp);
num = 0.0;
den = 0.0;
// Hacky... we would like to do this over the entire curve length,
// but the actual data is far too noisy to do this. Instead, we'll just
// do it for the first 5, which have the most data.
//for (int i = 0; i < curveData.length; i++)
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * exp);
// estimate a
double guessA = (curveData[i] - guessC) / value;
num += guessA * (curveData[i] - guessC);
den += curveData[i] - guessC;
if (DEBUG) {
System.out.println("Data: " + curveData[i] +
" Value: " + value + " guessA: " + guessA);
}
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
if (components == 2) {
double guessC = Double.MAX_VALUE;
//for (int i = 0; i < curveData.length; i++) {
for (int i = firstindex; i < curveData.length && i < lastindex; i++) {
if (curveData[i] < guessC) guessC = curveData[i];
}
curveEstimate[0][2] = guessC;
curveEstimate[1][2] = 0;
// First, get a guess for the exponents.
// To stabilize for error, do guesses over spans of 3 timepoints.
double high = 0.0d;
double low = Double.MAX_VALUE;
for (int i = firstindex + 3; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > guessC && curveData[i-3] > guessC + 10) {
//double time = curveData[i][0] - curveData[i-3][0];
double time = 3.0d;
double factor =
(curveData[i] - guessC) / (curveData[i-3] - guessC);
double guess = (1.0 / 3.0) * -Math.log(factor);
if (guess > high) high = guess;
if (guess < low) low = guess;
}
}
curveEstimate[0][1] = high;
curveEstimate[1][1] = low;
double highA = 0.0d;
double lowA = Double.MAX_VALUE;
for (int i=firstindex; i < 5 + firstindex && i < curveData.length; i++) {
if (curveData[i] > guessC + 10) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -i * low);
// estimate a
double guessA = curveData[i] / value;
if (guessA > highA) highA = guessA;
if (guessA < lowA) lowA = guessA;
}
}
/*
if (10.0 > lowA) lowA = 10.0;
if (20.0 > highA) highA = 20.0;
*/
curveEstimate[0][0] = highA - lowA;
curveEstimate[1][0] = lowA;
// It seems like the low estimates are pretty good, usually.
// It may be possible to get a better high estimate by subtracting out
// the low estimate, and then recalculating as if it were single
// exponential.
double[][] lowEst = new double[1][3];
lowEst[0][0] = curveEstimate[1][0];
lowEst[0][1] = curveEstimate[1][1];
lowEst[0][2] = curveEstimate[1][2];
int[] cdata = new int[lastindex - firstindex + 1];
System.arraycopy(curveData, firstindex, cdata, 0, cdata.length);
double[] lowData = getEstimates(cdata, lowEst);
double[][] lowValues = new double[cdata.length][2];
for (int i = 0; i < lowValues.length; i++) {
lowValues[i][0] = i;
lowValues[i][1] = cdata[i] - lowData[i];
}
// now, treat lowValues as a single exponent.
double num = 0.0;
double den = 0.0;
for (int i = 1; i < lowValues.length; i++) {
if (lowValues[i][1] > guessC && lowValues[i-1][1] > guessC) {
double time = lowValues[i][0] - lowValues[i-1][0];
double factor =
(lowValues[i][1] - guessC) / (lowValues[i-1][1] - guessC);
double guess = (1.0 / time) * -Math.log(factor);
num += (guess * (lowValues[i][1] - guessC));
den += lowValues[i][1] - guessC;
}
}
double exp = num/den;
num = 0.0;
den = 0.0;
//for (int i = 0; i < lowValues.length; i++)
int lowBound = lowValues.length < 5 ? lowValues.length : 5;
for (int i = 0; i < lowBound; i++) {
if (lowValues[i][1] > guessC) {
// calculate e^-bt based on our exponent estimate
double value = Math.pow(Math.E, -lowValues[i][0] * exp);
// estimate a
double guessA = lowValues[i][1] / value;
num += guessA * (lowValues[i][1] - guessC);
den += lowValues[i][1] - guessC;
}
}
double mult = num/den;
curveEstimate[0][0] = mult;
curveEstimate[0][1] = exp;
curveEstimate[0][2] = guessC;
}
// Sometimes, if the curve looks strange, we'll get a negative estimate
// This will really have to be fixed in iteration, but until then we want
// to get a "reasonable" positive estimate.
// We'll take the high point of the curve, and then the farthest away
// low point of the curve, and naively fit a single exponential to those
// two points. In the case of a multiple exponential curve, we'll split the
// a factor unevenly among the two, and then sort it out in iteration.
// This is all very "last ditch effort" estimation.
boolean doNegativeEstimation = false;
for (int i = 0; i < curveEstimate.length; i++) {
if (curveEstimate[i][1] < 0) {
doNegativeEstimation = true;
//System.out.println("Negative factor " +
// curveEstimate[i][1] + " found.");
}
}
if (doNegativeEstimation) {
// Find highest point in the curve
int maxIndex = -1;
int maxData = -1;
for (int i = firstindex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] > maxData) {
maxIndex = i;
maxData = curveData[i];
}
}
int minIndex = -1;
int minData = Integer.MAX_VALUE;
for (int i = maxIndex; i < lastindex && i < curveData.length; i++) {
if (curveData[i] <= minData) {
minIndex = i;
minData = curveData[i];
}
}
//System.out.println("maxIndex: " + maxIndex + " minIndex: " + minIndex);
// If we have valid min and max data, perform the "estimate"
double expguess = -1;
// ae^-b(t0)+c = x
// ae^-b(t1)+c = y.
// if t0 = 0, and c is minData, then a = x - minData. (e^0 = 1)
// Then, (x-min)e^-b(t1) = y
// e^-b(t1) = y / (x-min)
// ln e^-b(t1) = ln (y / (x - min))
// -b(t1) = ln (y / (x - min))
// -b = (ln (y / (x - min)) / t1)
// b = -(ln (y / (x - min)) / t1)
// and c = minData
if (maxData != -1 && minData != -1) {
double a = maxData - minData;
// min value for many trouble cases is 0, which is problematic.
// As an estimate, if minData is 0, we'll scan back to see how far it
// until data, and use that distance as an estimate.
double y = 0;
int newmin = minIndex;
while (curveData[newmin] == minData) newmin--;
y = 1.0 / (minIndex - newmin);
expguess = -(Math.log(y / (maxData - minData)) / (minIndex - maxIndex));
}
if (expguess < 0) {
// If the guess is still somehow negative
// (example, ascending curve), punt;
expguess = 1;
}
//System.out.println("Estimating: " + expguess);
//System.out.println("maxData: " + maxData + " firstindex: " +
// firstindex + " data: " + curveData[firstindex]);
if (components == 1) {
curveEstimate[0][0] = maxData - minData;
curveEstimate[0][1] = expguess;
curveEstimate[0][2] = minData;
} else {
// 2 components
curveEstimate[0][0] = maxData * .8;
curveEstimate[0][1] = expguess;
curveEstimate[1][0] = maxData * .2;
curveEstimate[1][1] = expguess;
curveEstimate[0][2] = minData;
}
}
// To update currentRCSE.
currentRCSE = getReducedChiSquaredError();
}
|
diff --git a/core/src/main/java/hudson/tasks/Ant.java b/core/src/main/java/hudson/tasks/Ant.java
index 1a513ce66..6f87f467f 100644
--- a/core/src/main/java/hudson/tasks/Ant.java
+++ b/core/src/main/java/hudson/tasks/Ant.java
@@ -1,318 +1,319 @@
package hudson.tasks;
import hudson.CopyOnWrite;
import hudson.Launcher;
import hudson.StructuredForm;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.TaskListener;
import hudson.remoting.Callable;
import hudson.util.ArgumentListBuilder;
import hudson.util.FormFieldValidator;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
/**
* Ant launcher.
*
* @author Kohsuke Kawaguchi
*/
public class Ant extends Builder {
/**
* The targets, properties, and other Ant options.
* Either separated by whitespace or newline.
*/
private final String targets;
/**
* Identifies {@link AntInstallation} to be used.
*/
private final String antName;
/**
* ANT_OPTS if not null.
*/
private final String antOpts;
/**
* Optional build script path relative to the workspace.
* Used for the Ant '-f' option.
*/
private final String buildFile;
/**
* Optional properties to be passed to Ant. Follows {@link Properties} syntax.
*/
private final String properties;
@DataBoundConstructor
public Ant(String targets,String antName, String antOpts, String buildFile, String properties) {
this.targets = targets;
this.antName = antName;
this.antOpts = Util.fixEmptyAndTrim(antOpts);
this.buildFile = Util.fixEmptyAndTrim(buildFile);
this.properties = Util.fixEmptyAndTrim(properties);
}
public String getBuildFile() {
return buildFile;
}
public String getProperties() {
return properties;
}
public String getTargets() {
return targets;
}
/**
* Gets the Ant to invoke,
* or null to invoke the default one.
*/
public AntInstallation getAnt() {
for( AntInstallation i : DESCRIPTOR.getInstallations() ) {
if(antName!=null && i.getName().equals(antName))
return i;
}
return null;
}
/**
* Gets the ANT_OPTS parameter, or null.
*/
public String getAntOpts() {
return antOpts;
}
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
AbstractProject proj = build.getProject();
ArgumentListBuilder args = new ArgumentListBuilder();
String execName;
if(launcher.isUnix())
execName = "ant";
else
execName = "ant.bat";
String normalizedTarget = targets.replaceAll("[\t\r\n]+"," ");
AntInstallation ai = getAnt();
if(ai==null)
args.add(execName);
else
args.add(ai.getExecutable(launcher));
if(buildFile!=null) {
args.add("-file", buildFile);
}
args.addKeyValuePairs("-D",build.getBuildVariables());
if (properties != null) {
Properties p = new Properties();
try {
p.load(new StringReader(properties));
} catch (NoSuchMethodError e) {
// load(Reader) method is only available on JDK6.
// this fall back version doesn't work correctly with non-ASCII characters,
// but there's no other easy ways out it seems.
p.load(new ByteArrayInputStream(properties.getBytes()));
}
for (Entry<Object,Object> entry : p.entrySet()) {
args.add("-D" + entry.getKey() + "=" + entry.getValue());
}
}
args.addTokenized(normalizedTarget);
Map<String,String> env = build.getEnvVars();
if(ai!=null)
env.put("ANT_HOME",ai.getAntHome());
if(antOpts!=null)
env.put("ANT_OPTS",antOpts);
if(!launcher.isUnix()) {
// on Windows, executing batch file can't return the correct error code,
// so we need to wrap it into cmd.exe.
// double %% is needed because we want ERRORLEVEL to be expanded after
// batch file executed, not before. This alone shows how broken Windows is...
args.add("&&","exit","%%ERRORLEVEL%%");
// on Windows, proper double quote handling requires extra surrounding quote.
// so we need to convert the entire argument list once into a string,
// then build the new list so that by the time JVM invokes CreateProcess win32 API,
// it puts additional double-quote. See issue #1007
// the 'addQuoted' is necessary because Process implementation for Windows (at least in Sun JVM)
// is too clever to avoid putting a quote around it if the argument begins with "
// see "cmd /?" for more about how cmd.exe handles quotation.
args = new ArgumentListBuilder().add("cmd.exe","/C").addQuoted(args.toStringWithQuote());
}
+ long startTime = System.currentTimeMillis();
try {
int r = launcher.launch(args.toCommandArray(),env,listener.getLogger(),proj.getModuleRoot()).join();
return r==0;
} catch (IOException e) {
Util.displayIOException(e,listener);
String errorMessage = "command execution failed";
- if(ai==null) {
+ if(ai==null && (System.currentTimeMillis()-startTime)<1000) {
if(DESCRIPTOR.getInstallations()==null)
// looks like the user didn't configure any Ant installation
errorMessage += ". Maybe you need to configure where your Ant installations are?";
else
// There are Ant installations configured but the project didn't pick it
errorMessage += ". Maybe you need to configure the job to choose one of your Ant installations?";
}
e.printStackTrace( listener.fatalError(errorMessage) );
return false;
}
}
public Descriptor<Builder> getDescriptor() {
return DESCRIPTOR;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends Descriptor<Builder> {
@CopyOnWrite
private volatile AntInstallation[] installations = new AntInstallation[0];
private DescriptorImpl() {
super(Ant.class);
load();
}
protected void convert(Map<String,Object> oldPropertyBag) {
if(oldPropertyBag.containsKey("installations"))
installations = (AntInstallation[]) oldPropertyBag.get("installations");
}
public String getHelpFile() {
return "/help/project-config/ant.html";
}
public String getDisplayName() {
return "Invoke Ant";
}
public AntInstallation[] getInstallations() {
return installations;
}
public boolean configure(StaplerRequest req) {
installations = req.bindJSONToList(
AntInstallation.class,StructuredForm.get(req).get("ant")).toArray(new AntInstallation[0]);
save();
return true;
}
public Ant newInstance(StaplerRequest req, JSONObject formData) throws FormException {
return req.bindJSON(Ant.class,formData);
}
//
// web methods
//
/**
* Checks if the ANT_HOME is valid.
*/
public void doCheckAntHome( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// this can be used to check the existence of a file on the server, so needs to be protected
new FormFieldValidator(req,rsp,true) {
public void check() throws IOException, ServletException {
File f = getFileParameter("value");
if(!f.isDirectory()) {
error(f+" is not a directory");
return;
}
File antJar = new File(f,"lib/ant.jar");
if(!antJar.exists()) {
error(f+" doesn't look like an Ant directory");
return;
}
ok();
}
}.process();
}
}
public static final class AntInstallation implements Serializable {
private final String name;
private final String antHome;
@DataBoundConstructor
public AntInstallation(String name, String home) {
this.name = name;
this.antHome = home;
}
/**
* install directory.
*/
public String getAntHome() {
return antHome;
}
/**
* Human readable display name.
*/
public String getName() {
return name;
}
/**
* Gets the executable path of this Ant on the given target system.
*/
public String getExecutable(Launcher launcher) throws IOException, InterruptedException {
final boolean isUnix = launcher.isUnix();
return launcher.getChannel().call(new Callable<String,IOException>() {
public String call() throws IOException {
File exe = getExeFile(isUnix);
if(exe.exists())
return exe.getPath();
return null;
}
});
}
private File getExeFile(boolean isUnix) {
String execName;
if(isUnix)
execName = "ant";
else
execName = "ant.bat";
return new File(getAntHome(),"bin/"+execName);
}
/**
* Returns true if the executable exists.
*/
public boolean getExists() throws IOException, InterruptedException {
return getExecutable(new Launcher.LocalLauncher(TaskListener.NULL))!=null;
}
private static final long serialVersionUID = 1L;
}
}
| false | true | public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
AbstractProject proj = build.getProject();
ArgumentListBuilder args = new ArgumentListBuilder();
String execName;
if(launcher.isUnix())
execName = "ant";
else
execName = "ant.bat";
String normalizedTarget = targets.replaceAll("[\t\r\n]+"," ");
AntInstallation ai = getAnt();
if(ai==null)
args.add(execName);
else
args.add(ai.getExecutable(launcher));
if(buildFile!=null) {
args.add("-file", buildFile);
}
args.addKeyValuePairs("-D",build.getBuildVariables());
if (properties != null) {
Properties p = new Properties();
try {
p.load(new StringReader(properties));
} catch (NoSuchMethodError e) {
// load(Reader) method is only available on JDK6.
// this fall back version doesn't work correctly with non-ASCII characters,
// but there's no other easy ways out it seems.
p.load(new ByteArrayInputStream(properties.getBytes()));
}
for (Entry<Object,Object> entry : p.entrySet()) {
args.add("-D" + entry.getKey() + "=" + entry.getValue());
}
}
args.addTokenized(normalizedTarget);
Map<String,String> env = build.getEnvVars();
if(ai!=null)
env.put("ANT_HOME",ai.getAntHome());
if(antOpts!=null)
env.put("ANT_OPTS",antOpts);
if(!launcher.isUnix()) {
// on Windows, executing batch file can't return the correct error code,
// so we need to wrap it into cmd.exe.
// double %% is needed because we want ERRORLEVEL to be expanded after
// batch file executed, not before. This alone shows how broken Windows is...
args.add("&&","exit","%%ERRORLEVEL%%");
// on Windows, proper double quote handling requires extra surrounding quote.
// so we need to convert the entire argument list once into a string,
// then build the new list so that by the time JVM invokes CreateProcess win32 API,
// it puts additional double-quote. See issue #1007
// the 'addQuoted' is necessary because Process implementation for Windows (at least in Sun JVM)
// is too clever to avoid putting a quote around it if the argument begins with "
// see "cmd /?" for more about how cmd.exe handles quotation.
args = new ArgumentListBuilder().add("cmd.exe","/C").addQuoted(args.toStringWithQuote());
}
try {
int r = launcher.launch(args.toCommandArray(),env,listener.getLogger(),proj.getModuleRoot()).join();
return r==0;
} catch (IOException e) {
Util.displayIOException(e,listener);
String errorMessage = "command execution failed";
if(ai==null) {
if(DESCRIPTOR.getInstallations()==null)
// looks like the user didn't configure any Ant installation
errorMessage += ". Maybe you need to configure where your Ant installations are?";
else
// There are Ant installations configured but the project didn't pick it
errorMessage += ". Maybe you need to configure the job to choose one of your Ant installations?";
}
e.printStackTrace( listener.fatalError(errorMessage) );
return false;
}
}
| public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
AbstractProject proj = build.getProject();
ArgumentListBuilder args = new ArgumentListBuilder();
String execName;
if(launcher.isUnix())
execName = "ant";
else
execName = "ant.bat";
String normalizedTarget = targets.replaceAll("[\t\r\n]+"," ");
AntInstallation ai = getAnt();
if(ai==null)
args.add(execName);
else
args.add(ai.getExecutable(launcher));
if(buildFile!=null) {
args.add("-file", buildFile);
}
args.addKeyValuePairs("-D",build.getBuildVariables());
if (properties != null) {
Properties p = new Properties();
try {
p.load(new StringReader(properties));
} catch (NoSuchMethodError e) {
// load(Reader) method is only available on JDK6.
// this fall back version doesn't work correctly with non-ASCII characters,
// but there's no other easy ways out it seems.
p.load(new ByteArrayInputStream(properties.getBytes()));
}
for (Entry<Object,Object> entry : p.entrySet()) {
args.add("-D" + entry.getKey() + "=" + entry.getValue());
}
}
args.addTokenized(normalizedTarget);
Map<String,String> env = build.getEnvVars();
if(ai!=null)
env.put("ANT_HOME",ai.getAntHome());
if(antOpts!=null)
env.put("ANT_OPTS",antOpts);
if(!launcher.isUnix()) {
// on Windows, executing batch file can't return the correct error code,
// so we need to wrap it into cmd.exe.
// double %% is needed because we want ERRORLEVEL to be expanded after
// batch file executed, not before. This alone shows how broken Windows is...
args.add("&&","exit","%%ERRORLEVEL%%");
// on Windows, proper double quote handling requires extra surrounding quote.
// so we need to convert the entire argument list once into a string,
// then build the new list so that by the time JVM invokes CreateProcess win32 API,
// it puts additional double-quote. See issue #1007
// the 'addQuoted' is necessary because Process implementation for Windows (at least in Sun JVM)
// is too clever to avoid putting a quote around it if the argument begins with "
// see "cmd /?" for more about how cmd.exe handles quotation.
args = new ArgumentListBuilder().add("cmd.exe","/C").addQuoted(args.toStringWithQuote());
}
long startTime = System.currentTimeMillis();
try {
int r = launcher.launch(args.toCommandArray(),env,listener.getLogger(),proj.getModuleRoot()).join();
return r==0;
} catch (IOException e) {
Util.displayIOException(e,listener);
String errorMessage = "command execution failed";
if(ai==null && (System.currentTimeMillis()-startTime)<1000) {
if(DESCRIPTOR.getInstallations()==null)
// looks like the user didn't configure any Ant installation
errorMessage += ". Maybe you need to configure where your Ant installations are?";
else
// There are Ant installations configured but the project didn't pick it
errorMessage += ". Maybe you need to configure the job to choose one of your Ant installations?";
}
e.printStackTrace( listener.fatalError(errorMessage) );
return false;
}
}
|
diff --git a/luni/src/test/java/tests/api/java/util/CurrencyTest.java b/luni/src/test/java/tests/api/java/util/CurrencyTest.java
index b7a5648d7..14068a3e2 100644
--- a/luni/src/test/java/tests/api/java/util/CurrencyTest.java
+++ b/luni/src/test/java/tests/api/java/util/CurrencyTest.java
@@ -1,469 +1,469 @@
/*
* 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 tests.api.java.util;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.AndroidOnly;
import java.util.Arrays;
import java.util.Collection;
import java.util.Currency;
import java.util.Iterator;
import java.util.Locale;
@TestTargetClass(Currency.class)
public class CurrencyTest extends junit.framework.TestCase {
private static Locale defaultLocale = Locale.getDefault();
/**
* @tests java.util.Currency#getInstance(java.lang.String)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "getInstance(String) method is tested in test_getInstanceLjava_util_Locale() test.",
method = "getInstance",
args = {java.lang.String.class}
)
public void test_getInstanceLjava_lang_String() {
// see test_getInstanceLjava_util_Locale() tests
}
/**
* @tests java.util.Currency#getInstance(java.util.Locale)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getInstance",
args = {java.util.Locale.class}
)
public void test_getInstanceLjava_util_Locale() {
/*
* the behaviour in all these three cases should be the same since this
* method ignores language and variant component of the locale.
*/
Currency c0 = Currency.getInstance("CAD");
Currency c1 = Currency.getInstance(new Locale("en", "CA"));
assertTrue(
"Currency.getInstance(new Locale(\"en\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
c1 == c0);
Currency c2 = Currency.getInstance(new Locale("fr", "CA"));
assertTrue(
"Currency.getInstance(new Locale(\"fr\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
c2 == c0);
Currency c3 = Currency.getInstance(new Locale("", "CA"));
assertTrue(
"Currency.getInstance(new Locale(\"\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
c3 == c0);
c0 = Currency.getInstance("JPY");
c1 = Currency.getInstance(new Locale("ja", "JP"));
assertTrue(
"Currency.getInstance(new Locale(\"ja\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
c1 == c0);
c2 = Currency.getInstance(new Locale("", "JP"));
assertTrue(
"Currency.getInstance(new Locale(\"\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
c2 == c0);
c3 = Currency.getInstance(new Locale("bogus", "JP"));
assertTrue(
"Currency.getInstance(new Locale(\"bogus\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
c3 == c0);
Locale localeGu = new Locale("gu", "IN");
Currency cGu = Currency.getInstance(localeGu);
Locale localeKn = new Locale("kn", "IN");
Currency cKn = Currency.getInstance(localeKn);
assertTrue("Currency.getInstance(Locale_" + localeGu.toString() + "))"
+ "isn't equal to " + "Currency.getInstance(Locale_"
+ localeKn.toString() + "))", cGu == cKn);
// some teritories do not have currencies, like Antarctica
Locale loc = new Locale("", "AQ");
try {
Currency curr = Currency.getInstance(loc);
assertNull(
"Currency.getInstance(new Locale(\"\", \"AQ\")) did not return null",
curr);
} catch (IllegalArgumentException e) {
fail("Unexpected IllegalArgumentException " + e);
}
// unsupported/legacy iso3 countries
loc = new Locale("", "ZR");
try {
Currency curr = Currency.getInstance(loc);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
loc = new Locale("", "ZAR");
try {
Currency curr = Currency.getInstance(loc);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
loc = new Locale("", "FX");
try {
Currency curr = Currency.getInstance(loc);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
loc = new Locale("", "FXX");
try {
Currency curr = Currency.getInstance(loc);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
}
/**
* @tests java.util.Currency#getSymbol()
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getSymbol",
args = {}
)
@AndroidOnly("icu and the RI have different data. Because Android"
+ "only defines a few locales as a must have, it was not possible"
+ "to find a set of combinations where no differences between"
+ "the RI and Android exist.")
public void test_getSymbol() {
Currency currK = Currency.getInstance("KRW");
Currency currI = Currency.getInstance("IEP");
Currency currUS = Currency.getInstance("USD");
Locale.setDefault(Locale.US);
// BEGIN android-changed
// KRW currency symbol is \u20a9 since CLDR1.7 release.
assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
// END android-changed
assertEquals("currI.getSymbol()", "IR\u00a3", currI.getSymbol());
assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
Locale.setDefault(new Locale("en", "IE"));
// BEGIN android-changed
assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
// END android-changed
assertEquals("currI.getSymbol()", "IR\u00a3", currI.getSymbol());
// BEGIN android-changed
assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
// END android-changed
// test what happens if this is an invalid locale,
// one with Korean country but an India language
Locale.setDefault(new Locale("kr", "KR"));
// BEGIN android-changed
assertEquals("currK.getSymbol()", "\u20a9", currK.getSymbol());
// END android-changed
assertEquals("currI.getSymbol()", "IR\u00a3", currI.getSymbol());
assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
}
/**
* @tests java.util.Currency#getSymbol(java.util.Locale)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getSymbol",
args = {java.util.Locale.class}
)
@AndroidOnly("specification doesn't include strong requirements for returnig symbol. On android platform used wrong character for yen sign: \u00a5 instead of \uffe5. Both of them give correct image though")
public void test_getSymbolLjava_util_Locale() {
//Tests was simplified because java specification not
// includes strong requirements for returnig symbol.
// on android platform used wrong character for yen
// sign: \u00a5 instead of \uffe5
Locale[] loc1 = new Locale[]{
Locale.JAPAN, Locale.JAPANESE,
Locale.FRANCE, Locale.FRENCH,
Locale.US, Locale.UK,
Locale.CANADA, Locale.CANADA_FRENCH,
Locale.ENGLISH,
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("fr", "FR"), new Locale("", "FR"),
new Locale("en", "US"), new Locale("", "US"),
new Locale("es", "US"), new Locale("ar", "US"),
new Locale("ja", "US"),
new Locale("en", "CA"), new Locale("fr", "CA"),
new Locale("", "CA"), new Locale("ar", "CA"),
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("ar", "JP"),
new Locale("ja", "AE"), new Locale("en", "AE"),
new Locale("ar", "AE"),
new Locale("da", "DK"), new Locale("", "DK"),
new Locale("da", ""), new Locale("ja", ""),
new Locale("en", "")};
String[] euro = new String[] {"EUR", "\u20ac"};
// \u00a5 and \uffe5 are actually the same symbol, just different code points.
// But the RI returns the \uffe5 and Android returns those with \u00a5
String[] yen = new String[] {"JPY", "\u00a5", "\u00a5JP", "JP\u00a5", "\uffe5", "\uffe5JP", "JP\uffe5"};
String[] dollar = new String[] {"USD", "$", "US$", "$US"};
// BEGIN android-changed
// Starting CLDR 1.7 release, currency symbol for CAD changed to CA$ in some locales such as ja.
- String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$Ca"};
+ String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$CA"};
// END android-changed
Currency currE = Currency.getInstance("EUR");
Currency currJ = Currency.getInstance("JPY");
Currency currUS = Currency.getInstance("USD");
Currency currCA = Currency.getInstance("CAD");
int i, j, k;
boolean flag;
for(k = 0; k < loc1.length; k++) {
Locale.setDefault(loc1[k]);
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < euro.length; j++) {
if (currE.getSymbol(loc1[i]).equals(euro[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Euro currency returned "
+ currE.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(euro), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < yen.length; j++) {
byte[] b1 = null;
byte[] b2 = null;
if (currJ.getSymbol(loc1[i]).equals(yen[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Yen currency returned "
+ currJ.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(yen), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < dollar.length; j++) {
if (currUS.getSymbol(loc1[i]).equals(dollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Dollar currency returned "
+ currUS.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(dollar), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < cDollar.length; j++) {
if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Canadian Dollar currency returned "
+ currCA.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(cDollar), flag);
}
}
}
/**
* @tests java.util.Currency#getDefaultFractionDigits()
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getDefaultFractionDigits",
args = {}
)
public void test_getDefaultFractionDigits() {
Currency c1 = Currency.getInstance("TND");
c1.getDefaultFractionDigits();
assertEquals(" Currency.getInstance(\"" + c1
+ "\") returned incorrect number of digits. ", 3, c1
.getDefaultFractionDigits());
Currency c2 = Currency.getInstance("EUR");
c2.getDefaultFractionDigits();
assertEquals(" Currency.getInstance(\"" + c2
+ "\") returned incorrect number of digits. ", 2, c2
.getDefaultFractionDigits());
Currency c3 = Currency.getInstance("JPY");
c3.getDefaultFractionDigits();
assertEquals(" Currency.getInstance(\"" + c3
+ "\") returned incorrect number of digits. ", 0, c3
.getDefaultFractionDigits());
Currency c4 = Currency.getInstance("XXX");
c4.getDefaultFractionDigits();
assertEquals(" Currency.getInstance(\"" + c4
+ "\") returned incorrect number of digits. ", -1, c4
.getDefaultFractionDigits());
}
/**
* @tests java.util.Currency#getCurrencyCode() Note: lines under remarks
* (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
* Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
* on SUN VM
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getCurrencyCode",
args = {}
)
public void test_getCurrencyCode() {
final Collection<Locale> locVal = Arrays.asList(
Locale.CANADA,
Locale.CANADA_FRENCH,
Locale.CHINA,
// Locale.CHINESE,
// Locale.ENGLISH,
Locale.FRANCE,
// Locale.FRENCH,
// Locale.GERMAN,
Locale.GERMANY,
// Locale.ITALIAN,
Locale.ITALY, Locale.JAPAN,
// Locale.JAPANESE,
Locale.KOREA,
// Locale.KOREAN,
Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
Locale.UK, Locale.US);
final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
"JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
Iterator<String> dat = locDat.iterator();
for (Locale l : locVal) {
String d = dat.next().trim();
assertEquals("For locale " + l + " currency code wrong", Currency.getInstance(l)
.getCurrencyCode(), d);
}
}
/**
* @tests java.util.Currency#toString() Note: lines under remarks
* (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
* Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
* on SUN VM
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "toString",
args = {}
)
public void test_toString() {
final Collection<Locale> locVal = Arrays.asList(
Locale.CANADA,
Locale.CANADA_FRENCH,
Locale.CHINA,
// Locale.CHINESE,
// Locale.ENGLISH,
Locale.FRANCE,
// Locale.FRENCH,
// Locale.GERMAN,
Locale.GERMANY,
// Locale.ITALIAN,
Locale.ITALY, Locale.JAPAN,
// Locale.JAPANESE,
Locale.KOREA,
// Locale.KOREAN,
Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
Locale.UK, Locale.US);
final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
"JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
Iterator<String> dat = locDat.iterator();
for (Locale l : locVal) {
String d = dat.next().trim();
assertEquals("For locale " + l + " Currency.toString method returns wrong value",
Currency.getInstance(l).toString(), d);
}
}
protected void setUp() {
Locale.setDefault(defaultLocale);
}
protected void tearDown() {
}
/**
* Helper method to display Currency info
*
* @param c
*/
private void printCurrency(Currency c) {
System.out.println();
System.out.println(c.getCurrencyCode());
System.out.println(c.getSymbol());
System.out.println(c.getDefaultFractionDigits());
}
/**
* helper method to display Locale info
*/
private static void printLocale(Locale loc) {
System.out.println();
System.out.println(loc.getDisplayName());
System.out.println(loc.getCountry());
System.out.println(loc.getLanguage());
System.out.println(loc.getDisplayCountry());
System.out.println(loc.getDisplayLanguage());
System.out.println(loc.getDisplayName());
System.out.println(loc.getISO3Country());
System.out.println(loc.getISO3Language());
}
}
| true | true | public void test_getSymbolLjava_util_Locale() {
//Tests was simplified because java specification not
// includes strong requirements for returnig symbol.
// on android platform used wrong character for yen
// sign: \u00a5 instead of \uffe5
Locale[] loc1 = new Locale[]{
Locale.JAPAN, Locale.JAPANESE,
Locale.FRANCE, Locale.FRENCH,
Locale.US, Locale.UK,
Locale.CANADA, Locale.CANADA_FRENCH,
Locale.ENGLISH,
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("fr", "FR"), new Locale("", "FR"),
new Locale("en", "US"), new Locale("", "US"),
new Locale("es", "US"), new Locale("ar", "US"),
new Locale("ja", "US"),
new Locale("en", "CA"), new Locale("fr", "CA"),
new Locale("", "CA"), new Locale("ar", "CA"),
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("ar", "JP"),
new Locale("ja", "AE"), new Locale("en", "AE"),
new Locale("ar", "AE"),
new Locale("da", "DK"), new Locale("", "DK"),
new Locale("da", ""), new Locale("ja", ""),
new Locale("en", "")};
String[] euro = new String[] {"EUR", "\u20ac"};
// \u00a5 and \uffe5 are actually the same symbol, just different code points.
// But the RI returns the \uffe5 and Android returns those with \u00a5
String[] yen = new String[] {"JPY", "\u00a5", "\u00a5JP", "JP\u00a5", "\uffe5", "\uffe5JP", "JP\uffe5"};
String[] dollar = new String[] {"USD", "$", "US$", "$US"};
// BEGIN android-changed
// Starting CLDR 1.7 release, currency symbol for CAD changed to CA$ in some locales such as ja.
String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$Ca"};
// END android-changed
Currency currE = Currency.getInstance("EUR");
Currency currJ = Currency.getInstance("JPY");
Currency currUS = Currency.getInstance("USD");
Currency currCA = Currency.getInstance("CAD");
int i, j, k;
boolean flag;
for(k = 0; k < loc1.length; k++) {
Locale.setDefault(loc1[k]);
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < euro.length; j++) {
if (currE.getSymbol(loc1[i]).equals(euro[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Euro currency returned "
+ currE.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(euro), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < yen.length; j++) {
byte[] b1 = null;
byte[] b2 = null;
if (currJ.getSymbol(loc1[i]).equals(yen[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Yen currency returned "
+ currJ.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(yen), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < dollar.length; j++) {
if (currUS.getSymbol(loc1[i]).equals(dollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Dollar currency returned "
+ currUS.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(dollar), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < cDollar.length; j++) {
if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Canadian Dollar currency returned "
+ currCA.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(cDollar), flag);
}
}
}
| public void test_getSymbolLjava_util_Locale() {
//Tests was simplified because java specification not
// includes strong requirements for returnig symbol.
// on android platform used wrong character for yen
// sign: \u00a5 instead of \uffe5
Locale[] loc1 = new Locale[]{
Locale.JAPAN, Locale.JAPANESE,
Locale.FRANCE, Locale.FRENCH,
Locale.US, Locale.UK,
Locale.CANADA, Locale.CANADA_FRENCH,
Locale.ENGLISH,
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("fr", "FR"), new Locale("", "FR"),
new Locale("en", "US"), new Locale("", "US"),
new Locale("es", "US"), new Locale("ar", "US"),
new Locale("ja", "US"),
new Locale("en", "CA"), new Locale("fr", "CA"),
new Locale("", "CA"), new Locale("ar", "CA"),
new Locale("ja", "JP"), new Locale("", "JP"),
new Locale("ar", "JP"),
new Locale("ja", "AE"), new Locale("en", "AE"),
new Locale("ar", "AE"),
new Locale("da", "DK"), new Locale("", "DK"),
new Locale("da", ""), new Locale("ja", ""),
new Locale("en", "")};
String[] euro = new String[] {"EUR", "\u20ac"};
// \u00a5 and \uffe5 are actually the same symbol, just different code points.
// But the RI returns the \uffe5 and Android returns those with \u00a5
String[] yen = new String[] {"JPY", "\u00a5", "\u00a5JP", "JP\u00a5", "\uffe5", "\uffe5JP", "JP\uffe5"};
String[] dollar = new String[] {"USD", "$", "US$", "$US"};
// BEGIN android-changed
// Starting CLDR 1.7 release, currency symbol for CAD changed to CA$ in some locales such as ja.
String[] cDollar = new String[] {"CA$", "CAD", "$", "Can$", "$CA"};
// END android-changed
Currency currE = Currency.getInstance("EUR");
Currency currJ = Currency.getInstance("JPY");
Currency currUS = Currency.getInstance("USD");
Currency currCA = Currency.getInstance("CAD");
int i, j, k;
boolean flag;
for(k = 0; k < loc1.length; k++) {
Locale.setDefault(loc1[k]);
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < euro.length; j++) {
if (currE.getSymbol(loc1[i]).equals(euro[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Euro currency returned "
+ currE.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(euro), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < yen.length; j++) {
byte[] b1 = null;
byte[] b2 = null;
if (currJ.getSymbol(loc1[i]).equals(yen[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Yen currency returned "
+ currJ.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(yen), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < dollar.length; j++) {
if (currUS.getSymbol(loc1[i]).equals(dollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Dollar currency returned "
+ currUS.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(dollar), flag);
}
for (i = 0; i < loc1.length; i++) {
flag = false;
for (j = 0; j < cDollar.length; j++) {
if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
flag = true;
break;
}
}
assertTrue("Default Locale is: " + Locale.getDefault()
+ ". For locale " + loc1[i]
+ " the Canadian Dollar currency returned "
+ currCA.getSymbol(loc1[i])
+ ". Expected was one of these: "
+ Arrays.toString(cDollar), flag);
}
}
}
|
diff --git a/org.openscada.ae.server.exporter.net/src/org/openscada/ae/server/exporter/net/Activator.java b/org.openscada.ae.server.exporter.net/src/org/openscada/ae/server/exporter/net/Activator.java
index ce14c1486..896daf27b 100644
--- a/org.openscada.ae.server.exporter.net/src/org/openscada/ae/server/exporter/net/Activator.java
+++ b/org.openscada.ae.server.exporter.net/src/org/openscada/ae/server/exporter/net/Activator.java
@@ -1,124 +1,124 @@
package org.openscada.ae.server.exporter.net;
import org.apache.log4j.Logger;
import org.openscada.ae.server.Service;
import org.openscada.ae.server.net.Exporter;
import org.openscada.core.ConnectionInformation;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
public class Activator implements BundleActivator
{
private final static Logger logger = Logger.getLogger ( Activator.class );
private ServiceListener listener;
private ServiceReference currentServiceReference;
private BundleContext context;
private final ConnectionInformation connectionInformation = ConnectionInformation.fromURI ( System.getProperty ( "openscada.ae.net.exportUri", "ae:net://0.0.0.0:1302" ) );
private Exporter exporter;
private Service currentService;
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start ( final BundleContext context ) throws Exception
{
this.context = context;
context.addServiceListener ( this.listener = new ServiceListener () {
public void serviceChanged ( final ServiceEvent event )
{
switch ( event.getType () )
{
case ServiceEvent.REGISTERED:
Activator.this.startExporter ( event.getServiceReference () );
break;
case ServiceEvent.UNREGISTERING:
Activator.this.stopExporter ( event.getServiceReference () );
break;
}
}
}, "(" + Constants.OBJECTCLASS + "=" + Service.class.getName () + ")" );
startExporter ( context.getServiceReference ( Service.class.getName () ) );
}
protected void stopExporter ( final ServiceReference serviceReference )
{
if ( this.currentServiceReference != serviceReference )
{
return;
}
try
{
this.exporter.stop ();
}
catch ( final Throwable e )
{
logger.warn ( "Failed to stop", e );
}
finally
{
this.context.ungetService ( this.currentServiceReference );
this.currentService = null;
this.exporter = null;
this.currentServiceReference = null;
}
}
protected void startExporter ( final ServiceReference serviceReference )
{
if ( this.currentServiceReference != null || serviceReference == null )
{
return;
}
final Object o = this.context.getService ( serviceReference );
if ( o instanceof Service )
{
try
{
logger.info ( "Exporting: " + serviceReference );
this.currentService = (Service)o;
this.exporter = new Exporter ( this.currentService, this.connectionInformation );
this.exporter.start ();
}
catch ( final Throwable e )
{
- e.printStackTrace ();
+ logger.warn ( "Failed to start", e );
this.exporter = null;
this.currentService = null;
this.context.ungetService ( serviceReference );
}
}
else
{
this.context.ungetService ( serviceReference );
}
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop ( final BundleContext context ) throws Exception
{
context.removeServiceListener ( this.listener );
this.context = null;
}
}
| true | true | protected void startExporter ( final ServiceReference serviceReference )
{
if ( this.currentServiceReference != null || serviceReference == null )
{
return;
}
final Object o = this.context.getService ( serviceReference );
if ( o instanceof Service )
{
try
{
logger.info ( "Exporting: " + serviceReference );
this.currentService = (Service)o;
this.exporter = new Exporter ( this.currentService, this.connectionInformation );
this.exporter.start ();
}
catch ( final Throwable e )
{
e.printStackTrace ();
this.exporter = null;
this.currentService = null;
this.context.ungetService ( serviceReference );
}
}
else
{
this.context.ungetService ( serviceReference );
}
}
| protected void startExporter ( final ServiceReference serviceReference )
{
if ( this.currentServiceReference != null || serviceReference == null )
{
return;
}
final Object o = this.context.getService ( serviceReference );
if ( o instanceof Service )
{
try
{
logger.info ( "Exporting: " + serviceReference );
this.currentService = (Service)o;
this.exporter = new Exporter ( this.currentService, this.connectionInformation );
this.exporter.start ();
}
catch ( final Throwable e )
{
logger.warn ( "Failed to start", e );
this.exporter = null;
this.currentService = null;
this.context.ungetService ( serviceReference );
}
}
else
{
this.context.ungetService ( serviceReference );
}
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoration.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoration.java
index 8c749070b..293af6f99 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoration.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSDecoration.java
@@ -1,432 +1,434 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 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.team.internal.ccvs.ui;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IDecoration;
import org.eclipse.swt.graphics.*;
import org.eclipse.team.internal.ccvs.core.ICVSRepositoryLocation;
import org.eclipse.team.internal.ccvs.ui.repo.RepositoryManager;
import org.eclipse.team.internal.ccvs.ui.repo.RepositoryRoot;
import org.eclipse.team.internal.ui.TeamUIPlugin;
import org.eclipse.team.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.themes.ITheme;
/**
* A decoration describes the annotations to a user interface element. The
* annotations can apply to text (e.g. prefix, suffix, color, font) and to an
* image (e.g. overlays).
* <p>
* This class is derived from an internal workbench class
* <code>IDecoration</code> and is often used in conjunction with the label
* decoration APIs. As such a client can convert between them using helpers
* defined in this class.
* </p>
* TODO:
* profile
* add colors and fonts to preferences instead of being hard coded
* what to do with CVSDecorationConfiguration class?
* preference page externalizations
* preference page preview should update when theme changes
*
* @since 3.1
*/
public class CVSDecoration {
public static final int MODEL = 1000;
// Decorations
private String prefix;
private String suffix;
private ImageDescriptor overlay;
private Color bkgColor;
private Color fgColor;
private Font font;
// Properties
private int resourceType = IResource.FILE;
private boolean watchEditEnabled = false;
private boolean isDirty = false;
private boolean isIgnored = false;
private boolean isAdded = false;
private boolean isNewResource = false;
private boolean hasRemote = false;
private boolean readOnly = false;
private boolean needsMerge = false;
private boolean virtualFolder = false;
private String tag;
private String revision;
private String repository;
private ICVSRepositoryLocation location;
private String keywordSubstitution;
// Text formatters
private String fileFormatter;
private String folderFormatter;
private String projectFormatter;
// Images cached for better performance
private static ImageDescriptor dirty;
private static ImageDescriptor checkedIn;
private static ImageDescriptor noRemoteDir;
private static ImageDescriptor added;
private static ImageDescriptor merged;
private static ImageDescriptor newResource;
private static ImageDescriptor edited;
// List of preferences used to configure the decorations that
// are applied.
private Preferences preferences;
/*
* Define a cached image descriptor which only creates the image data once
*/
public static class CachedImageDescriptor extends ImageDescriptor {
ImageDescriptor descriptor;
ImageData data;
public CachedImageDescriptor(ImageDescriptor descriptor) {
Assert.isNotNull(descriptor);
this.descriptor = descriptor;
}
public ImageData getImageData() {
if (data == null) {
data = descriptor.getImageData();
}
return data;
}
}
static {
dirty = new CachedImageDescriptor(TeamUIPlugin.getImageDescriptor(ISharedImages.IMG_DIRTY_OVR));
checkedIn = new CachedImageDescriptor(TeamUIPlugin.getImageDescriptor(ISharedImages.IMG_CHECKEDIN_OVR));
added = new CachedImageDescriptor(TeamUIPlugin.getImageDescriptor(ISharedImages.IMG_CHECKEDIN_OVR));
merged = new CachedImageDescriptor(CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_MERGED));
newResource = new CachedImageDescriptor(CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_QUESTIONABLE));
edited = new CachedImageDescriptor(CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_EDITED));
noRemoteDir = new CachedImageDescriptor(CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_NO_REMOTEDIR));
}
/**
* Default constructor uses the plug-in's preferences to determine text decoration
* formatters and preferences.
*/
public CVSDecoration() {
// TODO: for efficiency don't look up a pref until its needed
IPreferenceStore store = getStore();
Preferences prefs = new Preferences();
prefs.setValue(ICVSUIConstants.PREF_SHOW_DIRTY_DECORATION, store.getBoolean(ICVSUIConstants.PREF_SHOW_DIRTY_DECORATION));
prefs.setValue(ICVSUIConstants.PREF_SHOW_ADDED_DECORATION, store.getBoolean(ICVSUIConstants.PREF_SHOW_ADDED_DECORATION));
prefs.setValue(ICVSUIConstants.PREF_SHOW_HASREMOTE_DECORATION, store.getBoolean(ICVSUIConstants.PREF_SHOW_HASREMOTE_DECORATION));
prefs.setValue(ICVSUIConstants.PREF_SHOW_NEWRESOURCE_DECORATION, store.getBoolean(ICVSUIConstants.PREF_SHOW_NEWRESOURCE_DECORATION));
prefs.setValue(ICVSUIConstants.PREF_CALCULATE_DIRTY, store.getBoolean(ICVSUIConstants.PREF_CALCULATE_DIRTY));
prefs.setValue(ICVSUIConstants.PREF_DIRTY_FLAG, store.getString(ICVSUIConstants.PREF_DIRTY_FLAG));
prefs.setValue(ICVSUIConstants.PREF_ADDED_FLAG, store.getString(ICVSUIConstants.PREF_ADDED_FLAG));
prefs.setValue(ICVSUIConstants.PREF_USE_FONT_DECORATORS, store.getString(ICVSUIConstants.PREF_USE_FONT_DECORATORS));
initialize(prefs, store.getString(ICVSUIConstants.PREF_FILETEXT_DECORATION), store.getString(ICVSUIConstants.PREF_FOLDERTEXT_DECORATION), store.getString(ICVSUIConstants.PREF_PROJECTTEXT_DECORATION));
}
public CVSDecoration(Preferences preferences, String fileFormater, String folderFormatter, String projectFormatter) {
initialize(preferences, fileFormater, folderFormatter, projectFormatter);
}
private IPreferenceStore getStore() {
return CVSUIPlugin.getPlugin().getPreferenceStore();
}
private void initialize(Preferences preferences, String fileFormater, String folderFormatter, String projectFormatter) {
this.preferences = preferences;
this.fileFormatter = fileFormater;
this.folderFormatter = folderFormatter;
this.projectFormatter = projectFormatter;
}
public void addPrefix(String prefix) {
this.prefix = prefix;
}
public void addSuffix(String suffix) {
this.suffix = suffix;
}
public void setForegroundColor(Color fgColor) {
this.fgColor = fgColor;
}
public void setBackgroundColor(Color bkgColor) {
this.bkgColor = bkgColor;
}
public void setFont(Font font) {
this.font = font;
}
public Color getBackgroundColor() {
return bkgColor;
}
public Color getForegroundColor() {
return fgColor;
}
public Font getFont() {
return font;
}
public ImageDescriptor getOverlay() {
return overlay;
}
public String getPrefix() {
return prefix;
}
public String getSuffix() {
return suffix;
}
public void setResourceType(int type) {
this.resourceType = type;
}
public void apply(IDecoration decoration) {
compute();
// apply changes
String suffix = getSuffix();
if(suffix != null)
decoration.addSuffix(suffix);
String prefix = getPrefix();
if(prefix != null)
decoration.addPrefix(prefix);
ImageDescriptor overlay = getOverlay();
if(overlay != null)
decoration.addOverlay(overlay);
Color bc = getBackgroundColor();
if(bc != null)
decoration.setBackgroundColor(bc);
Color fc = getForegroundColor();
if(fc != null)
decoration.setForegroundColor(fc);
Font f = getFont();
if(f != null)
decoration.setFont(f);
}
public void compute() {
computeText();
overlay = computeImage();
computeColorsAndFonts();
}
private void computeText() {
+ if (isIgnored())
+ return;
Map bindings = new HashMap();
if (isDirty()) {
bindings.put(CVSDecoratorConfiguration.DIRTY_FLAG, preferences.getString(ICVSUIConstants.PREF_DIRTY_FLAG));
}
if (isAdded()) {
bindings.put(CVSDecoratorConfiguration.ADDED_FLAG, preferences.getString(ICVSUIConstants.PREF_ADDED_FLAG));
} else if(isHasRemote()){
bindings.put(CVSDecoratorConfiguration.FILE_REVISION, getRevision());
bindings.put(CVSDecoratorConfiguration.RESOURCE_TAG, getTag());
}
bindings.put(CVSDecoratorConfiguration.FILE_KEYWORD, getKeywordSubstitution());
if ((resourceType == IResource.FOLDER || resourceType == IResource.PROJECT) && location != null) {
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_HOST, location.getHost());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_METHOD, location.getMethod().getName());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_USER, location.getUsername());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_ROOT, location.getRootDirectory());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_REPOSITORY, repository);
RepositoryManager repositoryManager = CVSUIPlugin.getPlugin().getRepositoryManager();
RepositoryRoot root = repositoryManager.getRepositoryRootFor(location);
CVSUIPlugin.getPlugin().getRepositoryManager();
String label = root.getName();
if (label == null) {
label = location.getLocation(true);
}
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_LABEL, label);
}
CVSDecoratorConfiguration.decorate(this, getTextFormatter(), bindings);
}
private ImageDescriptor computeImage() {
// show newResource icon
if (preferences.getBoolean(ICVSUIConstants.PREF_SHOW_NEWRESOURCE_DECORATION) && isNewResource()) {
return newResource;
}
// show dirty icon
if (preferences.getBoolean(ICVSUIConstants.PREF_SHOW_DIRTY_DECORATION) && isDirty()) {
return dirty;
}
// show added
if (preferences.getBoolean(ICVSUIConstants.PREF_SHOW_ADDED_DECORATION) && isAdded()) {
return added;
}
// show watch edit
if (isWatchEditEnabled() && resourceType == IResource.FILE && !isReadOnly() && isHasRemote()) {
return edited;
}
// show checked in
if (preferences.getBoolean(ICVSUIConstants.PREF_SHOW_HASREMOTE_DECORATION) && isHasRemote()) {
if ((resourceType == IResource.FOLDER || resourceType == IResource.PROJECT) && isVirtualFolder()) {
return noRemoteDir;
}
return checkedIn;
}
if (needsMerge)
return merged;
//nothing matched
return null;
}
private void computeColorsAndFonts() {
if (!preferences.getBoolean(ICVSUIConstants.PREF_USE_FONT_DECORATORS))
return;
ITheme current = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme();
if(isIgnored()) {
setBackgroundColor(current.getColorRegistry().get(CVSDecoratorConfiguration.IGNORED_BACKGROUND_COLOR));
setForegroundColor(current.getColorRegistry().get(CVSDecoratorConfiguration.IGNORED_FOREGROUND_COLOR));
setFont(current.getFontRegistry().get(CVSDecoratorConfiguration.IGNORED_FONT));
} else if(isDirty()) {
setBackgroundColor(current.getColorRegistry().get(CVSDecoratorConfiguration.OUTGOING_CHANGE_BACKGROUND_COLOR));
setForegroundColor(current.getColorRegistry().get(CVSDecoratorConfiguration.OUTGOING_CHANGE_FOREGROUND_COLOR));
setFont(current.getFontRegistry().get(CVSDecoratorConfiguration.OUTGOING_CHANGE_FONT));
}
}
private String getTextFormatter() {
switch (resourceType) {
case IResource.FILE :
return fileFormatter;
case IResource.FOLDER :
return folderFormatter;
case IResource.PROJECT :
return projectFormatter;
case MODEL :
return folderFormatter;
}
return "no format specified"; //$NON-NLS-1$
}
public boolean isAdded() {
return isAdded;
}
public void setAdded(boolean isAdded) {
this.isAdded = isAdded;
}
public boolean isDirty() {
return isDirty;
}
public void setDirty(boolean isDirty) {
this.isDirty = isDirty;
}
public boolean isIgnored() {
return isIgnored;
}
public void setIgnored(boolean isIgnored) {
this.isIgnored = isIgnored;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public boolean isWatchEditEnabled() {
return watchEditEnabled;
}
public void setWatchEditEnabled(boolean watchEditEnabled) {
this.watchEditEnabled = watchEditEnabled;
}
public boolean isNewResource() {
return isNewResource;
}
public void setNewResource(boolean isNewResource) {
this.isNewResource = isNewResource;
}
public void setLocation(ICVSRepositoryLocation location) {
this.location = location;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
public String getKeywordSubstitution() {
return keywordSubstitution;
}
public void setKeywordSubstitution(String keywordSubstitution) {
this.keywordSubstitution = keywordSubstitution;
}
public void setNeedsMerge(boolean needsMerge) {
this.needsMerge = needsMerge;
}
public boolean isHasRemote() {
return hasRemote;
}
public void setHasRemote(boolean hasRemote) {
this.hasRemote = hasRemote;
}
public void setRepository(String repository) {
this.repository = repository;
}
public boolean isReadOnly() {
return readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public boolean isVirtualFolder() {
return virtualFolder;
}
public void setVirtualFolder(boolean virtualFolder) {
this.virtualFolder = virtualFolder;
}
}
| true | true | private void computeText() {
Map bindings = new HashMap();
if (isDirty()) {
bindings.put(CVSDecoratorConfiguration.DIRTY_FLAG, preferences.getString(ICVSUIConstants.PREF_DIRTY_FLAG));
}
if (isAdded()) {
bindings.put(CVSDecoratorConfiguration.ADDED_FLAG, preferences.getString(ICVSUIConstants.PREF_ADDED_FLAG));
} else if(isHasRemote()){
bindings.put(CVSDecoratorConfiguration.FILE_REVISION, getRevision());
bindings.put(CVSDecoratorConfiguration.RESOURCE_TAG, getTag());
}
bindings.put(CVSDecoratorConfiguration.FILE_KEYWORD, getKeywordSubstitution());
if ((resourceType == IResource.FOLDER || resourceType == IResource.PROJECT) && location != null) {
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_HOST, location.getHost());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_METHOD, location.getMethod().getName());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_USER, location.getUsername());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_ROOT, location.getRootDirectory());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_REPOSITORY, repository);
RepositoryManager repositoryManager = CVSUIPlugin.getPlugin().getRepositoryManager();
RepositoryRoot root = repositoryManager.getRepositoryRootFor(location);
CVSUIPlugin.getPlugin().getRepositoryManager();
String label = root.getName();
if (label == null) {
label = location.getLocation(true);
}
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_LABEL, label);
}
CVSDecoratorConfiguration.decorate(this, getTextFormatter(), bindings);
}
| private void computeText() {
if (isIgnored())
return;
Map bindings = new HashMap();
if (isDirty()) {
bindings.put(CVSDecoratorConfiguration.DIRTY_FLAG, preferences.getString(ICVSUIConstants.PREF_DIRTY_FLAG));
}
if (isAdded()) {
bindings.put(CVSDecoratorConfiguration.ADDED_FLAG, preferences.getString(ICVSUIConstants.PREF_ADDED_FLAG));
} else if(isHasRemote()){
bindings.put(CVSDecoratorConfiguration.FILE_REVISION, getRevision());
bindings.put(CVSDecoratorConfiguration.RESOURCE_TAG, getTag());
}
bindings.put(CVSDecoratorConfiguration.FILE_KEYWORD, getKeywordSubstitution());
if ((resourceType == IResource.FOLDER || resourceType == IResource.PROJECT) && location != null) {
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_HOST, location.getHost());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_METHOD, location.getMethod().getName());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_USER, location.getUsername());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_ROOT, location.getRootDirectory());
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_REPOSITORY, repository);
RepositoryManager repositoryManager = CVSUIPlugin.getPlugin().getRepositoryManager();
RepositoryRoot root = repositoryManager.getRepositoryRootFor(location);
CVSUIPlugin.getPlugin().getRepositoryManager();
String label = root.getName();
if (label == null) {
label = location.getLocation(true);
}
bindings.put(CVSDecoratorConfiguration.REMOTELOCATION_LABEL, label);
}
CVSDecoratorConfiguration.decorate(this, getTextFormatter(), bindings);
}
|
diff --git a/components/bio-formats/src/loci/formats/in/LeicaHandler.java b/components/bio-formats/src/loci/formats/in/LeicaHandler.java
index e10cdd678..1c7c81190 100644
--- a/components/bio-formats/src/loci/formats/in/LeicaHandler.java
+++ b/components/bio-formats/src/loci/formats/in/LeicaHandler.java
@@ -1,601 +1,602 @@
//
// LeicaHandler.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.util.*;
import loci.common.*;
import loci.formats.FormatException;
import loci.formats.meta.MetadataStore;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
/**
* SAX handler for parsing XML in Leica LIF and Leica TCS files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/LeicaHandler.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/LeicaHandler.java">SVN</a></dd></dl>
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class LeicaHandler extends DefaultHandler {
// -- Fields --
private String series, fullSeries;
private int count = 0, numChannels, extras;
private boolean firstElement = true, dcroiOpen = false;
private Vector extraDims, channels, widths, heights, zs, ts, bps;
private Vector seriesNames, containerNames, containerCounts;
private Vector xcal, ycal, zcal, bits;
private Vector lutNames;
private int numDatasets;
private Hashtable metadata;
private MetadataStore store;
private Vector nextPlane;
private int nextLaser, nextDetector;
private Vector laserNames, detectorNames;
private Vector xPosition, yPosition, zPosition;
private Hashtable timestamps;
// -- Constructor --
public LeicaHandler(MetadataStore store) {
super();
extraDims = new Vector();
channels = new Vector();
widths = new Vector();
heights = new Vector();
zs = new Vector();
ts = new Vector();
bps = new Vector();
seriesNames = new Vector();
containerNames = new Vector();
containerCounts = new Vector();
metadata = new Hashtable();
xcal = new Vector();
ycal = new Vector();
zcal = new Vector();
bits = new Vector();
lutNames = new Vector();
nextPlane = new Vector();
laserNames = new Vector();
detectorNames = new Vector();
xPosition = new Vector();
yPosition = new Vector();
zPosition = new Vector();
timestamps = new Hashtable();
this.store = store;
}
// -- LeicaHandler API methods --
public Vector getExtraDims() { return extraDims; }
public Vector getChannels() { return channels; }
public Vector getWidths() { return widths; }
public Vector getHeights() { return heights; }
public Vector getZs() { return zs; }
public Vector getTs() { return ts; }
public Vector getBPS() { return bps; }
public Vector getSeriesNames() { return seriesNames; }
public Vector getContainerNames() { return containerNames; }
public Vector getContainerCounts() { return containerCounts; }
public Hashtable getMetadata() { return metadata; }
public int getNumDatasets() { return numDatasets; }
public Vector getXCal() { return xcal; }
public Vector getYCal() { return ycal; }
public Vector getZCal() { return zcal; }
public Vector getBits() { return bits; }
public Vector getLutNames() { return lutNames; }
public Vector getXPosition() { return xPosition; }
public Vector getYPosition() { return yPosition; }
public Vector getZPosition() { return zPosition; }
public Hashtable getTimestamps() { return timestamps; }
// -- DefaultHandler API methods --
public void endElement(String uri, String localName, String qName) {
if (qName.equals("Element")) {
if (dcroiOpen) {
dcroiOpen = false;
return;
}
if (fullSeries.indexOf("/") != -1) {
fullSeries = fullSeries.substring(0, fullSeries.indexOf("/"));
}
else fullSeries = "";
extraDims.add(new Integer(extras));
if (numChannels == 0) numChannels = 1;
channels.add(new Integer(numChannels));
if (widths.size() < numDatasets && heights.size() < numDatasets) {
numDatasets--;
}
else if (widths.size() > numDatasets) {
numDatasets = widths.size();
}
if (widths.size() < numDatasets) widths.add(new Integer(1));
if (heights.size() < numDatasets) heights.add(new Integer(0));
if (zs.size() < numDatasets) zs.add(new Integer(1));
if (ts.size() < numDatasets) ts.add(new Integer(1));
if (bps.size() < numDatasets) bps.add(new Integer(8));
numChannels = 0;
extras = 1;
nextLaser = 0;
nextDetector = 0;
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (qName.equals("Element")) {
if (!attributes.getValue("Name").equals("DCROISet") && !firstElement) {
series = attributes.getValue("Name");
containerNames.add(series);
if (fullSeries == null || fullSeries.equals("")) fullSeries = series;
else fullSeries += "/" + series;
}
else if (firstElement) firstElement = false;
if (attributes.getValue("Name").equals("DCROISet")) {
dcroiOpen = true;
}
numDatasets++;
int idx = numDatasets - 1;
if (idx >= seriesNames.size()) {
numDatasets = seriesNames.size();
}
if (!dcroiOpen) {
numChannels = 0;
extras = 1;
}
}
else if (qName.equals("Experiment")) {
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(attributes.getQName(i), attributes.getValue(i));
}
}
else if (qName.equals("Image")) {
containerNames.remove(series);
if (containerCounts.size() < containerNames.size()) {
containerCounts.add(new Integer(1));
}
else if (containerCounts.size() > 0) {
int ndx = containerCounts.size() - 1;
int n = ((Integer) containerCounts.get(ndx)).intValue();
containerCounts.setElementAt(new Integer(n + 1), ndx);
}
if (fullSeries == null || fullSeries.equals("")) fullSeries = series;
seriesNames.add(fullSeries);
nextPlane.add(new Integer(0));
}
else if (qName.equals("ChannelDescription")) {
String prefix = "Channel " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(prefix + attributes.getQName(i), attributes.getValue(i));
}
count++;
numChannels++;
if (channels.size() > seriesNames.size() - 1) {
channels.setElementAt(new Integer(count), seriesNames.size() - 1);
}
else channels.add(new Integer(count));
if (numChannels == 1) {
bps.add(new Integer(attributes.getValue("Resolution")));
}
lutNames.add(attributes.getValue("LUTName"));
}
else if (qName.equals("DimensionDescription")) {
String prefix = "Dimension " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(prefix + attributes.getQName(i), attributes.getValue(i));
}
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
switch (id) {
case 1:
widths.add(new Integer(len));
int b = Integer.parseInt(attributes.getValue("BytesInc"));
bits.add(new Integer(b * 8));
break;
case 2:
if (widths.size() == heights.size()) {
if (zs.size() == heights.size()) {
zs.setElementAt(new Integer(len), zs.size() - 1);
}
else if (ts.size() == heights.size()) {
ts.setElementAt(new Integer(len), ts.size() - 1);
}
}
else heights.add(new Integer(len));
break;
case 3:
if (heights.size() < widths.size()) {
// XZ scan - swap Y and Z
heights.add(new Integer(len));
zs.add(new Integer(1));
}
else zs.add(new Integer(len));
break;
case 4:
if (heights.size() < widths.size()) {
// XT scan - swap Y and T
heights.add(new Integer(len));
ts.add(new Integer(1));
}
else ts.add(new Integer(len));
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord")) {
String identifier = attributes.getValue("Identifier");
String key = identifier + " - " + attributes.getValue("Description");
if (fullSeries != null && !fullSeries.equals("")) {
key = fullSeries + " - " + key;
}
metadata.put(key, attributes.getValue("Variant"));
if (identifier.startsWith("dblVoxel")) {
String size = attributes.getValue("Variant");
float cal = Float.parseFloat(size) * 1000000;
if (identifier.endsWith("X")) xcal.add(new Float(cal));
else if (identifier.endsWith("Y")) ycal.add(new Float(cal));
else if (identifier.endsWith("Z")) zcal.add(new Float(cal));
}
}
else if (qName.equals("FilterSettingRecord")) {
String object = attributes.getValue("ObjectName");
String key = object + " - " + attributes.getValue("Description") + " - " +
attributes.getValue("Attribute");
if (fullSeries != null && !fullSeries.equals("")) {
key = fullSeries + " - " + key;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
metadata.put(key + " - " + name, value);
if (name.equals("Variant")) {
if (key.endsWith("NumericalAperture")) {
store.setObjectiveLensNA(new Float(value), 0, 0);
}
else if (key.endsWith("HighVoltage")) {
if (!detectorNames.contains(object)) {
detectorNames.add(object);
}
int detector = detectorNames.indexOf(object);
store.setDetectorID("Detector:" + detector, 0, detector);
store.setDetectorVoltage(new Float(value), 0, detector);
store.setDetectorType("Unknown", 0, detector);
store.setDetectorSettingsDetector("Detector:" + detector,
seriesNames.size() - 1, nextDetector);
nextDetector++;
}
else if (key.endsWith("VideoOffset")) {
store.setDetectorOffset(new Float(value), 0, 0);
store.setDetectorType("Unknown", 0, 0);
}
else if (key.endsWith("OrderNumber")) {
store.setObjectiveSerialNumber(value, 0, 0);
}
else if (key.endsWith("Objective")) {
StringTokenizer tokens = new StringTokenizer(value, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
if (token.indexOf("x") != -1) {
foundMag = true;
String mag = token.substring(0, token.indexOf("x"));
String na = token.substring(token.indexOf("x") + 1);
store.setObjectiveNominalMagnification(
new Integer((int) Float.parseFloat(mag)), 0, 0);
store.setObjectiveLensNA(new Float(na), 0, 0);
break;
}
model.append(token);
model.append(" ");
}
if (tokens.hasMoreTokens()) {
String immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Unknown";
}
store.setObjectiveImmersion(immersion, 0, 0);
}
if (tokens.countTokens() > 1) {
Float temperature = new Float(tokens.nextToken());
tokens.nextToken();
}
if (tokens.hasMoreTokens()) {
store.setObjectiveCorrection(tokens.nextToken(), 0, 0);
}
store.setObjectiveModel(model.toString(), 0, 0);
}
else if (key.endsWith("RefractionIndex")) {
store.setObjectiveID("Objective:0", 0, 0);
store.setObjectiveSettingsObjective("Objective:0",
seriesNames.size() - 1);
store.setObjectiveSettingsRefractiveIndex(new Float(value),
seriesNames.size() - 1);
}
else if (key.endsWith("Laser wavelength - Wavelength")) {
if (!laserNames.contains(object)) {
int index = laserNames.size();
store.setLightSourceID("LightSource:" + index, 0, index);
store.setLaserType("Unknown", 0, index);
store.setLaserWavelength(new Integer(value), 0, index);
store.setLaserLaserMedium("Unknown", 0, index);
laserNames.add(object);
}
}
else if (key.endsWith("Laser output power - Output Power")) {
if (!laserNames.contains(object)) {
laserNames.add(object);
}
int laser = laserNames.indexOf(object);
store.setLightSourcePower(new Float(value), 0, laser);
store.setLightSourceSettingsLightSource("LightSource:" + laser,
seriesNames.size() - 1, nextLaser);
nextLaser++;
}
else if (key.endsWith("Stage Pos x - XPos")) {
while (xPosition.size() < seriesNames.size() - 1) {
xPosition.add(null);
}
xPosition.add(new Float(value));
}
else if (key.endsWith("Stage Pos y - YPos")) {
while (yPosition.size() < seriesNames.size() - 1) {
yPosition.add(null);
}
yPosition.add(new Float(value));
}
else if (key.endsWith("Stage Pos z - ZPos")) {
while (zPosition.size() < seriesNames.size() - 1) {
zPosition.add(null);
}
zPosition.add(new Float(value));
}
}
}
}
else if (qName.equals("ATLConfocalSettingDefinition")) {
if (fullSeries == null) fullSeries = "";
if (fullSeries.endsWith(" - Master sequential setting")) {
fullSeries = fullSeries.replaceAll("Master sequential setting",
"Sequential Setting 0");
}
if (fullSeries.indexOf("Sequential Setting ") == -1) {
if (fullSeries.equals("")) fullSeries = "Master sequential setting";
else fullSeries += " - Master sequential setting";
}
else {
int ndx = fullSeries.indexOf("Sequential Setting ") + 19;
try {
int n = Integer.parseInt(fullSeries.substring(ndx)) + 1;
fullSeries = fullSeries.substring(0, ndx) + String.valueOf(n);
}
catch (NumberFormatException exc) {
fullSeries = fullSeries.substring(0, fullSeries.indexOf("-")).trim();
}
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
metadata.put(fullSeries + " - " + name, value);
int s = seriesNames.size() - 1;
if (name.equals("StagePosX")) {
store.setStagePositionPositionX(new Float(value), s, 0, 0);
}
else if (name.equals("StagePosY")) {
store.setStagePositionPositionY(new Float(value), s, 0, 0);
}
else if (name.equals("StagePosZ")) {
store.setStagePositionPositionZ(new Float(value), s, 0, 0);
}
}
}
else if (qName.equals("Wheel")) {
String prefix = qName + " " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(prefix + attributes.getQName(i), attributes.getValue(i));
}
count++;
}
else if (qName.equals("WheelName")) {
String prefix = "Wheel " + (count - 1) + " - WheelName ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
int ndx = 0;
while (metadata.get(prefix + ndx) != null) ndx++;
metadata.put(prefix + ndx, attributes.getValue("FilterName"));
}
else if (qName.equals("MultiBand")) {
String prefix = qName + " Channel " + attributes.getValue("Channel");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
int s = seriesNames.size() - 1;
int channel = Integer.parseInt(attributes.getValue("Channel")) - 1;
- int channelCount = ((Integer) channels.get(s)).intValue();
+ int channelCount = s < channels.size() ?
+ ((Integer) channels.get(s)).intValue() : 1;
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
metadata.put(prefix + " - " + name, value);
if (name.equals("LeftWorld") && channel < channelCount) {
store.setLogicalChannelEmWave(
new Integer((int) Float.parseFloat(value)), s, channel);
}
else if (name.equals("RightWorld") && channel < channelCount) {
store.setLogicalChannelExWave(
new Integer((int) Float.parseFloat(value)), s, channel);
}
else if (name.equals("DyeName") && channel < channelCount) {
store.setLogicalChannelName(value, s, channel);
}
}
}
else if (qName.equals("LaserLineSetting")) {
String prefix = "LaserLine " + attributes.getValue("LaserLine");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
if (!name.equals("LaserLine")) {
metadata.put(prefix + " - " + name, attributes.getValue(i));
store.setLaserWavelength(
new Integer(attributes.getValue("LaserLine")), 0,
Integer.parseInt(attributes.getValue("LineIndex")));
}
}
}
else if (qName.equals("Detector")) {
String prefix = qName + " Channel " + attributes.getValue("Channel");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
if (!name.equals("Channel")) {
metadata.put(prefix + " - " + name, attributes.getValue(i));
}
}
}
else if (qName.equals("Laser")) {
String prefix = qName + " " + attributes.getValue("LaserName");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
if (!name.equals("LaserName")) {
metadata.put(prefix + " - " + name, attributes.getValue(i));
}
}
}
else if (qName.equals("TimeStamp")) {
long high = Long.parseLong(attributes.getValue("HighInteger"));
long low = Long.parseLong(attributes.getValue("LowInteger"));
high <<= 32;
if ((int) low < 0) {
low &= 0xffffffffL;
}
long stamp = high + low;
long ms = stamp / 10000;
String n = String.valueOf(count);
while (n.length() < 4) n = "0" + n;
metadata.put(fullSeries + " - " + qName + n,
DataTools.convertDate(ms, DataTools.COBOL));
count++;
}
else if (qName.equals("ChannelScalingInfo")) {
String prefix = qName + count;
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
metadata.put(prefix + " - " + name, attributes.getValue(i));
}
}
else if (qName.equals("RelTimeStamp")) {
String frame = attributes.getValue("Frame");
String time = attributes.getValue("Time");
metadata.put(fullSeries + " - " + qName + " - " + frame, time);
int originalPlane = Integer.parseInt(frame);
int planeNum =
((Integer) nextPlane.get(seriesNames.size() - 1)).intValue();
if (originalPlane < planeNum) return;
timestamps.put("Series " + (seriesNames.size() - 1) + " Plane " +
planeNum, new Float(time));
planeNum++;
nextPlane.setElementAt(new Integer(planeNum), seriesNames.size() - 1);
}
else count = 0;
}
}
| true | true | public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (qName.equals("Element")) {
if (!attributes.getValue("Name").equals("DCROISet") && !firstElement) {
series = attributes.getValue("Name");
containerNames.add(series);
if (fullSeries == null || fullSeries.equals("")) fullSeries = series;
else fullSeries += "/" + series;
}
else if (firstElement) firstElement = false;
if (attributes.getValue("Name").equals("DCROISet")) {
dcroiOpen = true;
}
numDatasets++;
int idx = numDatasets - 1;
if (idx >= seriesNames.size()) {
numDatasets = seriesNames.size();
}
if (!dcroiOpen) {
numChannels = 0;
extras = 1;
}
}
else if (qName.equals("Experiment")) {
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(attributes.getQName(i), attributes.getValue(i));
}
}
else if (qName.equals("Image")) {
containerNames.remove(series);
if (containerCounts.size() < containerNames.size()) {
containerCounts.add(new Integer(1));
}
else if (containerCounts.size() > 0) {
int ndx = containerCounts.size() - 1;
int n = ((Integer) containerCounts.get(ndx)).intValue();
containerCounts.setElementAt(new Integer(n + 1), ndx);
}
if (fullSeries == null || fullSeries.equals("")) fullSeries = series;
seriesNames.add(fullSeries);
nextPlane.add(new Integer(0));
}
else if (qName.equals("ChannelDescription")) {
String prefix = "Channel " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(prefix + attributes.getQName(i), attributes.getValue(i));
}
count++;
numChannels++;
if (channels.size() > seriesNames.size() - 1) {
channels.setElementAt(new Integer(count), seriesNames.size() - 1);
}
else channels.add(new Integer(count));
if (numChannels == 1) {
bps.add(new Integer(attributes.getValue("Resolution")));
}
lutNames.add(attributes.getValue("LUTName"));
}
else if (qName.equals("DimensionDescription")) {
String prefix = "Dimension " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(prefix + attributes.getQName(i), attributes.getValue(i));
}
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
switch (id) {
case 1:
widths.add(new Integer(len));
int b = Integer.parseInt(attributes.getValue("BytesInc"));
bits.add(new Integer(b * 8));
break;
case 2:
if (widths.size() == heights.size()) {
if (zs.size() == heights.size()) {
zs.setElementAt(new Integer(len), zs.size() - 1);
}
else if (ts.size() == heights.size()) {
ts.setElementAt(new Integer(len), ts.size() - 1);
}
}
else heights.add(new Integer(len));
break;
case 3:
if (heights.size() < widths.size()) {
// XZ scan - swap Y and Z
heights.add(new Integer(len));
zs.add(new Integer(1));
}
else zs.add(new Integer(len));
break;
case 4:
if (heights.size() < widths.size()) {
// XT scan - swap Y and T
heights.add(new Integer(len));
ts.add(new Integer(1));
}
else ts.add(new Integer(len));
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord")) {
String identifier = attributes.getValue("Identifier");
String key = identifier + " - " + attributes.getValue("Description");
if (fullSeries != null && !fullSeries.equals("")) {
key = fullSeries + " - " + key;
}
metadata.put(key, attributes.getValue("Variant"));
if (identifier.startsWith("dblVoxel")) {
String size = attributes.getValue("Variant");
float cal = Float.parseFloat(size) * 1000000;
if (identifier.endsWith("X")) xcal.add(new Float(cal));
else if (identifier.endsWith("Y")) ycal.add(new Float(cal));
else if (identifier.endsWith("Z")) zcal.add(new Float(cal));
}
}
else if (qName.equals("FilterSettingRecord")) {
String object = attributes.getValue("ObjectName");
String key = object + " - " + attributes.getValue("Description") + " - " +
attributes.getValue("Attribute");
if (fullSeries != null && !fullSeries.equals("")) {
key = fullSeries + " - " + key;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
metadata.put(key + " - " + name, value);
if (name.equals("Variant")) {
if (key.endsWith("NumericalAperture")) {
store.setObjectiveLensNA(new Float(value), 0, 0);
}
else if (key.endsWith("HighVoltage")) {
if (!detectorNames.contains(object)) {
detectorNames.add(object);
}
int detector = detectorNames.indexOf(object);
store.setDetectorID("Detector:" + detector, 0, detector);
store.setDetectorVoltage(new Float(value), 0, detector);
store.setDetectorType("Unknown", 0, detector);
store.setDetectorSettingsDetector("Detector:" + detector,
seriesNames.size() - 1, nextDetector);
nextDetector++;
}
else if (key.endsWith("VideoOffset")) {
store.setDetectorOffset(new Float(value), 0, 0);
store.setDetectorType("Unknown", 0, 0);
}
else if (key.endsWith("OrderNumber")) {
store.setObjectiveSerialNumber(value, 0, 0);
}
else if (key.endsWith("Objective")) {
StringTokenizer tokens = new StringTokenizer(value, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
if (token.indexOf("x") != -1) {
foundMag = true;
String mag = token.substring(0, token.indexOf("x"));
String na = token.substring(token.indexOf("x") + 1);
store.setObjectiveNominalMagnification(
new Integer((int) Float.parseFloat(mag)), 0, 0);
store.setObjectiveLensNA(new Float(na), 0, 0);
break;
}
model.append(token);
model.append(" ");
}
if (tokens.hasMoreTokens()) {
String immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Unknown";
}
store.setObjectiveImmersion(immersion, 0, 0);
}
if (tokens.countTokens() > 1) {
Float temperature = new Float(tokens.nextToken());
tokens.nextToken();
}
if (tokens.hasMoreTokens()) {
store.setObjectiveCorrection(tokens.nextToken(), 0, 0);
}
store.setObjectiveModel(model.toString(), 0, 0);
}
else if (key.endsWith("RefractionIndex")) {
store.setObjectiveID("Objective:0", 0, 0);
store.setObjectiveSettingsObjective("Objective:0",
seriesNames.size() - 1);
store.setObjectiveSettingsRefractiveIndex(new Float(value),
seriesNames.size() - 1);
}
else if (key.endsWith("Laser wavelength - Wavelength")) {
if (!laserNames.contains(object)) {
int index = laserNames.size();
store.setLightSourceID("LightSource:" + index, 0, index);
store.setLaserType("Unknown", 0, index);
store.setLaserWavelength(new Integer(value), 0, index);
store.setLaserLaserMedium("Unknown", 0, index);
laserNames.add(object);
}
}
else if (key.endsWith("Laser output power - Output Power")) {
if (!laserNames.contains(object)) {
laserNames.add(object);
}
int laser = laserNames.indexOf(object);
store.setLightSourcePower(new Float(value), 0, laser);
store.setLightSourceSettingsLightSource("LightSource:" + laser,
seriesNames.size() - 1, nextLaser);
nextLaser++;
}
else if (key.endsWith("Stage Pos x - XPos")) {
while (xPosition.size() < seriesNames.size() - 1) {
xPosition.add(null);
}
xPosition.add(new Float(value));
}
else if (key.endsWith("Stage Pos y - YPos")) {
while (yPosition.size() < seriesNames.size() - 1) {
yPosition.add(null);
}
yPosition.add(new Float(value));
}
else if (key.endsWith("Stage Pos z - ZPos")) {
while (zPosition.size() < seriesNames.size() - 1) {
zPosition.add(null);
}
zPosition.add(new Float(value));
}
}
}
}
else if (qName.equals("ATLConfocalSettingDefinition")) {
if (fullSeries == null) fullSeries = "";
if (fullSeries.endsWith(" - Master sequential setting")) {
fullSeries = fullSeries.replaceAll("Master sequential setting",
"Sequential Setting 0");
}
if (fullSeries.indexOf("Sequential Setting ") == -1) {
if (fullSeries.equals("")) fullSeries = "Master sequential setting";
else fullSeries += " - Master sequential setting";
}
else {
int ndx = fullSeries.indexOf("Sequential Setting ") + 19;
try {
int n = Integer.parseInt(fullSeries.substring(ndx)) + 1;
fullSeries = fullSeries.substring(0, ndx) + String.valueOf(n);
}
catch (NumberFormatException exc) {
fullSeries = fullSeries.substring(0, fullSeries.indexOf("-")).trim();
}
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
metadata.put(fullSeries + " - " + name, value);
int s = seriesNames.size() - 1;
if (name.equals("StagePosX")) {
store.setStagePositionPositionX(new Float(value), s, 0, 0);
}
else if (name.equals("StagePosY")) {
store.setStagePositionPositionY(new Float(value), s, 0, 0);
}
else if (name.equals("StagePosZ")) {
store.setStagePositionPositionZ(new Float(value), s, 0, 0);
}
}
}
else if (qName.equals("Wheel")) {
String prefix = qName + " " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(prefix + attributes.getQName(i), attributes.getValue(i));
}
count++;
}
else if (qName.equals("WheelName")) {
String prefix = "Wheel " + (count - 1) + " - WheelName ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
int ndx = 0;
while (metadata.get(prefix + ndx) != null) ndx++;
metadata.put(prefix + ndx, attributes.getValue("FilterName"));
}
else if (qName.equals("MultiBand")) {
String prefix = qName + " Channel " + attributes.getValue("Channel");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
int s = seriesNames.size() - 1;
int channel = Integer.parseInt(attributes.getValue("Channel")) - 1;
int channelCount = ((Integer) channels.get(s)).intValue();
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
metadata.put(prefix + " - " + name, value);
if (name.equals("LeftWorld") && channel < channelCount) {
store.setLogicalChannelEmWave(
new Integer((int) Float.parseFloat(value)), s, channel);
}
else if (name.equals("RightWorld") && channel < channelCount) {
store.setLogicalChannelExWave(
new Integer((int) Float.parseFloat(value)), s, channel);
}
else if (name.equals("DyeName") && channel < channelCount) {
store.setLogicalChannelName(value, s, channel);
}
}
}
else if (qName.equals("LaserLineSetting")) {
String prefix = "LaserLine " + attributes.getValue("LaserLine");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
if (!name.equals("LaserLine")) {
metadata.put(prefix + " - " + name, attributes.getValue(i));
store.setLaserWavelength(
new Integer(attributes.getValue("LaserLine")), 0,
Integer.parseInt(attributes.getValue("LineIndex")));
}
}
}
else if (qName.equals("Detector")) {
String prefix = qName + " Channel " + attributes.getValue("Channel");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
if (!name.equals("Channel")) {
metadata.put(prefix + " - " + name, attributes.getValue(i));
}
}
}
else if (qName.equals("Laser")) {
String prefix = qName + " " + attributes.getValue("LaserName");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
if (!name.equals("LaserName")) {
metadata.put(prefix + " - " + name, attributes.getValue(i));
}
}
}
else if (qName.equals("TimeStamp")) {
long high = Long.parseLong(attributes.getValue("HighInteger"));
long low = Long.parseLong(attributes.getValue("LowInteger"));
high <<= 32;
if ((int) low < 0) {
low &= 0xffffffffL;
}
long stamp = high + low;
long ms = stamp / 10000;
String n = String.valueOf(count);
while (n.length() < 4) n = "0" + n;
metadata.put(fullSeries + " - " + qName + n,
DataTools.convertDate(ms, DataTools.COBOL));
count++;
}
else if (qName.equals("ChannelScalingInfo")) {
String prefix = qName + count;
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
metadata.put(prefix + " - " + name, attributes.getValue(i));
}
}
else if (qName.equals("RelTimeStamp")) {
String frame = attributes.getValue("Frame");
String time = attributes.getValue("Time");
metadata.put(fullSeries + " - " + qName + " - " + frame, time);
int originalPlane = Integer.parseInt(frame);
int planeNum =
((Integer) nextPlane.get(seriesNames.size() - 1)).intValue();
if (originalPlane < planeNum) return;
timestamps.put("Series " + (seriesNames.size() - 1) + " Plane " +
planeNum, new Float(time));
planeNum++;
nextPlane.setElementAt(new Integer(planeNum), seriesNames.size() - 1);
}
else count = 0;
}
| public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (qName.equals("Element")) {
if (!attributes.getValue("Name").equals("DCROISet") && !firstElement) {
series = attributes.getValue("Name");
containerNames.add(series);
if (fullSeries == null || fullSeries.equals("")) fullSeries = series;
else fullSeries += "/" + series;
}
else if (firstElement) firstElement = false;
if (attributes.getValue("Name").equals("DCROISet")) {
dcroiOpen = true;
}
numDatasets++;
int idx = numDatasets - 1;
if (idx >= seriesNames.size()) {
numDatasets = seriesNames.size();
}
if (!dcroiOpen) {
numChannels = 0;
extras = 1;
}
}
else if (qName.equals("Experiment")) {
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(attributes.getQName(i), attributes.getValue(i));
}
}
else if (qName.equals("Image")) {
containerNames.remove(series);
if (containerCounts.size() < containerNames.size()) {
containerCounts.add(new Integer(1));
}
else if (containerCounts.size() > 0) {
int ndx = containerCounts.size() - 1;
int n = ((Integer) containerCounts.get(ndx)).intValue();
containerCounts.setElementAt(new Integer(n + 1), ndx);
}
if (fullSeries == null || fullSeries.equals("")) fullSeries = series;
seriesNames.add(fullSeries);
nextPlane.add(new Integer(0));
}
else if (qName.equals("ChannelDescription")) {
String prefix = "Channel " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(prefix + attributes.getQName(i), attributes.getValue(i));
}
count++;
numChannels++;
if (channels.size() > seriesNames.size() - 1) {
channels.setElementAt(new Integer(count), seriesNames.size() - 1);
}
else channels.add(new Integer(count));
if (numChannels == 1) {
bps.add(new Integer(attributes.getValue("Resolution")));
}
lutNames.add(attributes.getValue("LUTName"));
}
else if (qName.equals("DimensionDescription")) {
String prefix = "Dimension " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(prefix + attributes.getQName(i), attributes.getValue(i));
}
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
switch (id) {
case 1:
widths.add(new Integer(len));
int b = Integer.parseInt(attributes.getValue("BytesInc"));
bits.add(new Integer(b * 8));
break;
case 2:
if (widths.size() == heights.size()) {
if (zs.size() == heights.size()) {
zs.setElementAt(new Integer(len), zs.size() - 1);
}
else if (ts.size() == heights.size()) {
ts.setElementAt(new Integer(len), ts.size() - 1);
}
}
else heights.add(new Integer(len));
break;
case 3:
if (heights.size() < widths.size()) {
// XZ scan - swap Y and Z
heights.add(new Integer(len));
zs.add(new Integer(1));
}
else zs.add(new Integer(len));
break;
case 4:
if (heights.size() < widths.size()) {
// XT scan - swap Y and T
heights.add(new Integer(len));
ts.add(new Integer(1));
}
else ts.add(new Integer(len));
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord")) {
String identifier = attributes.getValue("Identifier");
String key = identifier + " - " + attributes.getValue("Description");
if (fullSeries != null && !fullSeries.equals("")) {
key = fullSeries + " - " + key;
}
metadata.put(key, attributes.getValue("Variant"));
if (identifier.startsWith("dblVoxel")) {
String size = attributes.getValue("Variant");
float cal = Float.parseFloat(size) * 1000000;
if (identifier.endsWith("X")) xcal.add(new Float(cal));
else if (identifier.endsWith("Y")) ycal.add(new Float(cal));
else if (identifier.endsWith("Z")) zcal.add(new Float(cal));
}
}
else if (qName.equals("FilterSettingRecord")) {
String object = attributes.getValue("ObjectName");
String key = object + " - " + attributes.getValue("Description") + " - " +
attributes.getValue("Attribute");
if (fullSeries != null && !fullSeries.equals("")) {
key = fullSeries + " - " + key;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
metadata.put(key + " - " + name, value);
if (name.equals("Variant")) {
if (key.endsWith("NumericalAperture")) {
store.setObjectiveLensNA(new Float(value), 0, 0);
}
else if (key.endsWith("HighVoltage")) {
if (!detectorNames.contains(object)) {
detectorNames.add(object);
}
int detector = detectorNames.indexOf(object);
store.setDetectorID("Detector:" + detector, 0, detector);
store.setDetectorVoltage(new Float(value), 0, detector);
store.setDetectorType("Unknown", 0, detector);
store.setDetectorSettingsDetector("Detector:" + detector,
seriesNames.size() - 1, nextDetector);
nextDetector++;
}
else if (key.endsWith("VideoOffset")) {
store.setDetectorOffset(new Float(value), 0, 0);
store.setDetectorType("Unknown", 0, 0);
}
else if (key.endsWith("OrderNumber")) {
store.setObjectiveSerialNumber(value, 0, 0);
}
else if (key.endsWith("Objective")) {
StringTokenizer tokens = new StringTokenizer(value, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
if (token.indexOf("x") != -1) {
foundMag = true;
String mag = token.substring(0, token.indexOf("x"));
String na = token.substring(token.indexOf("x") + 1);
store.setObjectiveNominalMagnification(
new Integer((int) Float.parseFloat(mag)), 0, 0);
store.setObjectiveLensNA(new Float(na), 0, 0);
break;
}
model.append(token);
model.append(" ");
}
if (tokens.hasMoreTokens()) {
String immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Unknown";
}
store.setObjectiveImmersion(immersion, 0, 0);
}
if (tokens.countTokens() > 1) {
Float temperature = new Float(tokens.nextToken());
tokens.nextToken();
}
if (tokens.hasMoreTokens()) {
store.setObjectiveCorrection(tokens.nextToken(), 0, 0);
}
store.setObjectiveModel(model.toString(), 0, 0);
}
else if (key.endsWith("RefractionIndex")) {
store.setObjectiveID("Objective:0", 0, 0);
store.setObjectiveSettingsObjective("Objective:0",
seriesNames.size() - 1);
store.setObjectiveSettingsRefractiveIndex(new Float(value),
seriesNames.size() - 1);
}
else if (key.endsWith("Laser wavelength - Wavelength")) {
if (!laserNames.contains(object)) {
int index = laserNames.size();
store.setLightSourceID("LightSource:" + index, 0, index);
store.setLaserType("Unknown", 0, index);
store.setLaserWavelength(new Integer(value), 0, index);
store.setLaserLaserMedium("Unknown", 0, index);
laserNames.add(object);
}
}
else if (key.endsWith("Laser output power - Output Power")) {
if (!laserNames.contains(object)) {
laserNames.add(object);
}
int laser = laserNames.indexOf(object);
store.setLightSourcePower(new Float(value), 0, laser);
store.setLightSourceSettingsLightSource("LightSource:" + laser,
seriesNames.size() - 1, nextLaser);
nextLaser++;
}
else if (key.endsWith("Stage Pos x - XPos")) {
while (xPosition.size() < seriesNames.size() - 1) {
xPosition.add(null);
}
xPosition.add(new Float(value));
}
else if (key.endsWith("Stage Pos y - YPos")) {
while (yPosition.size() < seriesNames.size() - 1) {
yPosition.add(null);
}
yPosition.add(new Float(value));
}
else if (key.endsWith("Stage Pos z - ZPos")) {
while (zPosition.size() < seriesNames.size() - 1) {
zPosition.add(null);
}
zPosition.add(new Float(value));
}
}
}
}
else if (qName.equals("ATLConfocalSettingDefinition")) {
if (fullSeries == null) fullSeries = "";
if (fullSeries.endsWith(" - Master sequential setting")) {
fullSeries = fullSeries.replaceAll("Master sequential setting",
"Sequential Setting 0");
}
if (fullSeries.indexOf("Sequential Setting ") == -1) {
if (fullSeries.equals("")) fullSeries = "Master sequential setting";
else fullSeries += " - Master sequential setting";
}
else {
int ndx = fullSeries.indexOf("Sequential Setting ") + 19;
try {
int n = Integer.parseInt(fullSeries.substring(ndx)) + 1;
fullSeries = fullSeries.substring(0, ndx) + String.valueOf(n);
}
catch (NumberFormatException exc) {
fullSeries = fullSeries.substring(0, fullSeries.indexOf("-")).trim();
}
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
metadata.put(fullSeries + " - " + name, value);
int s = seriesNames.size() - 1;
if (name.equals("StagePosX")) {
store.setStagePositionPositionX(new Float(value), s, 0, 0);
}
else if (name.equals("StagePosY")) {
store.setStagePositionPositionY(new Float(value), s, 0, 0);
}
else if (name.equals("StagePosZ")) {
store.setStagePositionPositionZ(new Float(value), s, 0, 0);
}
}
}
else if (qName.equals("Wheel")) {
String prefix = qName + " " + count + " - ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
metadata.put(prefix + attributes.getQName(i), attributes.getValue(i));
}
count++;
}
else if (qName.equals("WheelName")) {
String prefix = "Wheel " + (count - 1) + " - WheelName ";
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
int ndx = 0;
while (metadata.get(prefix + ndx) != null) ndx++;
metadata.put(prefix + ndx, attributes.getValue("FilterName"));
}
else if (qName.equals("MultiBand")) {
String prefix = qName + " Channel " + attributes.getValue("Channel");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
int s = seriesNames.size() - 1;
int channel = Integer.parseInt(attributes.getValue("Channel")) - 1;
int channelCount = s < channels.size() ?
((Integer) channels.get(s)).intValue() : 1;
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
metadata.put(prefix + " - " + name, value);
if (name.equals("LeftWorld") && channel < channelCount) {
store.setLogicalChannelEmWave(
new Integer((int) Float.parseFloat(value)), s, channel);
}
else if (name.equals("RightWorld") && channel < channelCount) {
store.setLogicalChannelExWave(
new Integer((int) Float.parseFloat(value)), s, channel);
}
else if (name.equals("DyeName") && channel < channelCount) {
store.setLogicalChannelName(value, s, channel);
}
}
}
else if (qName.equals("LaserLineSetting")) {
String prefix = "LaserLine " + attributes.getValue("LaserLine");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
if (!name.equals("LaserLine")) {
metadata.put(prefix + " - " + name, attributes.getValue(i));
store.setLaserWavelength(
new Integer(attributes.getValue("LaserLine")), 0,
Integer.parseInt(attributes.getValue("LineIndex")));
}
}
}
else if (qName.equals("Detector")) {
String prefix = qName + " Channel " + attributes.getValue("Channel");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
if (!name.equals("Channel")) {
metadata.put(prefix + " - " + name, attributes.getValue(i));
}
}
}
else if (qName.equals("Laser")) {
String prefix = qName + " " + attributes.getValue("LaserName");
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
if (!name.equals("LaserName")) {
metadata.put(prefix + " - " + name, attributes.getValue(i));
}
}
}
else if (qName.equals("TimeStamp")) {
long high = Long.parseLong(attributes.getValue("HighInteger"));
long low = Long.parseLong(attributes.getValue("LowInteger"));
high <<= 32;
if ((int) low < 0) {
low &= 0xffffffffL;
}
long stamp = high + low;
long ms = stamp / 10000;
String n = String.valueOf(count);
while (n.length() < 4) n = "0" + n;
metadata.put(fullSeries + " - " + qName + n,
DataTools.convertDate(ms, DataTools.COBOL));
count++;
}
else if (qName.equals("ChannelScalingInfo")) {
String prefix = qName + count;
if (fullSeries != null && !fullSeries.equals("")) {
prefix = fullSeries + " - " + prefix;
}
for (int i=0; i<attributes.getLength(); i++) {
String name = attributes.getQName(i);
metadata.put(prefix + " - " + name, attributes.getValue(i));
}
}
else if (qName.equals("RelTimeStamp")) {
String frame = attributes.getValue("Frame");
String time = attributes.getValue("Time");
metadata.put(fullSeries + " - " + qName + " - " + frame, time);
int originalPlane = Integer.parseInt(frame);
int planeNum =
((Integer) nextPlane.get(seriesNames.size() - 1)).intValue();
if (originalPlane < planeNum) return;
timestamps.put("Series " + (seriesNames.size() - 1) + " Plane " +
planeNum, new Float(time));
planeNum++;
nextPlane.setElementAt(new Integer(planeNum), seriesNames.size() - 1);
}
else count = 0;
}
|
diff --git a/src/game/entity/Entity.java b/src/game/entity/Entity.java
index 5d68b93..5b92595 100644
--- a/src/game/entity/Entity.java
+++ b/src/game/entity/Entity.java
@@ -1,65 +1,68 @@
package game.entity;
import java.awt.Rectangle;
import engine.WMath;
import engine.render.Renderable;
import game.WormsGame;
public abstract class Entity extends Renderable {
//Position and Size
protected float x, y, width, height;
//Movement
protected float xMotion, yMotion;
protected float fallDuration;
protected float fallDistance;
//Game Reference
protected WormsGame wormsGame;
public Entity(WormsGame wormsGame, int x, int y, int width, int height) {
super();
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.wormsGame = wormsGame;
setFalling(false);
}
public void setFalling(boolean b) {
fallDuration = (b) ? 1 : 0;
}
public boolean isOnGround() {
return wormsGame.collides(this, 0, -1);
}
public void doMovement() {
if(xMotion != 0 || yMotion != 0) {
setRenderUpdate(true);
x += xMotion;
y -= yMotion;
while(wormsGame.collides(this, 0, 1)) {
--y;
- --yMotion;
+ if(yMotion < 0)
+ ++yMotion;
+ else
+ --yMotion;
}
if(fallDuration > 0)
fallDistance += WMath.abs_f(yMotion);
xMotion = yMotion = 0;
}
}
public abstract void onTick();
public boolean isFalling() {
return fallDuration > 0;
}
public Rectangle getCollisionBox() {
return new Rectangle((int)x, (int)y, (int)width, (int)height);
}
}
| true | true | public void doMovement() {
if(xMotion != 0 || yMotion != 0) {
setRenderUpdate(true);
x += xMotion;
y -= yMotion;
while(wormsGame.collides(this, 0, 1)) {
--y;
--yMotion;
}
if(fallDuration > 0)
fallDistance += WMath.abs_f(yMotion);
xMotion = yMotion = 0;
}
}
| public void doMovement() {
if(xMotion != 0 || yMotion != 0) {
setRenderUpdate(true);
x += xMotion;
y -= yMotion;
while(wormsGame.collides(this, 0, 1)) {
--y;
if(yMotion < 0)
++yMotion;
else
--yMotion;
}
if(fallDuration > 0)
fallDistance += WMath.abs_f(yMotion);
xMotion = yMotion = 0;
}
}
|
diff --git a/src/Extensions/org/objectweb/proactive/extensions/vfsprovider/FileSystemServerDeployer.java b/src/Extensions/org/objectweb/proactive/extensions/vfsprovider/FileSystemServerDeployer.java
index bc89ce02a..88ac1008a 100644
--- a/src/Extensions/org/objectweb/proactive/extensions/vfsprovider/FileSystemServerDeployer.java
+++ b/src/Extensions/org/objectweb/proactive/extensions/vfsprovider/FileSystemServerDeployer.java
@@ -1,179 +1,179 @@
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2010 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* 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; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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
*
* If needed, contact us to obtain a release under GPL Version 2
* or a different license than the GPL.
*
* Initial developer(s): The ActiveEon Team
* http://www.activeeon.com/
* Contributor(s):
*
* ################################################################
* $$ACTIVEEON_INITIAL_DEV$$
*/
package org.objectweb.proactive.extensions.vfsprovider;
import java.io.IOException;
import java.net.URISyntaxException;
import org.objectweb.proactive.api.PARemoteObject;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.exceptions.IOException6;
import org.objectweb.proactive.core.remoteobject.RemoteObjectExposer;
import org.objectweb.proactive.core.remoteobject.RemoteObjectHelper;
import org.objectweb.proactive.core.remoteobject.exception.UnknownProtocolException;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.extensions.vfsprovider.client.ProActiveFileName;
import org.objectweb.proactive.extensions.vfsprovider.protocol.FileSystemServer;
import org.objectweb.proactive.extensions.vfsprovider.server.FileSystemServerImpl;
/**
* Deploys {@link FileSystemServer} with instance of {@link FileSystemServerImpl} implementation on
* the local runtime and provides URL access methods.
*/
public final class FileSystemServerDeployer {
private static final String FILE_SERVER_DEFAULT_NAME = "defaultFileSystemServer";
/** URL of the remote object */
final private String url;
/** URL of root file exposed through that server */
private String vfsRootURL;
private FileSystemServerImpl fileSystemServer;
private RemoteObjectExposer<FileSystemServerImpl> roe;
/**
* Deploys locally a FileSystemServer as a RemoteObject with a default name.
*
* @param rootPath the real path on which to bind the server
* @param autoclosing
* @throws IOException
*/
public FileSystemServerDeployer(String rootPath, boolean autoclosing) throws IOException {
this(FILE_SERVER_DEFAULT_NAME, rootPath, autoclosing);
}
/**
* Deploys locally a FileSystemServer as a RemoteObject with a default name.
*
* @param rootPath the real path on which to bind the server
* @param autoclosing
* @param rebind true if the service must rebind an existing one, false otherwise.
* @throws IOException
*/
public FileSystemServerDeployer(String rootPath, boolean autoclosing, boolean rebind) throws IOException {
this(FILE_SERVER_DEFAULT_NAME, rootPath, autoclosing, rebind);
}
/**
* Deploys locally a FileSystemServer as a RemoteObject with a given name.
*
* @param name of deployed RemoteObject
* @param rootPath the real path on which to bind the server
* @param autoclosing
* @throws IOException
*/
public FileSystemServerDeployer(String name, String rootPath, boolean autoclosing) throws IOException {
this(name, rootPath, autoclosing, false);
}
/**
* Deploys locally a FileSystemServer as a RemoteObject with a given name.
*
* @param name of deployed RemoteObject
* @param rootPath the real path on which to bind the server
* @param autoclosing
* @param rebind true if the service must rebind an existing one, false otherwise.
* @throws IOException
*/
public FileSystemServerDeployer(String name, String rootPath, boolean autoclosing, boolean rebind)
throws IOException {
fileSystemServer = new FileSystemServerImpl(rootPath);
try {
roe = PARemoteObject.newRemoteObject(FileSystemServer.class.getName(), this.fileSystemServer);
- roe.createRemoteObject(name, true);
+ roe.createRemoteObject(name, rebind);
url = roe.getURL();
} catch (ProActiveException e) {
// Ugly but createRemoteObject interface changed
throw new IOException6("", e);
}
try {
vfsRootURL = ProActiveFileName.getServerVFSRootURL(url);
} catch (URISyntaxException e) {
ProActiveLogger.logImpossibleException(ProActiveLogger.getLogger(Loggers.VFS_PROVIDER_SERVER), e);
throw new ProActiveRuntimeException(e);
} catch (UnknownProtocolException e) {
ProActiveLogger.logImpossibleException(ProActiveLogger.getLogger(Loggers.VFS_PROVIDER_SERVER), e);
throw new ProActiveRuntimeException(e);
}
if (autoclosing)
fileSystemServer.startAutoClosing();
}
public FileSystemServerImpl getLocalFileSystemServer() {
return this.fileSystemServer;
}
public FileSystemServer getRemoteFileSystemServer() throws ProActiveException {
return (FileSystemServer) RemoteObjectHelper.generatedObjectStub(this.roe.getRemoteObject());
}
/**
* <strong>internal use only!</strong>
*/
public String getRemoteFileSystemServerURL() {
return this.url;
}
/**
* @return URL pointing to root file exposed by this provider server; suitable for VFS provider
*/
public String getVFSRootURL() {
return vfsRootURL;
}
/**
* Unexport the remote object and stops the server.
*
* @throws ProActiveException
*/
public void terminate() throws ProActiveException {
if (roe != null) {
roe.unexportAll();
roe.unregisterAll();
roe = null;
fileSystemServer.stopServer();
fileSystemServer = null;
}
}
}
| true | true | public FileSystemServerDeployer(String name, String rootPath, boolean autoclosing, boolean rebind)
throws IOException {
fileSystemServer = new FileSystemServerImpl(rootPath);
try {
roe = PARemoteObject.newRemoteObject(FileSystemServer.class.getName(), this.fileSystemServer);
roe.createRemoteObject(name, true);
url = roe.getURL();
} catch (ProActiveException e) {
// Ugly but createRemoteObject interface changed
throw new IOException6("", e);
}
try {
vfsRootURL = ProActiveFileName.getServerVFSRootURL(url);
} catch (URISyntaxException e) {
ProActiveLogger.logImpossibleException(ProActiveLogger.getLogger(Loggers.VFS_PROVIDER_SERVER), e);
throw new ProActiveRuntimeException(e);
} catch (UnknownProtocolException e) {
ProActiveLogger.logImpossibleException(ProActiveLogger.getLogger(Loggers.VFS_PROVIDER_SERVER), e);
throw new ProActiveRuntimeException(e);
}
if (autoclosing)
fileSystemServer.startAutoClosing();
}
| public FileSystemServerDeployer(String name, String rootPath, boolean autoclosing, boolean rebind)
throws IOException {
fileSystemServer = new FileSystemServerImpl(rootPath);
try {
roe = PARemoteObject.newRemoteObject(FileSystemServer.class.getName(), this.fileSystemServer);
roe.createRemoteObject(name, rebind);
url = roe.getURL();
} catch (ProActiveException e) {
// Ugly but createRemoteObject interface changed
throw new IOException6("", e);
}
try {
vfsRootURL = ProActiveFileName.getServerVFSRootURL(url);
} catch (URISyntaxException e) {
ProActiveLogger.logImpossibleException(ProActiveLogger.getLogger(Loggers.VFS_PROVIDER_SERVER), e);
throw new ProActiveRuntimeException(e);
} catch (UnknownProtocolException e) {
ProActiveLogger.logImpossibleException(ProActiveLogger.getLogger(Loggers.VFS_PROVIDER_SERVER), e);
throw new ProActiveRuntimeException(e);
}
if (autoclosing)
fileSystemServer.startAutoClosing();
}
|
diff --git a/src/main/java/com/nesscomputing/tracking/TrackingToken.java b/src/main/java/com/nesscomputing/tracking/TrackingToken.java
index b547179..23afc38 100644
--- a/src/main/java/com/nesscomputing/tracking/TrackingToken.java
+++ b/src/main/java/com/nesscomputing/tracking/TrackingToken.java
@@ -1,63 +1,65 @@
/**
* Copyright (C) 2012 Ness Computing, 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.nesscomputing.tracking;
import java.util.UUID;
import org.apache.log4j.MDC;
import com.nesscomputing.scopes.threaddelegate.ThreadDelegatedContext.ScopeEvent;
import com.nesscomputing.scopes.threaddelegate.ThreadDelegatedContext.ScopeListener;
/**
* Represents the tracking UUID. This object is in the ThreadDelegated scope and will
* be notified whenever it gets handed onto another thread to allow updating of
* that's thread MDC information.
*/
public class TrackingToken implements ScopeListener
{
public static final String MDC_TRACKING_KEY = "track";
private UUID value = null;
public void setValue(final UUID value)
{
this.value = value;
if (value != null) {
MDC.put(MDC_TRACKING_KEY, value);
}
}
public UUID getValue()
{
return value;
}
@Override
public void event(final ScopeEvent event)
{
switch (event) {
case ENTER:
if (value != null) {
MDC.put(MDC_TRACKING_KEY, value);
}
break;
case LEAVE:
MDC.remove(MDC_TRACKING_KEY);
break;
+ default:
+ throw new IllegalStateException("Unknown Event: " + event);
}
}
}
| true | true | public void event(final ScopeEvent event)
{
switch (event) {
case ENTER:
if (value != null) {
MDC.put(MDC_TRACKING_KEY, value);
}
break;
case LEAVE:
MDC.remove(MDC_TRACKING_KEY);
break;
}
}
| public void event(final ScopeEvent event)
{
switch (event) {
case ENTER:
if (value != null) {
MDC.put(MDC_TRACKING_KEY, value);
}
break;
case LEAVE:
MDC.remove(MDC_TRACKING_KEY);
break;
default:
throw new IllegalStateException("Unknown Event: " + event);
}
}
|
diff --git a/src/soda/SodaSuiteParser.java b/src/soda/SodaSuiteParser.java
index 5457e00..1beda82 100644
--- a/src/soda/SodaSuiteParser.java
+++ b/src/soda/SodaSuiteParser.java
@@ -1,97 +1,102 @@
/*
Copyright 2011 Trampus Richmond. 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 TRAMPUS RICHMOND ``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
TRAMPUS RICHMOND 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
should not be interpreted as representing official policies, either expressed or implied, of Trampus Richmond.
*/
package soda;
import java.io.File;
import java.util.Arrays;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
public class SodaSuiteParser {
private SodaTestList tests = null;
public SodaSuiteParser(String suitefile) {
Document doc = null;
File suiteFD = null;
DocumentBuilderFactory dbf = null;
DocumentBuilder db = null;
try {
this.tests = new SodaTestList();
suiteFD = new File(suitefile);
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(suiteFD);
this.parse(doc.getDocumentElement().getChildNodes());
} catch (Exception exp) {
exp.printStackTrace();
}
}
public SodaTestList getTests() {
return this.tests;
}
private void parse(NodeList nodes) {
int len = nodes.getLength() -1;
for (int i = 0; i <= len; i++) {
String name = nodes.item(i).getNodeName();
if (name.contains("#text")) {
continue;
}
NamedNodeMap attrs = nodes.item(i).getAttributes();
int atts_len = attrs.getLength() -1;
for (int x = 0; x <= atts_len; x++) {
String attr_name = attrs.item(x).getNodeName();
String attr_value = attrs.item(x).getNodeValue();
File fd_tmp = null;
if (attr_name.contains("fileset")) {
fd_tmp = new File(attr_value);
String base_path = fd_tmp.getAbsolutePath();
String[] files = fd_tmp.list();
Arrays.sort(files);
for (int findex = 0; findex <= files.length -1; findex++) {
- this.tests.add(base_path+"/"+files[findex]);
+ if (files[findex].toLowerCase().matches(".*\\.xml")) {
+ this.tests.add(base_path+"/"+files[findex]);
+ System.out.printf("(*)Adding file to Soda Suite list: '%s'.\n", base_path+"/"+files[findex]);
+ } else {
+ System.out.printf("(!)Not adding file to Soda Suite list: '%s'.\n", base_path+"/"+files[findex]);
+ }
}
} else {
this.tests.add(attr_value);
}
}
}
}
}
| true | true | private void parse(NodeList nodes) {
int len = nodes.getLength() -1;
for (int i = 0; i <= len; i++) {
String name = nodes.item(i).getNodeName();
if (name.contains("#text")) {
continue;
}
NamedNodeMap attrs = nodes.item(i).getAttributes();
int atts_len = attrs.getLength() -1;
for (int x = 0; x <= atts_len; x++) {
String attr_name = attrs.item(x).getNodeName();
String attr_value = attrs.item(x).getNodeValue();
File fd_tmp = null;
if (attr_name.contains("fileset")) {
fd_tmp = new File(attr_value);
String base_path = fd_tmp.getAbsolutePath();
String[] files = fd_tmp.list();
Arrays.sort(files);
for (int findex = 0; findex <= files.length -1; findex++) {
this.tests.add(base_path+"/"+files[findex]);
}
} else {
this.tests.add(attr_value);
}
}
}
}
| private void parse(NodeList nodes) {
int len = nodes.getLength() -1;
for (int i = 0; i <= len; i++) {
String name = nodes.item(i).getNodeName();
if (name.contains("#text")) {
continue;
}
NamedNodeMap attrs = nodes.item(i).getAttributes();
int atts_len = attrs.getLength() -1;
for (int x = 0; x <= atts_len; x++) {
String attr_name = attrs.item(x).getNodeName();
String attr_value = attrs.item(x).getNodeValue();
File fd_tmp = null;
if (attr_name.contains("fileset")) {
fd_tmp = new File(attr_value);
String base_path = fd_tmp.getAbsolutePath();
String[] files = fd_tmp.list();
Arrays.sort(files);
for (int findex = 0; findex <= files.length -1; findex++) {
if (files[findex].toLowerCase().matches(".*\\.xml")) {
this.tests.add(base_path+"/"+files[findex]);
System.out.printf("(*)Adding file to Soda Suite list: '%s'.\n", base_path+"/"+files[findex]);
} else {
System.out.printf("(!)Not adding file to Soda Suite list: '%s'.\n", base_path+"/"+files[findex]);
}
}
} else {
this.tests.add(attr_value);
}
}
}
}
|
diff --git a/software/src/propinquity/hardware/HardwareDebugger.java b/software/src/propinquity/hardware/HardwareDebugger.java
index 790e997..5ac233e 100644
--- a/software/src/propinquity/hardware/HardwareDebugger.java
+++ b/software/src/propinquity/hardware/HardwareDebugger.java
@@ -1,250 +1,251 @@
package propinquity.hardware;
import processing.core.*;
import controlP5.*;
/**
* A hacky sketch to test patches or gloves, provded buttons and sliders to control active, vibe and LEDS as well as giving prox value back.
*
*/
public class HardwareDebugger extends PApplet implements ProxEventListener, AccelEventListener {
// Unique serialization ID
static final long serialVersionUID = 6340508174717159418L;
static final int[] PATCH_ADDR = new int[] { 3 };
static final int NUM_PATCHES = PATCH_ADDR.length;
static final int[] GLOVE_ADDR = new int[] {};
static final int NUM_GLOVES = GLOVE_ADDR.length;
XBeeBaseStation xbeeBaseStation;
Patch[] patches;
Glove[] gloves;
ControlP5 controlP5;
boolean show_controls = true;
Slider prox_sliders[];
Slider x_sliders[];
Slider y_sliders[];
Slider z_sliders[];
public void setup() {
size(1024, 800);
controlP5 = new ControlP5(this);
prox_sliders = new Slider[NUM_PATCHES];
x_sliders = new Slider[NUM_PATCHES];
y_sliders = new Slider[NUM_PATCHES];
z_sliders = new Slider[NUM_PATCHES];
controlP5.addButton("Re-Scan", 1, 10, 10, 50, 25);
for(int i = 0;i < NUM_PATCHES;i++) {
int x_offset = (width-100)/NUM_PATCHES*i+50;
int y_offset = 60;
int local_width = round((width-100)/NUM_PATCHES*0.95f);
int obj_width = 15;
int slider_height = 150;
int level_0 = -45;
int level_1 = 10;
int level_2 = level_1+(slider_height+20);
int level_3 = level_1+(slider_height+20)*2;
int level_4 = level_1+(slider_height+20)*3;
int num = 3;
int incr_offset = 0;
int incr_width = (local_width-incr_offset*2)/num;
int obj_offset = incr_offset+(incr_width-obj_width)/2;
ControlGroup group = controlP5.addGroup("Patch "+i, x_offset, y_offset, local_width);
Toggle toggle = controlP5.addToggle("Active "+i, incr_width*0+obj_offset, level_0, obj_width, obj_width);
toggle.setGroup(group);
Slider r_slider = controlP5.addSlider("Red "+i, 0, 255, 0, incr_width*0+obj_offset, level_1, obj_width, slider_height);
r_slider.setGroup(group);
Slider g_slider = controlP5.addSlider("Green "+i, 0, 255, 0, incr_width*1+obj_offset, level_1, obj_width, slider_height);
g_slider.setGroup(group);
Slider b_slider = controlP5.addSlider("Blue "+i, 0, 255, 0, incr_width*2+obj_offset, level_1, obj_width, slider_height);
b_slider.setGroup(group);
Slider duty_slider = controlP5.addSlider("Color Duty "+i, 0, 255, 0, incr_width*0+obj_offset, level_2, obj_width, slider_height);
duty_slider.setGroup(group);
Slider period_slider = controlP5.addSlider("Color Period "+i, 0, 255, 0, incr_width*1+obj_offset, level_2, obj_width, slider_height);
period_slider.setGroup(group);
prox_sliders[i] = controlP5.addSlider("Prox "+i, 0, 1024, 0, incr_width*2+obj_offset, level_2, obj_width, slider_height);
prox_sliders[i].lock();
prox_sliders[i].setGroup(group);
Slider vibe_slider = controlP5.addSlider("Vibe Level "+i, 0, 255, 0, incr_width*0+obj_offset, level_3, obj_width, slider_height);
vibe_slider.setGroup(group);
Slider vibe_duties_slider = controlP5.addSlider("Vibe Duty "+i, 0, 255, 0, incr_width*1+obj_offset, level_3, obj_width, slider_height);
vibe_duties_slider.setGroup(group);
Slider vibe_periods_slider = controlP5.addSlider("Vibe Period "+i, 0, 255, 0, incr_width*2+obj_offset, level_3, obj_width, slider_height);
vibe_periods_slider.setGroup(group);
- x_sliders[i] = controlP5.addSlider("X "+i, 0, 1024, 0, incr_width*0+obj_offset, level_4, obj_width, slider_height);
+ x_sliders[i] = controlP5.addSlider("X "+i, -128, 128, 0, incr_width*0+obj_offset, level_4, obj_width, slider_height);
x_sliders[i].lock();
x_sliders[i].setGroup(group);
- y_sliders[i] = controlP5.addSlider("Y "+i, 0, 1024, 0, incr_width*1+obj_offset, level_4, obj_width, slider_height);
+ y_sliders[i] = controlP5.addSlider("Y "+i, -128, 128, 0, incr_width*1+obj_offset, level_4, obj_width, slider_height);
y_sliders[i].lock();
y_sliders[i].setGroup(group);
- z_sliders[i] = controlP5.addSlider("Z "+i, 0, 1024, 0, incr_width*2+obj_offset, level_4, obj_width, slider_height);
+ z_sliders[i] = controlP5.addSlider("Z "+i, -128, 128, 0, incr_width*2+obj_offset, level_4, obj_width, slider_height);
z_sliders[i].lock();
z_sliders[i].setGroup(group);
}
// for(int i = 0;i < NUM_GLOVES;i++) {
// int x_offset = (width-100)/NUM_GLOVES*i+50;
// int y_offset = 60;
// int local_width = round((width-100)/NUM_GLOVES*0.95f);
// int obj_width = 15;
// int slider_height = 200;
// int level_0 = -45;
// int level_1 = 10;
// // int level_2 = 240;
// // int level_3 = 480;
// int num = 3;
// int incr_offset = 0;
// int incr_width = (local_width-incr_offset*2)/num;
// int obj_offset = incr_offset+(incr_width-obj_width)/2;
// ControlGroup group = controlP5.addGroup("Glove "+i, x_offset, y_offset, local_width);
// Toggle toggle = controlP5.addToggle("Active "+i, incr_width*0+obj_offset, level_0, obj_width, obj_width);
// toggle.setGroup(group);
// Slider vibe_slider = controlP5.addSlider("Vibe Level "+i, 0, 255, 0, incr_width*0+obj_offset, level_1, obj_width, slider_height);
// vibe_slider.setGroup(group);
// Slider vibe_duties_slider = controlP5.addSlider("Vibe Duty "+i, 0, 255, 0, incr_width*1+obj_offset, level_1, obj_width, slider_height);
// vibe_duties_slider.setGroup(group);
// Slider vibe_periods_slider = controlP5.addSlider("Vibe Period "+i, 0, 255, 0, incr_width*2+obj_offset, level_1, obj_width, slider_height);
// vibe_periods_slider.setGroup(group);
// }
if(!show_controls) controlP5.hide();
xbeeBaseStation = new XBeeBaseStation();
xbeeBaseStation.scan();
xbeeBaseStation.addProxEventListener(this);
+ xbeeBaseStation.addAccelEventListener(this);
patches = new Patch[NUM_PATCHES];
for(int i = 0;i < NUM_PATCHES;i++) {
patches[i] = new Patch(PATCH_ADDR[i], xbeeBaseStation);
xbeeBaseStation.addPatch(patches[i]);
}
// gloves = new Glove[NUM_GLOVES];
// for(int i = 0;i < NUM_GLOVES;i++) {
// gloves[i] = new Glove(GLOVE_ADDR[i], xbeeBaseStation);
// xbeeBaseStation.addGlove(gloves[i]);
// }
}
public void controlEvent(ControlEvent theEvent) {
String name = theEvent.controller().name();
int value = (int)theEvent.controller().value();
if(name.indexOf("Active") == -1 && value < 10) value = 0; //Snap to zero
if(name.equals("Re-Scan")) {
xbeeBaseStation.scan();
return;
} else {
for(int i = 0;i < NUM_PATCHES;i++) {
if(name.equals("Active "+i)) {
if(value != 0) patches[i].setActive(true);
else patches[i].setActive(false);
return;
} else if(name.equals("Red "+i)) {
int[] current_color = patches[i].getColor();
patches[i].setColor(value, current_color[1], current_color[2]);
return;
} else if(name.equals("Green "+i)) {
int[] current_color = patches[i].getColor();
patches[i].setColor(current_color[0], value, current_color[2]);
return;
} else if(name.equals("Blue "+i)) {
int[] current_color = patches[i].getColor();
patches[i].setColor(current_color[0], current_color[1], value);
return;
} else if(name.equals("Color Duty "+i)) {
patches[i].setColorDuty(value);
return;
} else if(name.equals("Color Period "+i)) {
patches[i].setColorPeriod(value);
return;
} else if(name.equals("Vibe Level "+i)) {
patches[i].setVibeLevel(value);
return;
} else if(name.equals("Vibe Duty "+i)) {
patches[i].setVibeDuty(value);
return;
} else if(name.equals("Vibe Period "+i)) {
patches[i].setVibePeriod(value);
return;
}
}
}
}
public void draw() {
if(xbeeBaseStation.isScanning()) background(30, 0, 0);
else background(0);
if(xbeeBaseStation.listXBees() != null && xbeeBaseStation.listXBees().length > 0) {
stroke(150);
fill(0, 75, 0);
} else {
stroke(150);
fill(75, 0, 0);
}
rect(5, height-30, 25, 25);
}
public void keyPressed() {
if(key == 's') {
xbeeBaseStation.scan();
} else if(key == 'h') {
show_controls = !show_controls;
if(!show_controls) controlP5.hide();
else controlP5.show();
}
}
public void proxEvent(Patch patch) {
for(int i = 0;i < NUM_PATCHES;i++) {
if(patch == patches[i]) {
prox_sliders[i].setValue(patch.getProx());
}
}
}
public void accelXYZEvent(Patch patch) {
for(int i = 0;i < NUM_PATCHES;i++) {
if(patch == patches[i]) {
x_sliders[i].setValue(patch.getAccelX());
y_sliders[i].setValue(patch.getAccelY());
z_sliders[i].setValue(patch.getAccelZ());
}
}
}
static public void main(String args[]) {
PApplet.main(new String[] { "propinquity.hardware.HardwareDebugger" });
}
}
| false | true | public void setup() {
size(1024, 800);
controlP5 = new ControlP5(this);
prox_sliders = new Slider[NUM_PATCHES];
x_sliders = new Slider[NUM_PATCHES];
y_sliders = new Slider[NUM_PATCHES];
z_sliders = new Slider[NUM_PATCHES];
controlP5.addButton("Re-Scan", 1, 10, 10, 50, 25);
for(int i = 0;i < NUM_PATCHES;i++) {
int x_offset = (width-100)/NUM_PATCHES*i+50;
int y_offset = 60;
int local_width = round((width-100)/NUM_PATCHES*0.95f);
int obj_width = 15;
int slider_height = 150;
int level_0 = -45;
int level_1 = 10;
int level_2 = level_1+(slider_height+20);
int level_3 = level_1+(slider_height+20)*2;
int level_4 = level_1+(slider_height+20)*3;
int num = 3;
int incr_offset = 0;
int incr_width = (local_width-incr_offset*2)/num;
int obj_offset = incr_offset+(incr_width-obj_width)/2;
ControlGroup group = controlP5.addGroup("Patch "+i, x_offset, y_offset, local_width);
Toggle toggle = controlP5.addToggle("Active "+i, incr_width*0+obj_offset, level_0, obj_width, obj_width);
toggle.setGroup(group);
Slider r_slider = controlP5.addSlider("Red "+i, 0, 255, 0, incr_width*0+obj_offset, level_1, obj_width, slider_height);
r_slider.setGroup(group);
Slider g_slider = controlP5.addSlider("Green "+i, 0, 255, 0, incr_width*1+obj_offset, level_1, obj_width, slider_height);
g_slider.setGroup(group);
Slider b_slider = controlP5.addSlider("Blue "+i, 0, 255, 0, incr_width*2+obj_offset, level_1, obj_width, slider_height);
b_slider.setGroup(group);
Slider duty_slider = controlP5.addSlider("Color Duty "+i, 0, 255, 0, incr_width*0+obj_offset, level_2, obj_width, slider_height);
duty_slider.setGroup(group);
Slider period_slider = controlP5.addSlider("Color Period "+i, 0, 255, 0, incr_width*1+obj_offset, level_2, obj_width, slider_height);
period_slider.setGroup(group);
prox_sliders[i] = controlP5.addSlider("Prox "+i, 0, 1024, 0, incr_width*2+obj_offset, level_2, obj_width, slider_height);
prox_sliders[i].lock();
prox_sliders[i].setGroup(group);
Slider vibe_slider = controlP5.addSlider("Vibe Level "+i, 0, 255, 0, incr_width*0+obj_offset, level_3, obj_width, slider_height);
vibe_slider.setGroup(group);
Slider vibe_duties_slider = controlP5.addSlider("Vibe Duty "+i, 0, 255, 0, incr_width*1+obj_offset, level_3, obj_width, slider_height);
vibe_duties_slider.setGroup(group);
Slider vibe_periods_slider = controlP5.addSlider("Vibe Period "+i, 0, 255, 0, incr_width*2+obj_offset, level_3, obj_width, slider_height);
vibe_periods_slider.setGroup(group);
x_sliders[i] = controlP5.addSlider("X "+i, 0, 1024, 0, incr_width*0+obj_offset, level_4, obj_width, slider_height);
x_sliders[i].lock();
x_sliders[i].setGroup(group);
y_sliders[i] = controlP5.addSlider("Y "+i, 0, 1024, 0, incr_width*1+obj_offset, level_4, obj_width, slider_height);
y_sliders[i].lock();
y_sliders[i].setGroup(group);
z_sliders[i] = controlP5.addSlider("Z "+i, 0, 1024, 0, incr_width*2+obj_offset, level_4, obj_width, slider_height);
z_sliders[i].lock();
z_sliders[i].setGroup(group);
}
// for(int i = 0;i < NUM_GLOVES;i++) {
// int x_offset = (width-100)/NUM_GLOVES*i+50;
// int y_offset = 60;
// int local_width = round((width-100)/NUM_GLOVES*0.95f);
// int obj_width = 15;
// int slider_height = 200;
// int level_0 = -45;
// int level_1 = 10;
// // int level_2 = 240;
// // int level_3 = 480;
// int num = 3;
// int incr_offset = 0;
// int incr_width = (local_width-incr_offset*2)/num;
// int obj_offset = incr_offset+(incr_width-obj_width)/2;
// ControlGroup group = controlP5.addGroup("Glove "+i, x_offset, y_offset, local_width);
// Toggle toggle = controlP5.addToggle("Active "+i, incr_width*0+obj_offset, level_0, obj_width, obj_width);
// toggle.setGroup(group);
// Slider vibe_slider = controlP5.addSlider("Vibe Level "+i, 0, 255, 0, incr_width*0+obj_offset, level_1, obj_width, slider_height);
// vibe_slider.setGroup(group);
// Slider vibe_duties_slider = controlP5.addSlider("Vibe Duty "+i, 0, 255, 0, incr_width*1+obj_offset, level_1, obj_width, slider_height);
// vibe_duties_slider.setGroup(group);
// Slider vibe_periods_slider = controlP5.addSlider("Vibe Period "+i, 0, 255, 0, incr_width*2+obj_offset, level_1, obj_width, slider_height);
// vibe_periods_slider.setGroup(group);
// }
if(!show_controls) controlP5.hide();
xbeeBaseStation = new XBeeBaseStation();
xbeeBaseStation.scan();
xbeeBaseStation.addProxEventListener(this);
patches = new Patch[NUM_PATCHES];
for(int i = 0;i < NUM_PATCHES;i++) {
patches[i] = new Patch(PATCH_ADDR[i], xbeeBaseStation);
xbeeBaseStation.addPatch(patches[i]);
}
// gloves = new Glove[NUM_GLOVES];
// for(int i = 0;i < NUM_GLOVES;i++) {
// gloves[i] = new Glove(GLOVE_ADDR[i], xbeeBaseStation);
// xbeeBaseStation.addGlove(gloves[i]);
// }
}
| public void setup() {
size(1024, 800);
controlP5 = new ControlP5(this);
prox_sliders = new Slider[NUM_PATCHES];
x_sliders = new Slider[NUM_PATCHES];
y_sliders = new Slider[NUM_PATCHES];
z_sliders = new Slider[NUM_PATCHES];
controlP5.addButton("Re-Scan", 1, 10, 10, 50, 25);
for(int i = 0;i < NUM_PATCHES;i++) {
int x_offset = (width-100)/NUM_PATCHES*i+50;
int y_offset = 60;
int local_width = round((width-100)/NUM_PATCHES*0.95f);
int obj_width = 15;
int slider_height = 150;
int level_0 = -45;
int level_1 = 10;
int level_2 = level_1+(slider_height+20);
int level_3 = level_1+(slider_height+20)*2;
int level_4 = level_1+(slider_height+20)*3;
int num = 3;
int incr_offset = 0;
int incr_width = (local_width-incr_offset*2)/num;
int obj_offset = incr_offset+(incr_width-obj_width)/2;
ControlGroup group = controlP5.addGroup("Patch "+i, x_offset, y_offset, local_width);
Toggle toggle = controlP5.addToggle("Active "+i, incr_width*0+obj_offset, level_0, obj_width, obj_width);
toggle.setGroup(group);
Slider r_slider = controlP5.addSlider("Red "+i, 0, 255, 0, incr_width*0+obj_offset, level_1, obj_width, slider_height);
r_slider.setGroup(group);
Slider g_slider = controlP5.addSlider("Green "+i, 0, 255, 0, incr_width*1+obj_offset, level_1, obj_width, slider_height);
g_slider.setGroup(group);
Slider b_slider = controlP5.addSlider("Blue "+i, 0, 255, 0, incr_width*2+obj_offset, level_1, obj_width, slider_height);
b_slider.setGroup(group);
Slider duty_slider = controlP5.addSlider("Color Duty "+i, 0, 255, 0, incr_width*0+obj_offset, level_2, obj_width, slider_height);
duty_slider.setGroup(group);
Slider period_slider = controlP5.addSlider("Color Period "+i, 0, 255, 0, incr_width*1+obj_offset, level_2, obj_width, slider_height);
period_slider.setGroup(group);
prox_sliders[i] = controlP5.addSlider("Prox "+i, 0, 1024, 0, incr_width*2+obj_offset, level_2, obj_width, slider_height);
prox_sliders[i].lock();
prox_sliders[i].setGroup(group);
Slider vibe_slider = controlP5.addSlider("Vibe Level "+i, 0, 255, 0, incr_width*0+obj_offset, level_3, obj_width, slider_height);
vibe_slider.setGroup(group);
Slider vibe_duties_slider = controlP5.addSlider("Vibe Duty "+i, 0, 255, 0, incr_width*1+obj_offset, level_3, obj_width, slider_height);
vibe_duties_slider.setGroup(group);
Slider vibe_periods_slider = controlP5.addSlider("Vibe Period "+i, 0, 255, 0, incr_width*2+obj_offset, level_3, obj_width, slider_height);
vibe_periods_slider.setGroup(group);
x_sliders[i] = controlP5.addSlider("X "+i, -128, 128, 0, incr_width*0+obj_offset, level_4, obj_width, slider_height);
x_sliders[i].lock();
x_sliders[i].setGroup(group);
y_sliders[i] = controlP5.addSlider("Y "+i, -128, 128, 0, incr_width*1+obj_offset, level_4, obj_width, slider_height);
y_sliders[i].lock();
y_sliders[i].setGroup(group);
z_sliders[i] = controlP5.addSlider("Z "+i, -128, 128, 0, incr_width*2+obj_offset, level_4, obj_width, slider_height);
z_sliders[i].lock();
z_sliders[i].setGroup(group);
}
// for(int i = 0;i < NUM_GLOVES;i++) {
// int x_offset = (width-100)/NUM_GLOVES*i+50;
// int y_offset = 60;
// int local_width = round((width-100)/NUM_GLOVES*0.95f);
// int obj_width = 15;
// int slider_height = 200;
// int level_0 = -45;
// int level_1 = 10;
// // int level_2 = 240;
// // int level_3 = 480;
// int num = 3;
// int incr_offset = 0;
// int incr_width = (local_width-incr_offset*2)/num;
// int obj_offset = incr_offset+(incr_width-obj_width)/2;
// ControlGroup group = controlP5.addGroup("Glove "+i, x_offset, y_offset, local_width);
// Toggle toggle = controlP5.addToggle("Active "+i, incr_width*0+obj_offset, level_0, obj_width, obj_width);
// toggle.setGroup(group);
// Slider vibe_slider = controlP5.addSlider("Vibe Level "+i, 0, 255, 0, incr_width*0+obj_offset, level_1, obj_width, slider_height);
// vibe_slider.setGroup(group);
// Slider vibe_duties_slider = controlP5.addSlider("Vibe Duty "+i, 0, 255, 0, incr_width*1+obj_offset, level_1, obj_width, slider_height);
// vibe_duties_slider.setGroup(group);
// Slider vibe_periods_slider = controlP5.addSlider("Vibe Period "+i, 0, 255, 0, incr_width*2+obj_offset, level_1, obj_width, slider_height);
// vibe_periods_slider.setGroup(group);
// }
if(!show_controls) controlP5.hide();
xbeeBaseStation = new XBeeBaseStation();
xbeeBaseStation.scan();
xbeeBaseStation.addProxEventListener(this);
xbeeBaseStation.addAccelEventListener(this);
patches = new Patch[NUM_PATCHES];
for(int i = 0;i < NUM_PATCHES;i++) {
patches[i] = new Patch(PATCH_ADDR[i], xbeeBaseStation);
xbeeBaseStation.addPatch(patches[i]);
}
// gloves = new Glove[NUM_GLOVES];
// for(int i = 0;i < NUM_GLOVES;i++) {
// gloves[i] = new Glove(GLOVE_ADDR[i], xbeeBaseStation);
// xbeeBaseStation.addGlove(gloves[i]);
// }
}
|
diff --git a/software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/persister/PersisterUtil.java b/software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/persister/PersisterUtil.java
index 79c3dc5c..3a9db5b2 100644
--- a/software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/persister/PersisterUtil.java
+++ b/software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/persister/PersisterUtil.java
@@ -1,608 +1,606 @@
package gov.nih.nci.ncicb.cadsr.loader.persister;
import gov.nih.nci.ncicb.cadsr.dao.AdminComponentDAO;
import gov.nih.nci.ncicb.cadsr.dao.AlternateNameDAO;
import gov.nih.nci.ncicb.cadsr.dao.ClassSchemeClassSchemeItemDAO;
import gov.nih.nci.ncicb.cadsr.domain.AdminComponent;
import gov.nih.nci.ncicb.cadsr.domain.AdminComponentClassSchemeClassSchemeItem;
import gov.nih.nci.ncicb.cadsr.domain.AlternateName;
import gov.nih.nci.ncicb.cadsr.domain.ClassSchemeClassSchemeItem;
import gov.nih.nci.ncicb.cadsr.domain.Concept;
import gov.nih.nci.ncicb.cadsr.domain.DataElementConcept;
import gov.nih.nci.ncicb.cadsr.domain.Definition;
import gov.nih.nci.ncicb.cadsr.domain.DomainObjectFactory;
import gov.nih.nci.ncicb.cadsr.domain.ReferenceDocument;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults;
import gov.nih.nci.ncicb.cadsr.loader.util.DAOAccessor;
import gov.nih.nci.ncicb.cadsr.loader.util.PropertyAccessor;
import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
public class PersisterUtil {
private static Logger logger = Logger.getLogger(PersisterUtil.class.getName());
private AdminComponentDAO adminComponentDAO;
private AlternateNameDAO alternateNameDAO;
private ClassSchemeClassSchemeItemDAO classSchemeClassSchemeItemDAO;
private UMLDefaults defaults = UMLDefaults.getInstance();
private ElementsLists elements = ElementsLists.getInstance();
public PersisterUtil() {
initDAOs();
}
Map<Character, Character> charReplacementMap = new HashMap<Character, Character>() {
{
put('�', 'Y');
put('�', '\'');
put('�', '\'');
}
};
/*
*/
void addAlternateName(AdminComponent ac, AlternateName altName) {
AlternateName queryAN = DomainObjectFactory.newAlternateName();
queryAN.setName(altName.getName());
queryAN.setType(altName.getType());
AlternateName foundAN = adminComponentDAO.getAlternateName(ac, queryAN);
// for now, only classify with one CS_CSI
String packageName = null;
for(AdminComponentClassSchemeClassSchemeItem acCsCsi : ac.getAcCsCsis()) {
ClassSchemeClassSchemeItem csCsi = acCsCsi.getCsCsi();
packageName = csCsi.getCsi().getLongName();
if(!StringUtil.isEmpty(packageName)) {
break;
}
}
ClassSchemeClassSchemeItem packageCsCsi = null;
if(packageName != null)
packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
if(foundAN != null) {
logger.info(PropertyAccessor.getProperty(
"existed.altName", altName.getName()));
if(packageCsCsi != null) {
ClassSchemeClassSchemeItem foundCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundAN, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null)
foundParentCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundAN, packageCsCsi);
if(foundCsCsi == null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundAN, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundAN, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
}
if(foundAN == null) {
AlternateName newAltName = DomainObjectFactory.newAlternateName();
newAltName.setContext(defaults.getContext());
newAltName.setAudit(defaults.getAudit());
newAltName.setName(altName.getName());
newAltName.setType(altName.getType());
altName.setId(adminComponentDAO.addAlternateName(ac, newAltName));
logger.info(PropertyAccessor.getProperty(
"added.altName",
new String[] {
altName.getName(),
ac.getLongName()
}));
if(packageName != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altName, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
if(packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altName, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
}
}
void addAlternateName(AdminComponent ac, String newName, String type, String packageName) {
AlternateName queryAN = DomainObjectFactory.newAlternateName();
queryAN.setName(newName);
queryAN.setType(type);
AlternateName foundAN = adminComponentDAO.getAlternateName(ac, queryAN);
ClassSchemeClassSchemeItem packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
if(foundAN != null) {
logger.info(PropertyAccessor.getProperty(
"existed.altName", newName));
if(packageName == null)
return;
ClassSchemeClassSchemeItem foundCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundAN, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null)
foundParentCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundAN, packageCsCsi);
if(foundCsCsi == null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundAN, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundAN, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
if(foundAN == null) {
AlternateName altName = DomainObjectFactory.newAlternateName();
altName.setContext(defaults.getContext());
altName.setAudit(defaults.getAudit());
altName.setName(newName);
altName.setType(type);
altName.setId(adminComponentDAO.addAlternateName(ac, altName));
logger.info(PropertyAccessor.getProperty(
"added.altName",
new String[] {
altName.getName(),
ac.getLongName()
}));
if(packageName != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altName, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
if(packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altName, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
}
}
void addAlternateDefinition(AdminComponent ac, Definition newDef) {
addAlternateDefinition(ac, newDef.getDefinition(), newDef.getType());
}
void addAlternateDefinition(AdminComponent ac, String newDef, String type) {
Definition queryDef = DomainObjectFactory.newDefinition();
queryDef.setDefinition(newDef);
queryDef.setType(type);
Definition foundDef = adminComponentDAO.getDefinition(ac, queryDef);
// for now, only classify with one CS_CSI
String packageName = null;
for(AdminComponentClassSchemeClassSchemeItem acCsCsi : ac.getAcCsCsis()) {
ClassSchemeClassSchemeItem csCsi = acCsCsi.getCsCsi();
packageName = csCsi.getCsi().getLongName();
if(!StringUtil.isEmpty(packageName)) {
break;
}
}
ClassSchemeClassSchemeItem packageCsCsi = null;
if(packageName != null)
packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
if(foundDef != null) {
logger.info(PropertyAccessor.getProperty(
"existed.altDef", newDef));
if(packageCsCsi != null) {
ClassSchemeClassSchemeItem foundCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null)
foundParentCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
if(foundCsCsi == null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
}
if(foundDef == null) {
Definition altDef = DomainObjectFactory.newDefinition();
altDef.setContext(defaults.getContext());
altDef.setDefinition(newDef);
altDef.setAudit(defaults.getAudit());
altDef.setType(type);
- logger.info(" definition before search = "+altDef.getDefinition());
StringBuilder builder = new StringBuilder();
for (char currentChar : altDef.getDefinition().toCharArray()) {
Character replacementChar = charReplacementMap.get(currentChar);
builder.append(replacementChar != null ? replacementChar : currentChar);
}
altDef.setDefinition(builder.toString());
- System.out.println("DEC def after encoding =="+altDef.getDefinition());
altDef.setId(adminComponentDAO.addDefinition(ac, altDef));
logger.info(PropertyAccessor.getProperty(
"added.altDef",
new String[] {
altDef.getId(),
altDef.getDefinition(),
ac.getLongName()
}));
if(packageCsCsi != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
if(packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
}
}
}
void addAlternateDefinition(AdminComponent ac, String newDef, String type, String packageName) {
Definition queryDef = DomainObjectFactory.newDefinition();
queryDef.setDefinition(newDef);
queryDef.setType(type);
Definition foundDef = adminComponentDAO.getDefinition(ac, queryDef);
ClassSchemeClassSchemeItem packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
if(foundDef != null) {
logger.info(PropertyAccessor.getProperty(
"existed.altDef", newDef));
ClassSchemeClassSchemeItem foundCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null)
foundParentCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
if(foundCsCsi == null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
if(foundDef == null) {
Definition altDef = DomainObjectFactory.newDefinition();
altDef.setContext(defaults.getContext());
altDef.setDefinition(newDef);
altDef.setAudit(defaults.getAudit());
altDef.setType(type);
altDef.setId(adminComponentDAO.addDefinition(ac, altDef));
logger.info(PropertyAccessor.getProperty(
"added.altDef",
new String[] {
altDef.getId(),
altDef.getDefinition(),
ac.getLongName()
}));
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
if(packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
}
}
public void updateRefDocs(final AdminComponent ac) {
List<ReferenceDocument> existingRDs = adminComponentDAO.getReferenceDocuments(ac);
List<ReferenceDocument> newRDs = filterNewRefDocs(existingRDs, ac.getReferenceDocuments());
if (!newRDs.isEmpty()) {
markPreferred(existingRDs, newRDs);
existingRDs.addAll(newRDs);
setRDACIdsAndContext(ac.getId(), existingRDs);
ac.setReferenceDocuments(existingRDs);
adminComponentDAO.updateRefDocs(ac);
}
}
private void setRDACIdsAndContext(String acId, List<ReferenceDocument> refDocs) {
for (ReferenceDocument refDoc: refDocs) {
refDoc.setAcId(acId);
refDoc.setContext(defaults.getContext());
}
}
private void markPreferred(List<ReferenceDocument> existingRDs, List<ReferenceDocument> newRDs) {
if (hasPreferredRD(existingRDs)) {
for (ReferenceDocument newRD: newRDs) {
newRD.setType("Alternate Question Text");
}
}
else {
boolean preferredMarked = false;
for (ReferenceDocument newRD: newRDs) {
if (preferredMarked) {
newRD.setType("Alternate Question Text");
}
if (!preferredMarked && newRD.getType().equalsIgnoreCase("Preferred Question Text")) {
preferredMarked = true;
}
}
}
}
private boolean hasPreferredRD(List<ReferenceDocument> refDocs) {
for(ReferenceDocument refDoc: refDocs) {
if (refDoc.getType().equalsIgnoreCase("Preferred Question Text")) {
return true;
}
}
return false;
}
private List<ReferenceDocument> filterNewRefDocs(List<ReferenceDocument> existingRDs, List<ReferenceDocument> newRDs) {
List<ReferenceDocument> newRefDocs = new ArrayList<ReferenceDocument>();
List<String> existingRefDocNames = getRefDocNames(existingRDs);
for (ReferenceDocument newRD: newRDs) {
String newRefDocName = newRD.getName();
if (!existingRefDocNames.contains(newRefDocName)) {
newRefDocs.add(newRD);
}
}
return newRefDocs;
}
private List<String> getRefDocNames(List<ReferenceDocument> refDocs) {
List<String> refDocNames = new ArrayList<String>();
for (ReferenceDocument refDoc: refDocs) {
refDocNames.add(refDoc.getName());
}
return refDocNames;
}
DataElementConcept lookupDec(String id) {
List<DataElementConcept> decs = elements.getElements(DomainObjectFactory.newDataElementConcept());
for (Iterator it = decs.iterator(); it.hasNext(); ) {
DataElementConcept o = (DataElementConcept) it.next();
if (o.getId().equals(id)) {
return o;
}
}
return null;
}
boolean isSameDefinition(String def, Concept[] concepts) {
if((def == null) || def.length() == 0)
return true;
StringBuffer sb = new StringBuffer();
for(int i=0; i < concepts.length; i++) {
if(sb.length() > 0)
sb.append("\n");
sb.append(concepts[i].getPreferredDefinition());
}
return def.equals(sb.toString());
}
protected void addPackageClassification(AdminComponent ac) {
// for now, only classify with one CS_CSI
String packageName = null;
for(AdminComponentClassSchemeClassSchemeItem acCsCsi : ac.getAcCsCsis()) {
ClassSchemeClassSchemeItem csCsi = acCsCsi.getCsCsi();
packageName = csCsi.getCsi().getLongName();
if(!StringUtil.isEmpty(packageName)) {
break;
}
}
ClassSchemeClassSchemeItem packageCsCsi = null;
if(packageName != null)
packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
if(packageCsCsi != null) {
ClassSchemeClassSchemeItem foundCsCsi = adminComponentDAO.getClassSchemeClassSchemeItem(ac, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null) {
foundParentCsCsi = adminComponentDAO.getClassSchemeClassSchemeItem(ac, packageCsCsi.getParent());
}
List csCsis = new ArrayList();
if (foundCsCsi == null) {
logger.info(PropertyAccessor.
getProperty("attach.package.classification"));
if (packageCsCsi != null) {
csCsis.add(packageCsCsi);
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null)
csCsis.add(packageCsCsi.getParent());
adminComponentDAO.addClassSchemeClassSchemeItems(ac, csCsis);
logger.info(PropertyAccessor
.getProperty("added.package",
new String[] {
packageName,
ac.getLongName()}));
} else {
logger.error(PropertyAccessor.getProperty("missing.package", new String[] {packageName, ac.getLongName()}));
}
}
}
}
protected void addPackageClassification(AdminComponent ac, String packageName) {
ClassSchemeClassSchemeItem packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
ClassSchemeClassSchemeItem foundCsCsi = adminComponentDAO.getClassSchemeClassSchemeItem(ac, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null) {
foundParentCsCsi = adminComponentDAO.getClassSchemeClassSchemeItem(ac, packageCsCsi.getParent());
}
List csCsis = new ArrayList();
if (foundCsCsi == null) {
logger.info(PropertyAccessor.
getProperty("attach.package.classification"));
if (packageCsCsi != null) {
csCsis.add(packageCsCsi);
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null)
csCsis.add(packageCsCsi.getParent());
adminComponentDAO.addClassSchemeClassSchemeItems(ac, csCsis);
logger.info(PropertyAccessor
.getProperty("added.package",
new String[] {
packageName,
ac.getLongName()}));
} else {
logger.error(PropertyAccessor.getProperty("missing.package", new String[] {packageName, ac.getLongName()}));
}
}
}
private void initDAOs() {
adminComponentDAO = DAOAccessor.getAdminComponentDAO();
alternateNameDAO = DAOAccessor.getAlternateNameDAO();
//
// dataElementDAO = DAOAccessor.getDataElementDAO();
// dataElementConceptDAO = DAOAccessor.getDataElementConceptDAO();
// valueDomainDAO = DAOAccessor.getValueDomainDAO();
// propertyDAO = DAOAccessor.getPropertyDAO();
// objectClassDAO = DAOAccessor.getObjectClassDAO();
// objectClassRelationshipDAO = DAOAccessor.getObjectClassRelationshipDAO();
// classificationSchemeDAO = DAOAccessor.getClassificationSchemeDAO();
// classificationSchemeItemDAO = DAOAccessor.getClassificationSchemeItemDAO();
classSchemeClassSchemeItemDAO = DAOAccessor.getClassSchemeClassSchemeItemDAO();
// conceptDAO = DAOAccessor.getConceptDAO();
}
}
| false | true | void addAlternateDefinition(AdminComponent ac, String newDef, String type) {
Definition queryDef = DomainObjectFactory.newDefinition();
queryDef.setDefinition(newDef);
queryDef.setType(type);
Definition foundDef = adminComponentDAO.getDefinition(ac, queryDef);
// for now, only classify with one CS_CSI
String packageName = null;
for(AdminComponentClassSchemeClassSchemeItem acCsCsi : ac.getAcCsCsis()) {
ClassSchemeClassSchemeItem csCsi = acCsCsi.getCsCsi();
packageName = csCsi.getCsi().getLongName();
if(!StringUtil.isEmpty(packageName)) {
break;
}
}
ClassSchemeClassSchemeItem packageCsCsi = null;
if(packageName != null)
packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
if(foundDef != null) {
logger.info(PropertyAccessor.getProperty(
"existed.altDef", newDef));
if(packageCsCsi != null) {
ClassSchemeClassSchemeItem foundCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null)
foundParentCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
if(foundCsCsi == null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
}
if(foundDef == null) {
Definition altDef = DomainObjectFactory.newDefinition();
altDef.setContext(defaults.getContext());
altDef.setDefinition(newDef);
altDef.setAudit(defaults.getAudit());
altDef.setType(type);
logger.info(" definition before search = "+altDef.getDefinition());
StringBuilder builder = new StringBuilder();
for (char currentChar : altDef.getDefinition().toCharArray()) {
Character replacementChar = charReplacementMap.get(currentChar);
builder.append(replacementChar != null ? replacementChar : currentChar);
}
altDef.setDefinition(builder.toString());
System.out.println("DEC def after encoding =="+altDef.getDefinition());
altDef.setId(adminComponentDAO.addDefinition(ac, altDef));
logger.info(PropertyAccessor.getProperty(
"added.altDef",
new String[] {
altDef.getId(),
altDef.getDefinition(),
ac.getLongName()
}));
if(packageCsCsi != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
if(packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
}
}
}
| void addAlternateDefinition(AdminComponent ac, String newDef, String type) {
Definition queryDef = DomainObjectFactory.newDefinition();
queryDef.setDefinition(newDef);
queryDef.setType(type);
Definition foundDef = adminComponentDAO.getDefinition(ac, queryDef);
// for now, only classify with one CS_CSI
String packageName = null;
for(AdminComponentClassSchemeClassSchemeItem acCsCsi : ac.getAcCsCsis()) {
ClassSchemeClassSchemeItem csCsi = acCsCsi.getCsCsi();
packageName = csCsi.getCsi().getLongName();
if(!StringUtil.isEmpty(packageName)) {
break;
}
}
ClassSchemeClassSchemeItem packageCsCsi = null;
if(packageName != null)
packageCsCsi = (ClassSchemeClassSchemeItem)defaults.getPackageCsCsis().get(packageName);
if(foundDef != null) {
logger.info(PropertyAccessor.getProperty(
"existed.altDef", newDef));
if(packageCsCsi != null) {
ClassSchemeClassSchemeItem foundCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
ClassSchemeClassSchemeItem foundParentCsCsi = null;
if(packageCsCsi.getParent() != null)
foundParentCsCsi = alternateNameDAO.getClassSchemeClassSchemeItem(foundDef, packageCsCsi);
if(foundCsCsi == null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
if((foundParentCsCsi == null) && packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(foundDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Name"
));
}
}
}
if(foundDef == null) {
Definition altDef = DomainObjectFactory.newDefinition();
altDef.setContext(defaults.getContext());
altDef.setDefinition(newDef);
altDef.setAudit(defaults.getAudit());
altDef.setType(type);
StringBuilder builder = new StringBuilder();
for (char currentChar : altDef.getDefinition().toCharArray()) {
Character replacementChar = charReplacementMap.get(currentChar);
builder.append(replacementChar != null ? replacementChar : currentChar);
}
altDef.setDefinition(builder.toString());
altDef.setId(adminComponentDAO.addDefinition(ac, altDef));
logger.info(PropertyAccessor.getProperty(
"added.altDef",
new String[] {
altDef.getId(),
altDef.getDefinition(),
ac.getLongName()
}));
if(packageCsCsi != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi);
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
if(packageCsCsi.getParent() != null) {
classSchemeClassSchemeItemDAO.addCsCsi(altDef, packageCsCsi.getParent());
logger.info(
PropertyAccessor.getProperty(
"linked.to.package",
"Alternate Definition"
));
}
}
}
}
|
diff --git a/protostuff-parser/src/main/java/com/dyuproject/protostuff/parser/Message.java b/protostuff-parser/src/main/java/com/dyuproject/protostuff/parser/Message.java
index 5ba2643..6a1c1c9 100644
--- a/protostuff-parser/src/main/java/com/dyuproject/protostuff/parser/Message.java
+++ b/protostuff-parser/src/main/java/com/dyuproject/protostuff/parser/Message.java
@@ -1,444 +1,444 @@
//========================================================================
//Copyright 2007-2009 David Yu [email protected]
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================
package com.dyuproject.protostuff.parser;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
/**
* TODO
*
* @author David Yu
* @created Dec 19, 2009
*/
public class Message implements HasName
{
String name;
Proto proto;
Message parentMessage;
final LinkedHashMap<String, Message> nestedMessages = new LinkedHashMap<String, Message>();
final LinkedHashMap<String,EnumGroup> nestedEnumGroups = new LinkedHashMap<String,EnumGroup>();
final LinkedHashMap<String,Field<?>> fields = new LinkedHashMap<String,Field<?>>();
final ArrayList<Field<?>> sortedFields = new ArrayList<Field<?>>();
// code generator helpers
boolean bytesFieldPresent, repeatedFieldPresent, requiredFieldPresent;
public Message()
{
}
public Message(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public Proto getProto()
{
Proto p = proto;
if(p==null)
p = proto = parentMessage.getProto();
return p;
}
public Message getRootMessage()
{
return parentMessage==null ? null : getRoot(parentMessage);
}
public Message getParentMessage()
{
return parentMessage;
}
public boolean isNested()
{
return parentMessage!=null;
}
public boolean hasNestedMessages()
{
return !nestedMessages.isEmpty();
}
public boolean hasNestedEnumGroups()
{
return !nestedEnumGroups.isEmpty();
}
public Collection<Message> getNestedMessages()
{
return nestedMessages.values();
}
public Message getNestedMessage(String name)
{
return nestedMessages.get(name);
}
void addNestedMessage(Message message)
{
nestedMessages.put(message.name, message);
message.parentMessage = this;
}
public Collection<EnumGroup> getNestedEnumGroups()
{
return nestedEnumGroups.values();
}
public EnumGroup getNestedEnumGroup(String name)
{
return nestedEnumGroups.get(name);
}
void addNestedEnumGroup(EnumGroup enumGroup)
{
nestedEnumGroups.put(enumGroup.name, enumGroup);
enumGroup.parentMessage = this;
}
public Collection<Field<?>> getFields()
{
return sortedFields;
}
public Field<?> getField(String name)
{
return fields.get(name);
}
public boolean isDescendant(Message other)
{
if(parentMessage==null)
return false;
return parentMessage == other || parentMessage.isDescendant(other);
}
public Message getDescendant(String name)
{
if(parentMessage==null)
return null;
return name.equals(parentMessage.name) ? parentMessage : parentMessage.getDescendant(name);
}
@SuppressWarnings("unchecked")
public <T extends Field<?>> T getField(String name, Class<T> typeClass)
{
return (T)fields.get(name);
}
void addField(Field<?> field)
{
if(field.number<1)
{
throw new IllegalArgumentException("Invalid field number " + field.number
+ " from field " + field.name);
}
fields.put(field.name, field);
}
public String toString()
{
return new StringBuilder()
.append('{')
.append("name:").append(name)
.append(',').append("enumGroups:").append(nestedEnumGroups.values())
.append(',').append("fields:").append(fields.values())
.append('}')
.toString();
}
public String getFullName()
{
StringBuilder buffer = new StringBuilder();
resolveFullName(this, buffer);
return buffer.toString();
}
public String getRelativeName()
{
StringBuilder buffer = new StringBuilder();
resolveRelativeName(this, buffer, null);
return buffer.toString();
}
public boolean isRepeatedFieldPresent()
{
return repeatedFieldPresent;
}
public boolean isBytesFieldPresent()
{
return bytesFieldPresent;
}
public boolean isRequiredFieldPresent()
{
return requiredFieldPresent;
}
// post parse
void resolveReferences(Message root)
{
Proto p = getProto();
for(Field<?> f : fields.values())
{
if(!root.repeatedFieldPresent && f.isRepeated())
root.repeatedFieldPresent = true;
- if(!requiredFieldPresent && f.isRequired())
- requiredFieldPresent = true;
+ if(!root.requiredFieldPresent && f.isRequired())
+ root.requiredFieldPresent = true;
if(f instanceof Field.Bytes)
{
if(!root.bytesFieldPresent)
root.bytesFieldPresent = true;
}
else if(f instanceof Field.String)
{
if(!root.bytesFieldPresent && f.defaultValue!=null)
root.bytesFieldPresent = true;
}
else if(f instanceof Field.Reference)
{
Field.Reference fr = (Field.Reference)f;
String refName = fr.refName;
String packageName = fr.packageName;
if(packageName==null)
{
Message msg = findMessageFrom(fr.message, refName);
if(msg!=null || (msg=p.getMessage(refName))!=null)
{
MessageField mf = newMessageField(msg, fr, this);
fields.put(mf.name, mf);
continue;
}
EnumGroup eg = fr.message.getNestedEnumGroup(refName);
if(eg!=null || (eg=p.getEnumGroup(refName))!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
continue;
}
throw new IllegalStateException("unknown field: " + refName);
}
int dotIdx = packageName.indexOf('.');
if(dotIdx==-1)
{
// could be a nested message/enum
Message msg = findMessageFrom(fr.message, packageName);
if(msg!=null || (msg=p.getMessage(packageName))!=null)
{
Message nestedMsg = msg.getNestedMessage(refName);
if(nestedMsg!=null)
{
MessageField mf = newMessageField(nestedMsg, fr, this);
fields.put(mf.name, mf);
continue;
}
EnumGroup eg = msg.getNestedEnumGroup(refName);
if(eg!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
continue;
}
}
}
else
{
Message m = null;
int last = -1;
boolean found = false;;
while(true)
{
String name = packageName.substring(last+1, dotIdx);
if(m==null)
{
// first iteration
m = findMessageFrom(fr.message, name);
if(m==null)
m = proto.getMessage(name);
}
else
m = m.getNestedMessage(name);
if(m==null)
break;
last = dotIdx;
dotIdx = packageName.indexOf('.', dotIdx+1);
if(dotIdx == -1)
{
// last
m = m.getNestedMessage(packageName.substring(last+1));
if(m==null)
break;
Message nestedMsg = m.getNestedMessage(refName);
if(nestedMsg!=null)
{
MessageField mf = newMessageField(nestedMsg, fr, this);
fields.put(mf.name, mf);
found = true;
}
else
{
EnumGroup eg = m.getNestedEnumGroup(refName);
if(eg!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
found = true;
}
}
break;
}
}
if(found)
continue;
}
Proto proto = p.getImportedProto(packageName);
if(proto==null)
throw new IllegalStateException("unknown field: " + packageName + "." + refName);
Message msg = proto.getMessage(refName);
if(msg!=null)
{
MessageField mf = newMessageField(msg, fr, this);
fields.put(mf.name, mf);
continue;
}
EnumGroup eg = proto.getEnumGroup(refName);
if(eg!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
continue;
}
throw new IllegalStateException("unknown field: " + packageName + "." + refName);
}
}
sortedFields.addAll(fields.values());
Collections.sort(sortedFields);
for(Message m : nestedMessages.values())
m.resolveReferences(root);
}
static MessageField newMessageField(Message message, Field.Reference fr, Message owner)
{
MessageField mf = new MessageField(message);
mf.owner = owner;
mf.packable = false;
copy(fr, mf);
//System.err.println(owner.getRelativeName() + "." + mf.name +": " + mf.getJavaType());
return mf;
}
static EnumField newEnumField(EnumGroup enumGroup, Field.Reference fr, Message owner)
{
EnumField ef = new EnumField(enumGroup);
ef.owner = owner;
ef.packable = true;
String refName = (String)fr.getDefaultValue();
if(refName == null)
ef.defaultValue = enumGroup.getFirstValue();
else
{
ef.defaultValue = enumGroup.getValue(refName);
if(ef.defaultValue == null)
{
throw new IllegalStateException("The field: " + ef.name +
" contains an unknown enum value: " + refName);
}
}
copy(fr, ef);
//System.err.println(owner.getRelativeName() + "." + ef.name +": " + ef.getJavaType());
return ef;
}
static void copy(Field<?> from, Field<?> to)
{
to.name = from.name;
to.number = from.number;
to.modifier = from.modifier;
}
static Message findMessageFrom(Message message, String name)
{
Message m = message.getNestedMessage(name);
if(m==null && message.isNested())
return findMessageFrom(message.parentMessage, name);
return m;
}
static void resolveFullName(Message message, StringBuilder buffer)
{
buffer.insert(0, message.name).insert(0, '.');
if(message.isNested())
resolveFullName(message.parentMessage, buffer);
else
buffer.insert(0, message.getProto().getJavaPackageName());
}
static void resolveRelativeName(Message message, StringBuilder buffer, Message descendant)
{
buffer.insert(0, message.name);
if(message.parentMessage!=null)
{
if(message.parentMessage!=descendant)
{
buffer.insert(0, '.');
resolveRelativeName(message.parentMessage, buffer, descendant);
}
}
}
static void computeName(Message message, Message owner, StringBuilder buffer)
{
if(owner==message || message.parentMessage==owner || owner.isDescendant(message))
buffer.append(message.name);
else if(message.isDescendant(owner))
Message.resolveRelativeName(message, buffer, owner);
else if(message.getProto().getJavaPackageName().equals(owner.getProto().getJavaPackageName()))
buffer.append(message.getRelativeName());
else
buffer.append(message.getFullName());
}
static Message getRoot(Message parent)
{
return parent.parentMessage==null ? parent: getRoot(parent.parentMessage);
}
}
| true | true | void resolveReferences(Message root)
{
Proto p = getProto();
for(Field<?> f : fields.values())
{
if(!root.repeatedFieldPresent && f.isRepeated())
root.repeatedFieldPresent = true;
if(!requiredFieldPresent && f.isRequired())
requiredFieldPresent = true;
if(f instanceof Field.Bytes)
{
if(!root.bytesFieldPresent)
root.bytesFieldPresent = true;
}
else if(f instanceof Field.String)
{
if(!root.bytesFieldPresent && f.defaultValue!=null)
root.bytesFieldPresent = true;
}
else if(f instanceof Field.Reference)
{
Field.Reference fr = (Field.Reference)f;
String refName = fr.refName;
String packageName = fr.packageName;
if(packageName==null)
{
Message msg = findMessageFrom(fr.message, refName);
if(msg!=null || (msg=p.getMessage(refName))!=null)
{
MessageField mf = newMessageField(msg, fr, this);
fields.put(mf.name, mf);
continue;
}
EnumGroup eg = fr.message.getNestedEnumGroup(refName);
if(eg!=null || (eg=p.getEnumGroup(refName))!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
continue;
}
throw new IllegalStateException("unknown field: " + refName);
}
int dotIdx = packageName.indexOf('.');
if(dotIdx==-1)
{
// could be a nested message/enum
Message msg = findMessageFrom(fr.message, packageName);
if(msg!=null || (msg=p.getMessage(packageName))!=null)
{
Message nestedMsg = msg.getNestedMessage(refName);
if(nestedMsg!=null)
{
MessageField mf = newMessageField(nestedMsg, fr, this);
fields.put(mf.name, mf);
continue;
}
EnumGroup eg = msg.getNestedEnumGroup(refName);
if(eg!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
continue;
}
}
}
else
{
Message m = null;
int last = -1;
boolean found = false;;
while(true)
{
String name = packageName.substring(last+1, dotIdx);
if(m==null)
{
// first iteration
m = findMessageFrom(fr.message, name);
if(m==null)
m = proto.getMessage(name);
}
else
m = m.getNestedMessage(name);
if(m==null)
break;
last = dotIdx;
dotIdx = packageName.indexOf('.', dotIdx+1);
if(dotIdx == -1)
{
// last
m = m.getNestedMessage(packageName.substring(last+1));
if(m==null)
break;
Message nestedMsg = m.getNestedMessage(refName);
if(nestedMsg!=null)
{
MessageField mf = newMessageField(nestedMsg, fr, this);
fields.put(mf.name, mf);
found = true;
}
else
{
EnumGroup eg = m.getNestedEnumGroup(refName);
if(eg!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
found = true;
}
}
break;
}
}
if(found)
continue;
}
Proto proto = p.getImportedProto(packageName);
if(proto==null)
throw new IllegalStateException("unknown field: " + packageName + "." + refName);
Message msg = proto.getMessage(refName);
if(msg!=null)
{
MessageField mf = newMessageField(msg, fr, this);
fields.put(mf.name, mf);
continue;
}
EnumGroup eg = proto.getEnumGroup(refName);
if(eg!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
continue;
}
throw new IllegalStateException("unknown field: " + packageName + "." + refName);
}
}
sortedFields.addAll(fields.values());
Collections.sort(sortedFields);
for(Message m : nestedMessages.values())
m.resolveReferences(root);
}
| void resolveReferences(Message root)
{
Proto p = getProto();
for(Field<?> f : fields.values())
{
if(!root.repeatedFieldPresent && f.isRepeated())
root.repeatedFieldPresent = true;
if(!root.requiredFieldPresent && f.isRequired())
root.requiredFieldPresent = true;
if(f instanceof Field.Bytes)
{
if(!root.bytesFieldPresent)
root.bytesFieldPresent = true;
}
else if(f instanceof Field.String)
{
if(!root.bytesFieldPresent && f.defaultValue!=null)
root.bytesFieldPresent = true;
}
else if(f instanceof Field.Reference)
{
Field.Reference fr = (Field.Reference)f;
String refName = fr.refName;
String packageName = fr.packageName;
if(packageName==null)
{
Message msg = findMessageFrom(fr.message, refName);
if(msg!=null || (msg=p.getMessage(refName))!=null)
{
MessageField mf = newMessageField(msg, fr, this);
fields.put(mf.name, mf);
continue;
}
EnumGroup eg = fr.message.getNestedEnumGroup(refName);
if(eg!=null || (eg=p.getEnumGroup(refName))!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
continue;
}
throw new IllegalStateException("unknown field: " + refName);
}
int dotIdx = packageName.indexOf('.');
if(dotIdx==-1)
{
// could be a nested message/enum
Message msg = findMessageFrom(fr.message, packageName);
if(msg!=null || (msg=p.getMessage(packageName))!=null)
{
Message nestedMsg = msg.getNestedMessage(refName);
if(nestedMsg!=null)
{
MessageField mf = newMessageField(nestedMsg, fr, this);
fields.put(mf.name, mf);
continue;
}
EnumGroup eg = msg.getNestedEnumGroup(refName);
if(eg!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
continue;
}
}
}
else
{
Message m = null;
int last = -1;
boolean found = false;;
while(true)
{
String name = packageName.substring(last+1, dotIdx);
if(m==null)
{
// first iteration
m = findMessageFrom(fr.message, name);
if(m==null)
m = proto.getMessage(name);
}
else
m = m.getNestedMessage(name);
if(m==null)
break;
last = dotIdx;
dotIdx = packageName.indexOf('.', dotIdx+1);
if(dotIdx == -1)
{
// last
m = m.getNestedMessage(packageName.substring(last+1));
if(m==null)
break;
Message nestedMsg = m.getNestedMessage(refName);
if(nestedMsg!=null)
{
MessageField mf = newMessageField(nestedMsg, fr, this);
fields.put(mf.name, mf);
found = true;
}
else
{
EnumGroup eg = m.getNestedEnumGroup(refName);
if(eg!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
found = true;
}
}
break;
}
}
if(found)
continue;
}
Proto proto = p.getImportedProto(packageName);
if(proto==null)
throw new IllegalStateException("unknown field: " + packageName + "." + refName);
Message msg = proto.getMessage(refName);
if(msg!=null)
{
MessageField mf = newMessageField(msg, fr, this);
fields.put(mf.name, mf);
continue;
}
EnumGroup eg = proto.getEnumGroup(refName);
if(eg!=null)
{
EnumField ef = newEnumField(eg, fr, this);
fields.put(ef.name, ef);
continue;
}
throw new IllegalStateException("unknown field: " + packageName + "." + refName);
}
}
sortedFields.addAll(fields.values());
Collections.sort(sortedFields);
for(Message m : nestedMessages.values())
m.resolveReferences(root);
}
|
diff --git a/frost-wot/source/frost/fcp/fcp07/persistence/FcpPersistentPut.java b/frost-wot/source/frost/fcp/fcp07/persistence/FcpPersistentPut.java
index 35596913..9de93d9f 100644
--- a/frost-wot/source/frost/fcp/fcp07/persistence/FcpPersistentPut.java
+++ b/frost-wot/source/frost/fcp/fcp07/persistence/FcpPersistentPut.java
@@ -1,103 +1,106 @@
/*
FcpPersistentPut.java / Frost
Copyright (C) 2007 Frost Project <jtcfrost.sourceforge.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 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.
*/
package frost.fcp.fcp07.persistence;
import frost.fcp.fcp07.*;
public class FcpPersistentPut extends FcpPersistentRequest {
// common
private boolean isDirect = false;
private String filename = null;
private String uri = null;
private long fileSize = -1;
// progress
private int doneBlocks = -1;
private int totalBlocks = -1;
private boolean isFinalized = false;
public FcpPersistentPut(NodeMessage msg, String id) {
super(msg, id);
// PersistentPut message
filename = msg.getStringValue("Filename");
uri = msg.getStringValue("URI");
fileSize = msg.getLongValue("DataLength");
String isDirectStr = msg.getStringValue("UploadFrom");
if( isDirectStr.equalsIgnoreCase("disk") ) {
isDirect = false;
} else {
isDirect = true;
}
+ if( filename == null ) {
+ filename = getIdentifier();
+ }
}
public boolean isPut() {
return true;
}
public void setProgress(NodeMessage msg) {
// SimpleProgress message
doneBlocks = msg.getIntValue("Succeeded");
totalBlocks = msg.getIntValue("Total");
isFinalized = msg.getBoolValue("FinalizedTotal");
super.setProgress();
}
public void setSuccess(NodeMessage msg) {
// PutSuccessful msg
uri = msg.getStringValue("URI");
int pos = uri.indexOf("CHK@");
if( pos > -1 ) {
uri = uri.substring(pos).trim();
}
super.setSuccess();
}
public void setFailed(NodeMessage msg) {
super.setFailed(msg);
}
public int getDoneBlocks() {
return doneBlocks;
}
public String getFilename() {
return filename;
}
public long getFileSize() {
return fileSize;
}
public boolean isDirect() {
return isDirect;
}
public boolean isFinalized() {
return isFinalized;
}
public int getTotalBlocks() {
return totalBlocks;
}
public String getUri() {
return uri;
}
}
| true | true | public FcpPersistentPut(NodeMessage msg, String id) {
super(msg, id);
// PersistentPut message
filename = msg.getStringValue("Filename");
uri = msg.getStringValue("URI");
fileSize = msg.getLongValue("DataLength");
String isDirectStr = msg.getStringValue("UploadFrom");
if( isDirectStr.equalsIgnoreCase("disk") ) {
isDirect = false;
} else {
isDirect = true;
}
}
| public FcpPersistentPut(NodeMessage msg, String id) {
super(msg, id);
// PersistentPut message
filename = msg.getStringValue("Filename");
uri = msg.getStringValue("URI");
fileSize = msg.getLongValue("DataLength");
String isDirectStr = msg.getStringValue("UploadFrom");
if( isDirectStr.equalsIgnoreCase("disk") ) {
isDirect = false;
} else {
isDirect = true;
}
if( filename == null ) {
filename = getIdentifier();
}
}
|
diff --git a/occjava/src-java/org/jcae/opencascade/test/Dimensions.java b/occjava/src-java/org/jcae/opencascade/test/Dimensions.java
index b9acf6d6..ba40b55a 100644
--- a/occjava/src-java/org/jcae/opencascade/test/Dimensions.java
+++ b/occjava/src-java/org/jcae/opencascade/test/Dimensions.java
@@ -1,44 +1,44 @@
package org.jcae.opencascade.test;
import org.jcae.opencascade.jni.*;
/**
* Example of BRepGProp and BRepBndLib
* @author Jerome Robert
*/
public class Dimensions
{
public static void main(String[] args)
{
// Create a shape for the example (a torus)
double[] axis=new double[]{
0,0,0, // position
0,0,1}; // direction
TopoDS_Shape torus=new BRepPrimAPI_MakeTorus(axis, 3, 1).shape();
// Compute the bounding box of the shape
Bnd_Box bbox = new Bnd_Box();
BRepBndLib.add(torus, bbox);
double[] bboxValues = bbox.get();
// Display the bounding box
System.out.println("Xmin="+bboxValues[0]);
- System.out.println("Ymin="+bboxValues[0]);
- System.out.println("Zmin="+bboxValues[0]);
- System.out.println("Xmax="+bboxValues[0]);
- System.out.println("Ymax="+bboxValues[0]);
- System.out.println("Zmax="+bboxValues[0]);
+ System.out.println("Ymin="+bboxValues[1]);
+ System.out.println("Zmin="+bboxValues[2]);
+ System.out.println("Xmax="+bboxValues[3]);
+ System.out.println("Ymax="+bboxValues[4]);
+ System.out.println("Zmax="+bboxValues[5]);
// Display various other properties
GProp_GProps property=new GProp_GProps();
BRepGProp.linearProperties(torus, property);
System.out.println("length="+property.mass());
BRepGProp.surfaceProperties(torus, property);
System.out.println("surface="+property.mass());
BRepGProp.volumeProperties(torus, property);
System.out.println("volume="+property.mass());
}
}
| true | true | public static void main(String[] args)
{
// Create a shape for the example (a torus)
double[] axis=new double[]{
0,0,0, // position
0,0,1}; // direction
TopoDS_Shape torus=new BRepPrimAPI_MakeTorus(axis, 3, 1).shape();
// Compute the bounding box of the shape
Bnd_Box bbox = new Bnd_Box();
BRepBndLib.add(torus, bbox);
double[] bboxValues = bbox.get();
// Display the bounding box
System.out.println("Xmin="+bboxValues[0]);
System.out.println("Ymin="+bboxValues[0]);
System.out.println("Zmin="+bboxValues[0]);
System.out.println("Xmax="+bboxValues[0]);
System.out.println("Ymax="+bboxValues[0]);
System.out.println("Zmax="+bboxValues[0]);
// Display various other properties
GProp_GProps property=new GProp_GProps();
BRepGProp.linearProperties(torus, property);
System.out.println("length="+property.mass());
BRepGProp.surfaceProperties(torus, property);
System.out.println("surface="+property.mass());
BRepGProp.volumeProperties(torus, property);
System.out.println("volume="+property.mass());
}
| public static void main(String[] args)
{
// Create a shape for the example (a torus)
double[] axis=new double[]{
0,0,0, // position
0,0,1}; // direction
TopoDS_Shape torus=new BRepPrimAPI_MakeTorus(axis, 3, 1).shape();
// Compute the bounding box of the shape
Bnd_Box bbox = new Bnd_Box();
BRepBndLib.add(torus, bbox);
double[] bboxValues = bbox.get();
// Display the bounding box
System.out.println("Xmin="+bboxValues[0]);
System.out.println("Ymin="+bboxValues[1]);
System.out.println("Zmin="+bboxValues[2]);
System.out.println("Xmax="+bboxValues[3]);
System.out.println("Ymax="+bboxValues[4]);
System.out.println("Zmax="+bboxValues[5]);
// Display various other properties
GProp_GProps property=new GProp_GProps();
BRepGProp.linearProperties(torus, property);
System.out.println("length="+property.mass());
BRepGProp.surfaceProperties(torus, property);
System.out.println("surface="+property.mass());
BRepGProp.volumeProperties(torus, property);
System.out.println("volume="+property.mass());
}
|
diff --git a/src/com/mobsandgeeks/saripaar/AnnotationToRuleConverter.java b/src/com/mobsandgeeks/saripaar/AnnotationToRuleConverter.java
index 8418ba1..92f68bd 100644
--- a/src/com/mobsandgeeks/saripaar/AnnotationToRuleConverter.java
+++ b/src/com/mobsandgeeks/saripaar/AnnotationToRuleConverter.java
@@ -1,269 +1,272 @@
/*
* Copyright (C) 2012 Mobs and Geeks
*
* 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.mobsandgeeks.saripaar;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.Checkable;
import android.widget.TextView;
import com.mobsandgeeks.saripaar.annotation.Checked;
import com.mobsandgeeks.saripaar.annotation.ConfirmPassword;
import com.mobsandgeeks.saripaar.annotation.Email;
import com.mobsandgeeks.saripaar.annotation.IpAddress;
import com.mobsandgeeks.saripaar.annotation.NumberRule;
import com.mobsandgeeks.saripaar.annotation.Password;
import com.mobsandgeeks.saripaar.annotation.Regex;
import com.mobsandgeeks.saripaar.annotation.Required;
import com.mobsandgeeks.saripaar.annotation.TextRule;
/**
* Class contains {@code static} methods that return appropriate {@link Rule}s for Saripaar
* annotations.
*
* @author Ragunath Jawahar <[email protected]>
*/
class AnnotationToRuleConverter {
// Debug
static final String TAG = AnnotationToRuleConverter.class.getSimpleName();
// Constants
static final String WARN_TEXT = "%s - @%s can only be applied to TextView and " +
"its subclasses.";
static final String WARN_CHECKABLE = "%s - @%s can only be applied to Checkable, " +
"its implementations and subclasses.";
public static Rule<?> getRule(Field field, View view, Annotation annotation) {
Class<?> annotationClass = annotation.getClass();
if (Required.class.isAssignableFrom(annotationClass)) {
return getRequiredRule(field, view, (Required) annotation);
} else if (Checked.class.isAssignableFrom(annotationClass)) {
return getCheckedRule(field, view, (Checked) annotation);
} else if (TextRule.class.isAssignableFrom(annotationClass)) {
return getTextRule(field, view, (TextRule) annotation);
} else if (Regex.class.isAssignableFrom(annotationClass)) {
return getRegexRule(field, view, (Regex) annotation);
} else if (NumberRule.class.isAssignableFrom(annotationClass)) {
return getNumberRule(field, view, (NumberRule) annotation);
} else if (Password.class.isAssignableFrom(annotationClass)) {
return getPasswordRule(field, view, (Password) annotation);
} else if (Email.class.isAssignableFrom(annotationClass)) {
return getEmailRule(field, view, (Email) annotation);
} else if (IpAddress.class.isAssignableFrom(annotationClass)) {
return getIpAddressRule(field, view, (IpAddress) annotation);
}
return null;
}
public static Rule<?> getRule(Field field, View view, Annotation annotation, Object... params) {
Class<?> annotationClass = annotation.getClass();
if (ConfirmPassword.class.isAssignableFrom(annotationClass)) {
TextView passwordTextView = (TextView) params[0];
return getConfirmPasswordRule(field, view, (ConfirmPassword) annotation,
passwordTextView);
}
return (params == null || params.length == 0) ? getRule(field, view, annotation) : null;
}
private static Rule<TextView> getRequiredRule(Field field, View view, Required required) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(), Required.class.getSimpleName()));
return null;
}
int messageResId = required.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
required.message();
return Rules.required(message, required.trim());
}
private static Rule<View> getTextRule(Field field, View view, TextRule textRule) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(), TextRule.class.getSimpleName()));
return null;
}
List<Rule<?>> rules = new ArrayList<Rule<?>>();
int messageResId = textRule.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
textRule.message();
if (textRule.minLength() > 0) {
rules.add(Rules.minLength(null, textRule.minLength(), textRule.trim()));
}
if (textRule.maxLength() != Integer.MAX_VALUE) {
rules.add(Rules.maxLength(null, textRule.maxLength(), textRule.trim()));
}
Rule<?>[] ruleArray = new Rule<?>[rules.size()];
rules.toArray(ruleArray);
return Rules.and(message, ruleArray);
}
private static Rule<TextView> getRegexRule(Field field, View view, Regex regexRule) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(), Regex.class.getSimpleName()));
return null;
}
Context context = view.getContext();
int messageResId = regexRule.messageResId();
String message = messageResId != 0 ? context.getString(messageResId) : regexRule.message();
int patternResId = regexRule.patternResId();
String pattern = patternResId != 0 ? view.getContext().getString(patternResId) :
regexRule.pattern();
return Rules.regex(message, pattern, regexRule.trim());
}
private static Rule<View> getNumberRule(Field field, View view, NumberRule numberRule) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(), NumberRule.class.getSimpleName()));
return null;
} else if (numberRule.type() == null) {
throw new IllegalArgumentException(String.format("@%s.type() cannot be null.",
NumberRule.class.getSimpleName()));
}
List<Rule<?>> rules = new ArrayList<Rule<?>>();
int messageResId = numberRule.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
numberRule.message();
switch (numberRule.type()) {
case INTEGER: case LONG:
Rules.regex(null, Rules.REGEX_INTEGER, true); break;
case FLOAT: case DOUBLE:
Rules.regex(null, Rules.REGEX_DECIMAL, true); break;
}
if (numberRule.lt() != Double.MIN_VALUE) {
String ltNumber = String.valueOf(numberRule.lt());
+ double number = Double.parseDouble(ltNumber);
switch (numberRule.type()) {
- case INTEGER: rules.add(Rules.lt(null, Integer.parseInt(ltNumber))); break;
+ case INTEGER: rules.add(Rules.lt(null, ((int) number))); break;
case LONG: rules.add(Rules.lt(null, Long.parseLong(ltNumber))); break;
case FLOAT: rules.add(Rules.lt(null, Float.parseFloat(ltNumber))); break;
case DOUBLE: rules.add(Rules.lt(null, Double.parseDouble(ltNumber))); break;
}
}
if (numberRule.gt() != Double.MAX_VALUE) {
String gtNumber = String.valueOf(numberRule.gt());
+ double number = Double.parseDouble(gtNumber);
switch (numberRule.type()) {
- case INTEGER: rules.add(Rules.gt(null, Integer.parseInt(gtNumber))); break;
+ case INTEGER: rules.add(Rules.gt(null, ((int) number))); break;
case LONG: rules.add(Rules.gt(null, Long.parseLong(gtNumber))); break;
case FLOAT: rules.add(Rules.gt(null, Float.parseFloat(gtNumber))); break;
case DOUBLE: rules.add(Rules.gt(null, Double.parseDouble(gtNumber))); break;
}
}
if (numberRule.eq() != Double.MAX_VALUE) {
- String gtNumber = String.valueOf(numberRule.gt());
+ String eqNumber = String.valueOf(numberRule.eq());
+ double number = Double.parseDouble(eqNumber);
switch (numberRule.type()) {
- case INTEGER: rules.add(Rules.eq(null, Integer.parseInt(gtNumber))); break;
- case LONG: rules.add(Rules.eq(null, Long.parseLong(gtNumber))); break;
- case FLOAT: rules.add(Rules.eq(null, Float.parseFloat(gtNumber))); break;
- case DOUBLE: rules.add(Rules.eq(null, Double.parseDouble(gtNumber))); break;
+ case INTEGER: rules.add(Rules.eq(null, ((int) number))); break;
+ case LONG: rules.add(Rules.eq(null, Long.parseLong(eqNumber))); break;
+ case FLOAT: rules.add(Rules.eq(null, Float.parseFloat(eqNumber))); break;
+ case DOUBLE: rules.add(Rules.eq(null, Double.parseDouble(eqNumber))); break;
}
}
Rule<?>[] ruleArray = new Rule<?>[rules.size()];
rules.toArray(ruleArray);
return Rules.and(message, ruleArray);
}
private static Rule<TextView> getPasswordRule(Field field, View view, Password password) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(), Password.class.getSimpleName()));
return null;
}
int messageResId = password.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
password.message();
return Rules.required(message, false);
}
private static Rule<TextView> getConfirmPasswordRule(Field field, View view,
ConfirmPassword confirmPassword, TextView passwordTextView) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(),
ConfirmPassword.class.getSimpleName()));
return null;
}
int messageResId = confirmPassword.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
confirmPassword.message();
return Rules.eq(message, passwordTextView);
}
private static Rule<View> getEmailRule(Field field, View view, Email email) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(), Regex.class.getSimpleName()));
return null;
}
int messageResId = email.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
email.message();
return Rules.or(message, Rules.eq(null, Rules.EMPTY_STRING),
Rules.regex(message, Rules.REGEX_EMAIL, true));
}
private static Rule<View> getIpAddressRule(Field field, View view, IpAddress ipAddress) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(), IpAddress.class.getSimpleName()));
return null;
}
int messageResId = ipAddress.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
ipAddress.message();
return Rules.or(message, Rules.eq(null, Rules.EMPTY_STRING),
Rules.regex(message, Rules.REGEX_IP_ADDRESS, true));
}
private static Rule<Checkable> getCheckedRule(Field field, View view, Checked checked) {
if (!Checkable.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_CHECKABLE, field.getName(),
Checked.class.getSimpleName()));
return null;
}
int messageResId = checked.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
checked.message();
return Rules.checked(message, checked.checked());
}
}
| false | true | private static Rule<View> getNumberRule(Field field, View view, NumberRule numberRule) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(), NumberRule.class.getSimpleName()));
return null;
} else if (numberRule.type() == null) {
throw new IllegalArgumentException(String.format("@%s.type() cannot be null.",
NumberRule.class.getSimpleName()));
}
List<Rule<?>> rules = new ArrayList<Rule<?>>();
int messageResId = numberRule.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
numberRule.message();
switch (numberRule.type()) {
case INTEGER: case LONG:
Rules.regex(null, Rules.REGEX_INTEGER, true); break;
case FLOAT: case DOUBLE:
Rules.regex(null, Rules.REGEX_DECIMAL, true); break;
}
if (numberRule.lt() != Double.MIN_VALUE) {
String ltNumber = String.valueOf(numberRule.lt());
switch (numberRule.type()) {
case INTEGER: rules.add(Rules.lt(null, Integer.parseInt(ltNumber))); break;
case LONG: rules.add(Rules.lt(null, Long.parseLong(ltNumber))); break;
case FLOAT: rules.add(Rules.lt(null, Float.parseFloat(ltNumber))); break;
case DOUBLE: rules.add(Rules.lt(null, Double.parseDouble(ltNumber))); break;
}
}
if (numberRule.gt() != Double.MAX_VALUE) {
String gtNumber = String.valueOf(numberRule.gt());
switch (numberRule.type()) {
case INTEGER: rules.add(Rules.gt(null, Integer.parseInt(gtNumber))); break;
case LONG: rules.add(Rules.gt(null, Long.parseLong(gtNumber))); break;
case FLOAT: rules.add(Rules.gt(null, Float.parseFloat(gtNumber))); break;
case DOUBLE: rules.add(Rules.gt(null, Double.parseDouble(gtNumber))); break;
}
}
if (numberRule.eq() != Double.MAX_VALUE) {
String gtNumber = String.valueOf(numberRule.gt());
switch (numberRule.type()) {
case INTEGER: rules.add(Rules.eq(null, Integer.parseInt(gtNumber))); break;
case LONG: rules.add(Rules.eq(null, Long.parseLong(gtNumber))); break;
case FLOAT: rules.add(Rules.eq(null, Float.parseFloat(gtNumber))); break;
case DOUBLE: rules.add(Rules.eq(null, Double.parseDouble(gtNumber))); break;
}
}
Rule<?>[] ruleArray = new Rule<?>[rules.size()];
rules.toArray(ruleArray);
return Rules.and(message, ruleArray);
}
| private static Rule<View> getNumberRule(Field field, View view, NumberRule numberRule) {
if (!TextView.class.isAssignableFrom(view.getClass())) {
Log.w(TAG, String.format(WARN_TEXT, field.getName(), NumberRule.class.getSimpleName()));
return null;
} else if (numberRule.type() == null) {
throw new IllegalArgumentException(String.format("@%s.type() cannot be null.",
NumberRule.class.getSimpleName()));
}
List<Rule<?>> rules = new ArrayList<Rule<?>>();
int messageResId = numberRule.messageResId();
String message = messageResId != 0 ? view.getContext().getString(messageResId) :
numberRule.message();
switch (numberRule.type()) {
case INTEGER: case LONG:
Rules.regex(null, Rules.REGEX_INTEGER, true); break;
case FLOAT: case DOUBLE:
Rules.regex(null, Rules.REGEX_DECIMAL, true); break;
}
if (numberRule.lt() != Double.MIN_VALUE) {
String ltNumber = String.valueOf(numberRule.lt());
double number = Double.parseDouble(ltNumber);
switch (numberRule.type()) {
case INTEGER: rules.add(Rules.lt(null, ((int) number))); break;
case LONG: rules.add(Rules.lt(null, Long.parseLong(ltNumber))); break;
case FLOAT: rules.add(Rules.lt(null, Float.parseFloat(ltNumber))); break;
case DOUBLE: rules.add(Rules.lt(null, Double.parseDouble(ltNumber))); break;
}
}
if (numberRule.gt() != Double.MAX_VALUE) {
String gtNumber = String.valueOf(numberRule.gt());
double number = Double.parseDouble(gtNumber);
switch (numberRule.type()) {
case INTEGER: rules.add(Rules.gt(null, ((int) number))); break;
case LONG: rules.add(Rules.gt(null, Long.parseLong(gtNumber))); break;
case FLOAT: rules.add(Rules.gt(null, Float.parseFloat(gtNumber))); break;
case DOUBLE: rules.add(Rules.gt(null, Double.parseDouble(gtNumber))); break;
}
}
if (numberRule.eq() != Double.MAX_VALUE) {
String eqNumber = String.valueOf(numberRule.eq());
double number = Double.parseDouble(eqNumber);
switch (numberRule.type()) {
case INTEGER: rules.add(Rules.eq(null, ((int) number))); break;
case LONG: rules.add(Rules.eq(null, Long.parseLong(eqNumber))); break;
case FLOAT: rules.add(Rules.eq(null, Float.parseFloat(eqNumber))); break;
case DOUBLE: rules.add(Rules.eq(null, Double.parseDouble(eqNumber))); break;
}
}
Rule<?>[] ruleArray = new Rule<?>[rules.size()];
rules.toArray(ruleArray);
return Rules.and(message, ruleArray);
}
|
diff --git a/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/model/ResultTreeTracker.java b/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/model/ResultTreeTracker.java
index 3635c485a..19b091cdb 100644
--- a/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/model/ResultTreeTracker.java
+++ b/org.eclipse.jubula.client.core/src/org/eclipse/jubula/client/core/model/ResultTreeTracker.java
@@ -1,311 +1,312 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 BREDEX GmbH.
* 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:
* BREDEX GmbH - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.jubula.client.core.model;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jubula.client.core.businessprocess.ExternalTestDataBP;
import org.eclipse.jubula.client.core.businessprocess.TestExecution;
import org.eclipse.jubula.client.core.i18n.Messages;
import org.eclipse.jubula.client.core.persistence.Persistor;
import org.eclipse.jubula.client.core.utils.ExecObject;
import org.eclipse.jubula.client.core.utils.ModelParamValueConverter;
import org.eclipse.jubula.client.core.utils.ParamValueConverter;
import org.eclipse.jubula.tools.constants.StringConstants;
import org.eclipse.jubula.tools.exception.InvalidDataException;
import org.eclipse.jubula.tools.exception.JBException;
import org.eclipse.jubula.tools.i18n.CompSystemI18n;
import org.eclipse.jubula.tools.messagehandling.MessageIDs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* class for tracking of result tree for display of test results
* @author BREDEX GmbH
* @created 14.04.2005
*/
public class ResultTreeTracker implements IExecStackModificationListener {
/** the logger */
private static Logger log =
LoggerFactory.getLogger(ResultTreeTracker.class);
/**
* <code>m_endNode</code> last result node in resultTree, which is associated
* with last execTestCase or with the testsuite
*/
private TestResultNode m_endNode;
/**
* <code>m_lastCap</code> resultNode to actual executed cap
*/
private TestResultNode m_lastNonCap;
/**
* here is saved how much extra hierarchy lvl we have caused by event
* handler
*/
private int m_eventHierarchy = 0;
/** business process for retrieving test data */
private ExternalTestDataBP m_externalTestDataBP;
/**
* @param root traverser for associated testexecution tree
* @param externalTestDataBP business process for retrieving test data
*/
public ResultTreeTracker(TestResultNode root,
ExternalTestDataBP externalTestDataBP) {
m_endNode = root;
m_lastNonCap = root;
m_externalTestDataBP = externalTestDataBP;
}
/**
* {@inheritDoc}
*/
public void stackIncremented(INodePO node) {
if (m_lastNonCap.getStatus() == TestResultNode.NOT_YET_TESTED) {
m_lastNonCap.setResult(TestResultNode.TESTING, null);
}
if (Persistor.isPoSubclass(node, IEventExecTestCasePO.class)
|| m_eventHierarchy > 0) {
m_eventHierarchy++;
}
if (m_eventHierarchy > 0) {
int nextIndex = m_lastNonCap.getNextChildIndex();
m_lastNonCap = new TestResultNode(
node,
m_lastNonCap,
nextIndex);
m_lastNonCap.getParent().updateResultNode(nextIndex, m_lastNonCap);
} else {
TestResultNode nextNonCap = m_lastNonCap.getResultNodeList().
get(m_lastNonCap.getNextChildIndex());
while (nextNonCap.getNode() != node) {
nextNonCap = m_lastNonCap.getResultNodeList().
get(m_lastNonCap.getNextChildIndex());
}
m_lastNonCap = nextNonCap;
}
m_endNode = m_lastNonCap;
if (m_lastNonCap.getStatus() == TestResultNode.NOT_YET_TESTED) {
m_lastNonCap.setResult(TestResultNode.TESTING, null);
if (node instanceof IParamNodePO) {
addParameters((IParamNodePO)node, m_lastNonCap);
}
}
if (m_lastNonCap.getParent().getStatus()
== TestResultNode.NOT_YET_TESTED) {
m_lastNonCap.getParent().setResult(TestResultNode.TESTING, null);
}
}
/**
* {@inheritDoc}
*/
public void stackDecremented() {
if (m_eventHierarchy > 0) {
m_eventHierarchy--;
}
if (m_lastNonCap.getStatus() == TestResultNode.NOT_YET_TESTED
|| m_lastNonCap.getStatus() == TestResultNode.TESTING) {
m_lastNonCap.setResult(TestResultNode.SUCCESS, null);
if (m_endNode.getStatus() == TestResultNode.NOT_YET_TESTED
|| m_endNode.getStatus() == TestResultNode.TESTING) {
m_endNode.setResult(TestResultNode.SUCCESS, null);
}
}
m_lastNonCap = m_lastNonCap.getParent();
m_endNode = m_lastNonCap;
}
/**
* {@inheritDoc}
*/
public void nextDataSetIteration() {
if (m_lastNonCap.getStatus() == TestResultNode.NOT_YET_TESTED
|| m_lastNonCap.getStatus() == TestResultNode.TESTING) {
m_lastNonCap.setResult(TestResultNode.SUCCESS, null);
if (m_endNode.getStatus() == TestResultNode.NOT_YET_TESTED
|| m_endNode.getStatus() == TestResultNode.TESTING) {
m_endNode.setResult(TestResultNode.SUCCESS, null);
}
}
int nextIndex = m_lastNonCap.getParent().getNextChildIndex();
if (m_eventHierarchy > 0) {
m_lastNonCap = new TestResultNode(m_lastNonCap.getNode(),
m_lastNonCap.getParent(), nextIndex);
m_lastNonCap.getParent().updateResultNode(nextIndex, m_lastNonCap);
} else {
m_lastNonCap = m_lastNonCap.getParent().
getResultNodeList().
get(nextIndex);
}
if (m_lastNonCap.getStatus() == TestResultNode.NOT_YET_TESTED) {
INodePO node = m_lastNonCap.getNode();
if (node instanceof IParamNodePO) {
addParameters((IParamNodePO)node, m_lastNonCap);
}
m_lastNonCap.setResult(TestResultNode.TESTING, null);
}
if (m_lastNonCap.getParent().getStatus()
== TestResultNode.NOT_YET_TESTED) {
m_lastNonCap.getParent().setResult(TestResultNode.TESTING, null);
}
}
/**
* {@inheritDoc}
*/
public void nextCap(ICapPO cap) {
int nextIndex = m_lastNonCap.getNextChildIndex();
if (m_eventHierarchy > 0) {
m_endNode = new TestResultNode(cap, m_lastNonCap);
m_endNode.getParent().updateResultNode(nextIndex, m_endNode);
m_endNode.setActionName(
CompSystemI18n.getString(cap.getActionName()));
m_endNode.setComponentType(
CompSystemI18n.getString(cap.getComponentType()));
} else {
m_endNode = m_lastNonCap.getResultNodeList().
get(nextIndex);
while (m_endNode.getNode() != cap) {
nextIndex = m_lastNonCap.getNextChildIndex();
m_endNode = m_lastNonCap.getResultNodeList().
get(nextIndex);
}
}
if (m_endNode.getStatus() == TestResultNode.NOT_YET_TESTED) {
m_endNode.setResult(TestResultNode.TESTING, null);
}
addParameters(cap, m_endNode);
}
/**
* Adds the parameters from the given cap to the given result node.
*
* @param paramNode The node from which to copy the parameter info.
* @param resultNode The result node to which the parameter info will
* be copied.
*/
private void addParameters(IParamNodePO paramNode,
TestResultNode resultNode) {
List<IParamDescriptionPO> parameterList = paramNode.getParameterList();
for (IParamDescriptionPO desc : parameterList) {
List<ExecObject> execList =
TestExecution.getInstance().getTrav().getExecStackAsList();
ExecObject currentExecObj = execList.get(execList.size() - 1);
resultNode.addParameter(new TestResultParameter(
desc.getName(), CompSystemI18n.getString(desc.getType()),
currentExecObj.getParameterValue(desc.getUniqueId())));
}
}
/**
* Adds the parameters from the given Test Step to the given result node.
*
* @param testStep The Test Step from which to copy the parameter info.
* @param resultNode The result node to which the parameter info will
* be copied.
*/
private void addParameters(ICapPO testStep,
TestResultNode resultNode) {
List<IParamDescriptionPO> parameterList = testStep.getParameterList();
String value = null;
for (IParamDescriptionPO desc : parameterList) {
ITDManager tdManager = null;
try {
tdManager =
m_externalTestDataBP.getExternalCheckedTDManager(
testStep);
} catch (JBException e) {
log.error(
Messages.TestDataNotAvailable + StringConstants.DOT, e);
}
TestExecution te = TestExecution.getInstance();
List <ExecObject> stackList =
new ArrayList<ExecObject>(te.getTrav().getExecStackAsList());
// Special handling for Test Steps. Their test data manager has
// information about multiple Data Sets, but we are only interested
// in the first one.
int dataSetIndex = 0;
if (tdManager.findColumnForParam(desc.getUniqueId()) == -1) {
IParameterInterfacePO referencedDataCube = testStep
.getReferencedDataCube();
if (referencedDataCube != null) {
desc = referencedDataCube.getParameterForName(desc
.getName());
}
}
ITestDataPO date = tdManager.getCell(dataSetIndex, desc);
ParamValueConverter conv = new ModelParamValueConverter(
date.getValue(te.getLocale()), testStep, te.getLocale(), desc);
try {
value = conv.getExecutionString(
stackList, te.getLocale());
} catch (InvalidDataException e) {
log.error(e.getMessage());
value = MessageIDs.getMessageObject(e.getErrorId()).
getMessage(new Object[] {});
}
resultNode.addParameter(new TestResultParameter(
- desc.getUniqueId(), desc.getType(),
+ CompSystemI18n.getString(desc.getUniqueId()),
+ CompSystemI18n.getString(desc.getType()),
StringUtils.defaultString(value)));
}
}
/**
* @return Returns the endNode.
*/
public TestResultNode getEndNode() {
return m_endNode;
}
/**
* {@inheritDoc}
*/
public void retryCap(ICapPO cap) {
int nextIndex = m_lastNonCap.getNextChildIndex();
m_endNode = new TestResultNode(cap, m_lastNonCap, nextIndex);
if (m_endNode.getStatus() == TestResultNode.NOT_YET_TESTED) {
m_endNode.setResult(TestResultNode.TESTING, null);
}
m_endNode.getParent().updateResultNode(nextIndex, m_endNode);
addParameters(cap, m_endNode);
}
}
| true | true | private void addParameters(ICapPO testStep,
TestResultNode resultNode) {
List<IParamDescriptionPO> parameterList = testStep.getParameterList();
String value = null;
for (IParamDescriptionPO desc : parameterList) {
ITDManager tdManager = null;
try {
tdManager =
m_externalTestDataBP.getExternalCheckedTDManager(
testStep);
} catch (JBException e) {
log.error(
Messages.TestDataNotAvailable + StringConstants.DOT, e);
}
TestExecution te = TestExecution.getInstance();
List <ExecObject> stackList =
new ArrayList<ExecObject>(te.getTrav().getExecStackAsList());
// Special handling for Test Steps. Their test data manager has
// information about multiple Data Sets, but we are only interested
// in the first one.
int dataSetIndex = 0;
if (tdManager.findColumnForParam(desc.getUniqueId()) == -1) {
IParameterInterfacePO referencedDataCube = testStep
.getReferencedDataCube();
if (referencedDataCube != null) {
desc = referencedDataCube.getParameterForName(desc
.getName());
}
}
ITestDataPO date = tdManager.getCell(dataSetIndex, desc);
ParamValueConverter conv = new ModelParamValueConverter(
date.getValue(te.getLocale()), testStep, te.getLocale(), desc);
try {
value = conv.getExecutionString(
stackList, te.getLocale());
} catch (InvalidDataException e) {
log.error(e.getMessage());
value = MessageIDs.getMessageObject(e.getErrorId()).
getMessage(new Object[] {});
}
resultNode.addParameter(new TestResultParameter(
desc.getUniqueId(), desc.getType(),
StringUtils.defaultString(value)));
}
}
| private void addParameters(ICapPO testStep,
TestResultNode resultNode) {
List<IParamDescriptionPO> parameterList = testStep.getParameterList();
String value = null;
for (IParamDescriptionPO desc : parameterList) {
ITDManager tdManager = null;
try {
tdManager =
m_externalTestDataBP.getExternalCheckedTDManager(
testStep);
} catch (JBException e) {
log.error(
Messages.TestDataNotAvailable + StringConstants.DOT, e);
}
TestExecution te = TestExecution.getInstance();
List <ExecObject> stackList =
new ArrayList<ExecObject>(te.getTrav().getExecStackAsList());
// Special handling for Test Steps. Their test data manager has
// information about multiple Data Sets, but we are only interested
// in the first one.
int dataSetIndex = 0;
if (tdManager.findColumnForParam(desc.getUniqueId()) == -1) {
IParameterInterfacePO referencedDataCube = testStep
.getReferencedDataCube();
if (referencedDataCube != null) {
desc = referencedDataCube.getParameterForName(desc
.getName());
}
}
ITestDataPO date = tdManager.getCell(dataSetIndex, desc);
ParamValueConverter conv = new ModelParamValueConverter(
date.getValue(te.getLocale()), testStep, te.getLocale(), desc);
try {
value = conv.getExecutionString(
stackList, te.getLocale());
} catch (InvalidDataException e) {
log.error(e.getMessage());
value = MessageIDs.getMessageObject(e.getErrorId()).
getMessage(new Object[] {});
}
resultNode.addParameter(new TestResultParameter(
CompSystemI18n.getString(desc.getUniqueId()),
CompSystemI18n.getString(desc.getType()),
StringUtils.defaultString(value)));
}
}
|
diff --git a/src/main/java/tconstruct/armor/ArmorProxyClient.java b/src/main/java/tconstruct/armor/ArmorProxyClient.java
index f7f15e8fd..a333967af 100644
--- a/src/main/java/tconstruct/armor/ArmorProxyClient.java
+++ b/src/main/java/tconstruct/armor/ArmorProxyClient.java
@@ -1,489 +1,493 @@
package tconstruct.armor;
import java.util.ArrayList;
import java.util.Random;
import mantle.lib.client.MantleClientRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.client.event.FOVUpdateEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.common.MinecraftForge;
import tconstruct.armor.gui.ArmorExtendedGui;
import tconstruct.armor.gui.KnapsackGui;
import tconstruct.armor.items.TravelGear;
import tconstruct.armor.model.BeltModel;
import tconstruct.armor.model.BootBump;
import tconstruct.armor.model.HiddenPlayerModel;
import tconstruct.armor.model.WingModel;
import tconstruct.armor.player.ArmorExtended;
import tconstruct.armor.player.KnapsackInventory;
import tconstruct.client.TControls;
import tconstruct.client.TKeyHandler;
import tconstruct.client.tabs.InventoryTabArmorExtended;
import tconstruct.client.tabs.InventoryTabKnapsack;
import tconstruct.client.tabs.InventoryTabVanilla;
import tconstruct.client.tabs.TabRegistry;
import tconstruct.common.TProxyCommon;
import tconstruct.library.accessory.IAccessoryModel;
import tconstruct.library.client.TConstructClientRegistry;
import tconstruct.world.TinkerWorld;
import com.google.common.collect.Lists;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class ArmorProxyClient extends ArmorProxyCommon
{
public static WingModel wings = new WingModel();
public static BootBump bootbump = new BootBump();
public static HiddenPlayerModel glove = new HiddenPlayerModel(0.25F, 4);
public static HiddenPlayerModel vest = new HiddenPlayerModel(0.25f, 1);
public static BeltModel belt = new BeltModel();
public static KnapsackInventory knapsack = new KnapsackInventory();
public static ArmorExtended armorExtended = new ArmorExtended();
@Override
public void initialize ()
{
registerGuiHandler();
registerKeys();
registerManualRecipes();
MinecraftForge.EVENT_BUS.register(this);
FMLCommonHandler.instance().bus().register(new ArmorAbilitiesClient(mc, controlInstance));
}
private void registerManualRecipes ()
{
ItemStack feather = new ItemStack(Items.feather);
ItemStack redstone = new ItemStack(Items.redstone);
ItemStack goggles = TinkerArmor.travelGoggles.getDefaultItem();
MantleClientRegistry.registerManualSmallRecipe("nightvision", goggles.copy(), new ItemStack(Items.flint_and_steel), new ItemStack(Items.potionitem, 1, 0), new ItemStack(Items.golden_carrot), null);
ItemStack vest = TinkerArmor.travelVest.getDefaultItem();
System.out.println("Travel Vest Item: "+vest);
MantleClientRegistry.registerManualIcon("travelvest", vest);
MantleClientRegistry.registerManualSmallRecipe("dodge", vest.copy(), new ItemStack(Items.ender_eye), new ItemStack(Items.ender_pearl), new ItemStack(Items.sugar), null);
MantleClientRegistry.registerManualSmallRecipe("stealth", vest.copy(), new ItemStack(Items.fermented_spider_eye), new ItemStack(Items.ender_eye), new ItemStack(Items.potionitem, 1, 0),
new ItemStack(Items.golden_carrot));
ItemStack wings = new ItemStack(TinkerArmor.travelWings);
MantleClientRegistry.registerManualIcon("travelwings", wings);
MantleClientRegistry.registerManualSmallRecipe("doublejump", wings.copy(), new ItemStack(Items.ghast_tear), new ItemStack(TinkerWorld.slimeGel, 1, 0), new ItemStack(Blocks.piston), null);
MantleClientRegistry.registerManualLargeRecipe("featherfall", wings.copy(), new ItemStack(TinkerWorld.slimeGel, 1, 0), feather, feather, feather, wings.copy(), feather, feather,
new ItemStack(Items.ender_pearl), feather);
ItemStack boots = TinkerArmor.travelBoots.getDefaultItem();
MantleClientRegistry.registerManualIcon("travelboots", boots);
MantleClientRegistry.registerManualSmallRecipe("doublejumpboots", boots.copy(), new ItemStack(Items.ghast_tear), new ItemStack(TinkerWorld.slimeGel, 1, 1), new ItemStack(Blocks.piston), null);
TConstructClientRegistry.registerManualModifier("waterwalk", boots.copy(), new ItemStack(Blocks.waterlily), new ItemStack(Blocks.waterlily));
TConstructClientRegistry.registerManualModifier("leadboots", boots.copy(), new ItemStack(Blocks.iron_block));
TConstructClientRegistry.registerManualModifier("slimysoles", boots.copy(), new ItemStack(TinkerWorld.slimePad, 1, 0), new ItemStack(TinkerWorld.slimePad, 1, 0));
ItemStack gloves = TinkerArmor.travelGlove.getDefaultItem();
MantleClientRegistry.registerManualIcon("travelgloves", gloves);
TConstructClientRegistry.registerManualModifier("glovehaste", gloves.copy(), redstone, new ItemStack(Blocks.redstone_block));
//MantleClientRegistry.registerManualSmallRecipe("gloveclimb", gloves.copy(), new ItemStack(Items.slime_ball), new ItemStack(Blocks.web), new ItemStack(TinkerTools.materials, 1, 25), null);
TConstructClientRegistry.registerManualModifier("gloveknuckles", gloves.copy(), new ItemStack(Items.quartz), new ItemStack(Blocks.quartz_block, 1, Short.MAX_VALUE));
}
@Override
protected void registerGuiHandler ()
{
super.registerGuiHandler();
TProxyCommon.registerClientGuiHandler(inventoryGui, this);
TProxyCommon.registerClientGuiHandler(armorGuiID, this);
TProxyCommon.registerClientGuiHandler(knapsackGuiID, this);
}
@Override
public Object getClientGuiElement (int ID, EntityPlayer player, World world, int x, int y, int z)
{
if (ID == ArmorProxyCommon.inventoryGui)
{
GuiInventory inventory = new GuiInventory(player);
return inventory;
}
if (ID == ArmorProxyCommon.armorGuiID)
{
ArmorProxyClient.armorExtended.init(Minecraft.getMinecraft().thePlayer);
return new ArmorExtendedGui(player.inventory, ArmorProxyClient.armorExtended);
}
if (ID == ArmorProxyCommon.knapsackGuiID)
{
ArmorProxyClient.knapsack.init(Minecraft.getMinecraft().thePlayer);
return new KnapsackGui(player.inventory, ArmorProxyClient.knapsack);
}
return null;
}
@Override
public void registerTickHandler ()
{
FMLCommonHandler.instance().bus().register(new ArmorTickHandler());
}
/* Keybindings */
public static TControls controlInstance;
@Override
public void registerKeys ()
{
controlInstance = new TControls();
uploadKeyBindingsToGame(Minecraft.getMinecraft().gameSettings, controlInstance);
TabRegistry.registerTab(new InventoryTabVanilla());
TabRegistry.registerTab(new InventoryTabArmorExtended());
TabRegistry.registerTab(new InventoryTabKnapsack());
}
public void uploadKeyBindingsToGame (GameSettings settings, TKeyHandler keyhandler)
{
ArrayList<KeyBinding> harvestedBindings = Lists.newArrayList();
for (KeyBinding kb : keyhandler.keyBindings)
{
harvestedBindings.add(kb);
}
KeyBinding[] modKeyBindings = harvestedBindings.toArray(new KeyBinding[harvestedBindings.size()]);
KeyBinding[] allKeys = new KeyBinding[settings.keyBindings.length + modKeyBindings.length];
System.arraycopy(settings.keyBindings, 0, allKeys, 0, settings.keyBindings.length);
System.arraycopy(modKeyBindings, 0, allKeys, settings.keyBindings.length, modKeyBindings.length);
settings.keyBindings = allKeys;
settings.loadOptions();
}
Minecraft mc = Minecraft.getMinecraft();
private static final ResourceLocation hearts = new ResourceLocation("tinker", "textures/gui/newhearts.png");
private static final ResourceLocation icons = new ResourceLocation("textures/gui/icons.png");
// public static int left_height = 39;
// public static int right_height = 39;
Random rand = new Random();
int updateCounter = 0;
GameSettings gs = Minecraft.getMinecraft().gameSettings;
@SubscribeEvent
public void goggleZoom (FOVUpdateEvent event)
{
if (TControls.zoom)
{
ItemStack helmet = event.entity.getCurrentArmor(3);
if (helmet != null && helmet.getItem() instanceof TravelGear)
{
event.newfov = 0.3f;
}
}
//ItemStack feet = player.getCurrentArmor(0);
//event.newfov = 1.0f;
}
/* HUD */
@SubscribeEvent
public void renderHealthbar (RenderGameOverlayEvent.Pre event)
{
- if (!Loader.isModLoaded("tukmc_Vz"))// Loader check to avoid conflicting
+ if (!Loader.isModLoaded("tukmc_Vz") || Loader.isModLoaded("borderlands"))// Loader check to avoid conflicting
// with a GUI mod (thanks Vazkii!)
{
if (event.type == ElementType.HEALTH)
{
updateCounter++;
ScaledResolution scaledresolution = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight);
int scaledWidth = scaledresolution.getScaledWidth();
int scaledHeight = scaledresolution.getScaledHeight();
int xBasePos = scaledWidth / 2 - 91;
int yBasePos = scaledHeight - 39;
boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1;
if (mc.thePlayer.hurtResistantTime < 10)
{
highlight = false;
}
IAttributeInstance attrMaxHealth = this.mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth);
int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth());
int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth);
float healthMax = (float) attrMaxHealth.getAttributeValue();
if (healthMax > 20)
healthMax = 20;
float absorb = this.mc.thePlayer.getAbsorptionAmount();
int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F);
int rowHeight = Math.max(10 - (healthRows - 2), 3);
this.rand.setSeed((long) (updateCounter * 312871));
int left = scaledWidth / 2 - 91;
int top = scaledHeight - GuiIngameForge.left_height;
int regen = -1;
if (mc.thePlayer.isPotionActive(Potion.regeneration))
{
regen = updateCounter % 25;
}
final int TOP = 9 * (mc.theWorld.getWorldInfo().isHardcoreModeEnabled() ? 5 : 0);
final int BACKGROUND = (highlight ? 25 : 16);
int MARGIN = 16;
if (mc.thePlayer.isPotionActive(Potion.poison))
MARGIN += 36;
else if (mc.thePlayer.isPotionActive(Potion.wither))
MARGIN += 72;
float absorbRemaining = absorb;
for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i)
{
int b0 = (highlight ? 1 : 0);
int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1;
int x = left + i % 10 * 8;
int y = top - row * rowHeight;
if (health <= 4)
y += rand.nextInt(2);
if (i == regen)
y -= 2;
drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9);
if (highlight)
{
if (i * 2 + 1 < healthLast)
drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // 6
else if (i * 2 + 1 == healthLast)
drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // 7
}
if (absorbRemaining > 0.0F)
{
if (absorbRemaining == absorb && absorb % 2.0F == 1.0F)
drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // 17
else
drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // 16
absorbRemaining -= 2.0F;
}
else
{
if (i * 2 + 1 < health)
drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // 4
else if (i * 2 + 1 == health)
drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // 5
}
}
+ int potionOffset = 0;
PotionEffect potion = mc.thePlayer.getActivePotionEffect(Potion.wither);
if (potion != null)
- return;
+ potionOffset = 18;
potion = mc.thePlayer.getActivePotionEffect(Potion.poison);
if (potion != null)
- return;
+ potionOffset = 9;
// Extra hearts
this.mc.getTextureManager().bindTexture(hearts);
int hp = MathHelper.ceiling_float_int(this.mc.thePlayer.getHealth());
for (int iter = 0; iter < hp / 20; iter++)
{
int renderHearts = (hp - 20 * (iter + 1)) / 2;
if (renderHearts > 10)
renderHearts = 10;
for (int i = 0; i < renderHearts; i++)
{
- this.drawTexturedModalRect(xBasePos + 8 * i, yBasePos, 0 + 18 * iter, 0, 8, 8);
+ int y = 0;
+ if (i == regen)
+ y -= 2;
+ this.drawTexturedModalRect(xBasePos + 8 * i, yBasePos + y, 0 + 18 * iter, potionOffset, 9, 9);
}
if (hp % 2 == 1 && renderHearts < 10)
{
- this.drawTexturedModalRect(xBasePos + 8 * renderHearts, yBasePos, 9 + 18 * iter, 0, 8, 8);
+ this.drawTexturedModalRect(xBasePos + 8 * renderHearts, yBasePos, 9 + 18 * iter, potionOffset, 9, 9);
}
}
this.mc.getTextureManager().bindTexture(icons);
GuiIngameForge.left_height += 10;
if (absorb > 0)
GuiIngameForge.left_height += 10;
event.setCanceled(true);
if (event.type == ElementType.CROSSHAIRS && gs.thirdPersonView != 0)
{
event.setCanceled(true);
}
}
}
}
public void drawTexturedModalRect (int par1, int par2, int par3, int par4, int par5, int par6)
{
float f = 0.00390625F;
float f1 = 0.00390625F;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double) (par1 + 0), (double) (par2 + par6), (double) this.zLevel, (double) ((float) (par3 + 0) * f), (double) ((float) (par4 + par6) * f1));
tessellator.addVertexWithUV((double) (par1 + par5), (double) (par2 + par6), (double) this.zLevel, (double) ((float) (par3 + par5) * f), (double) ((float) (par4 + par6) * f1));
tessellator.addVertexWithUV((double) (par1 + par5), (double) (par2 + 0), (double) this.zLevel, (double) ((float) (par3 + par5) * f), (double) ((float) (par4 + 0) * f1));
tessellator.addVertexWithUV((double) (par1 + 0), (double) (par2 + 0), (double) this.zLevel, (double) ((float) (par3 + 0) * f), (double) ((float) (par4 + 0) * f1));
tessellator.draw();
}
double zLevel = 0;
/* Armor rendering */
@SubscribeEvent
public void adjustArmor (RenderPlayerEvent.SetArmorModel event)
{
switch (event.slot)
{
case 1:
ArmorProxyClient.vest.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.vest.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.vest.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.vest.isSneak = event.renderer.modelBipedMain.isSneak;
case 2:
ArmorProxyClient.wings.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.wings.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.wings.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.wings.isSneak = event.renderer.modelBipedMain.isSneak;
ArmorProxyClient.glove.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.glove.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.glove.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.glove.isSneak = event.renderer.modelBipedMain.isSneak;
ArmorProxyClient.glove.heldItemLeft = event.renderer.modelBipedMain.heldItemLeft;
ArmorProxyClient.glove.heldItemRight = event.renderer.modelBipedMain.heldItemRight;
ArmorProxyClient.belt.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.belt.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.belt.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.belt.isSneak = event.renderer.modelBipedMain.isSneak;
renderArmorExtras(event);
break;
case 3:
ArmorProxyClient.bootbump.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.bootbump.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.bootbump.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.bootbump.isSneak = event.renderer.modelBipedMain.isSneak;
break;
}
}
void renderArmorExtras (RenderPlayerEvent.SetArmorModel event)
{
float partialTick = event.partialRenderTick;
EntityPlayer player = event.entityPlayer;
float posX = (float) (player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTick);
float posY = (float) (player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTick);
float posZ = (float) (player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTick);
float yawOffset = this.interpolateRotation(player.prevRenderYawOffset, player.renderYawOffset, partialTick);
float yawRotation = this.interpolateRotation(player.prevRotationYawHead, player.rotationYawHead, partialTick);
float pitch;
final float zeropointsixtwofive = 0.0625F;
if (player.isRiding() && player.ridingEntity instanceof EntityLivingBase)
{
EntityLivingBase entitylivingbase1 = (EntityLivingBase) player.ridingEntity;
yawOffset = this.interpolateRotation(entitylivingbase1.prevRenderYawOffset, entitylivingbase1.renderYawOffset, partialTick);
pitch = MathHelper.wrapAngleTo180_float(yawRotation - yawOffset);
if (pitch < -85.0F)
{
pitch = -85.0F;
}
if (pitch >= 85.0F)
{
pitch = 85.0F;
}
yawOffset = yawRotation - pitch;
if (pitch * pitch > 2500.0F)
{
yawOffset += pitch * 0.2F;
}
}
pitch = this.handleRotationFloat(player, partialTick);
float bodyRotation = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * partialTick;
float limbSwing = player.prevLimbSwingAmount + (player.limbSwingAmount - player.prevLimbSwingAmount) * partialTick;
float limbSwingMod = player.limbSwing - player.limbSwingAmount * (1.0F - partialTick);
//TPlayerStats stats = TPlayerStats.get(player);
ArmorExtended armor = ArmorProxyClient.armorExtended; //TODO: Do this for every player, not just the client
if (armor.inventory[1] != null)
{
Item item = armor.inventory[1].getItem();
ModelBiped model = item.getArmorModel(player, armor.inventory[1], 4);
if (item instanceof IAccessoryModel)
{
this.mc.getTextureManager().bindTexture(((IAccessoryModel) item).getWearbleTexture(player, armor.inventory[1], 1));
model.setLivingAnimations(player, limbSwingMod, limbSwing, partialTick);
model.render(player, limbSwingMod, limbSwing, pitch, yawRotation - yawOffset, bodyRotation, zeropointsixtwofive);
}
}
if (armor.inventory[3] != null)
{
Item item = armor.inventory[3].getItem();
ModelBiped model = item.getArmorModel(player, armor.inventory[3], 5);
if (item instanceof IAccessoryModel)
{
this.mc.getTextureManager().bindTexture(((IAccessoryModel) item).getWearbleTexture(player, armor.inventory[1], 1));
model.setLivingAnimations(player, limbSwingMod, limbSwing, partialTick);
model.render(player, limbSwingMod, limbSwing, pitch, yawRotation - yawOffset, bodyRotation, zeropointsixtwofive);
}
}
}
private float interpolateRotation (float par1, float par2, float par3)
{
float f3;
for (f3 = par2 - par1; f3 < -180.0F; f3 += 360.0F)
{
;
}
while (f3 >= 180.0F)
{
f3 -= 360.0F;
}
return par1 + par3 * f3;
}
protected float handleRotationFloat (EntityLivingBase par1EntityLivingBase, float par2)
{
return (float) par1EntityLivingBase.ticksExisted + par2;
}
}
| false | true | public void renderHealthbar (RenderGameOverlayEvent.Pre event)
{
if (!Loader.isModLoaded("tukmc_Vz"))// Loader check to avoid conflicting
// with a GUI mod (thanks Vazkii!)
{
if (event.type == ElementType.HEALTH)
{
updateCounter++;
ScaledResolution scaledresolution = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight);
int scaledWidth = scaledresolution.getScaledWidth();
int scaledHeight = scaledresolution.getScaledHeight();
int xBasePos = scaledWidth / 2 - 91;
int yBasePos = scaledHeight - 39;
boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1;
if (mc.thePlayer.hurtResistantTime < 10)
{
highlight = false;
}
IAttributeInstance attrMaxHealth = this.mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth);
int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth());
int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth);
float healthMax = (float) attrMaxHealth.getAttributeValue();
if (healthMax > 20)
healthMax = 20;
float absorb = this.mc.thePlayer.getAbsorptionAmount();
int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F);
int rowHeight = Math.max(10 - (healthRows - 2), 3);
this.rand.setSeed((long) (updateCounter * 312871));
int left = scaledWidth / 2 - 91;
int top = scaledHeight - GuiIngameForge.left_height;
int regen = -1;
if (mc.thePlayer.isPotionActive(Potion.regeneration))
{
regen = updateCounter % 25;
}
final int TOP = 9 * (mc.theWorld.getWorldInfo().isHardcoreModeEnabled() ? 5 : 0);
final int BACKGROUND = (highlight ? 25 : 16);
int MARGIN = 16;
if (mc.thePlayer.isPotionActive(Potion.poison))
MARGIN += 36;
else if (mc.thePlayer.isPotionActive(Potion.wither))
MARGIN += 72;
float absorbRemaining = absorb;
for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i)
{
int b0 = (highlight ? 1 : 0);
int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1;
int x = left + i % 10 * 8;
int y = top - row * rowHeight;
if (health <= 4)
y += rand.nextInt(2);
if (i == regen)
y -= 2;
drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9);
if (highlight)
{
if (i * 2 + 1 < healthLast)
drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // 6
else if (i * 2 + 1 == healthLast)
drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // 7
}
if (absorbRemaining > 0.0F)
{
if (absorbRemaining == absorb && absorb % 2.0F == 1.0F)
drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // 17
else
drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // 16
absorbRemaining -= 2.0F;
}
else
{
if (i * 2 + 1 < health)
drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // 4
else if (i * 2 + 1 == health)
drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // 5
}
}
PotionEffect potion = mc.thePlayer.getActivePotionEffect(Potion.wither);
if (potion != null)
return;
potion = mc.thePlayer.getActivePotionEffect(Potion.poison);
if (potion != null)
return;
// Extra hearts
this.mc.getTextureManager().bindTexture(hearts);
int hp = MathHelper.ceiling_float_int(this.mc.thePlayer.getHealth());
for (int iter = 0; iter < hp / 20; iter++)
{
int renderHearts = (hp - 20 * (iter + 1)) / 2;
if (renderHearts > 10)
renderHearts = 10;
for (int i = 0; i < renderHearts; i++)
{
this.drawTexturedModalRect(xBasePos + 8 * i, yBasePos, 0 + 18 * iter, 0, 8, 8);
}
if (hp % 2 == 1 && renderHearts < 10)
{
this.drawTexturedModalRect(xBasePos + 8 * renderHearts, yBasePos, 9 + 18 * iter, 0, 8, 8);
}
}
this.mc.getTextureManager().bindTexture(icons);
GuiIngameForge.left_height += 10;
if (absorb > 0)
GuiIngameForge.left_height += 10;
event.setCanceled(true);
if (event.type == ElementType.CROSSHAIRS && gs.thirdPersonView != 0)
{
event.setCanceled(true);
}
}
}
}
| public void renderHealthbar (RenderGameOverlayEvent.Pre event)
{
if (!Loader.isModLoaded("tukmc_Vz") || Loader.isModLoaded("borderlands"))// Loader check to avoid conflicting
// with a GUI mod (thanks Vazkii!)
{
if (event.type == ElementType.HEALTH)
{
updateCounter++;
ScaledResolution scaledresolution = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight);
int scaledWidth = scaledresolution.getScaledWidth();
int scaledHeight = scaledresolution.getScaledHeight();
int xBasePos = scaledWidth / 2 - 91;
int yBasePos = scaledHeight - 39;
boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1;
if (mc.thePlayer.hurtResistantTime < 10)
{
highlight = false;
}
IAttributeInstance attrMaxHealth = this.mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth);
int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth());
int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth);
float healthMax = (float) attrMaxHealth.getAttributeValue();
if (healthMax > 20)
healthMax = 20;
float absorb = this.mc.thePlayer.getAbsorptionAmount();
int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F);
int rowHeight = Math.max(10 - (healthRows - 2), 3);
this.rand.setSeed((long) (updateCounter * 312871));
int left = scaledWidth / 2 - 91;
int top = scaledHeight - GuiIngameForge.left_height;
int regen = -1;
if (mc.thePlayer.isPotionActive(Potion.regeneration))
{
regen = updateCounter % 25;
}
final int TOP = 9 * (mc.theWorld.getWorldInfo().isHardcoreModeEnabled() ? 5 : 0);
final int BACKGROUND = (highlight ? 25 : 16);
int MARGIN = 16;
if (mc.thePlayer.isPotionActive(Potion.poison))
MARGIN += 36;
else if (mc.thePlayer.isPotionActive(Potion.wither))
MARGIN += 72;
float absorbRemaining = absorb;
for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i)
{
int b0 = (highlight ? 1 : 0);
int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1;
int x = left + i % 10 * 8;
int y = top - row * rowHeight;
if (health <= 4)
y += rand.nextInt(2);
if (i == regen)
y -= 2;
drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9);
if (highlight)
{
if (i * 2 + 1 < healthLast)
drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // 6
else if (i * 2 + 1 == healthLast)
drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // 7
}
if (absorbRemaining > 0.0F)
{
if (absorbRemaining == absorb && absorb % 2.0F == 1.0F)
drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // 17
else
drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // 16
absorbRemaining -= 2.0F;
}
else
{
if (i * 2 + 1 < health)
drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // 4
else if (i * 2 + 1 == health)
drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // 5
}
}
int potionOffset = 0;
PotionEffect potion = mc.thePlayer.getActivePotionEffect(Potion.wither);
if (potion != null)
potionOffset = 18;
potion = mc.thePlayer.getActivePotionEffect(Potion.poison);
if (potion != null)
potionOffset = 9;
// Extra hearts
this.mc.getTextureManager().bindTexture(hearts);
int hp = MathHelper.ceiling_float_int(this.mc.thePlayer.getHealth());
for (int iter = 0; iter < hp / 20; iter++)
{
int renderHearts = (hp - 20 * (iter + 1)) / 2;
if (renderHearts > 10)
renderHearts = 10;
for (int i = 0; i < renderHearts; i++)
{
int y = 0;
if (i == regen)
y -= 2;
this.drawTexturedModalRect(xBasePos + 8 * i, yBasePos + y, 0 + 18 * iter, potionOffset, 9, 9);
}
if (hp % 2 == 1 && renderHearts < 10)
{
this.drawTexturedModalRect(xBasePos + 8 * renderHearts, yBasePos, 9 + 18 * iter, potionOffset, 9, 9);
}
}
this.mc.getTextureManager().bindTexture(icons);
GuiIngameForge.left_height += 10;
if (absorb > 0)
GuiIngameForge.left_height += 10;
event.setCanceled(true);
if (event.type == ElementType.CROSSHAIRS && gs.thirdPersonView != 0)
{
event.setCanceled(true);
}
}
}
}
|
diff --git a/deployers-impl/src/main/org/jboss/deployers/plugins/main/MainDeployerImpl.java b/deployers-impl/src/main/org/jboss/deployers/plugins/main/MainDeployerImpl.java
index 31b0a765..909b9826 100644
--- a/deployers-impl/src/main/org/jboss/deployers/plugins/main/MainDeployerImpl.java
+++ b/deployers-impl/src/main/org/jboss/deployers/plugins/main/MainDeployerImpl.java
@@ -1,842 +1,842 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.deployers.plugins.main;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.jboss.deployers.client.spi.Deployment;
import org.jboss.deployers.client.spi.main.MainDeployer;
import org.jboss.deployers.spi.DeploymentException;
import org.jboss.deployers.spi.DeploymentState;
import org.jboss.deployers.spi.deployer.Deployers;
import org.jboss.deployers.spi.deployer.managed.ManagedDeploymentCreator;
import org.jboss.deployers.structure.spi.DeploymentContext;
import org.jboss.deployers.structure.spi.DeploymentUnit;
import org.jboss.deployers.structure.spi.StructuralDeployers;
import org.jboss.deployers.structure.spi.main.MainDeployerStructure;
import org.jboss.logging.Logger;
import org.jboss.managed.api.ManagedDeployment;
import org.jboss.managed.api.ManagedObject;
import org.jboss.util.graph.Graph;
import org.jboss.util.graph.Vertex;
/**
* MainDeployerImpl.
*
* @author <a href="[email protected]">Adrian Brock</a>
* @author <a href="[email protected]">Scott Stark</a>
* @author <a href="[email protected]">Ales Justin</a>
* @version $Revision$
*/
public class MainDeployerImpl implements MainDeployer, MainDeployerStructure
{
/** The log */
private static final Logger log = Logger.getLogger(MainDeployerImpl.class);
/** Whether we are shutdown */
private AtomicBoolean shutdown = new AtomicBoolean(false);
/** The deployers */
private Deployers deployers;
/** The structural deployers */
private StructuralDeployers structuralDeployers;
/** The ManagedDeploymentCreator plugin */
private ManagedDeploymentCreator mgtDeploymentCreator = null;
/** The deployments by name */
private Map<String, DeploymentContext> topLevelDeployments = new ConcurrentHashMap<String, DeploymentContext>();
/** All deployments by name */
private Map<String, DeploymentContext> allDeployments = new ConcurrentHashMap<String, DeploymentContext>();
/** Deployments in error by name */
private Map<String, DeploymentContext> errorDeployments = new ConcurrentHashMap<String, DeploymentContext>();
/** Deployments missing deployers */
private Map<String, Deployment> missingDeployers = new ConcurrentHashMap<String, Deployment>();
/** The undeploy work */
private List<DeploymentContext> undeploy = new CopyOnWriteArrayList<DeploymentContext>();
/** The deploy work */
private List<DeploymentContext> deploy = new CopyOnWriteArrayList<DeploymentContext>();
/** The process lock */
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
/**
* Get the deployers
*
* @return the deployers
*/
public synchronized Deployers getDeployers()
{
return deployers;
}
/**
* Set the deployers
*
* @param deployers the deployers
* @throws IllegalArgumentException for null deployers
*/
public synchronized void setDeployers(Deployers deployers)
{
if (deployers == null)
throw new IllegalArgumentException("Null deployers");
this.deployers = deployers;
}
/**
* Get the structural deployers
*
* @return the structural deployers
*/
public synchronized StructuralDeployers getStructuralDeployers()
{
return structuralDeployers;
}
/**
* Set the structural deployers
*
* @param deployers the deployers
* @throws IllegalArgumentException for null deployers
*/
public synchronized void setStructuralDeployers(StructuralDeployers deployers)
{
if (deployers == null)
throw new IllegalArgumentException("Null deployers");
structuralDeployers = deployers;
}
public ManagedDeploymentCreator getMgtDeploymentCreator()
{
return mgtDeploymentCreator;
}
public void setMgtDeploymentCreator(ManagedDeploymentCreator mgtDeploymentCreator)
{
this.mgtDeploymentCreator = mgtDeploymentCreator;
}
public Deployment getDeployment(String name)
{
DeploymentContext context = getTopLevelDeploymentContext(name);
if (context == null)
return null;
return context.getDeployment();
}
public DeploymentContext getDeploymentContext(String name)
{
if (name == null)
throw new IllegalArgumentException("Null name");
return allDeployments.get(name);
}
public DeploymentContext getDeploymentContext(String name, boolean errorNotFound) throws DeploymentException
{
DeploymentContext context = getDeploymentContext(name);
if (errorNotFound && context == null)
throw new DeploymentException("Context " + name + " not found");
return context;
}
public DeploymentUnit getDeploymentUnit(String name)
{
DeploymentContext context = getDeploymentContext(name);
if (context == null)
return null;
return context.getDeploymentUnit();
}
public DeploymentUnit getDeploymentUnit(String name, boolean errorNotFound) throws DeploymentException
{
DeploymentUnit unit = getDeploymentUnit(name);
if (errorNotFound && unit == null)
throw new DeploymentException("Unit " + name + " not found");
return unit;
}
/**
* Get a top level deployment context by name
*
* @param name the name
* @return the context
*/
public DeploymentContext getTopLevelDeploymentContext(String name)
{
if (name == null)
throw new IllegalArgumentException("Null name");
return topLevelDeployments.get(name);
}
public Collection<DeploymentContext> getAll()
{
return Collections.unmodifiableCollection(allDeployments.values());
}
public Collection<DeploymentContext> getErrors()
{
return Collections.unmodifiableCollection(errorDeployments.values());
}
public Collection<Deployment> getMissingDeployer()
{
return Collections.unmodifiableCollection(missingDeployers.values());
}
public Collection<Deployment> getTopLevel()
{
List<Deployment> result = new ArrayList<Deployment>();
for (DeploymentContext context : topLevelDeployments.values())
{
Deployment deployment = context.getDeployment();
if (deployment != null)
result.add(deployment);
else
throw new IllegalStateException("Context has no deployment? " + context.getName());
}
return result;
}
public void addDeployment(Deployment deployment) throws DeploymentException
{
addDeployment(deployment, true);
}
/**
* Add a deployment
*
* @param deployment the deployment
* @param addToDeploy should we add this deployment to deploy collection
* @throws DeploymentException for any error
*/
protected void addDeployment(Deployment deployment, boolean addToDeploy) throws DeploymentException
{
if (deployment == null)
throw new DeploymentException("Null context");
lockRead();
try
{
if (shutdown.get())
throw new DeploymentException("The main deployer is shutdown");
String name = deployment.getName();
log.debug("Add deployment: " + name);
DeploymentContext previous = topLevelDeployments.get(name);
boolean topLevelFound = false;
if (previous != null)
{
log.debug("Removing previous deployment: " + previous.getName());
removeContext(previous, addToDeploy);
topLevelFound = true;
}
if (topLevelFound == false)
{
previous = allDeployments.get(name);
if (previous != null)
throw new IllegalStateException("Deployment already exists as a subdeployment: " + name);
}
DeploymentContext context = null;
try
{
context = determineStructure(deployment);
if (DeploymentState.ERROR.equals(context.getState()))
errorDeployments.put(name, context);
topLevelDeployments.put(name, context);
addContext(context, addToDeploy);
}
catch (DeploymentException e)
{
missingDeployers.put(name, deployment);
throw e;
}
catch (Throwable t)
{
// was structure determined?
- if (context != null)
+ if (context == null)
missingDeployers.put(name, deployment);
throw DeploymentException.rethrowAsDeploymentException("Error determining deployment structure for " + name, t);
}
}
finally
{
unlockRead();
}
}
public boolean removeDeployment(Deployment deployment) throws DeploymentException
{
return removeDeployment(deployment, true);
}
/**
* Remove a deployment by name
*
* @param deployment thedeployment
* @param addToUndeploy should we add to undeploy collection
* @return false when the context was previously unknown
* @throws DeploymentException for any error
*/
protected boolean removeDeployment(Deployment deployment, boolean addToUndeploy) throws DeploymentException
{
if (deployment == null)
throw new DeploymentException("Null deployment");
return removeDeployment(deployment.getName(), addToUndeploy);
}
public boolean removeDeployment(String name) throws DeploymentException
{
return removeDeployment(name, true);
}
/**
* Remove a deployment by name
*
* @param name the name of the deployment
* @param addToUndeploy should we add to undeploy collection
* @return false when the context was previously unknown
* @throws DeploymentException for any error
*/
protected boolean removeDeployment(String name, boolean addToUndeploy) throws DeploymentException
{
if (name == null)
throw new DeploymentException("Null name");
lockRead();
try
{
if (shutdown.get())
throw new IllegalStateException("The main deployer is shutdown");
log.debug("Remove deployment context: " + name);
DeploymentContext context = topLevelDeployments.remove(name);
if (context == null)
return false;
removeContext(context, addToUndeploy);
return true;
}
finally
{
unlockRead();
}
}
public void deploy(Deployment... deployments) throws DeploymentException
{
if (deployments == null)
throw new IllegalArgumentException("Null deployments.");
lockRead();
try
{
if (shutdown.get())
throw new IllegalStateException("The main deployer is shutdown");
DeploymentContext[] contexts = new DeploymentContext[deployments.length];
for(int i = 0; i < deployments.length; i++)
{
try
{
addDeployment(deployments[i], false);
DeploymentContext context = getDeploymentContext(deployments[i].getName(), true);
deployers.process(Collections.singletonList(context), null);
contexts[i] = context;
}
catch(Throwable t)
{
DeploymentContext[] deployedContexts = new DeploymentContext[i];
System.arraycopy(contexts, 0, deployedContexts, 0, i);
deployers.process(null, Arrays.asList(deployedContexts));
throw DeploymentException.rethrowAsDeploymentException("Unable to deploy deployments.", t);
}
}
try
{
deployers.checkComplete(contexts);
}
catch (DeploymentException e)
{
deployers.process(null, Arrays.asList(contexts));
throw e;
}
}
finally
{
unlockRead();
}
}
public void undeploy(Deployment... deployments) throws DeploymentException
{
if (deployments == null)
throw new IllegalArgumentException("Null deployments.");
lockRead();
try
{
if (shutdown.get())
throw new IllegalStateException("The main deployer is shutdown");
for(Deployment deployment : deployments)
{
DeploymentContext context = getDeploymentContext(deployment.getName());
if (context != null)
{
try
{
removeDeployment(deployment, false);
deployers.process(null, Collections.singletonList(context));
}
catch (DeploymentException e)
{
if (log.isTraceEnabled())
log.trace("Ignored exception while undeploying deployment " + deployment.getName() + ":" + e);
}
}
else if (log.isTraceEnabled())
{
log.trace("No such deployment present: " + deployment.getName());
}
}
}
finally
{
unlockRead();
}
}
public void undeploy(String... names) throws DeploymentException
{
if (names == null)
throw new IllegalArgumentException("Null names.");
List<Deployment> deployments = new ArrayList<Deployment>();
for(String name : names)
{
DeploymentContext context = getDeploymentContext(name);
if (context != null)
deployments.add(context.getDeployment());
else if (log.isTraceEnabled())
log.trace("No such deployment present: " + name);
}
if (deployments.isEmpty() == false)
undeploy(deployments.toArray(new Deployment[deployments.size()]));
}
public void process()
{
lockRead();
try
{
if (shutdown.get())
throw new IllegalStateException("The main deployer is shutdown");
List<DeploymentContext> undeployContexts = null;
List<DeploymentContext> deployContexts = null;
if (deployers == null)
throw new IllegalStateException("No deployers");
if (undeploy.isEmpty() == false)
{
// Undeploy in reverse order (subdeployments first)
undeployContexts = new ArrayList<DeploymentContext>(undeploy.size());
for (int i = undeploy.size() - 1; i >= 0; --i)
undeployContexts.add(undeploy.get(i));
undeploy.clear();
}
if (deploy.isEmpty() == false)
{
deployContexts = new ArrayList<DeploymentContext>(deploy);
deploy.clear();
}
if (undeployContexts == null && deployContexts == null)
{
log.debug("Asked to process() when there is nothing to do.");
return;
}
try
{
deployers.process(deployContexts, undeployContexts);
}
catch (RuntimeException e)
{
throw e;
}
catch (Error e)
{
throw e;
}
catch (Throwable t)
{
throw new RuntimeException("Unexpected error in process()", t);
}
}
finally
{
unlockRead();
}
}
// enable locking - so that we don't pick up current single deployments
public void shutdown()
{
lockWrite();
try
{
while (topLevelDeployments.isEmpty() == false)
{
// Remove all the contexts
for (DeploymentContext context : topLevelDeployments.values())
{
topLevelDeployments.remove(context.getName());
removeContext(context, true);
}
// Do it
process();
}
shutdown.set(true);
}
finally
{
unlockWrite();
}
}
public void checkComplete() throws DeploymentException
{
if (deployers == null)
throw new IllegalStateException("Null deployers");
deployers.checkComplete(errorDeployments.values(), missingDeployers.values());
}
/**
* Get the names from deployments.
*
* @param deployments the deployments
* @return depolyment names
*/
protected static String[] getDeploymentNames(Deployment... deployments)
{
if (deployments == null)
throw new IllegalArgumentException("Null deployments");
String[] names = new String[deployments.length];
for(int i = 0; i < deployments.length; i++)
{
if (deployments[i] == null)
throw new IllegalArgumentException("Null deployment: " + i);
names[i] = deployments[i].getName();
}
return names;
}
/**
* Get the deployment contexts.
*
* @param names the deployment names
* @return depolyment contexts
* @throws DeploymentException if context is not found
*/
protected DeploymentContext[] getDeploymentContexts(String... names) throws DeploymentException
{
if (names == null)
throw new IllegalArgumentException("Null names");
DeploymentContext[] contexts = new DeploymentContext[names.length];
for(int i = 0; i < names.length; i++)
contexts[i] = getDeploymentContext(names[i], true);
return contexts;
}
public void checkComplete(Deployment... deployments) throws DeploymentException
{
if (deployments == null)
throw new IllegalArgumentException("Null deployments");
checkComplete(getDeploymentNames(deployments));
}
public void checkComplete(String... names) throws DeploymentException
{
if (names == null)
throw new IllegalArgumentException("Null names");
if (deployers == null)
throw new IllegalStateException("Null deployers");
deployers.checkComplete(getDeploymentContexts(names));
}
public void checkStructureComplete(Deployment... deployments) throws DeploymentException
{
if (deployments == null)
throw new IllegalArgumentException("Null deployments");
checkStructureComplete(getDeploymentNames(deployments));
}
public void checkStructureComplete(String... names) throws DeploymentException
{
if (names == null)
throw new IllegalArgumentException("Null names");
if (deployers == null)
throw new IllegalStateException("Null deployers");
deployers.checkStructureComplete(getDeploymentContexts(names));
}
public DeploymentState getDeploymentState(String name)
{
DeploymentContext context = getDeploymentContext(name);
if (context == null)
return DeploymentState.UNDEPLOYED;
return context.getState();
}
public ManagedDeployment getManagedDeployment(String name) throws DeploymentException
{
DeploymentContext context = getDeploymentContext(name, true);
Map<String, ManagedObject> rootMOs = getManagedObjects(context);
ManagedDeployment root = mgtDeploymentCreator.build(context.getDeploymentUnit(), rootMOs, null);
for (DeploymentContext childContext : context.getChildren())
{
processManagedDeployment(childContext, root);
}
return root;
}
public Map<String, ManagedObject> getManagedObjects(String name) throws DeploymentException
{
DeploymentContext context = getDeploymentContext(name, true);
return getManagedObjects(context);
}
public Map<String, ManagedObject> getManagedObjects(DeploymentContext context) throws DeploymentException
{
if (context == null)
throw new IllegalArgumentException("Null context");
if (deployers == null)
throw new IllegalStateException("No deployers");
return deployers.getManagedObjects(context);
}
public Graph<Map<String, ManagedObject>> getDeepManagedObjects(String name) throws DeploymentException
{
DeploymentContext context = getDeploymentContext(name);
Graph<Map<String, ManagedObject>> managedObjectsGraph = new Graph<Map<String, ManagedObject>>();
Vertex<Map<String, ManagedObject>> parent = new Vertex<Map<String, ManagedObject>>(context.getName());
managedObjectsGraph.setRootVertex(parent);
Map<String, ManagedObject> managedObjects = getManagedObjects(context);
parent.setData(managedObjects);
processManagedObjects(context, managedObjectsGraph, parent);
return managedObjectsGraph;
}
/**
* Get the managed objects for a context
*
* @param context the context
* @param graph the graph
* @param parent the parent node
* @throws DeploymentException for any problem
*/
protected void processManagedObjects(DeploymentContext context, Graph<Map<String, ManagedObject>> graph, Vertex<Map<String, ManagedObject>> parent)
throws DeploymentException
{
List<DeploymentContext> children = context.getChildren();
for(DeploymentContext child : children)
{
Vertex<Map<String, ManagedObject>> vertex = new Vertex<Map<String, ManagedObject>>(child.getName());
Map<String, ManagedObject> managedObjects = getManagedObjects(context);
vertex.setData(managedObjects);
graph.addEdge(parent, vertex, 0);
processManagedObjects(child, graph, vertex);
}
}
/**
* Recursively process the DeploymentContext into ManagedDeployments.
*
* @param context the context
* @param parent the parent
* @throws DeploymentException for any error
*/
protected void processManagedDeployment(DeploymentContext context, ManagedDeployment parent)
throws DeploymentException
{
DeploymentUnit unit = context.getDeploymentUnit();
Map<String, ManagedObject> MOs = getManagedObjects(context);
ManagedDeployment md = mgtDeploymentCreator.build(unit, MOs, parent);
for (DeploymentContext childContext : context.getChildren())
{
processManagedDeployment(childContext, md);
}
}
/**
* Determine the structure of a deployment
*
* @param deployment the deployment
* @return the deployment context
* @throws DeploymentException for an error determining the deployment structure
*/
private DeploymentContext determineStructure(Deployment deployment) throws DeploymentException
{
StructuralDeployers structuralDeployers = getStructuralDeployers();
if (structuralDeployers != null)
{
DeploymentContext result = structuralDeployers.determineStructure(deployment);
if (result != null)
return result;
}
throw new DeploymentException("No structural deployers.");
}
/**
* Add a context.
*
* @param context the context
* @param addToDeploy should we add to deploy collection
*/
private void addContext(DeploymentContext context, boolean addToDeploy)
{
allDeployments.put(context.getName(), context);
if (context.getState() == DeploymentState.ERROR)
{
log.debug("Not scheduling addition of context already in error: " + context.getName() + " reason=" + context.getProblem());
return;
}
context.setState(DeploymentState.DEPLOYING);
DeploymentContext parent = context.getParent();
log.debug("Scheduling deployment: " + context.getName() + " parent=" + parent);
// Process the top level only
if (context.isTopLevel() && addToDeploy)
deploy.add(context);
// Add all the children
List<DeploymentContext> children = context.getChildren();
if (children != null)
{
for (DeploymentContext child : children)
addContext(child, addToDeploy);
}
}
/**
* Remove a context
*
* @param context the context
* @param addToUndeploy add to undeploy collection
*/
private void removeContext(DeploymentContext context, boolean addToUndeploy)
{
String name = context.getName();
allDeployments.remove(name);
errorDeployments.remove(name);
missingDeployers.remove(name);
if (DeploymentState.ERROR.equals(context.getState()) == false)
context.setState(DeploymentState.UNDEPLOYING);
DeploymentContext parent = context.getParent();
log.debug("Scheduling undeployment: " + name + " parent=" + parent);
// Process the top level only
if (context.isTopLevel() && addToUndeploy)
undeploy.add(context);
// Remove all the children
List<DeploymentContext> children = context.getChildren();
if (children != null)
{
for (DeploymentContext child : children)
removeContext(child, addToUndeploy);
}
}
/**
* Lock for read
*/
protected void lockRead()
{
lock.readLock().lock();
}
/**
* Unlock for read
*/
protected void unlockRead()
{
lock.readLock().unlock();
}
/**
* Lock for write
*/
protected void lockWrite()
{
lock.writeLock().lock();
}
/**
* Unlock for write
*/
protected void unlockWrite()
{
lock.writeLock().unlock();
}
}
| true | true | protected void addDeployment(Deployment deployment, boolean addToDeploy) throws DeploymentException
{
if (deployment == null)
throw new DeploymentException("Null context");
lockRead();
try
{
if (shutdown.get())
throw new DeploymentException("The main deployer is shutdown");
String name = deployment.getName();
log.debug("Add deployment: " + name);
DeploymentContext previous = topLevelDeployments.get(name);
boolean topLevelFound = false;
if (previous != null)
{
log.debug("Removing previous deployment: " + previous.getName());
removeContext(previous, addToDeploy);
topLevelFound = true;
}
if (topLevelFound == false)
{
previous = allDeployments.get(name);
if (previous != null)
throw new IllegalStateException("Deployment already exists as a subdeployment: " + name);
}
DeploymentContext context = null;
try
{
context = determineStructure(deployment);
if (DeploymentState.ERROR.equals(context.getState()))
errorDeployments.put(name, context);
topLevelDeployments.put(name, context);
addContext(context, addToDeploy);
}
catch (DeploymentException e)
{
missingDeployers.put(name, deployment);
throw e;
}
catch (Throwable t)
{
// was structure determined?
if (context != null)
missingDeployers.put(name, deployment);
throw DeploymentException.rethrowAsDeploymentException("Error determining deployment structure for " + name, t);
}
}
finally
{
unlockRead();
}
}
| protected void addDeployment(Deployment deployment, boolean addToDeploy) throws DeploymentException
{
if (deployment == null)
throw new DeploymentException("Null context");
lockRead();
try
{
if (shutdown.get())
throw new DeploymentException("The main deployer is shutdown");
String name = deployment.getName();
log.debug("Add deployment: " + name);
DeploymentContext previous = topLevelDeployments.get(name);
boolean topLevelFound = false;
if (previous != null)
{
log.debug("Removing previous deployment: " + previous.getName());
removeContext(previous, addToDeploy);
topLevelFound = true;
}
if (topLevelFound == false)
{
previous = allDeployments.get(name);
if (previous != null)
throw new IllegalStateException("Deployment already exists as a subdeployment: " + name);
}
DeploymentContext context = null;
try
{
context = determineStructure(deployment);
if (DeploymentState.ERROR.equals(context.getState()))
errorDeployments.put(name, context);
topLevelDeployments.put(name, context);
addContext(context, addToDeploy);
}
catch (DeploymentException e)
{
missingDeployers.put(name, deployment);
throw e;
}
catch (Throwable t)
{
// was structure determined?
if (context == null)
missingDeployers.put(name, deployment);
throw DeploymentException.rethrowAsDeploymentException("Error determining deployment structure for " + name, t);
}
}
finally
{
unlockRead();
}
}
|
diff --git a/search/src/java/cz/incad/Kramerius/ViewInfoServlet.java b/search/src/java/cz/incad/Kramerius/ViewInfoServlet.java
index ec2b4b1ba..8936eb847 100644
--- a/search/src/java/cz/incad/Kramerius/ViewInfoServlet.java
+++ b/search/src/java/cz/incad/Kramerius/ViewInfoServlet.java
@@ -1,238 +1,238 @@
package cz.incad.Kramerius;
import static cz.incad.utils.IKeys.UUID_PARAMETER;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.antlr.stringtemplate.language.DefaultTemplateLexer;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import cz.incad.Kramerius.backend.guice.GuiceServlet;
import cz.incad.Kramerius.security.CurrentLoggedUserProvider;
import cz.incad.kramerius.FedoraAccess;
import cz.incad.kramerius.SolrAccess;
import cz.incad.kramerius.imaging.DeepZoomCacheService;
import cz.incad.kramerius.security.IsActionAllowed;
import cz.incad.kramerius.security.RightCriteriumContextFactory;
import cz.incad.kramerius.security.RightsManager;
import cz.incad.kramerius.security.SecuredActions;
import cz.incad.kramerius.security.SecurityException;
import cz.incad.kramerius.security.SpecialObjects;
import cz.incad.kramerius.security.User;
import cz.incad.kramerius.utils.IOUtils;
import cz.incad.kramerius.utils.conf.KConfiguration;
import cz.incad.kramerius.utils.solr.SolrUtils;
public class ViewInfoServlet extends GuiceServlet {
public static final java.util.logging.Logger LOGGER = java.util.logging.Logger
.getLogger(MimeTypeServlet.class.getName());
@Inject
@Named("rawFedoraAccess")
FedoraAccess fedoraAccess;
@Inject
SolrAccess solrAccess;
@Inject
DeepZoomCacheService deepZoomCacheService;
@Inject
IsActionAllowed actionAllowed;
@Inject
RightsManager rightsManager;
@Inject
RightCriteriumContextFactory ctxFactory;
@Inject
Provider<User> currentLoggedUserProvider;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
String uuid = req.getParameter(UUID_PARAMETER);
String[] pathOfUUIDs = this.solrAccess.getPathOfUUIDs(uuid);
User user = currentLoggedUserProvider.get();
if ((uuid != null) && (!uuid.equals(""))) {
String mimeType = this.fedoraAccess.getImageFULLMimeType(uuid);
boolean generated = resolutionFilePresent(uuid);
boolean conf = deepZoomConfigurationEnabled(uuid);
boolean hasAlto = this.fedoraAccess.isStreamAvailable(uuid, "ALTO");
HashMap map = new HashMap();
map.put("deepZoomCacheGenerated", ""+generated);
map.put("deepZoomCofigurationEnabled", ""+conf);
map.put("imageServerConfigured", ""+(!KConfiguration.getInstance().getUrlOfIIPServer().equals("")));
map.put("uuid", uuid);
map.put("pathOfUuids",pathOfUUIDs);
if (this.currentLoggedUserProvider.get().hasSuperAdministratorRole()) {
// kam to jinam dat ??
map.put("canhandlecommongroup",true);
}
HashMap<String, HashMap<String, String>> secMapping = new HashMap<String, HashMap<String,String>>();
// interpretuj pravo READ pro celou cestu -
// standardne jsou zdroje chraneny pres securedFedoraAccess, zde je to jine,
// pravo se neineterpretuje vicekrat, interpretuje se jednou a vysledek
// se pak vyhodnoti
boolean[] vals = fillActionsToJSON(req, uuid, pathOfUUIDs, secMapping, SecuredActions.READ);
if (!firstMustBeTrue(vals)) {
//throw new SecurityException("access denided");
}
// pravo admin do kontext menu
fillActionsToJSON(req, uuid, pathOfUUIDs, secMapping, SecuredActions.ADMINISTRATE);
map.put("actions",secMapping);
HttpSession session = req.getSession();
if (session != null) {
- List<String> actions = (List<String>) session.getAttribute(CurrentLoggedUserProvider.SECURITY_FOR_REPOSITORY_KEY);
+ List<String> actions = new ArrayList<String>((List<String>) session.getAttribute(CurrentLoggedUserProvider.SECURITY_FOR_REPOSITORY_KEY));
if (actions != null) {
SecuredActions[] acts = new SecuredActions[] {SecuredActions.ADMINISTRATE, SecuredActions.READ};
for (SecuredActions act : acts) {
actions.remove(act.getFormalName());
}
map.put("globalActions", actions);
} else {
map.put("globalActions", null);
}
} else {
map.put("globalActions", null);
}
map.put("mimeType", mimeType);
map.put("hasAlto", ""+hasAlto);
resp.setContentType("text/plain");
StringTemplate template = stGroup().getInstanceOf("viewinfo");
template.setAttribute("data", map);
resp.getWriter().println(template.toString());
}
} catch (XPathExpressionException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (ParserConfigurationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (SAXException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch(SecurityException e) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
private boolean firstMustBeTrue(boolean[] vals) {
return (vals.length > 0) && (vals[0]);
}
private boolean atLeastOneTrue(boolean[] vals) {
boolean accessed = false;
for (boolean val : vals) {
if (val) {
accessed = true;
break;
}
}
return accessed;
}
public boolean[] fillActionsToJSON(HttpServletRequest req, String uuid, String[] pathOfUUIDs, HashMap<String, HashMap<String, String>> secMapping,SecuredActions act) {
ArrayList<String> pathWithRepository = new ArrayList<String>(Arrays.asList(pathOfUUIDs));
pathWithRepository.add(0, SpecialObjects.REPOSITORY.getUuid());
Collections.reverse(pathWithRepository);
boolean[] allowedActionForPath = actionAllowed.isActionAllowedForAllPath(act.getFormalName(), uuid,pathOfUUIDs);
for (int j = 0; j < allowedActionForPath.length; j++) {
if (!secMapping.containsKey(act.getFormalName())) {
secMapping.put(act.getFormalName(), new HashMap<String, String>());
}
HashMap<String, String> pathMap = secMapping.get(act.getFormalName());
pathMap.put(pathWithRepository.get(j), ""+allowedActionForPath[j]);
}
return allowedActionForPath;
}
private boolean resolutionFilePresent(String uuid) throws IOException, ParserConfigurationException, SAXException {
boolean resFile = deepZoomCacheService.isResolutionFilePresent(uuid);
return resFile;
}
private boolean deepZoomConfigurationEnabled(String uuid) {
try {
Document parseDocument = solrAccess.getSolrDataDocumentByUUID(uuid);
String pidPath = SolrUtils.disectPidPath(parseDocument);
return KConfiguration.getInstance().isDeepZoomEnabled() || KConfiguration.getInstance().isDeepZoomForPathEnabled(pidPath.split("/"));
} catch (XPathExpressionException e) {
LOGGER.severe(e.getMessage());
} catch (IOException e) {
LOGGER.severe(e.getMessage());
}
return false;
}
private StringTemplateGroup stGroup() throws IOException {
InputStream stream = GetRelsExt.class.getResourceAsStream("viewinfo.stg");
String string = IOUtils.readAsString(stream, Charset.forName("UTF-8"), true);
StringTemplateGroup group = new StringTemplateGroup(new StringReader(string), DefaultTemplateLexer.class);
return group;
}
public static void main(String[] args) {
StringTemplate template = new StringTemplate(
"$data.keys:{action| $data.(action).keys:{ key| $key$ : $data.(action).(key)$ };separator=\",\"$ }$") ;
HashMap map = new HashMap();
HashMap<String, String> data = new HashMap<String, String>(); {
data.put("drobnustky","true");
data.put("stranka","true");
data.put("repository","true");
};
map.put("edit",data);
template.setAttribute("data", map);
System.out.println(template.toString());
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
String uuid = req.getParameter(UUID_PARAMETER);
String[] pathOfUUIDs = this.solrAccess.getPathOfUUIDs(uuid);
User user = currentLoggedUserProvider.get();
if ((uuid != null) && (!uuid.equals(""))) {
String mimeType = this.fedoraAccess.getImageFULLMimeType(uuid);
boolean generated = resolutionFilePresent(uuid);
boolean conf = deepZoomConfigurationEnabled(uuid);
boolean hasAlto = this.fedoraAccess.isStreamAvailable(uuid, "ALTO");
HashMap map = new HashMap();
map.put("deepZoomCacheGenerated", ""+generated);
map.put("deepZoomCofigurationEnabled", ""+conf);
map.put("imageServerConfigured", ""+(!KConfiguration.getInstance().getUrlOfIIPServer().equals("")));
map.put("uuid", uuid);
map.put("pathOfUuids",pathOfUUIDs);
if (this.currentLoggedUserProvider.get().hasSuperAdministratorRole()) {
// kam to jinam dat ??
map.put("canhandlecommongroup",true);
}
HashMap<String, HashMap<String, String>> secMapping = new HashMap<String, HashMap<String,String>>();
// interpretuj pravo READ pro celou cestu -
// standardne jsou zdroje chraneny pres securedFedoraAccess, zde je to jine,
// pravo se neineterpretuje vicekrat, interpretuje se jednou a vysledek
// se pak vyhodnoti
boolean[] vals = fillActionsToJSON(req, uuid, pathOfUUIDs, secMapping, SecuredActions.READ);
if (!firstMustBeTrue(vals)) {
//throw new SecurityException("access denided");
}
// pravo admin do kontext menu
fillActionsToJSON(req, uuid, pathOfUUIDs, secMapping, SecuredActions.ADMINISTRATE);
map.put("actions",secMapping);
HttpSession session = req.getSession();
if (session != null) {
List<String> actions = (List<String>) session.getAttribute(CurrentLoggedUserProvider.SECURITY_FOR_REPOSITORY_KEY);
if (actions != null) {
SecuredActions[] acts = new SecuredActions[] {SecuredActions.ADMINISTRATE, SecuredActions.READ};
for (SecuredActions act : acts) {
actions.remove(act.getFormalName());
}
map.put("globalActions", actions);
} else {
map.put("globalActions", null);
}
} else {
map.put("globalActions", null);
}
map.put("mimeType", mimeType);
map.put("hasAlto", ""+hasAlto);
resp.setContentType("text/plain");
StringTemplate template = stGroup().getInstanceOf("viewinfo");
template.setAttribute("data", map);
resp.getWriter().println(template.toString());
}
} catch (XPathExpressionException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (ParserConfigurationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (SAXException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch(SecurityException e) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
String uuid = req.getParameter(UUID_PARAMETER);
String[] pathOfUUIDs = this.solrAccess.getPathOfUUIDs(uuid);
User user = currentLoggedUserProvider.get();
if ((uuid != null) && (!uuid.equals(""))) {
String mimeType = this.fedoraAccess.getImageFULLMimeType(uuid);
boolean generated = resolutionFilePresent(uuid);
boolean conf = deepZoomConfigurationEnabled(uuid);
boolean hasAlto = this.fedoraAccess.isStreamAvailable(uuid, "ALTO");
HashMap map = new HashMap();
map.put("deepZoomCacheGenerated", ""+generated);
map.put("deepZoomCofigurationEnabled", ""+conf);
map.put("imageServerConfigured", ""+(!KConfiguration.getInstance().getUrlOfIIPServer().equals("")));
map.put("uuid", uuid);
map.put("pathOfUuids",pathOfUUIDs);
if (this.currentLoggedUserProvider.get().hasSuperAdministratorRole()) {
// kam to jinam dat ??
map.put("canhandlecommongroup",true);
}
HashMap<String, HashMap<String, String>> secMapping = new HashMap<String, HashMap<String,String>>();
// interpretuj pravo READ pro celou cestu -
// standardne jsou zdroje chraneny pres securedFedoraAccess, zde je to jine,
// pravo se neineterpretuje vicekrat, interpretuje se jednou a vysledek
// se pak vyhodnoti
boolean[] vals = fillActionsToJSON(req, uuid, pathOfUUIDs, secMapping, SecuredActions.READ);
if (!firstMustBeTrue(vals)) {
//throw new SecurityException("access denided");
}
// pravo admin do kontext menu
fillActionsToJSON(req, uuid, pathOfUUIDs, secMapping, SecuredActions.ADMINISTRATE);
map.put("actions",secMapping);
HttpSession session = req.getSession();
if (session != null) {
List<String> actions = new ArrayList<String>((List<String>) session.getAttribute(CurrentLoggedUserProvider.SECURITY_FOR_REPOSITORY_KEY));
if (actions != null) {
SecuredActions[] acts = new SecuredActions[] {SecuredActions.ADMINISTRATE, SecuredActions.READ};
for (SecuredActions act : acts) {
actions.remove(act.getFormalName());
}
map.put("globalActions", actions);
} else {
map.put("globalActions", null);
}
} else {
map.put("globalActions", null);
}
map.put("mimeType", mimeType);
map.put("hasAlto", ""+hasAlto);
resp.setContentType("text/plain");
StringTemplate template = stGroup().getInstanceOf("viewinfo");
template.setAttribute("data", map);
resp.getWriter().println(template.toString());
}
} catch (XPathExpressionException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (ParserConfigurationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (SAXException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch(SecurityException e) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
|
diff --git a/htroot/BlacklistTest_p.java b/htroot/BlacklistTest_p.java
index 3e6051be7..606e1ee41 100644
--- a/htroot/BlacklistTest_p.java
+++ b/htroot/BlacklistTest_p.java
@@ -1,83 +1,92 @@
// BlacklistTest_p.java
// -----------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
//
// This File is contributed by Alexander Schier
//
// $LastChangedDate: 2008-10-30 01:03:14 +0100 (Do, 30 Okt 2008) $
// $LastChangedRevision: 5309 $
// $LastChangedBy: low012 $
//
// 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
// You must compile this file with
// javac -classpath .:../classes Blacklist_p.java
// if the shell's current path is HTROOT
import java.io.File;
import java.net.MalformedURLException;
import de.anomic.data.Blacklist;
import de.anomic.data.listManager;
import de.anomic.http.metadata.RequestHeader;
import de.anomic.search.Switchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyURL;
public class BlacklistTest_p {
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
// initialize the list manager
listManager.switchboard = (Switchboard) env;
listManager.listsPath = new File(listManager.switchboard.getRootPath(),listManager.switchboard.getConfig("listManager.listsPath", "DATA/LISTS"));
final serverObjects prop = new serverObjects();
prop.putHTML("blacklistEngine", Switchboard.urlBlacklist.getEngineInfo());
// do all post operations
if(post != null && post.containsKey("testList")) {
prop.put("testlist", "1");
String urlstring = post.get("testurl", "");
- if(!urlstring.startsWith("http://")) urlstring = "http://"+urlstring;
+ if(!urlstring.startsWith("http://") &&
+ !urlstring.startsWith("https://")&&
+ !urlstring.startsWith("ftp://")
+ ) urlstring = "http://"+urlstring;
yacyURL testurl = null;
try {
testurl = new yacyURL(urlstring, null);
} catch (final MalformedURLException e) { testurl = null; }
if(testurl != null) {
+ prop.putHTML("url",testurl.toString());
prop.putHTML("testlist_url",testurl.toString());
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_CRAWLER, testurl))
prop.put("testlist_listedincrawler", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_DHT, testurl))
prop.put("testlist_listedindht", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_NEWS, testurl))
prop.put("testlist_listedinnews", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_PROXY, testurl))
prop.put("testlist_listedinproxy", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_SEARCH, testurl))
prop.put("testlist_listedinsearch", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_SURFTIPS, testurl))
prop.put("testlist_listedinsurftips", "1");
}
- else prop.put("testlist_url","not valid");
+ else {
+ prop.putHTML("url",urlstring);
+ prop.put("testlist", "2");
+ }
+ } else {
+ prop.putHTML("url", "http://");
}
return prop;
}
}
| false | true | public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
// initialize the list manager
listManager.switchboard = (Switchboard) env;
listManager.listsPath = new File(listManager.switchboard.getRootPath(),listManager.switchboard.getConfig("listManager.listsPath", "DATA/LISTS"));
final serverObjects prop = new serverObjects();
prop.putHTML("blacklistEngine", Switchboard.urlBlacklist.getEngineInfo());
// do all post operations
if(post != null && post.containsKey("testList")) {
prop.put("testlist", "1");
String urlstring = post.get("testurl", "");
if(!urlstring.startsWith("http://")) urlstring = "http://"+urlstring;
yacyURL testurl = null;
try {
testurl = new yacyURL(urlstring, null);
} catch (final MalformedURLException e) { testurl = null; }
if(testurl != null) {
prop.putHTML("testlist_url",testurl.toString());
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_CRAWLER, testurl))
prop.put("testlist_listedincrawler", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_DHT, testurl))
prop.put("testlist_listedindht", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_NEWS, testurl))
prop.put("testlist_listedinnews", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_PROXY, testurl))
prop.put("testlist_listedinproxy", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_SEARCH, testurl))
prop.put("testlist_listedinsearch", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_SURFTIPS, testurl))
prop.put("testlist_listedinsurftips", "1");
}
else prop.put("testlist_url","not valid");
}
return prop;
}
| public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
// initialize the list manager
listManager.switchboard = (Switchboard) env;
listManager.listsPath = new File(listManager.switchboard.getRootPath(),listManager.switchboard.getConfig("listManager.listsPath", "DATA/LISTS"));
final serverObjects prop = new serverObjects();
prop.putHTML("blacklistEngine", Switchboard.urlBlacklist.getEngineInfo());
// do all post operations
if(post != null && post.containsKey("testList")) {
prop.put("testlist", "1");
String urlstring = post.get("testurl", "");
if(!urlstring.startsWith("http://") &&
!urlstring.startsWith("https://")&&
!urlstring.startsWith("ftp://")
) urlstring = "http://"+urlstring;
yacyURL testurl = null;
try {
testurl = new yacyURL(urlstring, null);
} catch (final MalformedURLException e) { testurl = null; }
if(testurl != null) {
prop.putHTML("url",testurl.toString());
prop.putHTML("testlist_url",testurl.toString());
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_CRAWLER, testurl))
prop.put("testlist_listedincrawler", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_DHT, testurl))
prop.put("testlist_listedindht", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_NEWS, testurl))
prop.put("testlist_listedinnews", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_PROXY, testurl))
prop.put("testlist_listedinproxy", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_SEARCH, testurl))
prop.put("testlist_listedinsearch", "1");
if(Switchboard.urlBlacklist.isListed(Blacklist.BLACKLIST_SURFTIPS, testurl))
prop.put("testlist_listedinsurftips", "1");
}
else {
prop.putHTML("url",urlstring);
prop.put("testlist", "2");
}
} else {
prop.putHTML("url", "http://");
}
return prop;
}
|
diff --git a/org.emftext.sdk/src/org/emftext/sdk/codegen/OptionManager.java b/org.emftext.sdk/src/org/emftext/sdk/codegen/OptionManager.java
index 7b6bfe310..42a682b3b 100644
--- a/org.emftext.sdk/src/org/emftext/sdk/codegen/OptionManager.java
+++ b/org.emftext.sdk/src/org/emftext/sdk/codegen/OptionManager.java
@@ -1,149 +1,146 @@
/*******************************************************************************
* Copyright (c) 2006-2009
* Software Technology Group, Dresden University of Technology
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version. This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU Lesser General Public License for more details. You should have
* received a copy of the GNU Lesser General Public License along with this
* program; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.sdk.codegen;
import java.util.List;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
import org.emftext.sdk.concretesyntax.Option;
import org.emftext.sdk.concretesyntax.OptionTypes;
/**
* A manager for code generation options. The manager can be queried
* for values of options of different types (integer, string and
* boolean options).
*/
public class OptionManager {
public final static OptionManager INSTANCE = new OptionManager();
public static final String ANTLR = "antlr";
public static final String SCALES = "scales";
private OptionManager() {
super();
}
public String getStringOptionValue(ConcreteSyntax concreteSyntax,
OptionTypes type) {
List<Option> options = concreteSyntax.getOptions();
if (options == null) {
return null;
}
Option option = findOptionByType(options, type);
if (option == null) {
return null;
}
return option.getValue();
}
public boolean getBooleanOptionValue(ConcreteSyntax concreteSyntax,
OptionTypes type) {
List<Option> options = concreteSyntax.getOptions();
if (options == null) {
return getBooleanOptionsDefaultValue(type);
}
Option option = findOptionByType(options, type);
if (option == null) {
return getBooleanOptionsDefaultValue(type);
}
String value = option.getValue();
if (value == null) {
return getBooleanOptionsDefaultValue(type);
}
if ("true".equals(value)) {
return true;
} else if ("false".equals(value)) {
return false;
} else {
return getBooleanOptionsDefaultValue(type);
}
}
private boolean getBooleanOptionsDefaultValue(OptionTypes option) {
// Attention: Any changes made to this default values must be
// documented in class OptionTypes!
if (option == OptionTypes.GENERATE_TEST_ACTION) {
return false;
}
- if (option == OptionTypes.GENERATE_PRINTER_STUB_ONLY) {
- return false;
- }
if (option == OptionTypes.OVERRIDE_REFERENCE_RESOLVERS) {
return false;
}
if (option == OptionTypes.OVERRIDE_TOKEN_RESOLVERS) {
return false;
}
if (option == OptionTypes.GENERATE_CODE_FROM_GENERATOR_MODEL) {
return false;
}
if (option == OptionTypes.AUTOFIX_SIMPLE_LEFTRECURSION) {
return false;
}
if (option == OptionTypes.RELOAD_GENERATOR_MODEL) {
return false;
}
return true;
}
public int getIntegerOptionValue(ConcreteSyntax syntax,
OptionTypes type, boolean expectPositiveValue, IProblemCollector problemCollector) {
Option option = findOptionByType(syntax.getOptions(), type);
if (option == null) {
return -1;
}
try {
int tempSpace = Integer.parseInt(option.getValue());
if (expectPositiveValue && tempSpace < 0) {
problemCollector.addProblem(new GenerationProblem(
"Only positive values are allowed for this option.",
option));
}
return tempSpace;
} catch (NumberFormatException e) {
problemCollector.addProblem(new GenerationProblem("No valid integer in option.", option));
}
return -1;
}
private Option findOptionByType(List<Option> options,
OptionTypes type) {
for (Option option : options) {
if (type == option.getType()) {
return option;
}
}
return null;
}
public boolean useScalesParser(ConcreteSyntax syntax) {
String value = getStringOptionValue(syntax, OptionTypes.PARSER_GENERATOR);
if (value == null) {
return false;
}
if (SCALES.equals(value)) {
return true;
}
return false;
}
}
| true | true | private boolean getBooleanOptionsDefaultValue(OptionTypes option) {
// Attention: Any changes made to this default values must be
// documented in class OptionTypes!
if (option == OptionTypes.GENERATE_TEST_ACTION) {
return false;
}
if (option == OptionTypes.GENERATE_PRINTER_STUB_ONLY) {
return false;
}
if (option == OptionTypes.OVERRIDE_REFERENCE_RESOLVERS) {
return false;
}
if (option == OptionTypes.OVERRIDE_TOKEN_RESOLVERS) {
return false;
}
if (option == OptionTypes.GENERATE_CODE_FROM_GENERATOR_MODEL) {
return false;
}
if (option == OptionTypes.AUTOFIX_SIMPLE_LEFTRECURSION) {
return false;
}
if (option == OptionTypes.RELOAD_GENERATOR_MODEL) {
return false;
}
return true;
}
| private boolean getBooleanOptionsDefaultValue(OptionTypes option) {
// Attention: Any changes made to this default values must be
// documented in class OptionTypes!
if (option == OptionTypes.GENERATE_TEST_ACTION) {
return false;
}
if (option == OptionTypes.OVERRIDE_REFERENCE_RESOLVERS) {
return false;
}
if (option == OptionTypes.OVERRIDE_TOKEN_RESOLVERS) {
return false;
}
if (option == OptionTypes.GENERATE_CODE_FROM_GENERATOR_MODEL) {
return false;
}
if (option == OptionTypes.AUTOFIX_SIMPLE_LEFTRECURSION) {
return false;
}
if (option == OptionTypes.RELOAD_GENERATOR_MODEL) {
return false;
}
return true;
}
|
diff --git a/src/java-server-framework/org/xins/server/Function.java b/src/java-server-framework/org/xins/server/Function.java
index a1085d035..00d6312e0 100644
--- a/src/java-server-framework/org/xins/server/Function.java
+++ b/src/java-server-framework/org/xins/server/Function.java
@@ -1,505 +1,505 @@
/*
* $Id$
*/
package org.xins.server;
import org.apache.log4j.Logger;
import org.xins.util.MandatoryArgumentChecker;
import org.xins.util.text.FastStringBuffer;
/**
* Base class for function implementation classes.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
public abstract class Function
extends Object
implements DefaultResultCodes {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
/**
* Checks if the specified value is <code>null</code> or an empty string.
* Only if it is then <code>true</code> is returned.
*
* @param value
* the value to check.
*
* @return
* <code>true</code> if and only if <code>value != null &&
* value.length() != 0</code>.
*/
protected static final boolean isMissing(String value) {
return value == null || value.length() == 0;
}
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>Function</code> object.
*
* @param api
* the API to which this function belongs, not <code>null</code>.
*
* @param name
* the name, not <code>null</code>.
*
* @param version
* the version of the specification this function implements, not
* <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>api == null || name == null || version == null</code>.
*/
protected Function(API api, String name, String version)
throws IllegalArgumentException {
// Check argument
MandatoryArgumentChecker.check("api", api, "name", name, "version", version);
_log = Logger.getLogger(getClass().getName());
_api = api;
_name = name;
_version = version;
_api.functionAdded(this);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* The logger used by this function. This field is initialized by the
* constructor and set to a non-<code>null</code> value.
*/
protected final Logger _log;
/**
* The API implementation this function is part of.
*/
private final API _api;
/**
* The name of this function.
*/
private final String _name;
/**
* The version of the specification this function implements.
*/
private final String _version;
/**
* Lock object for <code>_callCount</code>.
*/
private final Object _callCountLock = new Object();
/**
* The total number of calls executed up until now.
*/
private int _callCount;
/**
* Statistics object linked to this function.
*/
private final Statistics _statistics = new Statistics();
/**
* Lock object for a successful call.
*/
private final Object _successfulCallLock = new Object();
/**
* Lock object for an unsuccessful call.
*/
private final Object _unsuccessfulCallLock = new Object();
/**
* Buffer for log messages for successful calls. This field is
* initialized at construction time and cannot be <code>null</code>.
*/
private final FastStringBuffer _successfulCallStringBuffer = new FastStringBuffer(256);
/**
* Buffer for log messages for unsuccessful calls. This field is
* initialized at construction time and cannot be <code>null</code>.
*/
private final FastStringBuffer _unsuccessfulCallStringBuffer = new FastStringBuffer(256);
/**
* The number of successful calls executed up until now.
*/
private int _successfulCalls;
/**
* The number of unsuccessful calls executed up until now.
*/
private int _unsuccessfulCalls;
/**
* The start time of the most recent successful call.
*/
private long _lastSuccessfulStart;
/**
* The start time of the most recent unsuccessful call.
*/
private long _lastUnsuccessfulStart;
/**
* The duration of the most recent successful call.
*/
private long _lastSuccessfulDuration;
/**
* The duration of the most recent unsuccessful call.
*/
private long _lastUnsuccessfulDuration;
/**
* The total duration of all successful calls up until now.
*/
private long _successfulDuration;
/**
* The total duration of all unsuccessful calls up until now.
*/
private long _unsuccessfulDuration;
/**
* The minimum time a successful call took.
*/
private long _successfulMin = Long.MAX_VALUE;
/**
* The minimum time an unsuccessful call took.
*/
private long _unsuccessfulMin = Long.MAX_VALUE;
/**
* The maximum time a successful call took.
*/
private long _successfulMax;
/**
* The maximum time an unsuccessful call took.
*/
private long _unsuccessfulMax;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Returns the logger associated with this function.
*
* @return
* the associated logger, constant, and cannot be <code>null</code>.
*/
final Logger getLogger() {
return _log;
}
/**
* Returns the name of this function.
*
* @return
* the name, not <code>null</code>.
*/
final String getName() {
return _name;
}
/**
* Returns the specification version for this function.
*
* @return
* the version, not <code>null</code>.
*/
final String getVersion() {
return _version;
}
/**
* Returns the call statistics for this function.
*
* @return
* the statistics, never <code>null</code>.
*/
final Statistics getStatistics() {
return _statistics;
}
/**
* Assigns a new call ID for the caller. Every call to this method will
* return an increasing number.
*
* @return
* the assigned call ID, >= 0.
*/
final int assignCallID() {
synchronized (_callCountLock) {
return _callCount++;
}
}
/**
* Handles a call to this function.
*
* @param context
* the context for this call, never <code>null</code>.
*
* @throws Throwable
* if anything goes wrong.
*/
protected abstract void handleCall(CallContext context)
throws Throwable;
/**
* Callback method that may be called after a call to this function. This
* method will store statistics-related information.
*
* <p />This method does not <em>have</em> to be called. If statistics
* gathering is disabled, then this method should not be called.
*
* @param context
* the used call context, not <code>null</code>.
*
* @param duration
* the duration of the function call, as a number of milliseconds.
*
* @param success
* indication if the call was successful.
*
* @param code
* the function result code, or <code>null</code>.
*/
final void performedCall(CallContext context, boolean success, String code) {
long start = context.getStart();
long duration = System.currentTimeMillis() - start;
boolean debugEnabled = context.isDebugEnabled();
String message = null;
if (success) {
if (debugEnabled) {
synchronized (_successfulCallStringBuffer) {
_successfulCallStringBuffer.clear();
_successfulCallStringBuffer.append("Function ");
_successfulCallStringBuffer.append(_name);
_successfulCallStringBuffer.append(" call succeeded. Duration: ");
_successfulCallStringBuffer.append(String.valueOf(duration));
_successfulCallStringBuffer.append(" ms.");
if (code != null) {
_successfulCallStringBuffer.append(" Code: \"");
_successfulCallStringBuffer.append(code);
_successfulCallStringBuffer.append("\".");
}
- message = _unsuccessfulCallStringBuffer.toString();
+ message = _successfulCallStringBuffer.toString();
}
}
synchronized (_successfulCallLock) {
_lastSuccessfulStart = start;
_lastSuccessfulDuration = duration;
_successfulCalls++;
_successfulDuration += duration;
_successfulMin = _successfulMin > duration ? duration : _successfulMin;
_successfulMax = _successfulMax < duration ? duration : _successfulMax;
}
} else {
if (debugEnabled) {
synchronized (_unsuccessfulCallStringBuffer) {
_unsuccessfulCallStringBuffer.clear();
_unsuccessfulCallStringBuffer.append("Call failed. Duration: ");
_unsuccessfulCallStringBuffer.append(String.valueOf(duration));
_unsuccessfulCallStringBuffer.append(" ms.");
if (code != null) {
_unsuccessfulCallStringBuffer.append(" Code: \"");
_unsuccessfulCallStringBuffer.append(code);
_unsuccessfulCallStringBuffer.append("\".");
}
message = _unsuccessfulCallStringBuffer.toString();
}
}
synchronized (_unsuccessfulCallLock) {
_lastUnsuccessfulStart = start;
_lastUnsuccessfulDuration = duration;
_unsuccessfulCalls++;
_unsuccessfulDuration += duration;
_unsuccessfulMin = _unsuccessfulMin > duration ? duration : _unsuccessfulMin;
_unsuccessfulMax = _unsuccessfulMax < duration ? duration : _unsuccessfulMax;
}
}
if (debugEnabled) {
context.debug(message);
}
}
//-------------------------------------------------------------------------
// Inner classes
//-------------------------------------------------------------------------
/**
* Call statistics pertaining to a certain function.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
final class Statistics extends Object {
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
/**
* Constructs a new <code>Statistics</code> object.
*/
private Statistics() {
// empty
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
/**
* Returns the number of successful calls executed up until now.
*
* @return
* the number of successful calls executed up until now.
*/
public int getSuccessfulCalls() {
return _successfulCalls;
}
/**
* Returns the number of unsuccessful calls executed up until now.
*
* @return
* the number of unsuccessful calls executed up until now.
*/
public int getUnsuccessfulCalls() {
return _unsuccessfulCalls;
}
/**
* Returns the start time of the most recent successful call.
*
* @return
* the start time of the most recent successful call.
*/
public long getLastSuccessfulStart() {
return _lastSuccessfulStart;
}
/**
* Returns the start time of the most recent unsuccessful call.
*
* @return
* the start time of the most recent unsuccessful call.
*/
public long getLastUnsuccessfulStart() {
return _lastUnsuccessfulStart;
}
/**
* Returns the duration of the most recent successful call.
*
* @return
* the duration of the most recent successful call.
*/
public long getLastSuccessfulDuration() {
return _lastSuccessfulDuration;
}
/**
* Returns the duration of the most recent unsuccessful call.
*
* @return
* the duration of the most recent unsuccessful call.
*/
public long getLastUnsuccessfulDuration() {
return _unsuccessfulDuration;
}
/**
* Returns the total duration of all successful calls up until now.
*
* @return
* the total duration of all successful calls up until now.
*/
public long getSuccessfulDuration() {
return _successfulDuration;
}
/**
* Returns the total duration of all unsuccessful calls up until now.
*
* @return
* the total duration of all unsuccessful calls up until now.
*/
public long getUnsuccessfulDuration() {
return _unsuccessfulDuration;
}
/**
* Returns the minimum time a successful call took.
*
* @return
* the minimum time a successful call took.
*/
public long getSuccessfulMin() {
return _successfulMin;
}
/**
* Returns the minimum time an unsuccessful call took.
*
* @return
* the minimum time an unsuccessful call took.
*/
public long getUnsuccessfulMin() {
return _unsuccessfulMin;
}
/**
* Returns the maximum time a successful call took.
*
* @return
* the maximum time a successful call took.
*/
public long getSuccessfulMax() {
return _successfulMax;
}
/**
* Returns the maximum time an unsuccessful call took.
*
* @return
* the maximum time an unsuccessful call took.
*/
public long getUnsuccessfulMax() {
return _unsuccessfulMax;
}
}
}
| true | true | final void performedCall(CallContext context, boolean success, String code) {
long start = context.getStart();
long duration = System.currentTimeMillis() - start;
boolean debugEnabled = context.isDebugEnabled();
String message = null;
if (success) {
if (debugEnabled) {
synchronized (_successfulCallStringBuffer) {
_successfulCallStringBuffer.clear();
_successfulCallStringBuffer.append("Function ");
_successfulCallStringBuffer.append(_name);
_successfulCallStringBuffer.append(" call succeeded. Duration: ");
_successfulCallStringBuffer.append(String.valueOf(duration));
_successfulCallStringBuffer.append(" ms.");
if (code != null) {
_successfulCallStringBuffer.append(" Code: \"");
_successfulCallStringBuffer.append(code);
_successfulCallStringBuffer.append("\".");
}
message = _unsuccessfulCallStringBuffer.toString();
}
}
synchronized (_successfulCallLock) {
_lastSuccessfulStart = start;
_lastSuccessfulDuration = duration;
_successfulCalls++;
_successfulDuration += duration;
_successfulMin = _successfulMin > duration ? duration : _successfulMin;
_successfulMax = _successfulMax < duration ? duration : _successfulMax;
}
} else {
if (debugEnabled) {
synchronized (_unsuccessfulCallStringBuffer) {
_unsuccessfulCallStringBuffer.clear();
_unsuccessfulCallStringBuffer.append("Call failed. Duration: ");
_unsuccessfulCallStringBuffer.append(String.valueOf(duration));
_unsuccessfulCallStringBuffer.append(" ms.");
if (code != null) {
_unsuccessfulCallStringBuffer.append(" Code: \"");
_unsuccessfulCallStringBuffer.append(code);
_unsuccessfulCallStringBuffer.append("\".");
}
message = _unsuccessfulCallStringBuffer.toString();
}
}
synchronized (_unsuccessfulCallLock) {
_lastUnsuccessfulStart = start;
_lastUnsuccessfulDuration = duration;
_unsuccessfulCalls++;
_unsuccessfulDuration += duration;
_unsuccessfulMin = _unsuccessfulMin > duration ? duration : _unsuccessfulMin;
_unsuccessfulMax = _unsuccessfulMax < duration ? duration : _unsuccessfulMax;
}
}
if (debugEnabled) {
context.debug(message);
}
}
| final void performedCall(CallContext context, boolean success, String code) {
long start = context.getStart();
long duration = System.currentTimeMillis() - start;
boolean debugEnabled = context.isDebugEnabled();
String message = null;
if (success) {
if (debugEnabled) {
synchronized (_successfulCallStringBuffer) {
_successfulCallStringBuffer.clear();
_successfulCallStringBuffer.append("Function ");
_successfulCallStringBuffer.append(_name);
_successfulCallStringBuffer.append(" call succeeded. Duration: ");
_successfulCallStringBuffer.append(String.valueOf(duration));
_successfulCallStringBuffer.append(" ms.");
if (code != null) {
_successfulCallStringBuffer.append(" Code: \"");
_successfulCallStringBuffer.append(code);
_successfulCallStringBuffer.append("\".");
}
message = _successfulCallStringBuffer.toString();
}
}
synchronized (_successfulCallLock) {
_lastSuccessfulStart = start;
_lastSuccessfulDuration = duration;
_successfulCalls++;
_successfulDuration += duration;
_successfulMin = _successfulMin > duration ? duration : _successfulMin;
_successfulMax = _successfulMax < duration ? duration : _successfulMax;
}
} else {
if (debugEnabled) {
synchronized (_unsuccessfulCallStringBuffer) {
_unsuccessfulCallStringBuffer.clear();
_unsuccessfulCallStringBuffer.append("Call failed. Duration: ");
_unsuccessfulCallStringBuffer.append(String.valueOf(duration));
_unsuccessfulCallStringBuffer.append(" ms.");
if (code != null) {
_unsuccessfulCallStringBuffer.append(" Code: \"");
_unsuccessfulCallStringBuffer.append(code);
_unsuccessfulCallStringBuffer.append("\".");
}
message = _unsuccessfulCallStringBuffer.toString();
}
}
synchronized (_unsuccessfulCallLock) {
_lastUnsuccessfulStart = start;
_lastUnsuccessfulDuration = duration;
_unsuccessfulCalls++;
_unsuccessfulDuration += duration;
_unsuccessfulMin = _unsuccessfulMin > duration ? duration : _unsuccessfulMin;
_unsuccessfulMax = _unsuccessfulMax < duration ? duration : _unsuccessfulMax;
}
}
if (debugEnabled) {
context.debug(message);
}
}
|
diff --git a/src/mennov1/WebcamClient.java b/src/mennov1/WebcamClient.java
index 5c76130..099e1c0 100644
--- a/src/mennov1/WebcamClient.java
+++ b/src/mennov1/WebcamClient.java
@@ -1,39 +1,40 @@
package mennov1;
import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage;
import lib.SewerSender;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class WebcamClient implements Runnable {
final int INTERVAL=5000;///you may use interval
IplImage image;
@Override
public void run() {
try {
FrameGrabber grabber = new OpenCVFrameGrabber(0);
grabber.start();
IplImage img;
SewerSender.logMessage("Started webcam");
while (true) {
img = grabber.grab();
if (img != null) {
cvSaveImage("webcam/capture.jpg", img);
try {
Process process = Runtime.getRuntime().exec("webcam/upload");
if (0 != process.waitFor()) {
SewerSender.println("Uploading exited weird!");
}
- } catch (Exception e) { }
+ process.destroy();
+ } catch (Exception ex) { System.out.println(ex); }
} else {
System.out.println("Webcam frame is null");
}
Thread.sleep(INTERVAL);
}
} catch (Exception e) {
SewerSender.println("webcam kapot huilen!\n"+e.toString());
}
}
}
| true | true | public void run() {
try {
FrameGrabber grabber = new OpenCVFrameGrabber(0);
grabber.start();
IplImage img;
SewerSender.logMessage("Started webcam");
while (true) {
img = grabber.grab();
if (img != null) {
cvSaveImage("webcam/capture.jpg", img);
try {
Process process = Runtime.getRuntime().exec("webcam/upload");
if (0 != process.waitFor()) {
SewerSender.println("Uploading exited weird!");
}
} catch (Exception e) { }
} else {
System.out.println("Webcam frame is null");
}
Thread.sleep(INTERVAL);
}
} catch (Exception e) {
SewerSender.println("webcam kapot huilen!\n"+e.toString());
}
}
| public void run() {
try {
FrameGrabber grabber = new OpenCVFrameGrabber(0);
grabber.start();
IplImage img;
SewerSender.logMessage("Started webcam");
while (true) {
img = grabber.grab();
if (img != null) {
cvSaveImage("webcam/capture.jpg", img);
try {
Process process = Runtime.getRuntime().exec("webcam/upload");
if (0 != process.waitFor()) {
SewerSender.println("Uploading exited weird!");
}
process.destroy();
} catch (Exception ex) { System.out.println(ex); }
} else {
System.out.println("Webcam frame is null");
}
Thread.sleep(INTERVAL);
}
} catch (Exception e) {
SewerSender.println("webcam kapot huilen!\n"+e.toString());
}
}
|
diff --git a/src/java/com/frovi/ss/tests/testRecursive.java b/src/java/com/frovi/ss/tests/testRecursive.java
index 796ae1305..4856088d0 100755
--- a/src/java/com/frovi/ss/tests/testRecursive.java
+++ b/src/java/com/frovi/ss/tests/testRecursive.java
@@ -1,68 +1,68 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* 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. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including 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 com.frovi.ss.tests;
import java.util.Iterator;
import java.util.List;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentVersionController;
import org.infoglue.cms.entities.content.ContentVO;
import org.infoglue.cms.entities.content.ContentVersionVO;
import org.infoglue.cms.exception.ConstraintException;
import org.infoglue.cms.exception.SystemException;
/**
* @author ss
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class testRecursive {
public static void main(String[] args) throws ConstraintException, SystemException {
- List l = ContentVersionController.getContentVersionController().getContentVersionVOWithParentRecursive(new Integer(84),new Integer(0));
+ List l = ContentVersionController.getContentVersionController().getContentVersionVOWithParentRecursive(new Integer(84),new Integer(0), true);
Iterator it = l.iterator();
ContentVO contentVO = null;
ContentVersionVO contentVersionVO;
while (it.hasNext())
{
Object o = it.next();
contentVersionVO = (ContentVersionVO) o;
String cName = "N/A";
cName = contentVersionVO.getContentName();
String out = cName + " - " +
contentVersionVO.getLanguageName()
+ "(state:" + contentVersionVO.getStateId() + " isactive: " + contentVersionVO.getIsActive() + ")";
System.out.println(out);
}
}
}
| true | true | public static void main(String[] args) throws ConstraintException, SystemException {
List l = ContentVersionController.getContentVersionController().getContentVersionVOWithParentRecursive(new Integer(84),new Integer(0));
Iterator it = l.iterator();
ContentVO contentVO = null;
ContentVersionVO contentVersionVO;
while (it.hasNext())
{
Object o = it.next();
contentVersionVO = (ContentVersionVO) o;
String cName = "N/A";
cName = contentVersionVO.getContentName();
String out = cName + " - " +
contentVersionVO.getLanguageName()
+ "(state:" + contentVersionVO.getStateId() + " isactive: " + contentVersionVO.getIsActive() + ")";
System.out.println(out);
}
}
| public static void main(String[] args) throws ConstraintException, SystemException {
List l = ContentVersionController.getContentVersionController().getContentVersionVOWithParentRecursive(new Integer(84),new Integer(0), true);
Iterator it = l.iterator();
ContentVO contentVO = null;
ContentVersionVO contentVersionVO;
while (it.hasNext())
{
Object o = it.next();
contentVersionVO = (ContentVersionVO) o;
String cName = "N/A";
cName = contentVersionVO.getContentName();
String out = cName + " - " +
contentVersionVO.getLanguageName()
+ "(state:" + contentVersionVO.getStateId() + " isactive: " + contentVersionVO.getIsActive() + ")";
System.out.println(out);
}
}
|
diff --git a/core/src/visad/trunk/Contour2D.java b/core/src/visad/trunk/Contour2D.java
index 08242d15f..034932e0b 100644
--- a/core/src/visad/trunk/Contour2D.java
+++ b/core/src/visad/trunk/Contour2D.java
@@ -1,1231 +1,1231 @@
//
// Contour2D.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 1999 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/**
Contour2D is a class equipped with a 2-D contouring function.<P>
*/
public class Contour2D extends Applet implements MouseListener {
// Applet variables
protected Contour2D con;
protected int whichlabels = 0;
protected boolean showgrid;
protected int rows, cols, scale;
protected int[] num1, num2, num3, num4;
protected float[][] vx1, vy1, vx2, vy2, vx3, vy3, vx4, vy4;
/**
* Compute contour lines for a 2-D array. If the interval is negative,
* then contour lines less than base will be drawn as dashed lines.
* The contour lines will be computed for all V such that:<br>
* lowlimit <= V <= highlimit<br>
* and V = base + n*interval for some integer n<br>
* Note that the input array, g, should be in column-major (FORTRAN) order.
*
* @param g the 2-D array to contour.
* @param nr size of 2-D array in rows
* @param nc size of 2-D array in columns.
* @param interval contour interval
* @param lowlimit the lower limit on values to contour.
* @param highlimit the upper limit on values to contour.
* @param base base value to start contouring at.
* @param vx1 array to put contour line vertices (x value)
* @param vy1 array to put contour line vertices (y value)
* @param maxv1 size of vx1, vy1 arrays
* @param numv1 pointer to int to return number of vertices in vx1,vy1
* @param vx2 array to put 'hidden' contour line vertices (x value)
* @param vy2 array to put 'hidden' contour line vertices (y value)
* @param maxv2 size of vx2, vy2 arrays
* @param numv2 pointer to int to return number of vertices in vx2,vy2
* @param vx3 array to put contour label vertices (x value)
* @param vy3 array to put contour label vertices (y value)
* @param maxv3 size of vx3, vy3 arrays
* @param numv3 pointer to int to return number of vertices in vx3,vy3
* @param vx4 array to put contour label vertices, inverted (x value)
* @param vy4 array to put contour label vertices, inverted (y value)
* <br>** see note for VxB and VyB in PlotDigits.java **
* @param maxv4 size of vx4, vy4 arrays
* @param numv4 pointer to int to return number of vertices in vx4,vy4
*/
public static void contour( float g[], int nr, int nc, float interval,
float lowlimit, float highlimit, float base,
float vx1[][], float vy1[][], int maxv1, int[] numv1,
float vx2[][], float vy2[][], int maxv2, int[] numv2,
float vx3[][], float vy3[][], int maxv3, int[] numv3,
float vx4[][], float vy4[][], int maxv4, int[] numv4,
byte[][] auxValues, byte[][] auxLevels1,
byte[][] auxLevels2, byte[][] auxLevels3, boolean[] swap )
throws VisADException
{
boolean[] dashes = {false};
float[] intervals =
intervalToLevels(interval, lowlimit, highlimit, base, dashes);
boolean dash = dashes[0];
contour( g, nr, nc, intervals,
lowlimit, highlimit, base, dash,
vx1, vy1, maxv1, numv1,
vx2, vy2, maxv2, numv2,
vx3, vy3, maxv3, numv3,
vx4, vy4, maxv4, numv4,
auxValues, auxLevels1,
auxLevels2, auxLevels3, swap );
}
public static float[] intervalToLevels(float interval, float low,
float high, float ba, boolean[] dash)
throws VisADException {
float clow, chi;
float tmp1;
float[] levs = null;
if (interval == 0.0) {
throw new VisADException("Contour interval cannot be zero");
}
dash[0] = false;
if (interval < 0) {
dash[0] = true;
interval = -interval;
}
// compute list of contours
// compute clow and chi, low and high contour values in the box
tmp1 = (low - ba) / interval;
clow = ba + interval * ((int) (tmp1 + (tmp1 >= 0 ? 0.5 : -0.5)) - 1);
while (clow<low) {
clow += interval;
}
tmp1 = (high - ba) / interval;
chi = ba + interval * ((int) (tmp1 + (tmp1 >= 0 ? 0.5 : -0.5)) + 1);
while (chi>high) {
chi -= interval;
}
// how many contour lines are needed.
tmp1 = (chi-clow) / interval;
int numc = (int) (tmp1 + (tmp1 >= 0 ? 0.5 : -0.5)) + 1;
/*
System.out.println("clow = " + clow + "chigh = " + chi +
"tmp1 = " + tmp1 + "numc = " + numc);
*/
if (numc < 1) return levs;
if (numc > 1000) {
throw new VisADException("Contour interval too small");
}
try {
levs = new float[numc];
} catch (OutOfMemoryError e) {
throw new VisADException("Contour interval too small");
}
levs[0] = clow;
for (int i = 1; i < numc; i++) {
levs[i] = levs[i-1] + interval;
}
return levs;
}
/**
* Compute contour lines for a 2-D array. If the interval is negative,
* then contour lines less than base will be drawn as dashed lines.
* The contour lines will be computed for all V such that:<br>
* lowlimit <= V <= highlimit<br>
* and V = base + n*interval for some integer n<br>
* Note that the input array, g, should be in column-major (FORTRAN) order.
*
* @param g the 2-D array to contour.
* @param nr size of 2-D array in rows
* @param nc size of 2-D array in columns.
* @param values[] the values to be plotted
* @param lowlimit the lower limit on values to contour.
* @param highlimit the upper limit on values to contour.
* @param base base value to start contouring at.
* @param dash boolean to dash contours below base or not
* @param vx1 array to put contour line vertices (x value)
* @param vy1 array to put contour line vertices (y value)
* @param maxv1 size of vx1, vy1 arrays
* @param numv1 pointer to int to return number of vertices in vx1,vy1
* @param vx2 array to put 'hidden' contour line vertices (x value)
* @param vy2 array to put 'hidden' contour line vertices (y value)
* @param maxv2 size of vx2, vy2 arrays
* @param numv2 pointer to int to return number of vertices in vx2,vy2
* @param vx3 array to put contour label vertices (x value)
* @param vy3 array to put contour label vertices (y value)
* @param maxv3 size of vx3, vy3 arrays
* @param numv3 pointer to int to return number of vertices in vx3,vy3
* @param vx4 array to put contour label vertices, inverted (x value)
* @param vy4 array to put contour label vertices, inverted (y value)
* <br>** see note for VxB and VyB in PlotDigits.java **
* @param maxv4 size of vx4, vy4 arrays
* @param numv4 pointer to int to return number of vertices in vx4,vy4
*/
public static void contour( float g[], int nr, int nc, float[] values,
float lowlimit, float highlimit, float base, boolean dash,
float vx1[][], float vy1[][], int maxv1, int[] numv1,
float vx2[][], float vy2[][], int maxv2, int[] numv2,
float vx3[][], float vy3[][], int maxv3, int[] numv3,
float vx4[][], float vy4[][], int maxv4, int[] numv4,
byte[][] auxValues, byte[][] auxLevels1,
byte[][] auxLevels2, byte[][] auxLevels3, boolean[] swap )
throws VisADException {
/*
System.out.println("interval = " + values[0] + " lowlimit = " + lowlimit +
" highlimit = " + highlimit + " base = " + base);
boolean any = false;
boolean anymissing = false;
boolean anynotmissing = false;
*/
PlotDigits plot = new PlotDigits();
int ir, ic;
int nrm, ncm;
int numc, il;
int lr, lc, lc2, lrr, lr2, lcc;
float xd, yd ,xx, yy;
float xdd, ydd;
// float clow, chi;
float gg;
int maxsize = maxv1+maxv2;
float[] vx = new float[maxsize];
float[] vy = new float[maxsize];
int[] ipnt = new int[2*maxsize];
int nump, ip;
int numv;
/* DRM 1999-05-18, CTR 29 Jul 1999: values could be null */
float[] myvals = null;
if (values != null) {
myvals = (float[]) values.clone();
java.util.Arrays.sort(myvals);
}
int low;
int hi;
int t;
byte[][] auxLevels = null;
int naux = (auxValues != null) ? auxValues.length : 0;
if (naux > 0) {
if (auxLevels1 == null || auxLevels1.length != naux ||
auxLevels2 == null || auxLevels2.length != naux ||
auxLevels3 == null || auxLevels3.length != naux) {
throw new SetException("Contour2D.contour: "
+"auxLevels length doesn't match");
}
for (int i=0; i<naux; i++) {
if (auxValues[i].length != g.length) {
throw new SetException("Contour2D.contour: "
+"auxValues lengths don't match");
}
}
auxLevels = new byte[naux][maxsize];
}
else {
if (auxLevels1 != null || auxLevels2 != null || auxLevels3 != null) {
throw new SetException("Contour2D.contour: "
+"auxValues null but auxLevels not null");
}
}
// initialize vertex counts
numv1[0] = 0;
numv2[0] = 0;
numv3[0] = 0;
numv4[0] = 0;
- if (values != null) return; // WLH 24 Aug 99
+ if (values == null) return; // WLH 24 Aug 99
/* DRM: 1999-05-19 - Not needed since dash is a boolean
// check for bad contour interval
if (interval==0.0) {
throw new DisplayException("Contour2D.contour: interval cannot be 0");
}
if (!dash) {
// draw negative contour lines as dashed lines
interval = -interval;
idash = 1;
}
else {
idash = 0;
}
*/
nrm = nr-1;
ncm = nc-1;
xdd = ((nr-1)-0.0f)/(nr-1.0f); // = 1.0
ydd = ((nc-1)-0.0f)/(nc-1.0f); // = 1.0
xd = xdd - 0.0001f;
yd = ydd - 0.0001f;
/*
* set up mark array
* mark= 0 if avail for label center,
* 2 if in label, and
* 1 if not available and not in label
*
* lr and lc give label size in grid boxes
* lrr and lcc give unavailable radius
*/
if (swap[0]) {
lr = 1+(nr-2)/10;
lc = 1+(nc-2)/50;
}
else {
lr = 1+(nr-2)/50;
lc = 1+(nc-2)/10;
}
lc2 = lc/2;
lr2 = lr/2;
lrr = 1+(nr-2)/8;
lcc = 1+(nc-2)/8;
// allocate mark array
char[] mark = new char[nr * nc];
// initialize mark array to zeros
for (int i=0; i<nr * nc; i++) mark[i] = 0;
// set top and bottom rows to 1
for (ic=0;ic<nc;ic++) {
for (ir=0;ir<lr;ir++) {
mark[ (ic) * nr + (ir) ] = 1;
mark[ (ic) * nr + (nr-ir-2) ] = 1;
}
}
// set left and right columns to 1
for (ir=0;ir<nr;ir++) {
for (ic=0;ic<lc;ic++) {
mark[ (ic) * nr + (ir) ] = 1;
mark[ (nc-ic-2) * nr + (ir) ] = 1;
}
}
numv = nump = 0;
// compute contours
for (ir=0; ir<nrm; ir++) {
xx = xdd*ir+0.0f; // = ir
for (ic=0; ic<ncm; ic++) {
float ga, gb, gc, gd;
float gv, gn, gx;
float tmp1, tmp2;
// save index of first vertex in this grid box
ipnt[nump++] = numv;
yy = ydd*ic+0.0f; // = ic
/*
ga = ( g[ (ic) * nr + (ir) ] );
gb = ( g[ (ic) * nr + (ir+1) ] );
gc = ( g[ (ic+1) * nr + (ir) ] );
gd = ( g[ (ic+1) * nr + (ir+1) ] );
boolean miss = false;
if (ga != ga || gb != gb || gc != gc || gd != gd) {
miss = true;
System.out.println("ic, ir = " + ic + " " + ir + " gabcd = " +
ga + " " + gb + " " + gc + " " + gd);
}
*/
/*
if (ga != ga || gb != gb || gc != gc || gd != gd) {
if (!anymissing) {
anymissing = true;
System.out.println("missing");
}
}
else {
if (!anynotmissing) {
anynotmissing = true;
System.out.println("notmissing");
}
}
*/
// get 4 corner values, skip box if any are missing
ga = ( g[ (ic) * nr + (ir) ] );
// test for missing
if (ga != ga) continue;
gb = ( g[ (ic) * nr + (ir+1) ] );
// test for missing
if (gb != gb) continue;
gc = ( g[ (ic+1) * nr + (ir) ] );
// test for missing
if (gc != gc) continue;
gd = ( g[ (ic+1) * nr + (ir+1) ] );
// test for missing
if (gd != gd) continue;
byte[] auxa = null;
byte[] auxb = null;
byte[] auxc = null;
byte[] auxd = null;
if (naux > 0) {
auxa = new byte[naux];
auxb = new byte[naux];
auxc = new byte[naux];
auxd = new byte[naux];
for (int i=0; i<naux; i++) {
auxa[i] = auxValues[i][(ic) * nr + (ir)];
auxb[i] = auxValues[i][(ic) * nr + (ir+1)];
auxc[i] = auxValues[i][(ic+1) * nr + (ir)];
auxd[i] = auxValues[i][(ic+1) * nr + (ir+1)];
}
}
// find average, min, and max of 4 corner values
gv = (ga+gb+gc+gd)/4.0f;
// gn = MIN4(ga,gb,gc,gd);
tmp1 = ( (ga) < (gb) ? (ga) : (gb) );
tmp2 = ( (gc) < (gd) ? (gc) : (gd) );
gn = ( (tmp1) < (tmp2) ? (tmp1) : (tmp2) );
// gx = MAX4(ga,gb,gc,gd);
tmp1 = ( (ga) > (gb) ? (ga) : (gb) );
tmp2 = ( (gc) > (gd) ? (gc) : (gd) );
gx = ( (tmp1) > (tmp2) ? (tmp1) : (tmp2) );
/* remove for new signature, replace with code below
// compute clow and chi, low and high contour values in the box
tmp1 = (gn-base) / interval;
clow = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5)
: (int) ((tmp1)-0.5) )-1);
while (clow<gn) {
clow += interval;
}
tmp1 = (gx-base) / interval;
chi = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5)
: (int) ((tmp1)-0.5) )+1);
while (chi>gx) {
chi -= interval;
}
// how many contour lines in the box:
tmp1 = (chi-clow) / interval;
numc = 1+( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) );
// gg is current contour line value
gg = clow;
*/
low = 0;
hi = myvals.length - 1;
if (myvals[low] > gx || myvals[hi] < gn) // no contours
{
numc = 1;
}
else // some inside the box
{
for (int i = 0; i < myvals.length; i++)
{
if (i == 0 && myvals[i] >= gn) { low = i; }
else if (myvals[i] >= gn && myvals[i-1] < gn) { low = i; }
else if (myvals[i] > gx && myvals[i-1] < gn) { hi = i; }
}
numc = hi - low + 1;
}
gg = myvals[low];
/*
if (!any && numc > 0) {
System.out.println("numc = " + numc + " clow = " + myvals[low] +
" chi = " + myvals[hi]);
any = true;
}
*/
for (il=0; il<numc; il++) {
gg = myvals[low+il];
if (numv+8 >= maxsize || nump+4 >= 2*maxsize) {
// allocate more space
maxsize = 2 * maxsize;
int[] tt = ipnt;
ipnt = new int[2 * maxsize];
System.arraycopy(tt, 0, ipnt, 0, nump);
float[] tx = vx;
float[] ty = vy;
vx = new float[maxsize];
vy = new float[maxsize];
System.arraycopy(tx, 0, vx, 0, numv);
System.arraycopy(ty, 0, vy, 0, numv);
if (naux > 0) {
byte[][] ta = auxLevels;
auxLevels = new byte[naux][maxsize];
for (int i=0; i<naux; i++) {
System.arraycopy(ta[i], 0, auxLevels[i], 0, numv);
}
}
}
float gba, gca, gdb, gdc;
int ii;
// make sure gg is within contouring limits
if (gg < gn) continue;
if (gg > gx) break;
if (gg < lowlimit) continue;
if (gg > highlimit) break;
// compute orientation of lines inside box
ii = 0;
if (gg > ga) ii = 1;
if (gg > gb) ii += 2;
if (gg > gc) ii += 4;
if (gg > gd) ii += 8;
if (ii > 7) ii = 15 - ii;
if (ii <= 0) continue;
// DO LABEL HERE
if (( mark[ (ic) * nr + (ir) ] )==0) {
int kc, kr, mc, mr, jc, jr;
float xk, yk, xm, ym, value;
// Insert a label
// BOX TO AVOID
kc = ic-lc2-lcc;
kr = ir-lr2-lrr;
mc = kc+2*lcc+lc-1;
mr = kr+2*lrr+lr-1;
// OK here
for (jc=kc;jc<=mc;jc++) {
if (jc >= 0 && jc < nc) {
for (jr=kr;jr<=mr;jr++) {
if (jr >= 0 && jr < nr) {
if (( mark[ (jc) * nr + (jr) ] ) != 2) {
mark[ (jc) * nr + (jr) ] = 1;
}
}
}
}
}
// BOX TO HOLD LABEL
kc = ic-lc2;
kr = ir-lr2;
mc = kc+lc-1;
mr = kr+lr-1;
for (jc=kc;jc<=mc;jc++) {
if (jc >= 0 && jc < nc) {
for (jr=kr;jr<=mr;jr++) {
if (jr >= 0 && jr < nr) {
mark[ (jc) * nr + (jr) ] = 2;
}
}
}
}
xk = xdd*kr+0.0f;
yk = ydd*kc+0.0f;
xm = xdd*(mr+1.0f)+0.0f;
ym = ydd*(mc+1.0f)+0.0f;
value = gg;
if (numv4[0]+100 >= maxv4) {
// allocate more space
maxv4 = 2 * (numv4[0]+100);
float[][] tx = new float[][] {vx4[0]};
float[][] ty = new float[][] {vy4[0]};
vx4[0] = new float[maxv4];
vy4[0] = new float[maxv4];
System.arraycopy(tx[0], 0, vx4[0], 0, numv4[0]);
System.arraycopy(ty[0], 0, vy4[0], 0, numv4[0]);
}
if (numv3[0]+100 >= maxv3) {
// allocate more space
maxv3 = 2 * (numv3[0]+100);
float[][] tx = new float[][] {vx3[0]};
float[][] ty = new float[][] {vy3[0]};
vx3[0] = new float[maxv3];
vy3[0] = new float[maxv3];
System.arraycopy(tx[0], 0, vx3[0], 0, numv3[0]);
System.arraycopy(ty[0], 0, vy3[0], 0, numv3[0]);
if (naux > 0) {
byte[][] ta = auxLevels3;
for (int i=0; i<naux; i++) {
byte[] taa = auxLevels3[i];
auxLevels3[i] = new byte[maxv3];
System.arraycopy(taa, 0, auxLevels3[i], 0, numv3[0]);
}
}
}
plot.plotdigits( value, xk, yk, xm, ym, maxsize, swap);
System.arraycopy(plot.Vx, 0, vx3[0], numv3[0], plot.NumVerts);
System.arraycopy(plot.Vy, 0, vy3[0], numv3[0], plot.NumVerts);
if (naux > 0) {
for (int i=0; i<naux; i++) {
for (int j=numv3[0]; j<numv3[0]+plot.NumVerts; j++) {
auxLevels3[i][j] = auxa[i];
}
}
}
numv3[0] += plot.NumVerts;
System.arraycopy(plot.VxB, 0, vx4[0], numv4[0], plot.NumVerts);
System.arraycopy(plot.VyB, 0, vy4[0], numv4[0], plot.NumVerts);
numv4[0] += plot.NumVerts;
}
switch (ii) {
case 1:
gba = gb-ga;
gca = gc-ga;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratioca = (gg-ga)/gca;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) {
vx[numv] = xx;
}
else {
vx[numv] = xx+xd*(gg-ga)/gba;
}
vy[numv] = yy;
numv++;
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) {
vy[numv] = yy;
}
else {
vy[numv] = yy+yd*(gg-ga)/gca;
}
vx[numv] = xx;
numv++;
break;
case 2:
gba = gb-ga;
gdb = gd-gb;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratiodb = (gg-gb)/gdb;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-ga)/gba;
vy[numv] = yy;
numv++;
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
break;
case 3:
gca = gc-ga;
gdb = gd-gb;
if (naux > 0) {
float ratioca = (gg-ga)/gca;
float ratiodb = (gg-gb)/gdb;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
*/
}
}
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
break;
case 4:
gca = gc-ga;
gdc = gd-gc;
if (naux > 0) {
float ratioca = (gg-ga)/gca;
float ratiodc = (gg-gc)/gdc;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
case 5:
gba = gb-ga;
gdc = gd-gc;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratiodc = (gg-gc)/gdc;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-ga)/gba;
vy[numv] = yy;
numv++;
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
case 6:
gba = gb-ga;
gdc = gd-gc;
gca = gc-ga;
gdb = gd-gb;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratiodc = (gg-gc)/gdc;
float ratioca = (gg-ga)/gca;
float ratiodb = (gg-gb)/gdb;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
*/
if ( (gg>gv) ^ (ga<gb) ) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
/* MEM_WLH
auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
auxLevels[i][numv+2] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
*/
}
else {
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv+2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
/* MEM_WLH
auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
auxLevels[i][numv+2] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
*/
}
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv+3] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-ga)/gba;
vy[numv] = yy;
numv++;
// here's a brain teaser
if ( (gg>gv) ^ (ga<gb) ) { // (XOR)
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
}
else {
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
}
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
case 7:
gdb = gd-gb;
gdc = gd-gc;
if (naux > 0) {
float ratiodb = (gg-gb)/gdb;
float ratiodc = (gg-gc)/gdc;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxb[i] + (auxb[i]-auxb[i]) * ratiodb;
auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
} // switch
// If contour level is negative, make dashed line
if (gg < base && dash) { /* DRM: 1999-05-19 */
float vxa, vya, vxb, vyb;
vxa = vx[numv-2];
vya = vy[numv-2];
vxb = vx[numv-1];
vyb = vy[numv-1];
vx[numv-2] = (3.0f*vxa+vxb) * 0.25f;
vy[numv-2] = (3.0f*vya+vyb) * 0.25f;
vx[numv-1] = (vxa+3.0f*vxb) * 0.25f;
vy[numv-1] = (vya+3.0f*vyb) * 0.25f;
}
/*
if ((20.0 <= vy[numv-2] && vy[numv-2] < 22.0) ||
(20.0 <= vy[numv-1] && vy[numv-1] < 22.0)) {
System.out.println("vy = " + vy[numv-1] + " " + vy[numv-2] +
" ic, ir = " + ic + " " + ir);
}
*/
} // for il -- NOTE: gg incremented in for statement
} // for ic
} // for ir
ipnt[nump] = numv;
// copy vertices from vx, vy arrays to either v1 or v2 arrays
ip = 0;
for (ir=0;ir<nrm && ip<2*maxsize;ir++) {
for (ic=0;ic<ncm && ip<2*maxsize;ic++) {
int start, len;
start = ipnt[ip];
len = ipnt[ip+1] - start;
if (len>0) {
if (( mark[ (ic) * nr + (ir) ] )==2) {
if (numv2[0]+len >= maxv2) {
// allocate more space
maxv2 = 2 * (numv2[0]+len);
float[][] tx = new float[][] {vx2[0]};
float[][] ty = new float[][] {vy2[0]};
vx2[0] = new float[maxv2];
vy2[0] = new float[maxv2];
System.arraycopy(tx[0], 0, vx2[0], 0, numv2[0]);
System.arraycopy(ty[0], 0, vy2[0], 0, numv2[0]);
if (naux > 0) {
for (int i=0; i<naux; i++) {
byte[] ta = auxLevels2[i];
auxLevels2[i] = new byte[maxv2];
System.arraycopy(ta, 0, auxLevels2[i], 0, numv2[0]);
}
}
}
for (il=0;il<len;il++) {
vx2[0][numv2[0]+il] = vx[start+il];
vy2[0][numv2[0]+il] = vy[start+il];
}
if (naux > 0) {
for (int i=0; i<naux; i++) {
for (il=0;il<len;il++) {
auxLevels2[i][numv2[0]+il] = auxLevels[i][start+il];
}
}
}
numv2[0] += len;
}
else {
if (numv1[0]+len >= maxv1) {
// allocate more space
maxv1 = 2 * (numv1[0]+len);
float[][] tx = new float[][] {vx1[0]};
float[][] ty = new float[][] {vy1[0]};
vx1[0] = new float[maxv1];
vy1[0] = new float[maxv1];
System.arraycopy(tx[0], 0, vx1[0], 0, numv1[0]);
System.arraycopy(ty[0], 0, vy1[0], 0, numv1[0]);
if (naux > 0) {
for (int i=0; i<naux; i++) {
byte[] ta = auxLevels1[i];
auxLevels1[i] = new byte[maxv1];
System.arraycopy(ta, 0, auxLevels1[i], 0, numv1[0]);
}
}
}
for (il=0; il<len; il++) {
vx1[0][numv1[0]+il] = vx[start+il];
vy1[0][numv1[0]+il] = vy[start+il];
}
if (naux > 0) {
for (int i=0; i<naux; i++) {
for (il=0;il<len;il++) {
auxLevels1[i][numv1[0]+il] = auxLevels[i][start+il];
}
}
}
numv1[0] += len;
}
}
ip++;
}
}
}
// APPLET SECTION
/* run 'appletviewer contour.html' to test the Contour2D class. */
public void init() {
this.addMouseListener(this);
con = new Contour2D();
con.rows = 0;
con.cols = 0;
con.scale = 0;
float intv = 0;
int mxv1 = 0;
int mxv2 = 0;
int mxv3 = 0;
int mxv4 = 0;
try {
String temp = new String("true");
con.showgrid = temp.equalsIgnoreCase(getParameter("showgrid"));
con.rows = Integer.parseInt(getParameter("rows"));
con.cols = Integer.parseInt(getParameter("columns"));
con.scale = Integer.parseInt(getParameter("scale"));
intv = Double.valueOf(getParameter("interval")).floatValue();
mxv1 = Integer.parseInt(getParameter("capacity1"));
mxv2 = Integer.parseInt(getParameter("capacity2"));
mxv3 = Integer.parseInt(getParameter("capacity3"));
mxv4 = Integer.parseInt(getParameter("capacity4"));
}
catch (Exception e) {
System.out.println("Contour2D.paint: applet parameter error: "+e);
System.exit(1);
}
float[] g = new float[con.rows*con.cols];
float mr = con.rows/2;
float mc = con.cols/2;
for (int i=0; i<con.rows; i++) {
for (int j=0; j<con.cols; j++) {
g[con.rows*j+i] = (float) Math.sqrt((i-mr)*(i-mr) + (j-mc)*(j-mc));
}
}
float low = 0;
float high = 100;
float base = 1;
con.num1 = new int[1];
con.num2 = new int[1];
con.num3 = new int[1];
con.num4 = new int[1];
con.vx1 = new float[1][mxv1];
con.vy1 = new float[1][mxv1];
con.vx2 = new float[1][mxv2];
con.vy2 = new float[1][mxv2];
con.vx3 = new float[1][mxv3];
con.vy3 = new float[1][mxv3];
con.vx4 = new float[1][mxv4];
con.vy4 = new float[1][mxv4];
try {
boolean[] swap = {false, false, false};
float[] intervals = {.25f, .5f, 1.0f, 2.0f, 2.5f, 5.f, 10.f};
// con.contour(g, con.rows, con.cols, intervals, low, high, base, true,
con.contour(g, con.rows, con.cols, intv, low, high, base,
con.vx1, con.vy1, mxv1, con.num1,
con.vx2, con.vy2, mxv2, con.num2,
con.vx3, con.vy3, mxv3, con.num3,
con.vx4, con.vy4, mxv4, con.num4,
null, null, null, null, swap);
}
catch (VisADException VE) {
System.out.println("Contour2D.init: "+VE);
System.exit(1);
}
}
public void mouseClicked(MouseEvent e) {
// cycle between hidden contours, labels, and backwards labels
con.whichlabels = (con.whichlabels+1)%5;
Graphics g = getGraphics();
if (g != null) {
paint(g);
g.dispose();
}
}
public void mousePressed(MouseEvent e) {;}
public void mouseReleased(MouseEvent e) {;}
public void mouseEntered(MouseEvent e) {;}
public void mouseExited(MouseEvent e) {;}
public void paint(Graphics gr) {
// draw grid dots if option is set
if (con.showgrid) {
gr.setColor(Color.blue);
for (int i=0; i<con.cols; i++) {
for (int j=0; j<con.rows; j++) {
gr.drawRect(con.scale*i, con.scale*j, 2, 2);
}
}
}
// draw main contour lines
gr.setColor(Color.black);
for (int i=0; i<con.num1[0]; i+=2) {
int v1 = (int) (con.scale*con.vy1[0][i]);
int v2 = (int) (con.scale*con.vx1[0][i]);
int v3 = (int) (con.scale*con.vy1[0][(i+1)%con.num1[0]]);
int v4 = (int) (con.scale*con.vx1[0][(i+1)%con.num1[0]]);
gr.drawLine(v1, v2, v3, v4);
}
for (int ix=-1; ix<1; ix++) {
if (ix<0) gr.setColor(Color.white); else gr.setColor(Color.black);
switch ((con.whichlabels+ix+5)%5) {
case 0: // hidden contours are exposed
for (int i=0; i<con.num2[0]; i+=2) {
int v1 = (int) (con.scale*con.vy2[0][i]);
int v2 = (int) (con.scale*con.vx2[0][i]);
int v3 = (int) (con.scale*con.vy2[0][(i+1)%con.num2[0]]);
int v4 = (int) (con.scale*con.vx2[0][(i+1)%con.num2[0]]);
gr.drawLine(v1, v2, v3, v4);
}
break;
case 1: // numbers cover hidden contours
for (int i=0; i<con.num3[0]; i+=2) {
int v1 = (int) (con.scale*con.vy3[0][i]);
int v2 = (int) (con.scale*con.vx3[0][i]);
int v3 = (int) (con.scale*con.vy3[0][(i+1)%con.num3[0]]);
int v4 = (int) (con.scale*con.vx3[0][(i+1)%con.num3[0]]);
gr.drawLine(v1, v2, v3, v4);
}
break;
case 2: // numbers cover hidden contours, backwards
for (int i=0; i<con.num4[0]; i+=2) {
int v1 = (int) (con.scale*con.vy4[0][i]);
int v2 = (int) (con.scale*con.vx3[0][i]);
int v3 = (int) (con.scale*con.vy4[0][(i+1)%con.num4[0]]);
int v4 = (int) (con.scale*con.vx3[0][(i+1)%con.num3[0]]);
gr.drawLine(v1, v2, v3, v4);
}
break;
case 3: // numbers cover hidden contours, upside-down
for (int i=0; i<con.num3[0]; i+=2) {
int v1 = (int) (con.scale*con.vy3[0][i]);
int v2 = (int) (con.scale*con.vx4[0][i]);
int v3 = (int) (con.scale*con.vy3[0][(i+1)%con.num3[0]]);
int v4 = (int) (con.scale*con.vx4[0][(i+1)%con.num4[0]]);
gr.drawLine(v1, v2, v3, v4);
}
break;
case 4: // numbers cover hidden contours, upside-down & backwards
for (int i=0; i<con.num3[0]; i+=2) {
int v1 = (int) (con.scale*con.vy4[0][i]);
int v2 = (int) (con.scale*con.vx4[0][i]);
int v3 = (int) (con.scale*con.vy4[0][(i+1)%con.num4[0]]);
int v4 = (int) (con.scale*con.vx4[0][(i+1)%con.num4[0]]);
gr.drawLine(v1, v2, v3, v4);
}
} // end switch
}
}
} // end class
| true | true | public static void contour( float g[], int nr, int nc, float[] values,
float lowlimit, float highlimit, float base, boolean dash,
float vx1[][], float vy1[][], int maxv1, int[] numv1,
float vx2[][], float vy2[][], int maxv2, int[] numv2,
float vx3[][], float vy3[][], int maxv3, int[] numv3,
float vx4[][], float vy4[][], int maxv4, int[] numv4,
byte[][] auxValues, byte[][] auxLevels1,
byte[][] auxLevels2, byte[][] auxLevels3, boolean[] swap )
throws VisADException {
/*
System.out.println("interval = " + values[0] + " lowlimit = " + lowlimit +
" highlimit = " + highlimit + " base = " + base);
boolean any = false;
boolean anymissing = false;
boolean anynotmissing = false;
*/
PlotDigits plot = new PlotDigits();
int ir, ic;
int nrm, ncm;
int numc, il;
int lr, lc, lc2, lrr, lr2, lcc;
float xd, yd ,xx, yy;
float xdd, ydd;
// float clow, chi;
float gg;
int maxsize = maxv1+maxv2;
float[] vx = new float[maxsize];
float[] vy = new float[maxsize];
int[] ipnt = new int[2*maxsize];
int nump, ip;
int numv;
/* DRM 1999-05-18, CTR 29 Jul 1999: values could be null */
float[] myvals = null;
if (values != null) {
myvals = (float[]) values.clone();
java.util.Arrays.sort(myvals);
}
int low;
int hi;
int t;
byte[][] auxLevels = null;
int naux = (auxValues != null) ? auxValues.length : 0;
if (naux > 0) {
if (auxLevels1 == null || auxLevels1.length != naux ||
auxLevels2 == null || auxLevels2.length != naux ||
auxLevels3 == null || auxLevels3.length != naux) {
throw new SetException("Contour2D.contour: "
+"auxLevels length doesn't match");
}
for (int i=0; i<naux; i++) {
if (auxValues[i].length != g.length) {
throw new SetException("Contour2D.contour: "
+"auxValues lengths don't match");
}
}
auxLevels = new byte[naux][maxsize];
}
else {
if (auxLevels1 != null || auxLevels2 != null || auxLevels3 != null) {
throw new SetException("Contour2D.contour: "
+"auxValues null but auxLevels not null");
}
}
// initialize vertex counts
numv1[0] = 0;
numv2[0] = 0;
numv3[0] = 0;
numv4[0] = 0;
if (values != null) return; // WLH 24 Aug 99
/* DRM: 1999-05-19 - Not needed since dash is a boolean
// check for bad contour interval
if (interval==0.0) {
throw new DisplayException("Contour2D.contour: interval cannot be 0");
}
if (!dash) {
// draw negative contour lines as dashed lines
interval = -interval;
idash = 1;
}
else {
idash = 0;
}
*/
nrm = nr-1;
ncm = nc-1;
xdd = ((nr-1)-0.0f)/(nr-1.0f); // = 1.0
ydd = ((nc-1)-0.0f)/(nc-1.0f); // = 1.0
xd = xdd - 0.0001f;
yd = ydd - 0.0001f;
/*
* set up mark array
* mark= 0 if avail for label center,
* 2 if in label, and
* 1 if not available and not in label
*
* lr and lc give label size in grid boxes
* lrr and lcc give unavailable radius
*/
if (swap[0]) {
lr = 1+(nr-2)/10;
lc = 1+(nc-2)/50;
}
else {
lr = 1+(nr-2)/50;
lc = 1+(nc-2)/10;
}
lc2 = lc/2;
lr2 = lr/2;
lrr = 1+(nr-2)/8;
lcc = 1+(nc-2)/8;
// allocate mark array
char[] mark = new char[nr * nc];
// initialize mark array to zeros
for (int i=0; i<nr * nc; i++) mark[i] = 0;
// set top and bottom rows to 1
for (ic=0;ic<nc;ic++) {
for (ir=0;ir<lr;ir++) {
mark[ (ic) * nr + (ir) ] = 1;
mark[ (ic) * nr + (nr-ir-2) ] = 1;
}
}
// set left and right columns to 1
for (ir=0;ir<nr;ir++) {
for (ic=0;ic<lc;ic++) {
mark[ (ic) * nr + (ir) ] = 1;
mark[ (nc-ic-2) * nr + (ir) ] = 1;
}
}
numv = nump = 0;
// compute contours
for (ir=0; ir<nrm; ir++) {
xx = xdd*ir+0.0f; // = ir
for (ic=0; ic<ncm; ic++) {
float ga, gb, gc, gd;
float gv, gn, gx;
float tmp1, tmp2;
// save index of first vertex in this grid box
ipnt[nump++] = numv;
yy = ydd*ic+0.0f; // = ic
/*
ga = ( g[ (ic) * nr + (ir) ] );
gb = ( g[ (ic) * nr + (ir+1) ] );
gc = ( g[ (ic+1) * nr + (ir) ] );
gd = ( g[ (ic+1) * nr + (ir+1) ] );
boolean miss = false;
if (ga != ga || gb != gb || gc != gc || gd != gd) {
miss = true;
System.out.println("ic, ir = " + ic + " " + ir + " gabcd = " +
ga + " " + gb + " " + gc + " " + gd);
}
*/
/*
if (ga != ga || gb != gb || gc != gc || gd != gd) {
if (!anymissing) {
anymissing = true;
System.out.println("missing");
}
}
else {
if (!anynotmissing) {
anynotmissing = true;
System.out.println("notmissing");
}
}
*/
// get 4 corner values, skip box if any are missing
ga = ( g[ (ic) * nr + (ir) ] );
// test for missing
if (ga != ga) continue;
gb = ( g[ (ic) * nr + (ir+1) ] );
// test for missing
if (gb != gb) continue;
gc = ( g[ (ic+1) * nr + (ir) ] );
// test for missing
if (gc != gc) continue;
gd = ( g[ (ic+1) * nr + (ir+1) ] );
// test for missing
if (gd != gd) continue;
byte[] auxa = null;
byte[] auxb = null;
byte[] auxc = null;
byte[] auxd = null;
if (naux > 0) {
auxa = new byte[naux];
auxb = new byte[naux];
auxc = new byte[naux];
auxd = new byte[naux];
for (int i=0; i<naux; i++) {
auxa[i] = auxValues[i][(ic) * nr + (ir)];
auxb[i] = auxValues[i][(ic) * nr + (ir+1)];
auxc[i] = auxValues[i][(ic+1) * nr + (ir)];
auxd[i] = auxValues[i][(ic+1) * nr + (ir+1)];
}
}
// find average, min, and max of 4 corner values
gv = (ga+gb+gc+gd)/4.0f;
// gn = MIN4(ga,gb,gc,gd);
tmp1 = ( (ga) < (gb) ? (ga) : (gb) );
tmp2 = ( (gc) < (gd) ? (gc) : (gd) );
gn = ( (tmp1) < (tmp2) ? (tmp1) : (tmp2) );
// gx = MAX4(ga,gb,gc,gd);
tmp1 = ( (ga) > (gb) ? (ga) : (gb) );
tmp2 = ( (gc) > (gd) ? (gc) : (gd) );
gx = ( (tmp1) > (tmp2) ? (tmp1) : (tmp2) );
/* remove for new signature, replace with code below
// compute clow and chi, low and high contour values in the box
tmp1 = (gn-base) / interval;
clow = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5)
: (int) ((tmp1)-0.5) )-1);
while (clow<gn) {
clow += interval;
}
tmp1 = (gx-base) / interval;
chi = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5)
: (int) ((tmp1)-0.5) )+1);
while (chi>gx) {
chi -= interval;
}
// how many contour lines in the box:
tmp1 = (chi-clow) / interval;
numc = 1+( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) );
// gg is current contour line value
gg = clow;
*/
low = 0;
hi = myvals.length - 1;
if (myvals[low] > gx || myvals[hi] < gn) // no contours
{
numc = 1;
}
else // some inside the box
{
for (int i = 0; i < myvals.length; i++)
{
if (i == 0 && myvals[i] >= gn) { low = i; }
else if (myvals[i] >= gn && myvals[i-1] < gn) { low = i; }
else if (myvals[i] > gx && myvals[i-1] < gn) { hi = i; }
}
numc = hi - low + 1;
}
gg = myvals[low];
/*
if (!any && numc > 0) {
System.out.println("numc = " + numc + " clow = " + myvals[low] +
" chi = " + myvals[hi]);
any = true;
}
*/
for (il=0; il<numc; il++) {
gg = myvals[low+il];
if (numv+8 >= maxsize || nump+4 >= 2*maxsize) {
// allocate more space
maxsize = 2 * maxsize;
int[] tt = ipnt;
ipnt = new int[2 * maxsize];
System.arraycopy(tt, 0, ipnt, 0, nump);
float[] tx = vx;
float[] ty = vy;
vx = new float[maxsize];
vy = new float[maxsize];
System.arraycopy(tx, 0, vx, 0, numv);
System.arraycopy(ty, 0, vy, 0, numv);
if (naux > 0) {
byte[][] ta = auxLevels;
auxLevels = new byte[naux][maxsize];
for (int i=0; i<naux; i++) {
System.arraycopy(ta[i], 0, auxLevels[i], 0, numv);
}
}
}
float gba, gca, gdb, gdc;
int ii;
// make sure gg is within contouring limits
if (gg < gn) continue;
if (gg > gx) break;
if (gg < lowlimit) continue;
if (gg > highlimit) break;
// compute orientation of lines inside box
ii = 0;
if (gg > ga) ii = 1;
if (gg > gb) ii += 2;
if (gg > gc) ii += 4;
if (gg > gd) ii += 8;
if (ii > 7) ii = 15 - ii;
if (ii <= 0) continue;
// DO LABEL HERE
if (( mark[ (ic) * nr + (ir) ] )==0) {
int kc, kr, mc, mr, jc, jr;
float xk, yk, xm, ym, value;
// Insert a label
// BOX TO AVOID
kc = ic-lc2-lcc;
kr = ir-lr2-lrr;
mc = kc+2*lcc+lc-1;
mr = kr+2*lrr+lr-1;
// OK here
for (jc=kc;jc<=mc;jc++) {
if (jc >= 0 && jc < nc) {
for (jr=kr;jr<=mr;jr++) {
if (jr >= 0 && jr < nr) {
if (( mark[ (jc) * nr + (jr) ] ) != 2) {
mark[ (jc) * nr + (jr) ] = 1;
}
}
}
}
}
// BOX TO HOLD LABEL
kc = ic-lc2;
kr = ir-lr2;
mc = kc+lc-1;
mr = kr+lr-1;
for (jc=kc;jc<=mc;jc++) {
if (jc >= 0 && jc < nc) {
for (jr=kr;jr<=mr;jr++) {
if (jr >= 0 && jr < nr) {
mark[ (jc) * nr + (jr) ] = 2;
}
}
}
}
xk = xdd*kr+0.0f;
yk = ydd*kc+0.0f;
xm = xdd*(mr+1.0f)+0.0f;
ym = ydd*(mc+1.0f)+0.0f;
value = gg;
if (numv4[0]+100 >= maxv4) {
// allocate more space
maxv4 = 2 * (numv4[0]+100);
float[][] tx = new float[][] {vx4[0]};
float[][] ty = new float[][] {vy4[0]};
vx4[0] = new float[maxv4];
vy4[0] = new float[maxv4];
System.arraycopy(tx[0], 0, vx4[0], 0, numv4[0]);
System.arraycopy(ty[0], 0, vy4[0], 0, numv4[0]);
}
if (numv3[0]+100 >= maxv3) {
// allocate more space
maxv3 = 2 * (numv3[0]+100);
float[][] tx = new float[][] {vx3[0]};
float[][] ty = new float[][] {vy3[0]};
vx3[0] = new float[maxv3];
vy3[0] = new float[maxv3];
System.arraycopy(tx[0], 0, vx3[0], 0, numv3[0]);
System.arraycopy(ty[0], 0, vy3[0], 0, numv3[0]);
if (naux > 0) {
byte[][] ta = auxLevels3;
for (int i=0; i<naux; i++) {
byte[] taa = auxLevels3[i];
auxLevels3[i] = new byte[maxv3];
System.arraycopy(taa, 0, auxLevels3[i], 0, numv3[0]);
}
}
}
plot.plotdigits( value, xk, yk, xm, ym, maxsize, swap);
System.arraycopy(plot.Vx, 0, vx3[0], numv3[0], plot.NumVerts);
System.arraycopy(plot.Vy, 0, vy3[0], numv3[0], plot.NumVerts);
if (naux > 0) {
for (int i=0; i<naux; i++) {
for (int j=numv3[0]; j<numv3[0]+plot.NumVerts; j++) {
auxLevels3[i][j] = auxa[i];
}
}
}
numv3[0] += plot.NumVerts;
System.arraycopy(plot.VxB, 0, vx4[0], numv4[0], plot.NumVerts);
System.arraycopy(plot.VyB, 0, vy4[0], numv4[0], plot.NumVerts);
numv4[0] += plot.NumVerts;
}
switch (ii) {
case 1:
gba = gb-ga;
gca = gc-ga;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratioca = (gg-ga)/gca;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) {
vx[numv] = xx;
}
else {
vx[numv] = xx+xd*(gg-ga)/gba;
}
vy[numv] = yy;
numv++;
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) {
vy[numv] = yy;
}
else {
vy[numv] = yy+yd*(gg-ga)/gca;
}
vx[numv] = xx;
numv++;
break;
case 2:
gba = gb-ga;
gdb = gd-gb;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratiodb = (gg-gb)/gdb;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-ga)/gba;
vy[numv] = yy;
numv++;
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
break;
case 3:
gca = gc-ga;
gdb = gd-gb;
if (naux > 0) {
float ratioca = (gg-ga)/gca;
float ratiodb = (gg-gb)/gdb;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
*/
}
}
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
break;
case 4:
gca = gc-ga;
gdc = gd-gc;
if (naux > 0) {
float ratioca = (gg-ga)/gca;
float ratiodc = (gg-gc)/gdc;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
case 5:
gba = gb-ga;
gdc = gd-gc;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratiodc = (gg-gc)/gdc;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-ga)/gba;
vy[numv] = yy;
numv++;
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
case 6:
gba = gb-ga;
gdc = gd-gc;
gca = gc-ga;
gdb = gd-gb;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratiodc = (gg-gc)/gdc;
float ratioca = (gg-ga)/gca;
float ratiodb = (gg-gb)/gdb;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
*/
if ( (gg>gv) ^ (ga<gb) ) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
/* MEM_WLH
auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
auxLevels[i][numv+2] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
*/
}
else {
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv+2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
/* MEM_WLH
auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
auxLevels[i][numv+2] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
*/
}
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv+3] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-ga)/gba;
vy[numv] = yy;
numv++;
// here's a brain teaser
if ( (gg>gv) ^ (ga<gb) ) { // (XOR)
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
}
else {
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
}
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
case 7:
gdb = gd-gb;
gdc = gd-gc;
if (naux > 0) {
float ratiodb = (gg-gb)/gdb;
float ratiodc = (gg-gc)/gdc;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxb[i] + (auxb[i]-auxb[i]) * ratiodb;
auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
} // switch
// If contour level is negative, make dashed line
if (gg < base && dash) { /* DRM: 1999-05-19 */
float vxa, vya, vxb, vyb;
vxa = vx[numv-2];
vya = vy[numv-2];
vxb = vx[numv-1];
vyb = vy[numv-1];
vx[numv-2] = (3.0f*vxa+vxb) * 0.25f;
vy[numv-2] = (3.0f*vya+vyb) * 0.25f;
vx[numv-1] = (vxa+3.0f*vxb) * 0.25f;
vy[numv-1] = (vya+3.0f*vyb) * 0.25f;
}
/*
if ((20.0 <= vy[numv-2] && vy[numv-2] < 22.0) ||
(20.0 <= vy[numv-1] && vy[numv-1] < 22.0)) {
System.out.println("vy = " + vy[numv-1] + " " + vy[numv-2] +
" ic, ir = " + ic + " " + ir);
}
*/
} // for il -- NOTE: gg incremented in for statement
} // for ic
} // for ir
ipnt[nump] = numv;
// copy vertices from vx, vy arrays to either v1 or v2 arrays
ip = 0;
for (ir=0;ir<nrm && ip<2*maxsize;ir++) {
for (ic=0;ic<ncm && ip<2*maxsize;ic++) {
int start, len;
start = ipnt[ip];
len = ipnt[ip+1] - start;
if (len>0) {
if (( mark[ (ic) * nr + (ir) ] )==2) {
if (numv2[0]+len >= maxv2) {
// allocate more space
maxv2 = 2 * (numv2[0]+len);
float[][] tx = new float[][] {vx2[0]};
float[][] ty = new float[][] {vy2[0]};
vx2[0] = new float[maxv2];
vy2[0] = new float[maxv2];
System.arraycopy(tx[0], 0, vx2[0], 0, numv2[0]);
System.arraycopy(ty[0], 0, vy2[0], 0, numv2[0]);
if (naux > 0) {
for (int i=0; i<naux; i++) {
byte[] ta = auxLevels2[i];
auxLevels2[i] = new byte[maxv2];
System.arraycopy(ta, 0, auxLevels2[i], 0, numv2[0]);
}
}
}
for (il=0;il<len;il++) {
vx2[0][numv2[0]+il] = vx[start+il];
vy2[0][numv2[0]+il] = vy[start+il];
}
if (naux > 0) {
for (int i=0; i<naux; i++) {
for (il=0;il<len;il++) {
auxLevels2[i][numv2[0]+il] = auxLevels[i][start+il];
}
}
}
numv2[0] += len;
}
else {
if (numv1[0]+len >= maxv1) {
// allocate more space
maxv1 = 2 * (numv1[0]+len);
float[][] tx = new float[][] {vx1[0]};
float[][] ty = new float[][] {vy1[0]};
vx1[0] = new float[maxv1];
vy1[0] = new float[maxv1];
System.arraycopy(tx[0], 0, vx1[0], 0, numv1[0]);
System.arraycopy(ty[0], 0, vy1[0], 0, numv1[0]);
if (naux > 0) {
for (int i=0; i<naux; i++) {
byte[] ta = auxLevels1[i];
auxLevels1[i] = new byte[maxv1];
System.arraycopy(ta, 0, auxLevels1[i], 0, numv1[0]);
}
}
}
for (il=0; il<len; il++) {
vx1[0][numv1[0]+il] = vx[start+il];
vy1[0][numv1[0]+il] = vy[start+il];
}
if (naux > 0) {
for (int i=0; i<naux; i++) {
for (il=0;il<len;il++) {
auxLevels1[i][numv1[0]+il] = auxLevels[i][start+il];
}
}
}
numv1[0] += len;
}
}
ip++;
}
}
}
| public static void contour( float g[], int nr, int nc, float[] values,
float lowlimit, float highlimit, float base, boolean dash,
float vx1[][], float vy1[][], int maxv1, int[] numv1,
float vx2[][], float vy2[][], int maxv2, int[] numv2,
float vx3[][], float vy3[][], int maxv3, int[] numv3,
float vx4[][], float vy4[][], int maxv4, int[] numv4,
byte[][] auxValues, byte[][] auxLevels1,
byte[][] auxLevels2, byte[][] auxLevels3, boolean[] swap )
throws VisADException {
/*
System.out.println("interval = " + values[0] + " lowlimit = " + lowlimit +
" highlimit = " + highlimit + " base = " + base);
boolean any = false;
boolean anymissing = false;
boolean anynotmissing = false;
*/
PlotDigits plot = new PlotDigits();
int ir, ic;
int nrm, ncm;
int numc, il;
int lr, lc, lc2, lrr, lr2, lcc;
float xd, yd ,xx, yy;
float xdd, ydd;
// float clow, chi;
float gg;
int maxsize = maxv1+maxv2;
float[] vx = new float[maxsize];
float[] vy = new float[maxsize];
int[] ipnt = new int[2*maxsize];
int nump, ip;
int numv;
/* DRM 1999-05-18, CTR 29 Jul 1999: values could be null */
float[] myvals = null;
if (values != null) {
myvals = (float[]) values.clone();
java.util.Arrays.sort(myvals);
}
int low;
int hi;
int t;
byte[][] auxLevels = null;
int naux = (auxValues != null) ? auxValues.length : 0;
if (naux > 0) {
if (auxLevels1 == null || auxLevels1.length != naux ||
auxLevels2 == null || auxLevels2.length != naux ||
auxLevels3 == null || auxLevels3.length != naux) {
throw new SetException("Contour2D.contour: "
+"auxLevels length doesn't match");
}
for (int i=0; i<naux; i++) {
if (auxValues[i].length != g.length) {
throw new SetException("Contour2D.contour: "
+"auxValues lengths don't match");
}
}
auxLevels = new byte[naux][maxsize];
}
else {
if (auxLevels1 != null || auxLevels2 != null || auxLevels3 != null) {
throw new SetException("Contour2D.contour: "
+"auxValues null but auxLevels not null");
}
}
// initialize vertex counts
numv1[0] = 0;
numv2[0] = 0;
numv3[0] = 0;
numv4[0] = 0;
if (values == null) return; // WLH 24 Aug 99
/* DRM: 1999-05-19 - Not needed since dash is a boolean
// check for bad contour interval
if (interval==0.0) {
throw new DisplayException("Contour2D.contour: interval cannot be 0");
}
if (!dash) {
// draw negative contour lines as dashed lines
interval = -interval;
idash = 1;
}
else {
idash = 0;
}
*/
nrm = nr-1;
ncm = nc-1;
xdd = ((nr-1)-0.0f)/(nr-1.0f); // = 1.0
ydd = ((nc-1)-0.0f)/(nc-1.0f); // = 1.0
xd = xdd - 0.0001f;
yd = ydd - 0.0001f;
/*
* set up mark array
* mark= 0 if avail for label center,
* 2 if in label, and
* 1 if not available and not in label
*
* lr and lc give label size in grid boxes
* lrr and lcc give unavailable radius
*/
if (swap[0]) {
lr = 1+(nr-2)/10;
lc = 1+(nc-2)/50;
}
else {
lr = 1+(nr-2)/50;
lc = 1+(nc-2)/10;
}
lc2 = lc/2;
lr2 = lr/2;
lrr = 1+(nr-2)/8;
lcc = 1+(nc-2)/8;
// allocate mark array
char[] mark = new char[nr * nc];
// initialize mark array to zeros
for (int i=0; i<nr * nc; i++) mark[i] = 0;
// set top and bottom rows to 1
for (ic=0;ic<nc;ic++) {
for (ir=0;ir<lr;ir++) {
mark[ (ic) * nr + (ir) ] = 1;
mark[ (ic) * nr + (nr-ir-2) ] = 1;
}
}
// set left and right columns to 1
for (ir=0;ir<nr;ir++) {
for (ic=0;ic<lc;ic++) {
mark[ (ic) * nr + (ir) ] = 1;
mark[ (nc-ic-2) * nr + (ir) ] = 1;
}
}
numv = nump = 0;
// compute contours
for (ir=0; ir<nrm; ir++) {
xx = xdd*ir+0.0f; // = ir
for (ic=0; ic<ncm; ic++) {
float ga, gb, gc, gd;
float gv, gn, gx;
float tmp1, tmp2;
// save index of first vertex in this grid box
ipnt[nump++] = numv;
yy = ydd*ic+0.0f; // = ic
/*
ga = ( g[ (ic) * nr + (ir) ] );
gb = ( g[ (ic) * nr + (ir+1) ] );
gc = ( g[ (ic+1) * nr + (ir) ] );
gd = ( g[ (ic+1) * nr + (ir+1) ] );
boolean miss = false;
if (ga != ga || gb != gb || gc != gc || gd != gd) {
miss = true;
System.out.println("ic, ir = " + ic + " " + ir + " gabcd = " +
ga + " " + gb + " " + gc + " " + gd);
}
*/
/*
if (ga != ga || gb != gb || gc != gc || gd != gd) {
if (!anymissing) {
anymissing = true;
System.out.println("missing");
}
}
else {
if (!anynotmissing) {
anynotmissing = true;
System.out.println("notmissing");
}
}
*/
// get 4 corner values, skip box if any are missing
ga = ( g[ (ic) * nr + (ir) ] );
// test for missing
if (ga != ga) continue;
gb = ( g[ (ic) * nr + (ir+1) ] );
// test for missing
if (gb != gb) continue;
gc = ( g[ (ic+1) * nr + (ir) ] );
// test for missing
if (gc != gc) continue;
gd = ( g[ (ic+1) * nr + (ir+1) ] );
// test for missing
if (gd != gd) continue;
byte[] auxa = null;
byte[] auxb = null;
byte[] auxc = null;
byte[] auxd = null;
if (naux > 0) {
auxa = new byte[naux];
auxb = new byte[naux];
auxc = new byte[naux];
auxd = new byte[naux];
for (int i=0; i<naux; i++) {
auxa[i] = auxValues[i][(ic) * nr + (ir)];
auxb[i] = auxValues[i][(ic) * nr + (ir+1)];
auxc[i] = auxValues[i][(ic+1) * nr + (ir)];
auxd[i] = auxValues[i][(ic+1) * nr + (ir+1)];
}
}
// find average, min, and max of 4 corner values
gv = (ga+gb+gc+gd)/4.0f;
// gn = MIN4(ga,gb,gc,gd);
tmp1 = ( (ga) < (gb) ? (ga) : (gb) );
tmp2 = ( (gc) < (gd) ? (gc) : (gd) );
gn = ( (tmp1) < (tmp2) ? (tmp1) : (tmp2) );
// gx = MAX4(ga,gb,gc,gd);
tmp1 = ( (ga) > (gb) ? (ga) : (gb) );
tmp2 = ( (gc) > (gd) ? (gc) : (gd) );
gx = ( (tmp1) > (tmp2) ? (tmp1) : (tmp2) );
/* remove for new signature, replace with code below
// compute clow and chi, low and high contour values in the box
tmp1 = (gn-base) / interval;
clow = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5)
: (int) ((tmp1)-0.5) )-1);
while (clow<gn) {
clow += interval;
}
tmp1 = (gx-base) / interval;
chi = base + interval * (( (tmp1) >= 0 ? (int) ((tmp1) + 0.5)
: (int) ((tmp1)-0.5) )+1);
while (chi>gx) {
chi -= interval;
}
// how many contour lines in the box:
tmp1 = (chi-clow) / interval;
numc = 1+( (tmp1) >= 0 ? (int) ((tmp1) + 0.5) : (int) ((tmp1)-0.5) );
// gg is current contour line value
gg = clow;
*/
low = 0;
hi = myvals.length - 1;
if (myvals[low] > gx || myvals[hi] < gn) // no contours
{
numc = 1;
}
else // some inside the box
{
for (int i = 0; i < myvals.length; i++)
{
if (i == 0 && myvals[i] >= gn) { low = i; }
else if (myvals[i] >= gn && myvals[i-1] < gn) { low = i; }
else if (myvals[i] > gx && myvals[i-1] < gn) { hi = i; }
}
numc = hi - low + 1;
}
gg = myvals[low];
/*
if (!any && numc > 0) {
System.out.println("numc = " + numc + " clow = " + myvals[low] +
" chi = " + myvals[hi]);
any = true;
}
*/
for (il=0; il<numc; il++) {
gg = myvals[low+il];
if (numv+8 >= maxsize || nump+4 >= 2*maxsize) {
// allocate more space
maxsize = 2 * maxsize;
int[] tt = ipnt;
ipnt = new int[2 * maxsize];
System.arraycopy(tt, 0, ipnt, 0, nump);
float[] tx = vx;
float[] ty = vy;
vx = new float[maxsize];
vy = new float[maxsize];
System.arraycopy(tx, 0, vx, 0, numv);
System.arraycopy(ty, 0, vy, 0, numv);
if (naux > 0) {
byte[][] ta = auxLevels;
auxLevels = new byte[naux][maxsize];
for (int i=0; i<naux; i++) {
System.arraycopy(ta[i], 0, auxLevels[i], 0, numv);
}
}
}
float gba, gca, gdb, gdc;
int ii;
// make sure gg is within contouring limits
if (gg < gn) continue;
if (gg > gx) break;
if (gg < lowlimit) continue;
if (gg > highlimit) break;
// compute orientation of lines inside box
ii = 0;
if (gg > ga) ii = 1;
if (gg > gb) ii += 2;
if (gg > gc) ii += 4;
if (gg > gd) ii += 8;
if (ii > 7) ii = 15 - ii;
if (ii <= 0) continue;
// DO LABEL HERE
if (( mark[ (ic) * nr + (ir) ] )==0) {
int kc, kr, mc, mr, jc, jr;
float xk, yk, xm, ym, value;
// Insert a label
// BOX TO AVOID
kc = ic-lc2-lcc;
kr = ir-lr2-lrr;
mc = kc+2*lcc+lc-1;
mr = kr+2*lrr+lr-1;
// OK here
for (jc=kc;jc<=mc;jc++) {
if (jc >= 0 && jc < nc) {
for (jr=kr;jr<=mr;jr++) {
if (jr >= 0 && jr < nr) {
if (( mark[ (jc) * nr + (jr) ] ) != 2) {
mark[ (jc) * nr + (jr) ] = 1;
}
}
}
}
}
// BOX TO HOLD LABEL
kc = ic-lc2;
kr = ir-lr2;
mc = kc+lc-1;
mr = kr+lr-1;
for (jc=kc;jc<=mc;jc++) {
if (jc >= 0 && jc < nc) {
for (jr=kr;jr<=mr;jr++) {
if (jr >= 0 && jr < nr) {
mark[ (jc) * nr + (jr) ] = 2;
}
}
}
}
xk = xdd*kr+0.0f;
yk = ydd*kc+0.0f;
xm = xdd*(mr+1.0f)+0.0f;
ym = ydd*(mc+1.0f)+0.0f;
value = gg;
if (numv4[0]+100 >= maxv4) {
// allocate more space
maxv4 = 2 * (numv4[0]+100);
float[][] tx = new float[][] {vx4[0]};
float[][] ty = new float[][] {vy4[0]};
vx4[0] = new float[maxv4];
vy4[0] = new float[maxv4];
System.arraycopy(tx[0], 0, vx4[0], 0, numv4[0]);
System.arraycopy(ty[0], 0, vy4[0], 0, numv4[0]);
}
if (numv3[0]+100 >= maxv3) {
// allocate more space
maxv3 = 2 * (numv3[0]+100);
float[][] tx = new float[][] {vx3[0]};
float[][] ty = new float[][] {vy3[0]};
vx3[0] = new float[maxv3];
vy3[0] = new float[maxv3];
System.arraycopy(tx[0], 0, vx3[0], 0, numv3[0]);
System.arraycopy(ty[0], 0, vy3[0], 0, numv3[0]);
if (naux > 0) {
byte[][] ta = auxLevels3;
for (int i=0; i<naux; i++) {
byte[] taa = auxLevels3[i];
auxLevels3[i] = new byte[maxv3];
System.arraycopy(taa, 0, auxLevels3[i], 0, numv3[0]);
}
}
}
plot.plotdigits( value, xk, yk, xm, ym, maxsize, swap);
System.arraycopy(plot.Vx, 0, vx3[0], numv3[0], plot.NumVerts);
System.arraycopy(plot.Vy, 0, vy3[0], numv3[0], plot.NumVerts);
if (naux > 0) {
for (int i=0; i<naux; i++) {
for (int j=numv3[0]; j<numv3[0]+plot.NumVerts; j++) {
auxLevels3[i][j] = auxa[i];
}
}
}
numv3[0] += plot.NumVerts;
System.arraycopy(plot.VxB, 0, vx4[0], numv4[0], plot.NumVerts);
System.arraycopy(plot.VyB, 0, vy4[0], numv4[0], plot.NumVerts);
numv4[0] += plot.NumVerts;
}
switch (ii) {
case 1:
gba = gb-ga;
gca = gc-ga;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratioca = (gg-ga)/gca;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001) {
vx[numv] = xx;
}
else {
vx[numv] = xx+xd*(gg-ga)/gba;
}
vy[numv] = yy;
numv++;
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001) {
vy[numv] = yy;
}
else {
vy[numv] = yy+yd*(gg-ga)/gca;
}
vx[numv] = xx;
numv++;
break;
case 2:
gba = gb-ga;
gdb = gd-gb;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratiodb = (gg-gb)/gdb;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-ga)/gba;
vy[numv] = yy;
numv++;
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
break;
case 3:
gca = gc-ga;
gdb = gd-gb;
if (naux > 0) {
float ratioca = (gg-ga)/gca;
float ratiodb = (gg-gb)/gdb;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
*/
}
}
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
break;
case 4:
gca = gc-ga;
gdc = gd-gc;
if (naux > 0) {
float ratioca = (gg-ga)/gca;
float ratiodc = (gg-gc)/gdc;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
case 5:
gba = gb-ga;
gdc = gd-gc;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratiodc = (gg-gc)/gdc;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-ga)/gba;
vy[numv] = yy;
numv++;
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
case 6:
gba = gb-ga;
gdc = gd-gc;
gca = gc-ga;
gdb = gd-gb;
if (naux > 0) {
float ratioba = (gg-ga)/gba;
float ratiodc = (gg-gc)/gdc;
float ratioca = (gg-ga)/gca;
float ratiodb = (gg-gb)/gdb;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
*/
if ( (gg>gv) ^ (ga<gb) ) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
/* MEM_WLH
auxLevels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
auxLevels[i][numv+2] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
*/
}
else {
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
auxLevels[i][numv+2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256)));
/* MEM_WLH
auxLevels[i][numv+1] = auxb[i] + (auxd[i]-auxb[i]) * ratiodb;
auxLevels[i][numv+2] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
*/
}
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv+3] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gba) < 0 ? -(gba) : (gba) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-ga)/gba;
vy[numv] = yy;
numv++;
// here's a brain teaser
if ( (gg>gv) ^ (ga<gb) ) { // (XOR)
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
}
else {
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
if (( (gca) < 0 ? -(gca) : (gca) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-ga)/gca;
vx[numv] = xx;
numv++;
}
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
case 7:
gdb = gd-gb;
gdc = gd-gc;
if (naux > 0) {
float ratiodb = (gg-gb)/gdb;
float ratiodc = (gg-gc)/gdc;
for (int i=0; i<naux; i++) {
t = (int) ( (1.0f - ratiodb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiodb * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiodc) * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) +
ratiodc * ((auxd[i] < 0) ?
((float) auxd[i]) + 256.0f : ((float) auxd[i]) ) );
auxLevels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxLevels[i][numv] = auxb[i] + (auxb[i]-auxb[i]) * ratiodb;
auxLevels[i][numv+1] = auxc[i] + (auxd[i]-auxc[i]) * ratiodc;
*/
}
}
if (( (gdb) < 0 ? -(gdb) : (gdb) ) < 0.0000001)
vy[numv] = yy;
else
vy[numv] = yy+yd*(gg-gb)/gdb;
vx[numv] = xx+xd;
numv++;
if (( (gdc) < 0 ? -(gdc) : (gdc) ) < 0.0000001)
vx[numv] = xx;
else
vx[numv] = xx+xd*(gg-gc)/gdc;
vy[numv] = yy+yd;
numv++;
break;
} // switch
// If contour level is negative, make dashed line
if (gg < base && dash) { /* DRM: 1999-05-19 */
float vxa, vya, vxb, vyb;
vxa = vx[numv-2];
vya = vy[numv-2];
vxb = vx[numv-1];
vyb = vy[numv-1];
vx[numv-2] = (3.0f*vxa+vxb) * 0.25f;
vy[numv-2] = (3.0f*vya+vyb) * 0.25f;
vx[numv-1] = (vxa+3.0f*vxb) * 0.25f;
vy[numv-1] = (vya+3.0f*vyb) * 0.25f;
}
/*
if ((20.0 <= vy[numv-2] && vy[numv-2] < 22.0) ||
(20.0 <= vy[numv-1] && vy[numv-1] < 22.0)) {
System.out.println("vy = " + vy[numv-1] + " " + vy[numv-2] +
" ic, ir = " + ic + " " + ir);
}
*/
} // for il -- NOTE: gg incremented in for statement
} // for ic
} // for ir
ipnt[nump] = numv;
// copy vertices from vx, vy arrays to either v1 or v2 arrays
ip = 0;
for (ir=0;ir<nrm && ip<2*maxsize;ir++) {
for (ic=0;ic<ncm && ip<2*maxsize;ic++) {
int start, len;
start = ipnt[ip];
len = ipnt[ip+1] - start;
if (len>0) {
if (( mark[ (ic) * nr + (ir) ] )==2) {
if (numv2[0]+len >= maxv2) {
// allocate more space
maxv2 = 2 * (numv2[0]+len);
float[][] tx = new float[][] {vx2[0]};
float[][] ty = new float[][] {vy2[0]};
vx2[0] = new float[maxv2];
vy2[0] = new float[maxv2];
System.arraycopy(tx[0], 0, vx2[0], 0, numv2[0]);
System.arraycopy(ty[0], 0, vy2[0], 0, numv2[0]);
if (naux > 0) {
for (int i=0; i<naux; i++) {
byte[] ta = auxLevels2[i];
auxLevels2[i] = new byte[maxv2];
System.arraycopy(ta, 0, auxLevels2[i], 0, numv2[0]);
}
}
}
for (il=0;il<len;il++) {
vx2[0][numv2[0]+il] = vx[start+il];
vy2[0][numv2[0]+il] = vy[start+il];
}
if (naux > 0) {
for (int i=0; i<naux; i++) {
for (il=0;il<len;il++) {
auxLevels2[i][numv2[0]+il] = auxLevels[i][start+il];
}
}
}
numv2[0] += len;
}
else {
if (numv1[0]+len >= maxv1) {
// allocate more space
maxv1 = 2 * (numv1[0]+len);
float[][] tx = new float[][] {vx1[0]};
float[][] ty = new float[][] {vy1[0]};
vx1[0] = new float[maxv1];
vy1[0] = new float[maxv1];
System.arraycopy(tx[0], 0, vx1[0], 0, numv1[0]);
System.arraycopy(ty[0], 0, vy1[0], 0, numv1[0]);
if (naux > 0) {
for (int i=0; i<naux; i++) {
byte[] ta = auxLevels1[i];
auxLevels1[i] = new byte[maxv1];
System.arraycopy(ta, 0, auxLevels1[i], 0, numv1[0]);
}
}
}
for (il=0; il<len; il++) {
vx1[0][numv1[0]+il] = vx[start+il];
vy1[0][numv1[0]+il] = vy[start+il];
}
if (naux > 0) {
for (int i=0; i<naux; i++) {
for (il=0;il<len;il++) {
auxLevels1[i][numv1[0]+il] = auxLevels[i][start+il];
}
}
}
numv1[0] += len;
}
}
ip++;
}
}
}
|
diff --git a/onebusaway-nyc-integration-tests/src/test/java/org/onebusaway/nyc/integration_tests/vehicle_tracking_webapp/AbstractTraceRunner.java b/onebusaway-nyc-integration-tests/src/test/java/org/onebusaway/nyc/integration_tests/vehicle_tracking_webapp/AbstractTraceRunner.java
index a0325a69f..6742cf19a 100644
--- a/onebusaway-nyc-integration-tests/src/test/java/org/onebusaway/nyc/integration_tests/vehicle_tracking_webapp/AbstractTraceRunner.java
+++ b/onebusaway-nyc-integration-tests/src/test/java/org/onebusaway/nyc/integration_tests/vehicle_tracking_webapp/AbstractTraceRunner.java
@@ -1,348 +1,348 @@
/**
* Copyright (c) 2011 Metropolitan Transportation Authority
*
* 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.onebusaway.nyc.integration_tests.vehicle_tracking_webapp;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.onebusaway.nyc.integration_tests.TraceSupport;
import org.onebusaway.nyc.vehicle_tracking.model.NycTestInferredLocationRecord;
import org.onebusaway.realtime.api.EVehiclePhase;
import org.onebusaway.utility.DateLibrary;
import org.opentripplanner.routing.impl.DistanceLibrary;
import com.vividsolutions.jts.geom.Coordinate;
public class AbstractTraceRunner {
private static TraceSupport _traceSupport = new TraceSupport();
private String _factorySeed = "298763210";
private String _cdfSeed = "184970829";
private String _trace;
/**
* The max amount of time we should wait for a single record to process
*/
private long _maxTimeout = 40 * 1000;
public AbstractTraceRunner() {
}
public AbstractTraceRunner(String trace) {
_trace = trace;
}
public void setTrace(String trace) {
_trace = trace;
}
public void setMaxTimeout(long maxTimeout) {
_maxTimeout = maxTimeout;
}
public void setBundle(String bundleId, String date) throws Exception {
setBundle(bundleId, DateLibrary.getIso8601StringAsTime(date));
}
public void setBundle(String bundleId, Date date) throws Exception {
String port = System.getProperty(
"org.onebusaway.transit_data_federation_webapp.port", "9905");
String url = "http://localhost:" + port
+ "/onebusaway-nyc-vehicle-tracking-webapp/change-bundle.do?bundleId="
+ bundleId + "&time=" + DateLibrary.getTimeAsIso8601String(date);
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(url);
client.executeMethod(get);
String response = get.getResponseBodyAsString();
if (!response.equals("OK"))
throw new Exception("Bundle switch failed!");
}
@Before
public void setup() throws Exception {
setSeeds();
}
public void setSeeds() throws Exception {
String port = System.getProperty(
"org.onebusaway.transit_data_federation_webapp.port", "9905");
String urlStr = "http://localhost:"
+ port
+ "/onebusaway-nyc-vehicle-tracking-webapp/vehicle-location-simulation!set-seeds.do?factorySeed="
+ _factorySeed + "&cdfSeed=" + _cdfSeed;
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(urlStr);
client.executeMethod(get);
String response = get.getResponseBodyAsString();
if (!response.equals("OK"))
throw new Exception("Failed trying to execute:" + urlStr);
System.out.println("Successfully set seeds: phase=" + _factorySeed
+ ", cdf=" + _cdfSeed);
}
@Test
public void test() throws Throwable {
int tries = 3;
while(tries-- > 0) {
try {
theRealTest();
} catch (AssertionError e) {
// out of tries
if(tries == 1) {
throw e;
// try again
} else {
continue;
}
}
break;
}
}
private void theRealTest() throws Throwable {
// expected results
File trace = new File("src/integration-test/resources/traces/" + _trace);
List<NycTestInferredLocationRecord> expectedResults = _traceSupport.readRecords(trace);
// run to get inferred results
String taskId = _traceSupport.uploadTraceForSimulation(trace, false);
long t = System.currentTimeMillis();
int prevRecordCount = -1;
while (true) {
List<NycTestInferredLocationRecord> ourResults = _traceSupport.getSimulationResults(taskId);
System.out.println("records=" + ourResults.size() + "/"
+ expectedResults.size());
// wait for all records to come in
if (ourResults.size() < expectedResults.size()) {
if (t + _maxTimeout < System.currentTimeMillis()) {
fail("waited but never received enough records: expected="
- + expectedResults.size() + " actual=" + expectedResults.size());
+ + expectedResults.size() + " actual=" + ourResults.size());
}
// We reset our timeout if the record count is growing
if (ourResults.size() > prevRecordCount) {
t = System.currentTimeMillis();
prevRecordCount = ourResults.size();
}
Thread.sleep(1000);
continue;
}
// all results are in!
// TEST: We got a response for all records.
assertEquals(ourResults.size(), expectedResults.size());
try {
// TEST: Our results match expected results
for (int i = 0; i < ourResults.size(); i++) {
NycTestInferredLocationRecord ourResult = ourResults.get(i);
NycTestInferredLocationRecord expectedResult = expectedResults.get(i);
// mark new row
System.out.println("\n\nRecord "
+ (i + 1)
+ ", line "
+ (i + 2)
+ ", observed timestamp= "
+ expectedResult.getTimestampAsDate()
+ "\n============================================================");
// TEST: block level inference subcases
Boolean actualIsRunFormal = expectedResult.getActualIsRunFormal();
assertTrue(actualIsRunFormal != null);
if (actualIsRunFormal == true) {
// run ID should match
if (expectedResult.getActualRunId() != null
&& !StringUtils.isEmpty(expectedResult.getActualRunId())) {
System.out.println("RUN ID: expected="
+ expectedResult.getActualRunId() + ", inferred="
+ ourResult.getInferredRunId());
assertEquals(ourResult.getInferredRunId(),
expectedResult.getActualRunId());
}
// trip ID should match--we accept wildcards (pegged to end of
// value) here
if (expectedResult.getActualTripId() != null
&& !StringUtils.isEmpty(expectedResult.getActualTripId())) {
System.out.println("TRIP ID: expected="
+ expectedResult.getActualTripId() + ", inferred="
+ ourResult.getInferredTripId());
assertTrue(ourResult.getInferredTripId().endsWith(
expectedResult.getActualTripId()));
}
// block ID should match--we accept wildcards (pegged to end of
// value) here
if (expectedResult.getActualBlockId() != null
&& !StringUtils.isEmpty(expectedResult.getActualBlockId())) {
System.out.println("BLOCK ID: expected="
+ expectedResult.getActualBlockId() + ", inferred="
+ ourResult.getInferredBlockId());
assertTrue(ourResult.getInferredBlockId().endsWith(
expectedResult.getActualBlockId()));
}
}
// TEST: DSCs should always match if we're in_progress
String expectedDsc = expectedResult.getActualDsc();
System.out.println("DSC: expected=" + expectedDsc + ", inferred="
+ ourResult.getInferredDsc());
if (expectedDsc != null && !StringUtils.isEmpty(expectedDsc)
/*
* Enforce the statement above that the DSCs should match if we're in-progress
*/
&& EVehiclePhase.IN_PROGRESS == EVehiclePhase.valueOf(ourResult.getInferredPhase()))
assertEquals(ourResult.getInferredDsc(), expectedDsc);
// TEST: phase matches
assertTrue(ourResult.getInferredPhase() != null);
System.out.println("PHASE: expected="
+ expectedResult.getActualPhase() + ", inferred="
+ ourResult.getInferredPhase());
if (expectedResult.getActualPhase() != null
&& !StringUtils.isEmpty(expectedResult.getActualPhase())) {
String[] _acceptablePhases = StringUtils.split(
expectedResult.getActualPhase().toUpperCase(), "+");
Set<String> acceptablePhases = new HashSet<String>();
Collections.addAll(acceptablePhases, _acceptablePhases);
// allow partial matches for "wildcards"
boolean phasesMatched = false;
for (String acceptablePhase : acceptablePhases) {
// try wildcard matching straight up
phasesMatched = ourResult.getInferredPhase().toUpperCase().startsWith(
acceptablePhase);
if (phasesMatched == true)
break;
// if inference is expected to be not formal, make layovers
// equivalent to deadheads
phasesMatched = ourResult.getInferredPhase().toUpperCase().replaceAll(
"^LAYOVER_", "DEADHEAD_").startsWith(acceptablePhase);
if (phasesMatched == true)
break;
phasesMatched = ourResult.getInferredPhase().toUpperCase().replaceAll(
"^DEADHEAD_", "LAYOVER_").startsWith(acceptablePhase);
if (phasesMatched == true)
break;
}
assertTrue(phasesMatched == true);
}
// TEST: status matches
assertTrue(ourResult.getInferredStatus() != null);
Set<String> acceptableStatuses = new HashSet<String>();
if (expectedResult.getActualStatus() != null
&& !StringUtils.isEmpty(expectedResult.getActualStatus())) {
String[] _acceptableStatuses = StringUtils.split(
expectedResult.getActualStatus().toUpperCase(), "+");
Collections.addAll(acceptableStatuses, _acceptableStatuses);
}
Set<String> receivedStatuses = new HashSet<String>();
if (ourResult.getInferredStatus() != null
&& !StringUtils.isEmpty(ourResult.getInferredStatus())) {
String[] _receivedStatuses = StringUtils.split(
ourResult.getInferredStatus().toUpperCase(), "+");
Collections.addAll(receivedStatuses, _receivedStatuses);
}
System.out.println("STATUS: expected=" + acceptableStatuses
+ ", inferred=" + receivedStatuses);
// if inferred result is detoured, make sure we expect that here
if (!acceptableStatuses.isEmpty()
&& receivedStatuses.contains("DEVIATED")) {
assertTrue(acceptableStatuses.contains("DEVIATED"));
}
// If trace expects detoured, and only detour, then make sure we got that here.
// Note that this only holds when the inferred status is in-progress, since
// deadheads aren't deviated. Also, if the inferred phase wasn't acceptable, then
// we should've caught that earlier.
if (acceptableStatuses.size() == 1
&& ourResult.getInferredPhase() == "IN_PROGRESS"
&& acceptableStatuses.contains("DEVIATED")) {
assertTrue(receivedStatuses.contains("DEVIATED"));
}
// TEST: distance along block/inferred location/schedule deviation
assertTrue(ourResult.getInferredBlockLat() != Double.NaN);
assertTrue(ourResult.getInferredBlockLon() != Double.NaN);
Coordinate reportedLocation = new Coordinate(expectedResult.getLat(),
expectedResult.getLon());
Coordinate ourLocation = new Coordinate(
ourResult.getInferredBlockLat(), ourResult.getInferredBlockLon());
if (ourResult.getInferredPhase().toUpperCase().startsWith("LAYOVER_")
|| ourResult.getInferredPhase().toUpperCase().equals(
"IN_PROGRESS")) {
System.out.println("LOCATION: expected=" + reportedLocation
+ ", inferred=" + ourLocation);
assertTrue(DistanceLibrary.distance(reportedLocation, ourLocation) <= 500 * 2);
}
}
System.out.println("\n>> PASS.");
} catch (AssertionError e) {
System.out.println(">> TEST FAILED HERE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
throw e;
}
// break out of wait-for-completion loop
break;
}
}
}
| true | true | private void theRealTest() throws Throwable {
// expected results
File trace = new File("src/integration-test/resources/traces/" + _trace);
List<NycTestInferredLocationRecord> expectedResults = _traceSupport.readRecords(trace);
// run to get inferred results
String taskId = _traceSupport.uploadTraceForSimulation(trace, false);
long t = System.currentTimeMillis();
int prevRecordCount = -1;
while (true) {
List<NycTestInferredLocationRecord> ourResults = _traceSupport.getSimulationResults(taskId);
System.out.println("records=" + ourResults.size() + "/"
+ expectedResults.size());
// wait for all records to come in
if (ourResults.size() < expectedResults.size()) {
if (t + _maxTimeout < System.currentTimeMillis()) {
fail("waited but never received enough records: expected="
+ expectedResults.size() + " actual=" + expectedResults.size());
}
// We reset our timeout if the record count is growing
if (ourResults.size() > prevRecordCount) {
t = System.currentTimeMillis();
prevRecordCount = ourResults.size();
}
Thread.sleep(1000);
continue;
}
// all results are in!
// TEST: We got a response for all records.
assertEquals(ourResults.size(), expectedResults.size());
try {
// TEST: Our results match expected results
for (int i = 0; i < ourResults.size(); i++) {
NycTestInferredLocationRecord ourResult = ourResults.get(i);
NycTestInferredLocationRecord expectedResult = expectedResults.get(i);
// mark new row
System.out.println("\n\nRecord "
+ (i + 1)
+ ", line "
+ (i + 2)
+ ", observed timestamp= "
+ expectedResult.getTimestampAsDate()
+ "\n============================================================");
// TEST: block level inference subcases
Boolean actualIsRunFormal = expectedResult.getActualIsRunFormal();
assertTrue(actualIsRunFormal != null);
if (actualIsRunFormal == true) {
// run ID should match
if (expectedResult.getActualRunId() != null
&& !StringUtils.isEmpty(expectedResult.getActualRunId())) {
System.out.println("RUN ID: expected="
+ expectedResult.getActualRunId() + ", inferred="
+ ourResult.getInferredRunId());
assertEquals(ourResult.getInferredRunId(),
expectedResult.getActualRunId());
}
// trip ID should match--we accept wildcards (pegged to end of
// value) here
if (expectedResult.getActualTripId() != null
&& !StringUtils.isEmpty(expectedResult.getActualTripId())) {
System.out.println("TRIP ID: expected="
+ expectedResult.getActualTripId() + ", inferred="
+ ourResult.getInferredTripId());
assertTrue(ourResult.getInferredTripId().endsWith(
expectedResult.getActualTripId()));
}
// block ID should match--we accept wildcards (pegged to end of
// value) here
if (expectedResult.getActualBlockId() != null
&& !StringUtils.isEmpty(expectedResult.getActualBlockId())) {
System.out.println("BLOCK ID: expected="
+ expectedResult.getActualBlockId() + ", inferred="
+ ourResult.getInferredBlockId());
assertTrue(ourResult.getInferredBlockId().endsWith(
expectedResult.getActualBlockId()));
}
}
// TEST: DSCs should always match if we're in_progress
String expectedDsc = expectedResult.getActualDsc();
System.out.println("DSC: expected=" + expectedDsc + ", inferred="
+ ourResult.getInferredDsc());
if (expectedDsc != null && !StringUtils.isEmpty(expectedDsc)
/*
* Enforce the statement above that the DSCs should match if we're in-progress
*/
&& EVehiclePhase.IN_PROGRESS == EVehiclePhase.valueOf(ourResult.getInferredPhase()))
assertEquals(ourResult.getInferredDsc(), expectedDsc);
// TEST: phase matches
assertTrue(ourResult.getInferredPhase() != null);
System.out.println("PHASE: expected="
+ expectedResult.getActualPhase() + ", inferred="
+ ourResult.getInferredPhase());
if (expectedResult.getActualPhase() != null
&& !StringUtils.isEmpty(expectedResult.getActualPhase())) {
String[] _acceptablePhases = StringUtils.split(
expectedResult.getActualPhase().toUpperCase(), "+");
Set<String> acceptablePhases = new HashSet<String>();
Collections.addAll(acceptablePhases, _acceptablePhases);
// allow partial matches for "wildcards"
boolean phasesMatched = false;
for (String acceptablePhase : acceptablePhases) {
// try wildcard matching straight up
phasesMatched = ourResult.getInferredPhase().toUpperCase().startsWith(
acceptablePhase);
if (phasesMatched == true)
break;
// if inference is expected to be not formal, make layovers
// equivalent to deadheads
phasesMatched = ourResult.getInferredPhase().toUpperCase().replaceAll(
"^LAYOVER_", "DEADHEAD_").startsWith(acceptablePhase);
if (phasesMatched == true)
break;
phasesMatched = ourResult.getInferredPhase().toUpperCase().replaceAll(
"^DEADHEAD_", "LAYOVER_").startsWith(acceptablePhase);
if (phasesMatched == true)
break;
}
assertTrue(phasesMatched == true);
}
// TEST: status matches
assertTrue(ourResult.getInferredStatus() != null);
Set<String> acceptableStatuses = new HashSet<String>();
if (expectedResult.getActualStatus() != null
&& !StringUtils.isEmpty(expectedResult.getActualStatus())) {
String[] _acceptableStatuses = StringUtils.split(
expectedResult.getActualStatus().toUpperCase(), "+");
Collections.addAll(acceptableStatuses, _acceptableStatuses);
}
Set<String> receivedStatuses = new HashSet<String>();
if (ourResult.getInferredStatus() != null
&& !StringUtils.isEmpty(ourResult.getInferredStatus())) {
String[] _receivedStatuses = StringUtils.split(
ourResult.getInferredStatus().toUpperCase(), "+");
Collections.addAll(receivedStatuses, _receivedStatuses);
}
System.out.println("STATUS: expected=" + acceptableStatuses
+ ", inferred=" + receivedStatuses);
// if inferred result is detoured, make sure we expect that here
if (!acceptableStatuses.isEmpty()
&& receivedStatuses.contains("DEVIATED")) {
assertTrue(acceptableStatuses.contains("DEVIATED"));
}
// If trace expects detoured, and only detour, then make sure we got that here.
// Note that this only holds when the inferred status is in-progress, since
// deadheads aren't deviated. Also, if the inferred phase wasn't acceptable, then
// we should've caught that earlier.
if (acceptableStatuses.size() == 1
&& ourResult.getInferredPhase() == "IN_PROGRESS"
&& acceptableStatuses.contains("DEVIATED")) {
assertTrue(receivedStatuses.contains("DEVIATED"));
}
// TEST: distance along block/inferred location/schedule deviation
assertTrue(ourResult.getInferredBlockLat() != Double.NaN);
assertTrue(ourResult.getInferredBlockLon() != Double.NaN);
Coordinate reportedLocation = new Coordinate(expectedResult.getLat(),
expectedResult.getLon());
Coordinate ourLocation = new Coordinate(
ourResult.getInferredBlockLat(), ourResult.getInferredBlockLon());
if (ourResult.getInferredPhase().toUpperCase().startsWith("LAYOVER_")
|| ourResult.getInferredPhase().toUpperCase().equals(
"IN_PROGRESS")) {
System.out.println("LOCATION: expected=" + reportedLocation
+ ", inferred=" + ourLocation);
assertTrue(DistanceLibrary.distance(reportedLocation, ourLocation) <= 500 * 2);
}
}
System.out.println("\n>> PASS.");
} catch (AssertionError e) {
System.out.println(">> TEST FAILED HERE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
throw e;
}
// break out of wait-for-completion loop
break;
}
}
| private void theRealTest() throws Throwable {
// expected results
File trace = new File("src/integration-test/resources/traces/" + _trace);
List<NycTestInferredLocationRecord> expectedResults = _traceSupport.readRecords(trace);
// run to get inferred results
String taskId = _traceSupport.uploadTraceForSimulation(trace, false);
long t = System.currentTimeMillis();
int prevRecordCount = -1;
while (true) {
List<NycTestInferredLocationRecord> ourResults = _traceSupport.getSimulationResults(taskId);
System.out.println("records=" + ourResults.size() + "/"
+ expectedResults.size());
// wait for all records to come in
if (ourResults.size() < expectedResults.size()) {
if (t + _maxTimeout < System.currentTimeMillis()) {
fail("waited but never received enough records: expected="
+ expectedResults.size() + " actual=" + ourResults.size());
}
// We reset our timeout if the record count is growing
if (ourResults.size() > prevRecordCount) {
t = System.currentTimeMillis();
prevRecordCount = ourResults.size();
}
Thread.sleep(1000);
continue;
}
// all results are in!
// TEST: We got a response for all records.
assertEquals(ourResults.size(), expectedResults.size());
try {
// TEST: Our results match expected results
for (int i = 0; i < ourResults.size(); i++) {
NycTestInferredLocationRecord ourResult = ourResults.get(i);
NycTestInferredLocationRecord expectedResult = expectedResults.get(i);
// mark new row
System.out.println("\n\nRecord "
+ (i + 1)
+ ", line "
+ (i + 2)
+ ", observed timestamp= "
+ expectedResult.getTimestampAsDate()
+ "\n============================================================");
// TEST: block level inference subcases
Boolean actualIsRunFormal = expectedResult.getActualIsRunFormal();
assertTrue(actualIsRunFormal != null);
if (actualIsRunFormal == true) {
// run ID should match
if (expectedResult.getActualRunId() != null
&& !StringUtils.isEmpty(expectedResult.getActualRunId())) {
System.out.println("RUN ID: expected="
+ expectedResult.getActualRunId() + ", inferred="
+ ourResult.getInferredRunId());
assertEquals(ourResult.getInferredRunId(),
expectedResult.getActualRunId());
}
// trip ID should match--we accept wildcards (pegged to end of
// value) here
if (expectedResult.getActualTripId() != null
&& !StringUtils.isEmpty(expectedResult.getActualTripId())) {
System.out.println("TRIP ID: expected="
+ expectedResult.getActualTripId() + ", inferred="
+ ourResult.getInferredTripId());
assertTrue(ourResult.getInferredTripId().endsWith(
expectedResult.getActualTripId()));
}
// block ID should match--we accept wildcards (pegged to end of
// value) here
if (expectedResult.getActualBlockId() != null
&& !StringUtils.isEmpty(expectedResult.getActualBlockId())) {
System.out.println("BLOCK ID: expected="
+ expectedResult.getActualBlockId() + ", inferred="
+ ourResult.getInferredBlockId());
assertTrue(ourResult.getInferredBlockId().endsWith(
expectedResult.getActualBlockId()));
}
}
// TEST: DSCs should always match if we're in_progress
String expectedDsc = expectedResult.getActualDsc();
System.out.println("DSC: expected=" + expectedDsc + ", inferred="
+ ourResult.getInferredDsc());
if (expectedDsc != null && !StringUtils.isEmpty(expectedDsc)
/*
* Enforce the statement above that the DSCs should match if we're in-progress
*/
&& EVehiclePhase.IN_PROGRESS == EVehiclePhase.valueOf(ourResult.getInferredPhase()))
assertEquals(ourResult.getInferredDsc(), expectedDsc);
// TEST: phase matches
assertTrue(ourResult.getInferredPhase() != null);
System.out.println("PHASE: expected="
+ expectedResult.getActualPhase() + ", inferred="
+ ourResult.getInferredPhase());
if (expectedResult.getActualPhase() != null
&& !StringUtils.isEmpty(expectedResult.getActualPhase())) {
String[] _acceptablePhases = StringUtils.split(
expectedResult.getActualPhase().toUpperCase(), "+");
Set<String> acceptablePhases = new HashSet<String>();
Collections.addAll(acceptablePhases, _acceptablePhases);
// allow partial matches for "wildcards"
boolean phasesMatched = false;
for (String acceptablePhase : acceptablePhases) {
// try wildcard matching straight up
phasesMatched = ourResult.getInferredPhase().toUpperCase().startsWith(
acceptablePhase);
if (phasesMatched == true)
break;
// if inference is expected to be not formal, make layovers
// equivalent to deadheads
phasesMatched = ourResult.getInferredPhase().toUpperCase().replaceAll(
"^LAYOVER_", "DEADHEAD_").startsWith(acceptablePhase);
if (phasesMatched == true)
break;
phasesMatched = ourResult.getInferredPhase().toUpperCase().replaceAll(
"^DEADHEAD_", "LAYOVER_").startsWith(acceptablePhase);
if (phasesMatched == true)
break;
}
assertTrue(phasesMatched == true);
}
// TEST: status matches
assertTrue(ourResult.getInferredStatus() != null);
Set<String> acceptableStatuses = new HashSet<String>();
if (expectedResult.getActualStatus() != null
&& !StringUtils.isEmpty(expectedResult.getActualStatus())) {
String[] _acceptableStatuses = StringUtils.split(
expectedResult.getActualStatus().toUpperCase(), "+");
Collections.addAll(acceptableStatuses, _acceptableStatuses);
}
Set<String> receivedStatuses = new HashSet<String>();
if (ourResult.getInferredStatus() != null
&& !StringUtils.isEmpty(ourResult.getInferredStatus())) {
String[] _receivedStatuses = StringUtils.split(
ourResult.getInferredStatus().toUpperCase(), "+");
Collections.addAll(receivedStatuses, _receivedStatuses);
}
System.out.println("STATUS: expected=" + acceptableStatuses
+ ", inferred=" + receivedStatuses);
// if inferred result is detoured, make sure we expect that here
if (!acceptableStatuses.isEmpty()
&& receivedStatuses.contains("DEVIATED")) {
assertTrue(acceptableStatuses.contains("DEVIATED"));
}
// If trace expects detoured, and only detour, then make sure we got that here.
// Note that this only holds when the inferred status is in-progress, since
// deadheads aren't deviated. Also, if the inferred phase wasn't acceptable, then
// we should've caught that earlier.
if (acceptableStatuses.size() == 1
&& ourResult.getInferredPhase() == "IN_PROGRESS"
&& acceptableStatuses.contains("DEVIATED")) {
assertTrue(receivedStatuses.contains("DEVIATED"));
}
// TEST: distance along block/inferred location/schedule deviation
assertTrue(ourResult.getInferredBlockLat() != Double.NaN);
assertTrue(ourResult.getInferredBlockLon() != Double.NaN);
Coordinate reportedLocation = new Coordinate(expectedResult.getLat(),
expectedResult.getLon());
Coordinate ourLocation = new Coordinate(
ourResult.getInferredBlockLat(), ourResult.getInferredBlockLon());
if (ourResult.getInferredPhase().toUpperCase().startsWith("LAYOVER_")
|| ourResult.getInferredPhase().toUpperCase().equals(
"IN_PROGRESS")) {
System.out.println("LOCATION: expected=" + reportedLocation
+ ", inferred=" + ourLocation);
assertTrue(DistanceLibrary.distance(reportedLocation, ourLocation) <= 500 * 2);
}
}
System.out.println("\n>> PASS.");
} catch (AssertionError e) {
System.out.println(">> TEST FAILED HERE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n");
throw e;
}
// break out of wait-for-completion loop
break;
}
}
|
diff --git a/kryonet/src/com/esotericsoftware/kryonet/Server.java b/kryonet/src/com/esotericsoftware/kryonet/Server.java
index 25c807e..25f2f32 100644
--- a/kryonet/src/com/esotericsoftware/kryonet/Server.java
+++ b/kryonet/src/com/esotericsoftware/kryonet/Server.java
@@ -1,549 +1,555 @@
package com.esotericsoftware.kryonet;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.util.IntMap;
import com.esotericsoftware.kryonet.FrameworkMessage.DiscoverHost;
import com.esotericsoftware.kryonet.FrameworkMessage.RegisterTCP;
import com.esotericsoftware.kryonet.FrameworkMessage.RegisterUDP;
import static com.esotericsoftware.minlog.Log.*;
/** Manages TCP and optionally UDP connections from many {@link Client Clients}.
* @author Nathan Sweet <[email protected]> */
public class Server implements EndPoint {
private final Serialization serialization;
private final int writeBufferSize, objectBufferSize;
private final Selector selector;
private ServerSocketChannel serverChannel;
private UdpConnection udp;
private Connection[] connections = {};
private IntMap<Connection> pendingConnections = new IntMap();
Listener[] listeners = {};
private Object listenerLock = new Object();
private int nextConnectionID = 1;
private volatile boolean shutdown;
private Object updateLock = new Object();
private Thread updateThread;
private ByteBuffer emptyBuffer = ByteBuffer.allocate(0);
private Listener dispatchListener = new Listener() {
public void connected (Connection connection) {
Listener[] listeners = Server.this.listeners;
for (int i = 0, n = listeners.length; i < n; i++)
listeners[i].connected(connection);
}
public void disconnected (Connection connection) {
removeConnection(connection);
Listener[] listeners = Server.this.listeners;
for (int i = 0, n = listeners.length; i < n; i++)
listeners[i].disconnected(connection);
}
public void received (Connection connection, Object object) {
Listener[] listeners = Server.this.listeners;
for (int i = 0, n = listeners.length; i < n; i++)
listeners[i].received(connection, object);
}
public void idle (Connection connection) {
Listener[] listeners = Server.this.listeners;
for (int i = 0, n = listeners.length; i < n; i++)
listeners[i].idle(connection);
}
};
/** Creates a Server with a write buffer size of 16384 and an object buffer size of 2048. */
public Server () {
this(16384, 2048);
}
/** @param writeBufferSize One buffer of this size is allocated for each connected client. Objects are serialized to the write
* buffer where the bytes are queued until they can be written to the socket.
* <p>
* Normally the socket is writable and the bytes are written immediately. If the socket cannot be written to and
* enough serialized objects are queued to overflow the buffer, then the connection will be closed.
* <p>
* The write buffer should be sized at least as large as the largest object that will be sent, plus some head room to
* allow for some serialized objects to be queued in case the buffer is temporarily not writable. The amount of head
* room needed is dependent upon the size of objects being sent and how often they are sent.
* @param objectBufferSize Two (using only TCP) or four (using both TCP and UDP) buffers of this size are allocated. These
* buffers are used to hold the bytes for a single object graph until it can be sent over the network or
* deserialized.
* <p>
* The object buffers should be sized at least as large as the largest object that will be sent or received. */
public Server (int writeBufferSize, int objectBufferSize) {
this(writeBufferSize, objectBufferSize, new KryoSerialization());
}
public Server (int writeBufferSize, int objectBufferSize, Serialization serialization) {
this.writeBufferSize = writeBufferSize;
this.objectBufferSize = objectBufferSize;
this.serialization = serialization;
try {
selector = Selector.open();
} catch (IOException ex) {
throw new RuntimeException("Error opening selector.", ex);
}
}
public Serialization getSerialization () {
return serialization;
}
public Kryo getKryo () {
return ((KryoSerialization)serialization).getKryo();
}
/** Opens a TCP only server.
* @throws IOException if the server could not be opened. */
public void bind (int tcpPort) throws IOException {
bind(new InetSocketAddress(tcpPort), null);
}
/** Opens a TCP and UDP server.
* @throws IOException if the server could not be opened. */
public void bind (int tcpPort, int udpPort) throws IOException {
bind(new InetSocketAddress(tcpPort), new InetSocketAddress(udpPort));
}
/** @param udpPort May be null. */
public void bind (InetSocketAddress tcpPort, InetSocketAddress udpPort) throws IOException {
close();
synchronized (updateLock) {
selector.wakeup();
try {
serverChannel = selector.provider().openServerSocketChannel();
serverChannel.socket().bind(tcpPort);
serverChannel.configureBlocking(false);
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
if (DEBUG) debug("kryonet", "Accepting connections on port: " + tcpPort + "/TCP");
if (udpPort != null) {
udp = new UdpConnection(serialization, objectBufferSize);
udp.bind(selector, udpPort);
if (DEBUG) debug("kryonet", "Accepting connections on port: " + udpPort + "/UDP");
}
} catch (IOException ex) {
close();
throw ex;
}
}
if (INFO) info("kryonet", "Server opened.");
}
/** Accepts any new connections and reads or writes any pending data for the current connections.
* @param timeout Wait for up to the specified milliseconds for a connection to be ready to process. May be zero to return
* immediately if there are no connections to process. */
public void update (int timeout) throws IOException {
updateThread = Thread.currentThread();
synchronized (updateLock) { // Blocks to avoid a select while the selector is used to bind the server connection.
}
long startTime = System.currentTimeMillis();
int select = 0;
if (timeout > 0) {
select = selector.select(timeout);
} else {
select = selector.selectNow();
}
System.out.println(select);
if (select == 0) {
// NIO freaks and returns immediately with 0 sometimes, so try to keep from hogging the CPU.
long elapsedTime = System.currentTimeMillis() - startTime;
try {
if (elapsedTime < 25) Thread.sleep(25 - elapsedTime);
} catch (InterruptedException ex) {
}
} else {
Set<SelectionKey> keys = selector.selectedKeys();
synchronized (keys) {
UdpConnection udp = this.udp;
outer:
for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) {
SelectionKey selectionKey = iter.next();
iter.remove();
+ Connection fromConnection = (Connection)selectionKey.attachment();
try {
int ops = selectionKey.readyOps();
- Connection fromConnection = (Connection)selectionKey.attachment();
if (fromConnection != null) { // Must be a TCP read or write operation.
if (udp != null && fromConnection.udpRemoteAddress == null) {
fromConnection.close();
continue;
}
if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
try {
while (true) {
Object object = fromConnection.tcp.readObject(fromConnection);
if (object == null) break;
if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (!(object instanceof FrameworkMessage)) {
debug("kryonet", fromConnection + " received TCP: " + objectString);
} else if (TRACE) {
trace("kryonet", fromConnection + " received TCP: " + objectString);
}
}
fromConnection.notifyReceived(object);
}
} catch (IOException ex) {
if (TRACE) {
trace("kryonet", "Unable to read TCP from: " + fromConnection, ex);
} else if (DEBUG) {
debug("kryonet", fromConnection + " update: " + ex.getMessage());
}
fromConnection.close();
} catch (KryoNetException ex) {
if (ERROR) error("kryonet", "Error reading TCP from connection: " + fromConnection, ex);
fromConnection.close();
}
}
if ((ops & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
try {
fromConnection.tcp.writeOperation();
} catch (IOException ex) {
if (TRACE) {
trace("kryonet", "Unable to write TCP to connection: " + fromConnection, ex);
} else if (DEBUG) {
debug("kryonet", fromConnection + " update: " + ex.getMessage());
}
fromConnection.close();
}
}
continue;
}
if ((ops & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
ServerSocketChannel serverChannel = this.serverChannel;
if (serverChannel == null) continue;
try {
SocketChannel socketChannel = serverChannel.accept();
if (socketChannel != null) acceptOperation(socketChannel);
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to accept new connection.", ex);
}
continue;
}
// Must be a UDP read operation.
- if (udp == null) continue;
+ if (udp == null) {
+ selectionKey.channel().close();
+ continue;
+ }
InetSocketAddress fromAddress;
try {
fromAddress = udp.readFromAddress();
} catch (IOException ex) {
if (WARN) warn("kryonet", "Error reading UDP data.", ex);
continue;
}
if (fromAddress == null) continue;
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (fromAddress.equals(connection.udpRemoteAddress)) {
fromConnection = connection;
break;
}
}
Object object;
try {
object = udp.readObject(fromConnection);
} catch (KryoNetException ex) {
if (WARN) {
if (fromConnection != null) {
if (ERROR) error("kryonet", "Error reading UDP from connection: " + fromConnection, ex);
} else
warn("kryonet", "Error reading UDP from unregistered address: " + fromAddress, ex);
}
continue;
}
if (object instanceof FrameworkMessage) {
if (object instanceof RegisterUDP) {
// Store the fromAddress on the connection and reply over TCP with a RegisterUDP to indicate success.
int fromConnectionID = ((RegisterUDP)object).connectionID;
Connection connection = pendingConnections.remove(fromConnectionID);
if (connection != null) {
if (connection.udpRemoteAddress != null) continue outer;
connection.udpRemoteAddress = fromAddress;
addConnection(connection);
connection.sendTCP(new RegisterUDP());
if (DEBUG)
debug("kryonet", "Port " + udp.datagramChannel.socket().getLocalPort() + "/UDP connected to: "
+ fromAddress);
connection.notifyConnected();
continue;
}
if (DEBUG)
debug("kryonet", "Ignoring incoming RegisterUDP with invalid connection ID: " + fromConnectionID);
continue;
}
if (object instanceof DiscoverHost) {
try {
udp.datagramChannel.send(emptyBuffer, fromAddress);
if (DEBUG) debug("kryonet", "Responded to host discovery from: " + fromAddress);
} catch (IOException ex) {
if (WARN) warn("kryonet", "Error replying to host discovery from: " + fromAddress, ex);
}
continue;
}
}
if (fromConnection != null) {
if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (object instanceof FrameworkMessage) {
if (TRACE) trace("kryonet", fromConnection + " received UDP: " + objectString);
} else
debug("kryonet", fromConnection + " received UDP: " + objectString);
}
fromConnection.notifyReceived(object);
continue;
}
if (DEBUG) debug("kryonet", "Ignoring UDP from unregistered address: " + fromAddress);
- } catch (CancelledKeyException ignored) {
- // Connection is closed.
+ } catch (CancelledKeyException ex) {
+ if (fromConnection != null)
+ fromConnection.close();
+ else
+ selectionKey.channel().close();
}
}
}
}
long time = System.currentTimeMillis();
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.tcp.isTimedOut(time)) {
if (DEBUG) debug("kryonet", connection + " timed out.");
connection.close();
} else {
if (connection.tcp.needsKeepAlive(time)) connection.sendTCP(FrameworkMessage.keepAlive);
}
if (connection.isIdle()) connection.notifyIdle();
}
}
public void run () {
if (TRACE) trace("kryonet", "Server thread started.");
shutdown = false;
while (!shutdown) {
try {
update(250);
} catch (IOException ex) {
if (ERROR) error("kryonet", "Error updating server connections.", ex);
close();
}
}
if (TRACE) trace("kryonet", "Server thread stopped.");
}
public void start () {
new Thread(this, "Server").start();
}
public void stop () {
if (shutdown) return;
close();
if (TRACE) trace("kryonet", "Server thread stopping.");
shutdown = true;
}
private void acceptOperation (SocketChannel socketChannel) {
Connection connection = newConnection();
connection.initialize(serialization, writeBufferSize, objectBufferSize);
connection.endPoint = this;
UdpConnection udp = this.udp;
if (udp != null) connection.udp = udp;
try {
SelectionKey selectionKey = connection.tcp.accept(selector, socketChannel);
selectionKey.attach(connection);
int id = nextConnectionID++;
if (nextConnectionID == -1) nextConnectionID = 1;
connection.id = id;
connection.setConnected(true);
connection.addListener(dispatchListener);
if (udp == null)
addConnection(connection);
else
pendingConnections.put(id, connection);
RegisterTCP registerConnection = new RegisterTCP();
registerConnection.connectionID = id;
connection.sendTCP(registerConnection);
if (udp == null) connection.notifyConnected();
} catch (IOException ex) {
connection.close();
if (DEBUG) debug("kryonet", "Unable to accept TCP connection.", ex);
}
}
/** Allows the connections used by the server to be subclassed. This can be useful for storage per connection without an
* additional lookup. */
protected Connection newConnection () {
return new Connection();
}
private void addConnection (Connection connection) {
Connection[] newConnections = new Connection[connections.length + 1];
newConnections[0] = connection;
System.arraycopy(connections, 0, newConnections, 1, connections.length);
connections = newConnections;
}
void removeConnection (Connection connection) {
ArrayList<Connection> temp = new ArrayList(Arrays.asList(connections));
temp.remove(connection);
connections = temp.toArray(new Connection[temp.size()]);
pendingConnections.remove(connection.id);
}
// BOZO - Provide mechanism for sending to multiple clients without serializing multiple times.
public void sendToAllTCP (Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
connection.sendTCP(object);
}
}
public void sendToAllExceptTCP (int connectionID, Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.id != connectionID) connection.sendTCP(object);
}
}
public void sendToTCP (int connectionID, Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.id == connectionID) {
connection.sendTCP(object);
break;
}
}
}
public void sendToAllUDP (Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
connection.sendUDP(object);
}
}
public void sendToAllExceptUDP (int connectionID, Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.id != connectionID) connection.sendUDP(object);
}
}
public void sendToUDP (int connectionID, Object object) {
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.id == connectionID) {
connection.sendUDP(object);
break;
}
}
}
public void addListener (Listener listener) {
if (listener == null) throw new IllegalArgumentException("listener cannot be null.");
synchronized (listenerLock) {
Listener[] listeners = this.listeners;
int n = listeners.length;
for (int i = 0; i < n; i++)
if (listener == listeners[i]) return;
Listener[] newListeners = new Listener[n + 1];
newListeners[0] = listener;
System.arraycopy(listeners, 0, newListeners, 1, n);
this.listeners = newListeners;
}
if (TRACE) trace("kryonet", "Server listener added: " + listener.getClass().getName());
}
public void removeListener (Listener listener) {
if (listener == null) throw new IllegalArgumentException("listener cannot be null.");
synchronized (listenerLock) {
Listener[] listeners = this.listeners;
int n = listeners.length;
Listener[] newListeners = new Listener[n - 1];
for (int i = 0, ii = 0; i < n; i++) {
Listener copyListener = listeners[i];
if (listener == copyListener) continue;
if (ii == n - 1) return;
newListeners[ii++] = copyListener;
}
this.listeners = newListeners;
}
if (TRACE) trace("kryonet", "Server listener removed: " + listener.getClass().getName());
}
/** Closes all open connections and the server port(s). */
public void close () {
Connection[] connections = this.connections;
if (INFO && connections.length > 0) info("kryonet", "Closing server connections...");
for (int i = 0, n = connections.length; i < n; i++)
connections[i].close();
connections = new Connection[0];
ServerSocketChannel serverChannel = this.serverChannel;
if (serverChannel != null) {
try {
serverChannel.close();
if (INFO) info("kryonet", "Server closed.");
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to close server.", ex);
}
this.serverChannel = null;
}
UdpConnection udp = this.udp;
if (udp != null) {
udp.close();
this.udp = null;
}
// Select one last time to complete closing the socket.
synchronized (updateLock) {
selector.wakeup();
try {
selector.selectNow();
} catch (IOException ignored) {
}
}
}
public Thread getUpdateThread () {
return updateThread;
}
/** Returns the current connections. The array returned should not be modified. */
public Connection[] getConnections () {
return connections;
}
}
| false | true | public void update (int timeout) throws IOException {
updateThread = Thread.currentThread();
synchronized (updateLock) { // Blocks to avoid a select while the selector is used to bind the server connection.
}
long startTime = System.currentTimeMillis();
int select = 0;
if (timeout > 0) {
select = selector.select(timeout);
} else {
select = selector.selectNow();
}
System.out.println(select);
if (select == 0) {
// NIO freaks and returns immediately with 0 sometimes, so try to keep from hogging the CPU.
long elapsedTime = System.currentTimeMillis() - startTime;
try {
if (elapsedTime < 25) Thread.sleep(25 - elapsedTime);
} catch (InterruptedException ex) {
}
} else {
Set<SelectionKey> keys = selector.selectedKeys();
synchronized (keys) {
UdpConnection udp = this.udp;
outer:
for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) {
SelectionKey selectionKey = iter.next();
iter.remove();
try {
int ops = selectionKey.readyOps();
Connection fromConnection = (Connection)selectionKey.attachment();
if (fromConnection != null) { // Must be a TCP read or write operation.
if (udp != null && fromConnection.udpRemoteAddress == null) {
fromConnection.close();
continue;
}
if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
try {
while (true) {
Object object = fromConnection.tcp.readObject(fromConnection);
if (object == null) break;
if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (!(object instanceof FrameworkMessage)) {
debug("kryonet", fromConnection + " received TCP: " + objectString);
} else if (TRACE) {
trace("kryonet", fromConnection + " received TCP: " + objectString);
}
}
fromConnection.notifyReceived(object);
}
} catch (IOException ex) {
if (TRACE) {
trace("kryonet", "Unable to read TCP from: " + fromConnection, ex);
} else if (DEBUG) {
debug("kryonet", fromConnection + " update: " + ex.getMessage());
}
fromConnection.close();
} catch (KryoNetException ex) {
if (ERROR) error("kryonet", "Error reading TCP from connection: " + fromConnection, ex);
fromConnection.close();
}
}
if ((ops & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
try {
fromConnection.tcp.writeOperation();
} catch (IOException ex) {
if (TRACE) {
trace("kryonet", "Unable to write TCP to connection: " + fromConnection, ex);
} else if (DEBUG) {
debug("kryonet", fromConnection + " update: " + ex.getMessage());
}
fromConnection.close();
}
}
continue;
}
if ((ops & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
ServerSocketChannel serverChannel = this.serverChannel;
if (serverChannel == null) continue;
try {
SocketChannel socketChannel = serverChannel.accept();
if (socketChannel != null) acceptOperation(socketChannel);
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to accept new connection.", ex);
}
continue;
}
// Must be a UDP read operation.
if (udp == null) continue;
InetSocketAddress fromAddress;
try {
fromAddress = udp.readFromAddress();
} catch (IOException ex) {
if (WARN) warn("kryonet", "Error reading UDP data.", ex);
continue;
}
if (fromAddress == null) continue;
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (fromAddress.equals(connection.udpRemoteAddress)) {
fromConnection = connection;
break;
}
}
Object object;
try {
object = udp.readObject(fromConnection);
} catch (KryoNetException ex) {
if (WARN) {
if (fromConnection != null) {
if (ERROR) error("kryonet", "Error reading UDP from connection: " + fromConnection, ex);
} else
warn("kryonet", "Error reading UDP from unregistered address: " + fromAddress, ex);
}
continue;
}
if (object instanceof FrameworkMessage) {
if (object instanceof RegisterUDP) {
// Store the fromAddress on the connection and reply over TCP with a RegisterUDP to indicate success.
int fromConnectionID = ((RegisterUDP)object).connectionID;
Connection connection = pendingConnections.remove(fromConnectionID);
if (connection != null) {
if (connection.udpRemoteAddress != null) continue outer;
connection.udpRemoteAddress = fromAddress;
addConnection(connection);
connection.sendTCP(new RegisterUDP());
if (DEBUG)
debug("kryonet", "Port " + udp.datagramChannel.socket().getLocalPort() + "/UDP connected to: "
+ fromAddress);
connection.notifyConnected();
continue;
}
if (DEBUG)
debug("kryonet", "Ignoring incoming RegisterUDP with invalid connection ID: " + fromConnectionID);
continue;
}
if (object instanceof DiscoverHost) {
try {
udp.datagramChannel.send(emptyBuffer, fromAddress);
if (DEBUG) debug("kryonet", "Responded to host discovery from: " + fromAddress);
} catch (IOException ex) {
if (WARN) warn("kryonet", "Error replying to host discovery from: " + fromAddress, ex);
}
continue;
}
}
if (fromConnection != null) {
if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (object instanceof FrameworkMessage) {
if (TRACE) trace("kryonet", fromConnection + " received UDP: " + objectString);
} else
debug("kryonet", fromConnection + " received UDP: " + objectString);
}
fromConnection.notifyReceived(object);
continue;
}
if (DEBUG) debug("kryonet", "Ignoring UDP from unregistered address: " + fromAddress);
} catch (CancelledKeyException ignored) {
// Connection is closed.
}
}
}
}
long time = System.currentTimeMillis();
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.tcp.isTimedOut(time)) {
if (DEBUG) debug("kryonet", connection + " timed out.");
connection.close();
} else {
if (connection.tcp.needsKeepAlive(time)) connection.sendTCP(FrameworkMessage.keepAlive);
}
if (connection.isIdle()) connection.notifyIdle();
}
}
| public void update (int timeout) throws IOException {
updateThread = Thread.currentThread();
synchronized (updateLock) { // Blocks to avoid a select while the selector is used to bind the server connection.
}
long startTime = System.currentTimeMillis();
int select = 0;
if (timeout > 0) {
select = selector.select(timeout);
} else {
select = selector.selectNow();
}
System.out.println(select);
if (select == 0) {
// NIO freaks and returns immediately with 0 sometimes, so try to keep from hogging the CPU.
long elapsedTime = System.currentTimeMillis() - startTime;
try {
if (elapsedTime < 25) Thread.sleep(25 - elapsedTime);
} catch (InterruptedException ex) {
}
} else {
Set<SelectionKey> keys = selector.selectedKeys();
synchronized (keys) {
UdpConnection udp = this.udp;
outer:
for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) {
SelectionKey selectionKey = iter.next();
iter.remove();
Connection fromConnection = (Connection)selectionKey.attachment();
try {
int ops = selectionKey.readyOps();
if (fromConnection != null) { // Must be a TCP read or write operation.
if (udp != null && fromConnection.udpRemoteAddress == null) {
fromConnection.close();
continue;
}
if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
try {
while (true) {
Object object = fromConnection.tcp.readObject(fromConnection);
if (object == null) break;
if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (!(object instanceof FrameworkMessage)) {
debug("kryonet", fromConnection + " received TCP: " + objectString);
} else if (TRACE) {
trace("kryonet", fromConnection + " received TCP: " + objectString);
}
}
fromConnection.notifyReceived(object);
}
} catch (IOException ex) {
if (TRACE) {
trace("kryonet", "Unable to read TCP from: " + fromConnection, ex);
} else if (DEBUG) {
debug("kryonet", fromConnection + " update: " + ex.getMessage());
}
fromConnection.close();
} catch (KryoNetException ex) {
if (ERROR) error("kryonet", "Error reading TCP from connection: " + fromConnection, ex);
fromConnection.close();
}
}
if ((ops & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
try {
fromConnection.tcp.writeOperation();
} catch (IOException ex) {
if (TRACE) {
trace("kryonet", "Unable to write TCP to connection: " + fromConnection, ex);
} else if (DEBUG) {
debug("kryonet", fromConnection + " update: " + ex.getMessage());
}
fromConnection.close();
}
}
continue;
}
if ((ops & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
ServerSocketChannel serverChannel = this.serverChannel;
if (serverChannel == null) continue;
try {
SocketChannel socketChannel = serverChannel.accept();
if (socketChannel != null) acceptOperation(socketChannel);
} catch (IOException ex) {
if (DEBUG) debug("kryonet", "Unable to accept new connection.", ex);
}
continue;
}
// Must be a UDP read operation.
if (udp == null) {
selectionKey.channel().close();
continue;
}
InetSocketAddress fromAddress;
try {
fromAddress = udp.readFromAddress();
} catch (IOException ex) {
if (WARN) warn("kryonet", "Error reading UDP data.", ex);
continue;
}
if (fromAddress == null) continue;
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (fromAddress.equals(connection.udpRemoteAddress)) {
fromConnection = connection;
break;
}
}
Object object;
try {
object = udp.readObject(fromConnection);
} catch (KryoNetException ex) {
if (WARN) {
if (fromConnection != null) {
if (ERROR) error("kryonet", "Error reading UDP from connection: " + fromConnection, ex);
} else
warn("kryonet", "Error reading UDP from unregistered address: " + fromAddress, ex);
}
continue;
}
if (object instanceof FrameworkMessage) {
if (object instanceof RegisterUDP) {
// Store the fromAddress on the connection and reply over TCP with a RegisterUDP to indicate success.
int fromConnectionID = ((RegisterUDP)object).connectionID;
Connection connection = pendingConnections.remove(fromConnectionID);
if (connection != null) {
if (connection.udpRemoteAddress != null) continue outer;
connection.udpRemoteAddress = fromAddress;
addConnection(connection);
connection.sendTCP(new RegisterUDP());
if (DEBUG)
debug("kryonet", "Port " + udp.datagramChannel.socket().getLocalPort() + "/UDP connected to: "
+ fromAddress);
connection.notifyConnected();
continue;
}
if (DEBUG)
debug("kryonet", "Ignoring incoming RegisterUDP with invalid connection ID: " + fromConnectionID);
continue;
}
if (object instanceof DiscoverHost) {
try {
udp.datagramChannel.send(emptyBuffer, fromAddress);
if (DEBUG) debug("kryonet", "Responded to host discovery from: " + fromAddress);
} catch (IOException ex) {
if (WARN) warn("kryonet", "Error replying to host discovery from: " + fromAddress, ex);
}
continue;
}
}
if (fromConnection != null) {
if (DEBUG) {
String objectString = object == null ? "null" : object.getClass().getSimpleName();
if (object instanceof FrameworkMessage) {
if (TRACE) trace("kryonet", fromConnection + " received UDP: " + objectString);
} else
debug("kryonet", fromConnection + " received UDP: " + objectString);
}
fromConnection.notifyReceived(object);
continue;
}
if (DEBUG) debug("kryonet", "Ignoring UDP from unregistered address: " + fromAddress);
} catch (CancelledKeyException ex) {
if (fromConnection != null)
fromConnection.close();
else
selectionKey.channel().close();
}
}
}
}
long time = System.currentTimeMillis();
Connection[] connections = this.connections;
for (int i = 0, n = connections.length; i < n; i++) {
Connection connection = connections[i];
if (connection.tcp.isTimedOut(time)) {
if (DEBUG) debug("kryonet", connection + " timed out.");
connection.close();
} else {
if (connection.tcp.needsKeepAlive(time)) connection.sendTCP(FrameworkMessage.keepAlive);
}
if (connection.isIdle()) connection.notifyIdle();
}
}
|
diff --git a/bundles/jcr/modeshape-server-it/src/test/java/com/sourcesense/stone/jcr/modeshape/server/JNDIRMITest.java b/bundles/jcr/modeshape-server-it/src/test/java/com/sourcesense/stone/jcr/modeshape/server/JNDIRMITest.java
index 8aa676a..a99e75d 100644
--- a/bundles/jcr/modeshape-server-it/src/test/java/com/sourcesense/stone/jcr/modeshape/server/JNDIRMITest.java
+++ b/bundles/jcr/modeshape-server-it/src/test/java/com/sourcesense/stone/jcr/modeshape/server/JNDIRMITest.java
@@ -1,35 +1,35 @@
package com.sourcesense.stone.jcr.modeshape.server;
import static com.sourcesense.stone.jcr.modeshape.server.PaxConfigurations.slingBasicConfiguration;
import static com.sourcesense.stone.jcr.modeshape.server.PaxConfigurations.stoneInMemoryConfiguration;
import static com.sourcesense.stone.jcr.modeshape.server.PaxConfigurations.debug;
import static org.junit.Assert.*;
import static org.ops4j.pax.exam.CoreOptions.options;
import javax.jcr.Repository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Inject;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.osgi.framework.BundleContext;
import com.sourcesense.stone.jcr.base.util.RepositoryAccessor;
@RunWith(JUnit4TestRunner.class)
public class JNDIRMITest {
@Inject
BundleContext bundleContext;
@Configuration
public Option[] configuration() {
return options(debug(), slingBasicConfiguration(), stoneInMemoryConfiguration());
}
@Test
public void connectionRetrieved() throws Exception {
RepositoryAccessor repositoryAccessor = new RepositoryAccessor();
- Repository repository = repositoryAccessor.getRepositoryFromURL("jndi://modeshape:java.naming.factory.initial=org.modeshape.common.naming.DummyInitialContextFactory,java.naming.provider.url=localhost");
+ Repository repository = repositoryAccessor.getRepositoryFromURL("jndi://modeshape:java.naming.factory.initial=org.modeshape.common.naming.SingletonInitialContextFactory,java.naming.provider.url=localhost");
assertNotNull(repository);
}
}
| true | true | public void connectionRetrieved() throws Exception {
RepositoryAccessor repositoryAccessor = new RepositoryAccessor();
Repository repository = repositoryAccessor.getRepositoryFromURL("jndi://modeshape:java.naming.factory.initial=org.modeshape.common.naming.DummyInitialContextFactory,java.naming.provider.url=localhost");
assertNotNull(repository);
}
| public void connectionRetrieved() throws Exception {
RepositoryAccessor repositoryAccessor = new RepositoryAccessor();
Repository repository = repositoryAccessor.getRepositoryFromURL("jndi://modeshape:java.naming.factory.initial=org.modeshape.common.naming.SingletonInitialContextFactory,java.naming.provider.url=localhost");
assertNotNull(repository);
}
|
diff --git a/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/core/DLTKLanguageManager.java b/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/core/DLTKLanguageManager.java
index c36137235..783b2c4ca 100644
--- a/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/core/DLTKLanguageManager.java
+++ b/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/core/DLTKLanguageManager.java
@@ -1,414 +1,419 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.core;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.dltk.ast.parser.ISourceParser;
import org.eclipse.dltk.ast.parser.SourceParserManager;
import org.eclipse.dltk.codeassist.ICompletionEngine;
import org.eclipse.dltk.codeassist.ISelectionEngine;
import org.eclipse.dltk.compiler.problem.DefaultProblemFactory;
import org.eclipse.dltk.compiler.problem.IProblemFactory;
import org.eclipse.dltk.core.PriorityDLTKExtensionManager.ElementInfo;
import org.eclipse.dltk.core.model.binary.IBinaryElementParser;
import org.eclipse.dltk.core.search.DLTKSearchParticipant;
import org.eclipse.dltk.core.search.IDLTKSearchScope;
import org.eclipse.dltk.core.search.IMatchLocatorParser;
import org.eclipse.dltk.core.search.SearchPatternProcessor;
import org.eclipse.dltk.core.search.indexing.SourceIndexerRequestor;
import org.eclipse.dltk.core.search.matching.IMatchLocator;
import org.eclipse.dltk.core.search.matching.MatchLocator;
import org.eclipse.dltk.core.search.matching.MatchLocatorParser;
import org.eclipse.dltk.internal.core.InternalDLTKLanguageManager;
public class DLTKLanguageManager {
public static IDLTKLanguageToolkit getLanguageToolkit(String natureId) {
return (IDLTKLanguageToolkit) InternalDLTKLanguageManager
.getLanguageToolkitsManager().getObject(natureId);
}
public static IDLTKLanguageToolkit[] getLanguageToolkits() {
final PriorityClassDLTKExtensionManager tkManager = InternalDLTKLanguageManager
.getLanguageToolkitsManager();
ElementInfo[] elementInfos = tkManager.getElementInfos();
IDLTKLanguageToolkit[] toolkits = new IDLTKLanguageToolkit[elementInfos.length];
for (int j = 0; j < elementInfos.length; j++) {
toolkits[j] = (IDLTKLanguageToolkit) tkManager
.getInitObject(elementInfos[j]);
}
return toolkits;
}
private static IDLTKLanguageToolkit findAppropriateToolkitByObject(
Object object) {
final PriorityClassDLTKExtensionManager toolkitManager = InternalDLTKLanguageManager
.getLanguageToolkitsManager();
final ElementInfo[] elementInfos = toolkitManager.getElementInfos();
for (int j = 0; j < elementInfos.length; j++) {
IDLTKLanguageToolkit toolkit = (IDLTKLanguageToolkit) toolkitManager
.getInitObject(elementInfos[j]);
+ if (toolkit == null) {
+ // toolkit instantiation failed, skip it
+ // TODO (alex) remove this ElementInfo entry
+ continue;
+ }
if (object instanceof IResource) {
if (DLTKContentTypeManager.isValidResourceForContentType(
toolkit, (IResource) object)) {
return toolkit;
}
} else if (object instanceof IPath) {
if (DLTKContentTypeManager.isValidFileNameForContentType(
toolkit, (IPath) object)) {
return toolkit;
}
} else {
return null;
}
}
return null;
}
public static boolean hasScriptNature(IProject project) {
return InternalDLTKLanguageManager.getLanguageToolkitsManager()
.findScriptNature(project) != null;
}
public static IDLTKLanguageToolkit getLanguageToolkit(IModelElement element) {
IDLTKLanguageToolkit toolkit = (IDLTKLanguageToolkit) InternalDLTKLanguageManager
.getLanguageToolkitsManager().getObject(element);
if (toolkit == null) {
while (element != null
&& element.getElementType() != IModelElement.SOURCE_MODULE) {
element = element.getParent();
}
if (element != null
&& element.getElementType() == IModelElement.SOURCE_MODULE) {
if (element.getResource() != null) {
IDLTKLanguageToolkit tk = findAppropriateToolkitByObject(element
.getResource());
if (tk != null) {
return tk;
}
}
return findAppropriateToolkitByObject(element.getPath());
}
}
return toolkit;
}
/**
* The behavior of this method was not correct - it could return incorrect
* results for files without extension. For compatibility purposes and to
* allow smooth migration it is marked as deprecated -- AlexPanchenko
*/
@Deprecated
public static IDLTKLanguageToolkit findToolkit(IResource resource) {
IDLTKLanguageToolkit toolkit = findAppropriateToolkitByObject(resource);
if (toolkit == null) {
toolkit = findToolkit(resource.getProject());
}
return toolkit;
}
/**
* Returns the toolkit of the specified {@link IProject} or null if not
* found.
*
* @param project
* @return
*/
public static IDLTKLanguageToolkit findToolkit(IProject project) {
return (IDLTKLanguageToolkit) InternalDLTKLanguageManager
.getLanguageToolkitsManager().getObject(project);
}
/**
* Return the toolkit of the specified resource or <code>null</code>.
*
* @param resource
* @return
*/
public static IDLTKLanguageToolkit findToolkitForResource(IResource resource) {
if (resource.getType() == IResource.PROJECT) {
return findToolkit((IProject) resource);
} else {
final IModelElement parent = DLTKCore.create(resource.getParent());
if (parent == null) {
return null;
}
return DLTKLanguageManager.findToolkit(parent, resource, false);
}
}
/**
* Return the language toolkit of the specified resource in the specified
* project. Until multiple languages are allowed for the same project - it
* will just return the first matching toolkit of the project.
*
* @param scriptProject
* @param resource
* @param useDefault
* if resource does not match project toolkit - return project
* toolkit or <code>null</code>
* @return
*/
public static IDLTKLanguageToolkit findToolkit(IModelElement parent,
IResource resource, boolean useDefault) {
final IDLTKLanguageToolkit toolkit = getLanguageToolkit(parent);
if (toolkit != null) {
if (DLTKContentTypeManager.isValidResourceForContentType(toolkit,
resource)) {
return toolkit;
}
/*
* TODO check other toolkits of the projects when projects will be
* supporting multiple DLTK languages
*/
return useDefault ? toolkit : null;
} else {
return findAppropriateToolkitByObject(resource);
}
}
public static IDLTKLanguageToolkit findToolkit(IPath path) {
return findAppropriateToolkitByObject(path);
}
public static ISourceElementParser getSourceElementParser(String nature) {
return (ISourceElementParser) InternalDLTKLanguageManager
.getSourceElementParsersManager().getObject(nature);
}
public static ISourceElementParser getSourceElementParser(
IModelElement element) {
return (ISourceElementParser) InternalDLTKLanguageManager
.getSourceElementParsersManager().getObject(element);
}
/**
* @since 2.0
*/
public static IBinaryElementParser getBinaryElementParser(String nature) {
return (IBinaryElementParser) InternalDLTKLanguageManager
.getBinaryElementParsersManager().getObject(nature);
}
/**
* @since 2.0
*/
public static IBinaryElementParser getBinaryElementParser(
IModelElement element) {
return (IBinaryElementParser) InternalDLTKLanguageManager
.getBinaryElementParsersManager().getObject(element);
}
// public static ISourceParser getSourceParser( String nature ) throws
// CoreException {
// return (ISourceElementParser) sourceParsersManager.getObject(nature);
// }
//
// public static ISourceParser getSourceParser( IModelElement element )
// throws
// CoreException {
// return (ISourceElementParser) sourceParsersManager.getObject(element);
// }
public static IProblemFactory getProblemFactory(String natureID) {
IProblemFactory factory = (IProblemFactory) InternalDLTKLanguageManager
.getProblemFactoryManager().getObject(natureID);
if (factory != null) {
return factory;
}
return new DefaultProblemFactory();
}
public static IProblemFactory getProblemFactory(IModelElement element) {
IProblemFactory factory = (IProblemFactory) InternalDLTKLanguageManager
.getProblemFactoryManager().getObject(element);
if (factory != null) {
return factory;
}
return new DefaultProblemFactory();
}
@Deprecated
public static ICompletionEngine getCompletionEngine(String natureID) {
final ICompletionEngine[] engines = getCompletionEngines(natureID);
return engines != null ? engines[0] : null;
}
public static ICompletionEngine[] getCompletionEngines(String natureID) {
return InternalDLTKLanguageManager.getCompletionEngineManager()
.getInstances(natureID);
}
public static ISelectionEngine getSelectionEngine(String natureID) {
return (ISelectionEngine) InternalDLTKLanguageManager
.getSelectionEngineManager().getObject(natureID);
}
public static ISourceParser getSourceParser(String natureID) {
return getSourceParser(null, natureID);
}
/**
* @param project
* @param natureID
* @return
* @since 2.0
*/
public static ISourceParser getSourceParser(IProject project,
String natureID) {
return SourceParserManager.getInstance().getSourceParser(project,
natureID);
}
public static DLTKSearchParticipant createSearchParticipant(String natureID) {
ISearchFactory factory = getSearchFactory(natureID);
if (factory != null) {
DLTKSearchParticipant participant = factory
.createSearchParticipant();
if (participant != null) {
return participant;
}
}
return new DLTKSearchParticipant();
}
public static ISearchFactory getSearchFactory(String natureId) {
return (ISearchFactory) InternalDLTKLanguageManager.getSearchManager()
.getObject(natureId);
}
public static IMatchLocator createMatchLocator(String natureID) {
return InternalDLTKLanguageManager.createMatchLocator(natureID);
}
public static SourceIndexerRequestor createSourceRequestor(String natureID) {
ISearchFactory factory = getSearchFactory(natureID);
if (factory != null) {
SourceIndexerRequestor requestor = factory.createSourceRequestor();
if (requestor != null) {
requestor.setSearchFactory(factory);
return requestor;
}
}
return new SourceIndexerRequestor();
}
public static IMatchLocatorParser createMatchParser(String natureID,
MatchLocator matchLocator) {
ISearchFactory factory = getSearchFactory(natureID);
if (factory != null) {
return factory.createMatchParser(matchLocator);
}
return new MatchLocatorParser(matchLocator) {
};
}
public static ICalleeProcessor createCalleeProcessor(String natureID,
IMethod member, IProgressMonitor progressMonitor,
IDLTKSearchScope scope) {
ICallHierarchyFactory factory = getCallHierarchyFactory(natureID);
if (factory != null) {
ICalleeProcessor processor = factory.createCalleeProcessor(member,
progressMonitor, scope);
return processor;
}
return null;
}
private static ICallHierarchyFactory getCallHierarchyFactory(String natureId) {
return (ICallHierarchyFactory) InternalDLTKLanguageManager
.getCallHierarchyManager().getObject(natureId);
}
public static ICallProcessor createCallProcessor(String natureID) {
ICallHierarchyFactory factory = getCallHierarchyFactory(natureID);
if (factory != null) {
return factory.createCallProcessor();
}
return null;
}
public static IFileHierarchyResolver getFileHierarchyResolver(
String natureId) {
return (IFileHierarchyResolver) InternalDLTKLanguageManager
.getFileHierarchyResolversManager().getObject(natureId);
}
/**
* @since 2.0
*/
public static ISearchPatternProcessor getSearchPatternProcessor(
String natureId) {
final ISearchFactory factory = getSearchFactory(natureId);
if (factory != null) {
return factory.createSearchPatternProcessor();
} else {
return null;
}
}
/**
* @since 2.0
*/
public static ISearchPatternProcessor getSearchPatternProcessor(
IDLTKLanguageToolkit toolkit) {
return getSearchPatternProcessor(toolkit, false);
}
/**
* @since 3.0
*/
public static ISearchPatternProcessor getSearchPatternProcessor(
IDLTKLanguageToolkit toolkit, boolean allowDefault) {
if (toolkit != null) {
final ISearchPatternProcessor processor = getSearchPatternProcessor(toolkit
.getNatureId());
if (processor != null) {
return processor;
}
}
if (allowDefault) {
return SearchPatternProcessor.getDefault();
} else {
return null;
}
}
private static final String FILENAME_ASSOCIATION_EXT_POINT = DLTKCore.PLUGIN_ID
+ ".filenameAssociation"; //$NON-NLS-1$
/**
* @since 2.0
*/
public static Set<String> loadFilenameAssociations(final String natureId) {
final IConfigurationElement[] elements = Platform
.getExtensionRegistry().getConfigurationElementsFor(
FILENAME_ASSOCIATION_EXT_POINT);
final Set<String> patterns = new HashSet<String>();
for (IConfigurationElement element : elements) {
if (natureId.equals(element.getAttribute("nature"))) { //$NON-NLS-1$
final String pattern = element.getAttribute("pattern"); //$NON-NLS-1$
if (pattern != null && pattern.length() != 0) {
patterns.add(pattern);
}
}
}
return patterns;
}
}
| true | true | private static IDLTKLanguageToolkit findAppropriateToolkitByObject(
Object object) {
final PriorityClassDLTKExtensionManager toolkitManager = InternalDLTKLanguageManager
.getLanguageToolkitsManager();
final ElementInfo[] elementInfos = toolkitManager.getElementInfos();
for (int j = 0; j < elementInfos.length; j++) {
IDLTKLanguageToolkit toolkit = (IDLTKLanguageToolkit) toolkitManager
.getInitObject(elementInfos[j]);
if (object instanceof IResource) {
if (DLTKContentTypeManager.isValidResourceForContentType(
toolkit, (IResource) object)) {
return toolkit;
}
} else if (object instanceof IPath) {
if (DLTKContentTypeManager.isValidFileNameForContentType(
toolkit, (IPath) object)) {
return toolkit;
}
} else {
return null;
}
}
return null;
}
| private static IDLTKLanguageToolkit findAppropriateToolkitByObject(
Object object) {
final PriorityClassDLTKExtensionManager toolkitManager = InternalDLTKLanguageManager
.getLanguageToolkitsManager();
final ElementInfo[] elementInfos = toolkitManager.getElementInfos();
for (int j = 0; j < elementInfos.length; j++) {
IDLTKLanguageToolkit toolkit = (IDLTKLanguageToolkit) toolkitManager
.getInitObject(elementInfos[j]);
if (toolkit == null) {
// toolkit instantiation failed, skip it
// TODO (alex) remove this ElementInfo entry
continue;
}
if (object instanceof IResource) {
if (DLTKContentTypeManager.isValidResourceForContentType(
toolkit, (IResource) object)) {
return toolkit;
}
} else if (object instanceof IPath) {
if (DLTKContentTypeManager.isValidFileNameForContentType(
toolkit, (IPath) object)) {
return toolkit;
}
} else {
return null;
}
}
return null;
}
|
diff --git a/sbia/ch14/src/test/java/com/manning/sbia/ch14/partition/PartitionSpringIntegrationStepTest.java b/sbia/ch14/src/test/java/com/manning/sbia/ch14/partition/PartitionSpringIntegrationStepTest.java
index c1bf681..e13f42d 100644
--- a/sbia/ch14/src/test/java/com/manning/sbia/ch14/partition/PartitionSpringIntegrationStepTest.java
+++ b/sbia/ch14/src/test/java/com/manning/sbia/ch14/partition/PartitionSpringIntegrationStepTest.java
@@ -1,33 +1,33 @@
package com.manning.sbia.ch14.partition;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class PartitionSpringIntegrationStepTest {
@Autowired
private JobLauncher launcher;
@Autowired
@Qualifier("partitionImportProductsJob")
private Job partitionImportProductsJob;
@Test
public void testMultithreadedStep() throws Exception {
- JobExecution partitionImportProductsJobExec = launcher.run(
+ /*JobExecution partitionImportProductsJobExec = launcher.run(
partitionImportProductsJob,
new JobParametersBuilder()
.toJobParameters()
- );
+ );*/
}
}
| false | true | public void testMultithreadedStep() throws Exception {
JobExecution partitionImportProductsJobExec = launcher.run(
partitionImportProductsJob,
new JobParametersBuilder()
.toJobParameters()
);
}
| public void testMultithreadedStep() throws Exception {
/*JobExecution partitionImportProductsJobExec = launcher.run(
partitionImportProductsJob,
new JobParametersBuilder()
.toJobParameters()
);*/
}
|
diff --git a/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/ValidatePersistentMethod.java b/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/ValidatePersistentMethod.java
index 4bba2e802..4db6f5891 100644
--- a/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/ValidatePersistentMethod.java
+++ b/src/persistence/org/codehaus/groovy/grails/orm/hibernate/metaclass/ValidatePersistentMethod.java
@@ -1,71 +1,70 @@
/* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.orm.hibernate.metaclass;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.metaclass.DelegatingMetaClass;
import org.codehaus.groovy.grails.metaclass.DomainClassMethods;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.hibernate.SessionFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
/**
* A method that validates an instance of a domain class against its constraints
*
* @author Graeme Rocher
* @since 07-Nov-2005
*/
public class ValidatePersistentMethod extends AbstractDynamicPersistentMethod {
private static final String METHOD_NAME = "validate";
private GrailsApplication application;
public ValidatePersistentMethod(SessionFactory sessionFactory, ClassLoader classLoader, GrailsApplication application) {
super(METHOD_NAME, sessionFactory, classLoader);
if(application == null)
throw new IllegalArgumentException("Constructor argument 'application' cannot be null");
this.application = application;
}
protected Object doInvokeInternal(Object target, Object[] arguments) {
Errors errors = new BindException(target, target.getClass().getName());
GrailsDomainClass domainClass = application.getGrailsDomainClass( target.getClass().getName() );
Validator validator = null;
if(domainClass != null)
validator = application.getGrailsDomainClass( target.getClass().getName() ).getValidator();
Boolean valid = new Boolean(true);
if(validator != null) {
validator.validate(target,errors);
if(errors.hasErrors()) {
valid = new Boolean(!errors.hasErrors());
DelegatingMetaClass metaClass = (DelegatingMetaClass)InvokerHelper.getInstance().getMetaRegistry().getMetaClass(target.getClass());
- metaClass.setProperty(target,DomainClassMethods.HAS_ERRORS_PROPERTY,valid);
metaClass.setProperty(target,DomainClassMethods.ERRORS_PROPERTY,errors);
}
}
return valid;
}
}
| true | true | protected Object doInvokeInternal(Object target, Object[] arguments) {
Errors errors = new BindException(target, target.getClass().getName());
GrailsDomainClass domainClass = application.getGrailsDomainClass( target.getClass().getName() );
Validator validator = null;
if(domainClass != null)
validator = application.getGrailsDomainClass( target.getClass().getName() ).getValidator();
Boolean valid = new Boolean(true);
if(validator != null) {
validator.validate(target,errors);
if(errors.hasErrors()) {
valid = new Boolean(!errors.hasErrors());
DelegatingMetaClass metaClass = (DelegatingMetaClass)InvokerHelper.getInstance().getMetaRegistry().getMetaClass(target.getClass());
metaClass.setProperty(target,DomainClassMethods.HAS_ERRORS_PROPERTY,valid);
metaClass.setProperty(target,DomainClassMethods.ERRORS_PROPERTY,errors);
}
}
return valid;
}
| protected Object doInvokeInternal(Object target, Object[] arguments) {
Errors errors = new BindException(target, target.getClass().getName());
GrailsDomainClass domainClass = application.getGrailsDomainClass( target.getClass().getName() );
Validator validator = null;
if(domainClass != null)
validator = application.getGrailsDomainClass( target.getClass().getName() ).getValidator();
Boolean valid = new Boolean(true);
if(validator != null) {
validator.validate(target,errors);
if(errors.hasErrors()) {
valid = new Boolean(!errors.hasErrors());
DelegatingMetaClass metaClass = (DelegatingMetaClass)InvokerHelper.getInstance().getMetaRegistry().getMetaClass(target.getClass());
metaClass.setProperty(target,DomainClassMethods.ERRORS_PROPERTY,errors);
}
}
return valid;
}
|
diff --git a/src/test/java/org/nuxeo/ecm/diff/TestXMLUnit.java b/src/test/java/org/nuxeo/ecm/diff/TestXMLUnit.java
index 8d3f695..7d98a33 100644
--- a/src/test/java/org/nuxeo/ecm/diff/TestXMLUnit.java
+++ b/src/test/java/org/nuxeo/ecm/diff/TestXMLUnit.java
@@ -1,277 +1,281 @@
/*
* (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* ataillefer
*/
package org.nuxeo.ecm.diff;
import java.util.List;
import org.custommonkey.xmlunit.AbstractNodeTester;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.DifferenceConstants;
import org.custommonkey.xmlunit.DifferenceListener;
import org.custommonkey.xmlunit.ElementNameAndTextQualifier;
import org.custommonkey.xmlunit.IgnoreTextAndAttributeValuesDifferenceListener;
import org.custommonkey.xmlunit.NodeTest;
import org.custommonkey.xmlunit.NodeTestException;
import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
import org.custommonkey.xmlunit.examples.CountingNodeTester;
import org.dom4j.Node;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Tests and illustrates XMLUnit basic features.
*
* @author <a href="mailto:[email protected]">Antoine Taillefer</a>
*/
public class TestXMLUnit extends XMLTestCase {
/**
* Test for equality.
*
* @throws Exception the exception
*/
public void testForEquality() throws Exception {
String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
String myTestXML = "<msg><localId>2376</localId></msg>";
assertXMLNotEqual("Comparing test xml to control xml", myControlXML,
myTestXML);
}
/**
* Test xml identical.
*
* @throws Exception the exception
*/
public void testXMLIdentical() throws Exception {
String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
Diff myDiff = new Diff(myControlXML, myTestXML);
assertTrue("XML similar " + myDiff.toString(), myDiff.similar());
assertFalse("XML identical " + myDiff.toString(), myDiff.identical());
}
/**
* Test all differences.
*
* @throws Exception the exception
*/
@SuppressWarnings("unchecked")
public void testAllDifferences() throws Exception {
String myControlXML = "<news><item id=\"1\">War</item>"
+ "<item id=\"2\">Plague</item>"
+ "<item id=\"3\">Famine</item></news>";
String myTestXML = "<news><item id=\"1\">Peace</item>"
+ "<item id=\"2\">Health</item>"
+ "<item id=\"3\">Plenty</item></news>";
DetailedDiff myDiff = new DetailedDiff(
new Diff(myControlXML, myTestXML));
List<Difference> allDifferences = myDiff.getAllDifferences();
assertEquals(myDiff.toString(), 3, allDifferences.size());
}
/**
* Test compare to skeleton xml.
*
* @throws Exception the exception
*/
public void testCompareToSkeletonXML() throws Exception {
String myControlXML = "<location><street-address>22 any street</street-address><postcode>XY00 99Z</postcode></location>";
String myTestXML = "<location><street-address>20 east cheap</street-address><postcode>EC3M 1EB</postcode></location>";
Diff myDiff = new Diff(myControlXML, myTestXML);
assertFalse("test XML matches control skeleton XML", myDiff.similar());
myDiff = new Diff(myControlXML, myTestXML);
DifferenceListener myDifferenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
myDiff.overrideDifferenceListener(myDifferenceListener);
assertTrue("test XML matches control skeleton XML", myDiff.similar());
}
/**
* Test repeated child elements.
*
* @throws Exception the exception
*/
public void testRepeatedChildElements() throws Exception {
String myControlXML = "<suite>"
+ "<test status=\"pass\">FirstTestCase</test>"
+ "<test status=\"pass\">SecondTestCase</test></suite>";
String myTestXML = "<suite>"
+ "<test status=\"pass\">SecondTestCase</test>"
+ "<test status=\"pass\">FirstTestCase</test></suite>";
assertXMLNotEqual(
"Repeated child elements in different sequence order are not equal by default",
myControlXML, myTestXML);
Diff myDiff = new Diff(myControlXML, myTestXML);
myDiff.overrideElementQualifier(new ElementNameAndTextQualifier());
assertXMLEqual(
"But they are equal when an ElementQualifier controls which test element is compared with each control element",
myDiff, true);
}
/**
* Test x paths.
*
* @throws Exception the exception
*/
public void testXPaths() throws Exception {
String mySolarSystemXML = "<solar-system>"
+ "<planet name='Earth' position='3' supportsLife='yes'/>"
+ "<planet name='Venus' position='4'/></solar-system>";
assertXpathExists("//planet[@name='Earth']", mySolarSystemXML);
assertXpathNotExists("//star[@name='alpha centauri']", mySolarSystemXML);
assertXpathsEqual("//planet[@name='Earth']", "//planet[@position='3']",
mySolarSystemXML);
assertXpathsNotEqual("//planet[@name='Venus']",
"//planet[@supportsLife='yes']", mySolarSystemXML);
}
// we
/**
* Test x path values.
*
* @throws Exception the exception
*/
public void testXPathValues() throws Exception {
String myJavaFlavours = "<java-flavours>"
+ "<jvm current='some platforms'>1.1.x</jvm>"
+ "<jvm current='no'>1.2.x</jvm>"
+ "<jvm current='yes'>1.3.x</jvm>"
+ "<jvm current='yes' latest='yes'>1.4.x</jvm></java-flavours>";
assertXpathEvaluatesTo("2", "count(//jvm[@current='yes'])",
myJavaFlavours);
assertXpathValuesEqual("//jvm[4]/@latest", "//jvm[4]/@current",
myJavaFlavours);
assertXpathValuesNotEqual("//jvm[2]/@current", "//jvm[3]/@current",
myJavaFlavours);
}
/**
* Test counting node tester.
*
* @throws Exception the exception
*/
public void testCountingNodeTester() throws Exception {
String testXML = "<fibonacci><val>1</val><val>2</val><val>3</val>"
+ "<val>5</val><val>9</val></fibonacci>";
CountingNodeTester countingNodeTester = new CountingNodeTester(5);
assertNodeTestPasses(testXML, countingNodeTester, Node.TEXT_NODE);
}
/**
* Test custom node tester.
*
* @throws Exception the exception
*/
public void testCustomNodeTester() throws Exception {
String testXML = "<fibonacci><val>1</val><val>2</val><val>3</val>"
+ "<val>5</val><val>8</val></fibonacci>";
NodeTest nodeTest = new NodeTest(testXML);
assertNodeTestPasses(nodeTest, new FibonacciNodeTester(), new short[] {
Node.TEXT_NODE, Node.ELEMENT_NODE }, true);
}
/**
* FibonacciNodeTester.
*/
private class FibonacciNodeTester extends AbstractNodeTester {
private int nextVal = 1;
private int lastVal = 1;
public void testText(Text text) throws NodeTestException {
int val = Integer.parseInt(text.getData());
if (nextVal != val) {
throw new NodeTestException("Incorrect value", text);
}
nextVal = val + lastVal;
lastVal = val;
}
public void testElement(Element element) throws NodeTestException {
String name = element.getLocalName();
if ("fibonacci".equals(name) || "val".equals(name)) {
return;
}
throw new NodeTestException("Unexpected element", element);
}
public void noMoreNodes(NodeTest nodeTest) throws NodeTestException {
}
}
/**
* Test unmatched nodes comparison.
*
* @throws Exception the exception
*/
@SuppressWarnings("unchecked")
public void testCompareUnmatchedNodes() throws Exception {
String myControlXML = "<document><item>First item</item>"
+ "<item>Second item</item></document>";
String myTestXML = "<document><item>First item</item></document>";
assertXMLNotEqual("Test XML has a missing child node", myControlXML,
myTestXML);
// ---------------------------
// Compare unmatched nodes
// ---------------------------
+ // First make sure that we have the default behavior for comparing
+ // unmatched nodes by doing XMLUnit.setCompareUnmatched(true).
+ // Indeed, it may have been set to false by a previous test.
+ XMLUnit.setCompareUnmatched(true);
DetailedDiff myDiff = new DetailedDiff(
new Diff(myControlXML, myTestXML));
List<Difference> allDifferences = myDiff.getAllDifferences();
assertEquals("Wrong number of differences", 3, allDifferences.size());
Difference diff1 = allDifferences.get(0);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODELIST_LENGTH_ID, diff1.getId());
// "CHILD_NODE_NOT_FOUND on the test side" strange behavior
// => considered as a TEXT_VALUE difference
Difference diff2 = allDifferences.get(1);
assertEquals("Wrong difference type",
DifferenceConstants.TEXT_VALUE_ID, diff2.getId());
Difference diff3 = allDifferences.get(2);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID, diff3.getId());
// ---------------------------
// Don't compare unmatched nodes
// ---------------------------
XMLUnit.setCompareUnmatched(false);
myDiff = new DetailedDiff(new Diff(myControlXML, myTestXML));
allDifferences = myDiff.getAllDifferences();
assertEquals("Wrong number of differences", 2, allDifferences.size());
diff1 = allDifferences.get(0);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODELIST_LENGTH_ID, diff1.getId());
diff2 = allDifferences.get(1);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODE_NOT_FOUND_ID, diff2.getId());
}
}
| true | true | public void testCompareUnmatchedNodes() throws Exception {
String myControlXML = "<document><item>First item</item>"
+ "<item>Second item</item></document>";
String myTestXML = "<document><item>First item</item></document>";
assertXMLNotEqual("Test XML has a missing child node", myControlXML,
myTestXML);
// ---------------------------
// Compare unmatched nodes
// ---------------------------
DetailedDiff myDiff = new DetailedDiff(
new Diff(myControlXML, myTestXML));
List<Difference> allDifferences = myDiff.getAllDifferences();
assertEquals("Wrong number of differences", 3, allDifferences.size());
Difference diff1 = allDifferences.get(0);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODELIST_LENGTH_ID, diff1.getId());
// "CHILD_NODE_NOT_FOUND on the test side" strange behavior
// => considered as a TEXT_VALUE difference
Difference diff2 = allDifferences.get(1);
assertEquals("Wrong difference type",
DifferenceConstants.TEXT_VALUE_ID, diff2.getId());
Difference diff3 = allDifferences.get(2);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID, diff3.getId());
// ---------------------------
// Don't compare unmatched nodes
// ---------------------------
XMLUnit.setCompareUnmatched(false);
myDiff = new DetailedDiff(new Diff(myControlXML, myTestXML));
allDifferences = myDiff.getAllDifferences();
assertEquals("Wrong number of differences", 2, allDifferences.size());
diff1 = allDifferences.get(0);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODELIST_LENGTH_ID, diff1.getId());
diff2 = allDifferences.get(1);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODE_NOT_FOUND_ID, diff2.getId());
}
| public void testCompareUnmatchedNodes() throws Exception {
String myControlXML = "<document><item>First item</item>"
+ "<item>Second item</item></document>";
String myTestXML = "<document><item>First item</item></document>";
assertXMLNotEqual("Test XML has a missing child node", myControlXML,
myTestXML);
// ---------------------------
// Compare unmatched nodes
// ---------------------------
// First make sure that we have the default behavior for comparing
// unmatched nodes by doing XMLUnit.setCompareUnmatched(true).
// Indeed, it may have been set to false by a previous test.
XMLUnit.setCompareUnmatched(true);
DetailedDiff myDiff = new DetailedDiff(
new Diff(myControlXML, myTestXML));
List<Difference> allDifferences = myDiff.getAllDifferences();
assertEquals("Wrong number of differences", 3, allDifferences.size());
Difference diff1 = allDifferences.get(0);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODELIST_LENGTH_ID, diff1.getId());
// "CHILD_NODE_NOT_FOUND on the test side" strange behavior
// => considered as a TEXT_VALUE difference
Difference diff2 = allDifferences.get(1);
assertEquals("Wrong difference type",
DifferenceConstants.TEXT_VALUE_ID, diff2.getId());
Difference diff3 = allDifferences.get(2);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID, diff3.getId());
// ---------------------------
// Don't compare unmatched nodes
// ---------------------------
XMLUnit.setCompareUnmatched(false);
myDiff = new DetailedDiff(new Diff(myControlXML, myTestXML));
allDifferences = myDiff.getAllDifferences();
assertEquals("Wrong number of differences", 2, allDifferences.size());
diff1 = allDifferences.get(0);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODELIST_LENGTH_ID, diff1.getId());
diff2 = allDifferences.get(1);
assertEquals("Wrong difference type",
DifferenceConstants.CHILD_NODE_NOT_FOUND_ID, diff2.getId());
}
|
diff --git a/src/main/java/com/googlecode/mgwt/linker/client/cache/html5/Html5ApplicationCache.java b/src/main/java/com/googlecode/mgwt/linker/client/cache/html5/Html5ApplicationCache.java
index d16bc86a..188c2237 100644
--- a/src/main/java/com/googlecode/mgwt/linker/client/cache/html5/Html5ApplicationCache.java
+++ b/src/main/java/com/googlecode/mgwt/linker/client/cache/html5/Html5ApplicationCache.java
@@ -1,176 +1,176 @@
package com.googlecode.mgwt.linker.client.cache.html5;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.googlecode.mgwt.linker.client.cache.ApplicationCache;
import com.googlecode.mgwt.linker.client.cache.ApplicationCacheStatus;
import com.googlecode.mgwt.linker.client.cache.event.CachedEvent;
import com.googlecode.mgwt.linker.client.cache.event.CheckingEvent;
import com.googlecode.mgwt.linker.client.cache.event.CheckingEvent.Handler;
import com.googlecode.mgwt.linker.client.cache.event.DownloadingEvent;
import com.googlecode.mgwt.linker.client.cache.event.ErrorEvent;
import com.googlecode.mgwt.linker.client.cache.event.NoUpadateEvent;
import com.googlecode.mgwt.linker.client.cache.event.ObsoluteEvent;
import com.googlecode.mgwt.linker.client.cache.event.ProgressEvent;
import com.googlecode.mgwt.linker.client.cache.event.UpdateReadyEvent;
public class Html5ApplicationCache implements ApplicationCache {
private static final ApplicationCacheStatus[] STATUS_MAPPING = new ApplicationCacheStatus[] {
ApplicationCacheStatus.UNCACHED, ApplicationCacheStatus.IDLE, ApplicationCacheStatus.CHECKING, ApplicationCacheStatus.DOWNLOADING, ApplicationCacheStatus.UPDATEREADY,
ApplicationCacheStatus.OBSOLTE};
public static Html5ApplicationCache createIfSupported() {
if (!isSupported()) {
return null;
}
return new Html5ApplicationCache();
}
protected static native boolean isSupported()/*-{
return typeof ($wnd.applicationCache) == "object";
}-*/;
protected EventBus eventBus = new SimpleEventBus();
protected Html5ApplicationCache() {
initialize();
}
@Override
public ApplicationCacheStatus getStatus() {
int status0 = getStatus0();
return STATUS_MAPPING[status0];
}
@Override
public HandlerRegistration addCheckingHandler(Handler handler) {
return eventBus.addHandler(CheckingEvent.getType(), handler);
}
@Override
public HandlerRegistration addCachedHandler(com.googlecode.mgwt.linker.client.cache.event.CachedEvent.Handler handler) {
return eventBus.addHandler(CachedEvent.getType(), handler);
}
@Override
public HandlerRegistration addDownloadingHandler(com.googlecode.mgwt.linker.client.cache.event.DownloadingEvent.Handler handler) {
return eventBus.addHandler(DownloadingEvent.getType(), handler);
}
@Override
public HandlerRegistration addErrorHandler(com.googlecode.mgwt.linker.client.cache.event.ErrorEvent.Handler handler) {
return eventBus.addHandler(ErrorEvent.getType(), handler);
}
@Override
public HandlerRegistration addNoUpdateHandler(com.googlecode.mgwt.linker.client.cache.event.NoUpadateEvent.Handler handler) {
return eventBus.addHandler(NoUpadateEvent.getType(), handler);
}
@Override
public HandlerRegistration addObsoluteHandler(com.googlecode.mgwt.linker.client.cache.event.ObsoluteEvent.Handler handler) {
return eventBus.addHandler(ObsoluteEvent.getType(), handler);
}
@Override
public HandlerRegistration addProgressHandler(com.googlecode.mgwt.linker.client.cache.event.ProgressEvent.Handler handler) {
return eventBus.addHandler(ProgressEvent.getType(), handler);
}
@Override
public HandlerRegistration addUpdateReadyHandler(com.googlecode.mgwt.linker.client.cache.event.UpdateReadyEvent.Handler handler) {
return eventBus.addHandler(UpdateReadyEvent.getType(), handler);
}
protected native int getStatus0()/*-{
return $wnd.applicationCache.status;
}-*/;
protected void onChecking() {
eventBus.fireEventFromSource(new CheckingEvent(), this);
}
protected void onError() {
eventBus.fireEventFromSource(new ErrorEvent(), this);
}
protected void onNoUpdate() {
eventBus.fireEventFromSource(new NoUpadateEvent(), this);
}
protected void onDownloading() {
eventBus.fireEventFromSource(new DownloadingEvent(), this);
}
protected void onProgress() {
eventBus.fireEventFromSource(new ProgressEvent(), this);
}
protected void onUpdateReady() {
eventBus.fireEventFromSource(new UpdateReadyEvent(), this);
}
protected void onCached() {
eventBus.fireEventFromSource(new CachedEvent(), this);
}
protected void onObsolete() {
eventBus.fireEventFromSource(new ObsoluteEvent(), this);
}
protected native void initialize() /*-{
var that = this;
var check = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onChecking()();
});
$wnd.applicationCache.addEventListener("checking", check);
var onError = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onError()();
});
- $wnd.applicationCache.addEventListener("onerror", onError);
+ $wnd.applicationCache.addEventListener("error", onError);
var onUpdate = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onNoUpdate()();
});
- $wnd.applicationCache.addEventListener("onnoupdate", onUpdate);
+ $wnd.applicationCache.addEventListener("noupdate", onUpdate);
var ondownloading = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onDownloading()();
});
- $wnd.applicationCache.addEventListener("ondownloading", ondownloading);
+ $wnd.applicationCache.addEventListener("downloading", ondownloading);
var onprogress = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onProgress()();
});
- $wnd.applicationCache.addEventListener("onprogress", onprogress);
+ $wnd.applicationCache.addEventListener("progress", onprogress);
var onupdateReady = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onUpdateReady()();
});
- $wnd.applicationCache.addEventListener("onupdateready", onupdateReady);
+ $wnd.applicationCache.addEventListener("updateready", onupdateReady);
var oncached = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onCached()();
});
- $wnd.applicationCache.addEventListener("oncached", oncached);
+ $wnd.applicationCache.addEventListener("cached", oncached);
var onobsolete = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onObsolete()();
});
- $wnd.applicationCache.addEventListener("onobsolete", onobsolete);
+ $wnd.applicationCache.addEventListener("obsolete", onobsolete);
}-*/;
@Override
public native void swapCache() /*-{
$wnd.applicationCache.swapCache();
}-*/;
}
| false | true | protected native void initialize() /*-{
var that = this;
var check = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onChecking()();
});
$wnd.applicationCache.addEventListener("checking", check);
var onError = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onError()();
});
$wnd.applicationCache.addEventListener("onerror", onError);
var onUpdate = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onNoUpdate()();
});
$wnd.applicationCache.addEventListener("onnoupdate", onUpdate);
var ondownloading = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onDownloading()();
});
$wnd.applicationCache.addEventListener("ondownloading", ondownloading);
var onprogress = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onProgress()();
});
$wnd.applicationCache.addEventListener("onprogress", onprogress);
var onupdateReady = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onUpdateReady()();
});
$wnd.applicationCache.addEventListener("onupdateready", onupdateReady);
var oncached = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onCached()();
});
$wnd.applicationCache.addEventListener("oncached", oncached);
var onobsolete = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onObsolete()();
});
$wnd.applicationCache.addEventListener("onobsolete", onobsolete);
}-*/;
| protected native void initialize() /*-{
var that = this;
var check = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onChecking()();
});
$wnd.applicationCache.addEventListener("checking", check);
var onError = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onError()();
});
$wnd.applicationCache.addEventListener("error", onError);
var onUpdate = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onNoUpdate()();
});
$wnd.applicationCache.addEventListener("noupdate", onUpdate);
var ondownloading = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onDownloading()();
});
$wnd.applicationCache.addEventListener("downloading", ondownloading);
var onprogress = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onProgress()();
});
$wnd.applicationCache.addEventListener("progress", onprogress);
var onupdateReady = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onUpdateReady()();
});
$wnd.applicationCache.addEventListener("updateready", onupdateReady);
var oncached = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onCached()();
});
$wnd.applicationCache.addEventListener("cached", oncached);
var onobsolete = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onObsolete()();
});
$wnd.applicationCache.addEventListener("obsolete", onobsolete);
}-*/;
|
diff --git a/freeplane_plugin_workspace/src/org/freeplane/plugin/workspace/dnd/DefaultWorkspaceDropTargetDispatcher.java b/freeplane_plugin_workspace/src/org/freeplane/plugin/workspace/dnd/DefaultWorkspaceDropTargetDispatcher.java
index 6b33b4e93..32c4fc984 100644
--- a/freeplane_plugin_workspace/src/org/freeplane/plugin/workspace/dnd/DefaultWorkspaceDropTargetDispatcher.java
+++ b/freeplane_plugin_workspace/src/org/freeplane/plugin/workspace/dnd/DefaultWorkspaceDropTargetDispatcher.java
@@ -1,52 +1,52 @@
/**
* author: Marcel Genzmehr
* 21.10.2011
*/
package org.freeplane.plugin.workspace.dnd;
import java.awt.dnd.DropTargetDropEvent;
import org.freeplane.plugin.workspace.WorkspaceController;
import org.freeplane.plugin.workspace.model.node.AWorkspaceTreeNode;
/**
*
*/
public class DefaultWorkspaceDropTargetDispatcher implements IDropTargetDispatcher {
/***********************************************************************************
* CONSTRUCTORS
**********************************************************************************/
/***********************************************************************************
* METHODS
**********************************************************************************/
private IDropAcceptor getDropAcceptor(final DropTargetDropEvent event) {
AWorkspaceTreeNode targetNode = (AWorkspaceTreeNode) WorkspaceController.getController().getWorkspaceViewTree()
.getPathForLocation(event.getLocation().x, event.getLocation().y).getLastPathComponent();
- while(targetNode != null && targetNode instanceof IDropAcceptor) {
- if(((IDropAcceptor)targetNode).acceptDrop(event.getCurrentDataFlavors())) {
+ while(targetNode != null) {
+ if(targetNode instanceof IDropAcceptor && ((IDropAcceptor)targetNode).acceptDrop(event.getCurrentDataFlavors())) {
return (IDropAcceptor)targetNode;
}
targetNode = targetNode.getParent();
}
return null;
}
/***********************************************************************************
* REQUIRED METHODS FOR INTERFACES
**********************************************************************************/
/**
*/
public boolean dispatchDropEvent(DropTargetDropEvent event) {
IDropAcceptor acceptor = getDropAcceptor(event);
if(acceptor != null) {
return acceptor.processDrop(event);
}
return false;
}
}
| true | true | private IDropAcceptor getDropAcceptor(final DropTargetDropEvent event) {
AWorkspaceTreeNode targetNode = (AWorkspaceTreeNode) WorkspaceController.getController().getWorkspaceViewTree()
.getPathForLocation(event.getLocation().x, event.getLocation().y).getLastPathComponent();
while(targetNode != null && targetNode instanceof IDropAcceptor) {
if(((IDropAcceptor)targetNode).acceptDrop(event.getCurrentDataFlavors())) {
return (IDropAcceptor)targetNode;
}
targetNode = targetNode.getParent();
}
return null;
}
| private IDropAcceptor getDropAcceptor(final DropTargetDropEvent event) {
AWorkspaceTreeNode targetNode = (AWorkspaceTreeNode) WorkspaceController.getController().getWorkspaceViewTree()
.getPathForLocation(event.getLocation().x, event.getLocation().y).getLastPathComponent();
while(targetNode != null) {
if(targetNode instanceof IDropAcceptor && ((IDropAcceptor)targetNode).acceptDrop(event.getCurrentDataFlavors())) {
return (IDropAcceptor)targetNode;
}
targetNode = targetNode.getParent();
}
return null;
}
|
diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/importing/BundleImporterExtension.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/importing/BundleImporterExtension.java
index f0201a961..fba820315 100644
--- a/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/importing/BundleImporterExtension.java
+++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/internal/core/importing/BundleImporterExtension.java
@@ -1,112 +1,112 @@
/*******************************************************************************
* Copyright (c) 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.team.internal.core.importing;
import java.util.*;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.*;
import org.eclipse.team.core.RepositoryProviderType;
import org.eclipse.team.core.ScmUrlImportDescription;
import org.eclipse.team.core.importing.provisional.*;
import org.eclipse.team.internal.core.TeamPlugin;
/**
* A bundle importer extension.
*
* @since 3.7
*/
public class BundleImporterExtension implements IBundleImporter {
private IBundleImporterDelegate delegate;
private IConfigurationElement element;
/**
* Constructs a bundle importer extension on the given element.
*
* @param element contribution
*/
public BundleImporterExtension(IConfigurationElement element) {
this.element = element;
}
/* (non-Javadoc)
* @see org.eclipse.pde.core.project.IBundleImporterDelegate#validateImport(java.util.Map[])
*/
public ScmUrlImportDescription[] validateImport(Map[] manifests) {
try {
return getDelegate().validateImport(manifests);
} catch (CoreException e) {
TeamPlugin.log(e);
return null;
}
}
/**
* Returns underlying delegate.
*
* @return delegate
* @exception CoreException if unable to instantiate delegate
*/
private synchronized IBundleImporterDelegate getDelegate() throws CoreException {
if (delegate == null) {
delegate = new BundleImporterDelegate() {
private Set supportedValues;
private RepositoryProviderType providerType;
protected Set getSupportedValues() {
if (supportedValues == null) {
- IConfigurationElement[] supported = element.getChildren("supported"); //$NON-NLS-1$
+ IConfigurationElement[] supported = element.getChildren("supports"); //$NON-NLS-1$
supportedValues = new HashSet(supported.length);
for (int i = 0; i < supported.length; i++) {
- supportedValues.add(supported[i].getAttribute("value")); //$NON-NLS-1$
+ supportedValues.add(supported[i].getAttribute("prefix")); //$NON-NLS-1$
}
}
return supportedValues;
}
protected RepositoryProviderType getProviderType() {
if (providerType == null)
providerType = RepositoryProviderType.getProviderType(element.getAttribute("repository")); //$NON-NLS-1$
return providerType;
}
};
}
return delegate;
}
/* (non-Javadoc)
* @see org.eclipse.pde.core.importing.IBundleImporterDelegate#performImport(org.eclipse.pde.core.importing.BundleImportDescription[], org.eclipse.core.runtime.IProgressMonitor)
*/
public IProject[] performImport(ScmUrlImportDescription[] descriptions, IProgressMonitor monitor) throws CoreException {
return getDelegate().performImport(descriptions, monitor);
}
/* (non-Javadoc)
* @see org.eclipse.pde.core.project.IBundleImporter#getId()
*/
public String getId() {
return element.getAttribute("id"); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.pde.core.project.IBundleImporter#getDescription()
*/
public String getDescription() {
return element.getAttribute("description"); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.pde.core.project.IBundleImporter#getName()
*/
public String getName() {
return element.getAttribute("name"); //$NON-NLS-1$
}
}
| false | true | private synchronized IBundleImporterDelegate getDelegate() throws CoreException {
if (delegate == null) {
delegate = new BundleImporterDelegate() {
private Set supportedValues;
private RepositoryProviderType providerType;
protected Set getSupportedValues() {
if (supportedValues == null) {
IConfigurationElement[] supported = element.getChildren("supported"); //$NON-NLS-1$
supportedValues = new HashSet(supported.length);
for (int i = 0; i < supported.length; i++) {
supportedValues.add(supported[i].getAttribute("value")); //$NON-NLS-1$
}
}
return supportedValues;
}
protected RepositoryProviderType getProviderType() {
if (providerType == null)
providerType = RepositoryProviderType.getProviderType(element.getAttribute("repository")); //$NON-NLS-1$
return providerType;
}
};
}
return delegate;
}
| private synchronized IBundleImporterDelegate getDelegate() throws CoreException {
if (delegate == null) {
delegate = new BundleImporterDelegate() {
private Set supportedValues;
private RepositoryProviderType providerType;
protected Set getSupportedValues() {
if (supportedValues == null) {
IConfigurationElement[] supported = element.getChildren("supports"); //$NON-NLS-1$
supportedValues = new HashSet(supported.length);
for (int i = 0; i < supported.length; i++) {
supportedValues.add(supported[i].getAttribute("prefix")); //$NON-NLS-1$
}
}
return supportedValues;
}
protected RepositoryProviderType getProviderType() {
if (providerType == null)
providerType = RepositoryProviderType.getProviderType(element.getAttribute("repository")); //$NON-NLS-1$
return providerType;
}
};
}
return delegate;
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.processes.core/src/org/eclipse/tcf/te/tcf/processes/core/model/runtime/services/RuntimeModelRefreshService.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.processes.core/src/org/eclipse/tcf/te/tcf/processes/core/model/runtime/services/RuntimeModelRefreshService.java
index 4ed499f90..4691dd03b 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.processes.core/src/org/eclipse/tcf/te/tcf/processes/core/model/runtime/services/RuntimeModelRefreshService.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.processes.core/src/org/eclipse/tcf/te/tcf/processes/core/model/runtime/services/RuntimeModelRefreshService.java
@@ -1,1059 +1,1059 @@
/*******************************************************************************
* Copyright (c) 2013 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.tcf.te.tcf.processes.core.model.runtime.services;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.IToken;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.IProcesses;
import org.eclipse.tcf.services.ISysMonitor;
import org.eclipse.tcf.services.ISysMonitor.SysMonitorContext;
import org.eclipse.tcf.te.runtime.callback.AsyncCallbackCollector;
import org.eclipse.tcf.te.runtime.callback.Callback;
import org.eclipse.tcf.te.runtime.interfaces.callback.ICallback;
import org.eclipse.tcf.te.runtime.model.interfaces.IContainerModelNode;
import org.eclipse.tcf.te.runtime.model.interfaces.IModelNode;
import org.eclipse.tcf.te.runtime.model.interfaces.contexts.IAsyncRefreshableCtx;
import org.eclipse.tcf.te.runtime.model.interfaces.contexts.IAsyncRefreshableCtx.QueryState;
import org.eclipse.tcf.te.runtime.model.interfaces.contexts.IAsyncRefreshableCtx.QueryType;
import org.eclipse.tcf.te.runtime.services.ServiceManager;
import org.eclipse.tcf.te.runtime.services.interfaces.IDelegateService;
import org.eclipse.tcf.te.tcf.core.async.CallbackInvocationDelegate;
import org.eclipse.tcf.te.tcf.core.model.interfaces.services.IModelChannelService;
import org.eclipse.tcf.te.tcf.core.model.services.AbstractModelService;
import org.eclipse.tcf.te.tcf.processes.core.activator.CoreBundleActivator;
import org.eclipse.tcf.te.tcf.processes.core.model.interfaces.IProcessContextNode;
import org.eclipse.tcf.te.tcf.processes.core.model.interfaces.IProcessContextNode.TYPE;
import org.eclipse.tcf.te.tcf.processes.core.model.interfaces.IProcessContextNodeProperties;
import org.eclipse.tcf.te.tcf.processes.core.model.interfaces.runtime.IRuntimeModel;
import org.eclipse.tcf.te.tcf.processes.core.model.interfaces.runtime.IRuntimeModelRefreshService;
import org.eclipse.tcf.te.tcf.processes.core.model.interfaces.runtime.IRuntimeModelUpdateService;
import org.eclipse.tcf.te.tcf.processes.core.nls.Messages;
/**
* Runtime model refresh service implementation.
* <p>
* <b>Service implementation assumptions</b>
* <ul>
* <li>Refresh operations do not update the model or the existing process context model nodes directly. Any
* refresh operation is creating a parallel tree of nodes which is merged into the model <i>at the end</i>
* of the refresh operation.</li>
* <li>Refresh operations do not modify the status of asynchronous refreshable context of the refresh operation
* root. The caller of the refresh service is responsible for handling the asynchronous refreshable context
* state of the refresh operation root.</li>
* <li>Refresh operations requested for the same root while still running are queued and the callbacks are fired
* all at once when the first refresh operation completes.</li>
* <li>Auto-refresh operations are walking the whole process context model node tree, starting from the model root,
* and triggers an refresh of all process context model nodes found where the child list query marker is set to done.</li>
* </ul>
*/
public class RuntimeModelRefreshService extends AbstractModelService<IRuntimeModel> implements IRuntimeModelRefreshService {
// For each root context to refresh, remember the callbacks to invoke.
private final Map<IModelNode, List<ICallback>> ctx2cb = new HashMap<IModelNode, List<ICallback>>();
// The default processes runtime model refresh service delegate
/* default */ final IRuntimeModelRefreshService.IDelegate defaultDelegate = new DefaultDelegate();
/**
* Default processes runtime model refresh service delegate implementation.
*/
/* default */ final class DefaultDelegate implements IRuntimeModelRefreshService.IDelegate {
private final String[] managedPropertyNames = new String[] { IProcessContextNodeProperties.PROPERTY_CMD_LINE };
/* (non-Javadoc)
* @see org.eclipse.tcf.te.tcf.processes.core.model.interfaces.runtime.IRuntimeModelRefreshService.IDelegate#setNodeType(java.lang.String, org.eclipse.tcf.te.tcf.processes.core.model.interfaces.IProcessContextNode)
*/
@Override
public void setNodeType(String parentContextId, IProcessContextNode node) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(node);
node.setType(parentContextId == null ? TYPE.Process : TYPE.Thread);
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.tcf.processes.core.model.interfaces.runtime.IRuntimeModelRefreshService.IDelegate#postRefreshContext(org.eclipse.tcf.protocol.IChannel, org.eclipse.tcf.te.tcf.processes.core.model.interfaces.IProcessContextNode, org.eclipse.tcf.te.runtime.interfaces.callback.ICallback)
*/
@Override
public void postRefreshContext(final IChannel channel, final IProcessContextNode node, final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(channel);
Assert.isNotNull(node);
Assert.isNotNull(callback);
// The channel must be opened, otherwise the query cannot run
if (channel.getState() != IChannel.STATE_OPEN) {
IStatus status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), Messages.RuntimeModelRefreshService_error_channelClosed);
callback.done(RuntimeModelRefreshService.this, status);
return;
}
// Get the required services
final ISysMonitor sysMonService = channel.getRemoteService(ISysMonitor.class);
// The system monitor service must be available
if (sysMonService == null) {
callback.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
return;
}
// The context id must be set
String contextId = node.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID);
if (contextId == null) {
callback.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
return;
}
// Get the command line of the context
sysMonService.getCommandLine(contextId, new ISysMonitor.DoneGetCommandLine() {
@Override
public void doneGetCommandLine(IToken token, Exception error, String[] cmd_line) {
node.setProperty(IProcessContextNodeProperties.PROPERTY_CMD_LINE, error == null ? cmd_line : null);
callback.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
}
});
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.tcf.processes.core.model.interfaces.runtime.IRuntimeModelRefreshService.IDelegate#getManagedPropertyNames()
*/
@Override
public String[] getManagedPropertyNames() {
return managedPropertyNames;
}
}
/**
* Constructor
*
* @param model The parent model. Must not be <code>null</code>.
*/
public RuntimeModelRefreshService(IRuntimeModel model) {
super(model);
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.tcf.core.model.interfaces.services.IModelRefreshService#refresh(org.eclipse.tcf.te.runtime.interfaces.callback.ICallback)
*/
@Override
public void refresh(final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
// Get the parent model
final IRuntimeModel model = getModel();
Assert.isNotNull(model);
// If the parent model is already disposed, the service will drop out immediately
if (model.isDisposed()) {
if (callback != null) callback.done(this, Status.OK_STATUS);
return;
}
// A refresh for the passed in node is already running if the model
// is associated with a callback list in 'ctx2cb'.
final boolean isRefreshAlreadyRunning = ctx2cb.containsKey(model);
// Queue the callback to invoke once the refresh is done
List<ICallback> callbacks = ctx2cb.get(model);
if (callbacks == null) {
callbacks = new ArrayList<ICallback>();
ctx2cb.put(model, callbacks);
}
Assert.isNotNull(callbacks);
if (callback != null) callbacks.add(callback);
// If a refresh is already running, drop out. The callback is already
// queued and will be invoked once the refresh operation is done.
if (isRefreshAlreadyRunning) return;
// The refresh operation is building up a parallel data tree. Pass in an empty container
// to receive the fetched children.
final IProcessContextNode container = model.getFactory().newInstance(IProcessContextNode.class);
// Mark the container as refresh in progress
final IAsyncRefreshableCtx containerRefreshable = (IAsyncRefreshableCtx)container.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(containerRefreshable);
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.IN_PROGRESS);
// Initiate the refresh of the level 1 children
refreshChildrenLevel1(null, 2, container, new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Mark the container refresh as done
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.DONE);
// If the refresh succeeded, update the tree
if (status.isOK()) {
// Process the new child list and merge it with the model
model.getService(IRuntimeModelUpdateService.class).updateChildren(model, container);
// Walk the tree on check the children at level 2 to determine if there are
// nodes which got expanded by the user and must be refreshed therefore too.
final List<IProcessContextNode> children = new ArrayList<IProcessContextNode>();
// Get the first level children from the model
List<IProcessContextNode> candidates = model.getChildren(IProcessContextNode.class);
for (IProcessContextNode candidate : candidates) {
// If the child list got not queried for the candidate, skip it
IAsyncRefreshableCtx refreshable = (IAsyncRefreshableCtx)candidate.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(refreshable);
if (refreshable.getQueryState(QueryType.CHILD_LIST) != QueryState.DONE) continue;
// Get the second level children and find those candidates where
// the child list query is marked done. Add those candidates to
// the list of children to refresh too.
List<IProcessContextNode> candidates2 = candidate.getChildren(IProcessContextNode.class);
for (IProcessContextNode candidate2 : candidates2) {
// Get the asynchronous refreshable for the candidate
refreshable = (IAsyncRefreshableCtx)candidate2.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(refreshable);
if (refreshable.getQueryState(QueryType.CHILD_LIST) != QueryState.DONE) continue;
// This child needs an additional refresh
children.add(candidate2);
}
}
// Run the auto-refresh logic for all children we have found
final ICallback callback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Invoke the callbacks
invokeCallbacks(model, RuntimeModelRefreshService.this, status);
}
};
// Create the callback collector to fire once all refresh operations are completed
final AsyncCallbackCollector collector = new AsyncCallbackCollector(callback, new CallbackInvocationDelegate());
// Get the first level of children and check if they are need to be refreshed
if (children.size() > 0) {
// Initiate the refresh of the children
doAutoRefresh(model, children.toArray(new IProcessContextNode[children.size()]), 0, collector);
}
// Mark the collector initialization done
collector.initDone();
} else {
// Invoke the callbacks
invokeCallbacks(model, RuntimeModelRefreshService.this, status);
}
}
});
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.tcf.core.model.interfaces.services.IModelRefreshService#refresh(org.eclipse.tcf.te.runtime.model.interfaces.IModelNode, org.eclipse.tcf.te.runtime.interfaces.callback.ICallback)
*/
@Override
public void refresh(final IModelNode node, final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(node);
// Get the parent model
final IRuntimeModel model = getModel();
Assert.isNotNull(model);
// If the model is already disposed, drop out immediately
if (model.isDisposed() || !(node instanceof IProcessContextNode)) {
if (callback != null) callback.done(this, Status.OK_STATUS);
return;
}
// Get the context id
final String contextId = node.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID);
if (contextId == null) {
if (callback != null) callback.done(this, Status.OK_STATUS);
return;
}
// A refresh for the passed in node is already running if the node
// is associated with a callback list in 'ctx2cb'.
final boolean isRefreshAlreadyRunning = ctx2cb.containsKey(node);
// Queue the callback to invoke once the refresh is done
List<ICallback> callbacks = ctx2cb.get(node);
if (callbacks == null) {
callbacks = new ArrayList<ICallback>();
ctx2cb.put(node, callbacks);
}
Assert.isNotNull(callbacks);
// Add the current callback to the list of callbacks
if (callback != null) callbacks.add(callback);
// If a refresh is already running, drop out. The callback is already
// queued and will be invoked once the refresh operation is done.
if (isRefreshAlreadyRunning) return;
// The refresh operation is building up a parallel data tree. Pass in an empty container
// to receive the fetched context properties and context children.
final IProcessContextNode container = model.getFactory().newInstance(IProcessContextNode.class);
// Mark the container as refresh in progress
final IAsyncRefreshableCtx containerRefreshable = (IAsyncRefreshableCtx)container.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(containerRefreshable);
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.IN_PROGRESS);
// The context id must be set to the container (asserted by the update service)
container.setProperty(IProcessContextNodeProperties.PROPERTY_ID, contextId);
// The container has the same type as the original node
container.setType(((IProcessContextNode)node).getType());
// Initiate the refresh of context
refreshContextLevel1(contextId, 2, container, new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Mark the container refresh as done
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.DONE);
// If the refresh succeeded, update the original node
if (status.isOK()) {
// Process the new context node and merge it with the original context node
model.getService(IRuntimeModelUpdateService.class).update(node, container);
// Walk the tree on check the children at level 2 to determine if there are
// nodes which got expanded by the user and must be refreshed therefore too.
final List<IProcessContextNode> children = new ArrayList<IProcessContextNode>();
// Get the first level children from the model
List<IProcessContextNode> candidates = ((IProcessContextNode)node).getChildren(IProcessContextNode.class);
for (IProcessContextNode candidate : candidates) {
// If the child list got not queried for the candidate, skip it
IAsyncRefreshableCtx refreshable = (IAsyncRefreshableCtx)candidate.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(refreshable);
if (refreshable.getQueryState(QueryType.CHILD_LIST) != QueryState.DONE) continue;
// Get the second level children and find those candidates where
// the child list query is marked done. Add those candidates to
// the list of children to refresh too.
List<IProcessContextNode> candidates2 = candidate.getChildren(IProcessContextNode.class);
for (IProcessContextNode candidate2 : candidates2) {
// Get the asynchronous refreshable for the candidate
refreshable = (IAsyncRefreshableCtx)candidate2.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(refreshable);
if (refreshable.getQueryState(QueryType.CHILD_LIST) != QueryState.DONE) continue;
// This child needs an additional refresh
children.add(candidate2);
}
}
// Run the auto-refresh logic for all children we have found
final ICallback callback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Invoke the callbacks
- invokeCallbacks(model, RuntimeModelRefreshService.this, status);
+ invokeCallbacks(node, RuntimeModelRefreshService.this, status);
}
};
// Create the callback collector to fire once all refresh operations are completed
final AsyncCallbackCollector collector = new AsyncCallbackCollector(callback, new CallbackInvocationDelegate());
// Get the first level of children and check if they are need to be refreshed
if (children.size() > 0) {
// Initiate the refresh of the children
doAutoRefresh(model, children.toArray(new IProcessContextNode[children.size()]), 0, collector);
}
// Mark the collector initialization done
collector.initDone();
} else {
// Invoke the callbacks
invokeCallbacks(node, RuntimeModelRefreshService.this, status);
}
}
});
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.tcf.processes.core.model.interfaces.runtime.IRuntimeModelRefreshService#autoRefresh(org.eclipse.tcf.te.runtime.interfaces.callback.ICallback)
*/
@Override
public void autoRefresh(ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
// Get the parent model
final IRuntimeModel model = getModel();
// If the parent model is already disposed, the service will drop out immediately
if (model.isDisposed()) {
if (callback != null) callback.done(this, Status.OK_STATUS);
return;
}
// Determine if there is already a model refresh running.
// A model refresh can be initiated via refresh(...) or autoRefresh(...).
final boolean isRefreshAlreadyRunning = ctx2cb.containsKey(model);
// Queue the callback to invoke once the refresh is done
List<ICallback> callbacks = ctx2cb.get(model);
if (callbacks == null) {
callbacks = new ArrayList<ICallback>();
ctx2cb.put(model, callbacks);
}
Assert.isNotNull(callbacks);
// Add the current callback to the list of callbacks
if (callback != null) callbacks.add(callback);
// If a refresh is already running, drop out. The callback is already
// queued and will be invoked once the refresh operation is done.
if (isRefreshAlreadyRunning) return;
// Create the inner callback which will invoke all queued callbacks
final ICallback innerCallback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Invoke the callbacks
invokeCallbacks(model, RuntimeModelRefreshService.this, status);
}
};
// Create the callback collector to fire once all refresh operations are completed
final AsyncCallbackCollector collector = new AsyncCallbackCollector(innerCallback, new CallbackInvocationDelegate());
// Get the first level of children and check if they are need to be refreshed
List<IProcessContextNode> children = model.getChildren(IProcessContextNode.class);
if (children.size() > 0) {
// Initiate the refresh of the children
doAutoRefresh(model, children.toArray(new IProcessContextNode[children.size()]), 0, collector);
}
// Mark the collector initialization done
collector.initDone();
}
// ----- Non-API refresh methods -----
/**
* Performs the auto refresh of the given nodes.
*
* @param model The runtime model. Must not be <code>null</code>.
* @param nodes The nodes. Must not be <code>null</code>.
* @param index The index of the node to refresh within the nodes array. Must be greater or equal than 0 and less than the array length.
* @param collector The callback collector. Must not be <code>null</code>.
*/
/* default */ void doAutoRefresh(final IRuntimeModel model, final IProcessContextNode[] nodes, final int index, final AsyncCallbackCollector collector) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(model);
Assert.isNotNull(nodes);
Assert.isTrue(index >= 0 && index < nodes.length);
Assert.isNotNull(collector);
final IProcessContextNode node = nodes[index];
// Get the asynchronous refresh context adapter
final IAsyncRefreshableCtx refreshable = (IAsyncRefreshableCtx)node.getAdapter(IAsyncRefreshableCtx.class);
if (refreshable != null) {
// Schedule a refresh if the node got refreshed before
if (refreshable.getQueryState(QueryType.CHILD_LIST).equals(QueryState.DONE)) {
// Create a new callback for the collector to wait for
final ICallback callback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// We need a reference to the outer callback (== this)
final ICallback outerCallback = this;
// Create the inner callback
final ICallback innerCallback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// More nodes to process?
int newIndex = index + 1;
if (newIndex < nodes.length) {
doAutoRefresh(model, nodes, newIndex, collector);
}
// Remove the outer callback from the collector
collector.removeCallback(outerCallback);
}
};
// If the node has children, process them first
List<IProcessContextNode> children = node.getChildren(IProcessContextNode.class);
if (children.size() > 0) {
// Create a new callback collector for processing the children
final AsyncCallbackCollector childCollector = new AsyncCallbackCollector(innerCallback, new CallbackInvocationDelegate());
// Initiate the refresh of the children
doAutoRefresh(model, children.toArray(new IProcessContextNode[children.size()]), 0, childCollector);
// Mark the collector initialization done
childCollector.initDone();
} else {
// Invoke the inner callback right away
innerCallback.done(this, Status.OK_STATUS);
}
}
};
collector.addCallback(callback);
// Get the context id
final String contextId = node.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID);
if (contextId == null) {
callback.done(this, Status.OK_STATUS);
return;
}
// The refresh operation is building up a parallel data tree. Pass in an empty container
// to receive the fetched context properties and context children.
final IProcessContextNode container = model.getFactory().newInstance(IProcessContextNode.class);
// Mark the container as refresh in progress
final IAsyncRefreshableCtx containerRefreshable = (IAsyncRefreshableCtx)container.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(containerRefreshable);
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.IN_PROGRESS);
// The context id must be set to the container (asserted by the update service)
container.setProperty(IProcessContextNodeProperties.PROPERTY_ID, contextId);
// The container has the same type as the original node
container.setType(node.getType());
// Initiate the refresh of context (only node and the direct children)
refreshContextLevel1(contextId, 1, container, new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Mark the container refresh as done
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.DONE);
// If the refresh succeeded, update the original node
if (status.isOK()) {
// Auto refresh requires to update the children of any new child found for
// the node refreshed. Collect all child nodes not being children of the original node.
List<IProcessContextNode> oldChildren = node.getChildren(IProcessContextNode.class);
List<IProcessContextNode> newChildren = container.getChildren(IProcessContextNode.class);
for (IProcessContextNode child : oldChildren) {
// Get the context id of the exiting child
String id = child.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID);
if (id == null) continue;
// Find the context id in the new children list
IProcessContextNode node = null;
for (IProcessContextNode candidate : newChildren) {
if (id.equals(candidate.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID))) {
node = candidate;
break;
}
}
// If found in the new children list, remove it
if (node != null) newChildren.remove(node);
}
// Process the new context node and merge it with the original context node
model.getService(IRuntimeModelUpdateService.class).update(node, container);
// If there are any new children detected, update the child list of those new children
if (newChildren.size() > 0) {
// Create the collector firing the final callback at the end
final AsyncCallbackCollector collector = new AsyncCallbackCollector(callback, new CallbackInvocationDelegate());
// Get the real children list
oldChildren = node.getChildren(IProcessContextNode.class);
for (IProcessContextNode child : newChildren) {
// Get the context id of the child
String id = child.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID);
if (id == null) continue;
// Find the real child node
IProcessContextNode realChild = null;
for (IProcessContextNode candidate : oldChildren) {
if (id.equals(candidate.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID))) {
realChild = candidate;
break;
}
}
if (realChild == null) continue;
// The refresh operation is building up a parallel data tree. Pass in an empty container
// to receive the fetched context properties and context children.
final IProcessContextNode container = model.getFactory().newInstance(IProcessContextNode.class);
// Mark the container as refresh in progress
final IAsyncRefreshableCtx containerRefreshable = (IAsyncRefreshableCtx)container.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(containerRefreshable);
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.IN_PROGRESS);
// The context id must be set to the container (asserted by the update service)
container.setProperty(IProcessContextNodeProperties.PROPERTY_ID, contextId);
// The container has the same type as the original node
container.setType(node.getType());
// Create the callback to invoke
final IProcessContextNode finRealChild = realChild;
final ICallback cb = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Mark the container refresh as done
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.DONE);
// If the refresh succeeded, update the original child node
if (status.isOK()) {
model.getService(IRuntimeModelUpdateService.class).updateChildren(finRealChild, container);
}
// Remove the callback from the collector
if (status.getException() != null) {
collector.handleError(status.getException());
} else {
collector.removeCallback(this);
}
}
};
collector.addCallback(cb);
// Refresh the children of the new child
refreshChildrenLevel1(id, 1, container, cb);
}
collector.initDone();
} else {
// Invoke the callback
callback.done(RuntimeModelRefreshService.this, status);
}
} else {
// Invoke the callback
callback.done(RuntimeModelRefreshService.this, status);
}
}
});
}
}
}
/**
* Refresh the context properties for the given context id.
* <p>
* The method fetches the children of the given context id and generates a new set of process
* context nodes to represent the children until the max depth is reached.
* <p>
* The fetched properties are added to the given container.
*
* @param contextId The context id. Must not be <code>null</code>.
* @param maxDepth The max depth of the tree to refresh. Must be greater than 0.
* @param container The container. Must not be <code>null</code>.
* @param callback The callback to invoke once the operation is completed. Must not be <code>null</code>.
*/
protected void refreshContextLevel1(final String contextId, final int maxDepth, final IProcessContextNode container, final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(contextId);
Assert.isTrue(maxDepth > 0);
Assert.isNotNull(container);
Assert.isNotNull(callback);
// Make sure that the callback is invoked even for unexpected cases
try {
// Get an open channel
IModelChannelService channelService = getModel().getService(IModelChannelService.class);
channelService.openChannel(new IModelChannelService.DoneOpenChannel() {
@Override
public void doneOpenChannel(Throwable error, final IChannel channel) {
if (error == null) {
// Query the context properties
refreshContext(channel, contextId, container, new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
if (status.isOK()) {
// Query the first level child contexts
refreshChildContexts(channel, contextId, container, new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Refresh the next level if the depth is still larger than 0
if (maxDepth - 1 > 0) {
List<IProcessContextNode> children = container.getChildren(IProcessContextNode.class);
Assert.isNotNull(children);
refreshChildrenLevelN(channel, children.toArray(new IProcessContextNode[children.size()]), maxDepth - 1, callback);
} else {
// Refresh completed, invoke the callback
callback.done(RuntimeModelRefreshService.this, status);
}
}
});
} else {
callback.done(RuntimeModelRefreshService.this, status);
}
}
});
} else {
callback.done(RuntimeModelRefreshService.this, new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), error.getLocalizedMessage(), error));
}
}
});
} catch (Throwable e) {
callback.done(RuntimeModelRefreshService.this, new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), e.getLocalizedMessage(), e));
}
}
/**
* Fetches the first level of children for the given parent context id.
* <p>
* The method fetches the first level of children and generates a new set of process
* context nodes to represent the children. Each child is refresh itself until the max
* depth is reached.
* <p>
* The fetched first level children are added to the given container.
*
* @param parentContextId The parent context id or <code>null</code> for the root context.
* @param maxDepth The max depth of the tree to refresh. Must be greater than 0.
* @param container The container. Must not be <code>null</code>.
* @param callback The callback to invoke once the operation is completed. Must not be <code>null</code>.
*/
/* default */ void refreshChildrenLevel1(final String parentContextId, final int maxDepth, final IProcessContextNode container, final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isTrue(maxDepth > 0);
Assert.isNotNull(container);
Assert.isNotNull(callback);
// Make sure that the callback is invoked even for unexpected cases
try {
// Get an open channel
IModelChannelService channelService = getModel().getService(IModelChannelService.class);
channelService.openChannel(new IModelChannelService.DoneOpenChannel() {
@Override
public void doneOpenChannel(Throwable error, final IChannel channel) {
if (error == null) {
// Query the first level child contexts
refreshChildContexts(channel, parentContextId, container, new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Refresh the next level if the depth is still larger than 0
if (maxDepth - 1 > 0) {
List<IProcessContextNode> children = container.getChildren(IProcessContextNode.class);
Assert.isNotNull(children);
refreshChildrenLevelN(channel, children.toArray(new IProcessContextNode[children.size()]), maxDepth - 1, callback);
} else {
// Refresh completed, invoke the callback
callback.done(RuntimeModelRefreshService.this, status);
}
}
});
} else {
callback.done(RuntimeModelRefreshService.this, new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), error.getLocalizedMessage(), error));
}
}
});
} catch (Throwable e) {
callback.done(RuntimeModelRefreshService.this, new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), e.getLocalizedMessage(), e));
}
}
/**
* Fetches the children of the given parent context nodes.
* <p>
* The method calls itself recursively until <code>maxDepth - 1 == 0</code> is true.
*
* @param channel An open channel. Must not be <code>null</code>.
* @param parents The parent contexts. Must not be <code>null</code>.
* @param maxDepth The max depth of the tree to refresh. Must be greater than 0.
* @param callback The callback to invoke once the operation is completed. Must not be <code>null</code>.
*/
/* default */ void refreshChildrenLevelN(final IChannel channel, final IProcessContextNode[] parents, final int maxDepth, final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(channel);
Assert.isNotNull(parents);
Assert.isTrue(maxDepth > 0);
Assert.isNotNull(callback);
// The channel must be opened, otherwise the query cannot run
if (channel.getState() != IChannel.STATE_OPEN) {
IStatus status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), Messages.RuntimeModelRefreshService_error_channelClosed);
callback.done(RuntimeModelRefreshService.this, status);
return;
}
// If the parents list is empty, there is nothing to refresh
if (parents.length == 0) {
callback.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
return;
}
// The callback collector to be fired if the children of all parents got fully refreshed
final AsyncCallbackCollector collector = new AsyncCallbackCollector(new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Refresh the next level if the depth is still larger than 0
if (maxDepth - 1 > 0) {
// The callback collector to be fired if the children of all children of all parent contexts got fully refreshed
final AsyncCallbackCollector collector2 = new AsyncCallbackCollector(callback, new CallbackInvocationDelegate());
for (IProcessContextNode parent : parents) {
List<IProcessContextNode> children = parent.getChildren(IProcessContextNode.class);
Assert.isNotNull(children);
refreshChildrenLevelN(channel, children.toArray(new IProcessContextNode[children.size()]), maxDepth - 1, new AsyncCallbackCollector.SimpleCollectorCallback(collector2));
}
collector2.initDone();
} else {
// Refresh completed, invoke the callback
callback.done(RuntimeModelRefreshService.this, status);
}
}
}, new CallbackInvocationDelegate());
// Loop the parent contexts and refresh the children of each one.
for (final IProcessContextNode parent : parents) {
// Get the context id of the parent. Must be not null here.
String parentContextId = parent.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID);
if (parentContextId == null) continue;
// Create the callback
final ICallback cb = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
// Get the asynchronous refresh context adapter
final IAsyncRefreshableCtx refreshable = (IAsyncRefreshableCtx)parent.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(refreshable);
// If not IN_PROGRESS, initiate the refresh
if (!refreshable.getQueryState(QueryType.CHILD_LIST).equals(QueryState.IN_PROGRESS)) {
// Mark the refresh as in progress
refreshable.setQueryState(QueryType.CHILD_LIST, QueryState.IN_PROGRESS);
// Don't send change events while refreshing
final boolean changed = parent.setChangeEventsEnabled(false);
// Refresh the children of the parent context
refreshChildContexts(channel, parentContextId, parent, new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Mark the refresh as done
refreshable.setQueryState(QueryType.CHILD_LIST, QueryState.DONE);
// Re-enable the change events if they had been enabled before
if (changed) parent.setChangeEventsEnabled(true);
// Invoke the callback
cb.done(RuntimeModelRefreshService.this, status);
}
});
} else {
// Invoke the callback
cb.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
}
}
collector.initDone();
}
/**
* Refresh the properties of the given context id using the given channel.
* All context properties are <i>added</i> to the passed in node.
*
* @param channel An open channel. Must not be <code>null</code>.
* @param contextId The context id. Must not be <code>null</code>.
* @param node The node. Must not be <code>null</code>.
* @param callback The callback to invoke once the operation is completed. Must not be <code>null</code>.
*/
/* default */ void refreshContext(final IChannel channel, final String contextId, final IProcessContextNode node, final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(channel);
Assert.isNotNull(contextId);
Assert.isNotNull(node);
Assert.isNotNull(callback);
// The channel must be opened, otherwise the query cannot run
if (channel.getState() != IChannel.STATE_OPEN) {
IStatus status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), Messages.RuntimeModelRefreshService_error_channelClosed);
callback.done(RuntimeModelRefreshService.this, status);
return;
}
// Get the required services
final IProcesses service = channel.getRemoteService(IProcesses.class);
final ISysMonitor sysMonService = channel.getRemoteService(ISysMonitor.class);
// At least the processes and the system monitor service must be available
if (service == null || sysMonService == null) {
callback.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
return;
}
// Callback collector to fire once the system monitor and process context queries completed
final AsyncCallbackCollector collector = new AsyncCallbackCollector(new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Determine if a delegate is registered
IDelegateService service = ServiceManager.getInstance().getService(channel.getRemotePeer(), IDelegateService.class, false);
IRuntimeModelRefreshService.IDelegate delegate = service != null ? service.getDelegate(channel.getRemotePeer(), IRuntimeModelRefreshService.IDelegate.class) : null;
// Run the post refresh context delegate
if (delegate == null) delegate = defaultDelegate;
Assert.isNotNull(delegate);
delegate.postRefreshContext(channel, node, callback);
}
}, new CallbackInvocationDelegate());
// Query the system monitor context object
final ICallback cb1 = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
sysMonService.getContext(contextId, new ISysMonitor.DoneGetContext() {
@Override
public void doneGetContext(IToken token, Exception error, SysMonitorContext context) {
// Ignore errors. Some of the context might be OS context we do not have
// permissions to read the properties from.
node.setSysMonitorContext(context);
// Invoke the callback
cb1.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
}
});
// Query the process context object
final ICallback cb2 = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
service.getContext(contextId, new IProcesses.DoneGetContext() {
@Override
public void doneGetContext(IToken token, Exception error, IProcesses.ProcessContext context) {
// Errors are ignored
node.setProcessContext(context);
// Set the context name from the process context if available
if (context != null) node.setProperty(IProcessContextNodeProperties.PROPERTY_NAME, context.getName());
// Invoke the callback
cb2.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
}
});
collector.initDone();
}
/**
* Refresh the child contexts of the given parent context id using the given channel.
* All child contexts are <i>added</i> to the passed in container.
*
* @param channel An open channel. Must not be <code>null</code>.
* @param parentContextId The parent context id or <code>null</code> for the root context.
* @param container The container. Must not be <code>null</code>.
* @param callback The callback to invoke once the operation is completed. Must not be <code>null</code>.
*/
/* default */ void refreshChildContexts(final IChannel channel, final String parentContextId, final IContainerModelNode container, final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(channel);
Assert.isNotNull(container);
Assert.isNotNull(callback);
// The channel must be opened, otherwise the query cannot run
if (channel.getState() != IChannel.STATE_OPEN) {
IStatus status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), Messages.RuntimeModelRefreshService_error_channelClosed);
callback.done(RuntimeModelRefreshService.this, status);
return;
}
// Get the required services
final IProcesses service = channel.getRemoteService(IProcesses.class);
final ISysMonitor sysMonService = channel.getRemoteService(ISysMonitor.class);
// At least the processes and the system monitor service must be available
if (service == null || sysMonService == null) {
callback.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
return;
}
// Get the child context id's of the given parent context id
sysMonService.getChildren(parentContextId, new ISysMonitor.DoneGetChildren() {
@Override
public void doneGetChildren(IToken token, Exception error, String[] context_ids) {
if (error == null) {
if (context_ids != null && context_ids.length > 0) {
// Callback collector to fire the passed in callback once all child contexts got fully refreshed
final AsyncCallbackCollector collector = new AsyncCallbackCollector(callback, new CallbackInvocationDelegate());
// Loop the returned context id's and query the context data
for (String id : context_ids) {
final String contextId = id;
// Create the context node for the current context id
final IProcessContextNode node = createContextNodeFrom(contextId);
Assert.isNotNull(node);
// Add the node to the container
container.add(node);
// Callback collector to fire once the system monitor and process context queries completed
final ICallback innerCallback = new AsyncCallbackCollector.SimpleCollectorCallback(collector);
final AsyncCallbackCollector innerCollector = new AsyncCallbackCollector(new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Determine if a delegate is registered
IDelegateService service = ServiceManager.getInstance().getService(channel.getRemotePeer(), IDelegateService.class, false);
IRuntimeModelRefreshService.IDelegate delegate = service != null ? service.getDelegate(channel.getRemotePeer(), IRuntimeModelRefreshService.IDelegate.class) : null;
// Determine the node type
if (delegate != null) delegate.setNodeType(parentContextId, node);
// Fallback to the default delegate if node type is not set by delegate
if (node.getType() == TYPE.Unknown) defaultDelegate.setNodeType(parentContextId, node);
// Run the post refresh context delegate
if (delegate == null) delegate = defaultDelegate;
Assert.isNotNull(delegate);
delegate.postRefreshContext(channel, node, innerCallback);
}
}, new CallbackInvocationDelegate());
// Query the system monitor context object
final ICallback cb1 = new AsyncCallbackCollector.SimpleCollectorCallback(innerCollector);
sysMonService.getContext(contextId, new ISysMonitor.DoneGetContext() {
@Override
public void doneGetContext(IToken token, Exception error, SysMonitorContext context) {
// Ignore errors. Some of the context might be OS context we do not have
// permissions to read the properties from.
node.setSysMonitorContext(context);
// Invoke the callback
cb1.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
}
});
// Query the process context object
final ICallback cb2 = new AsyncCallbackCollector.SimpleCollectorCallback(innerCollector);
service.getContext(contextId, new IProcesses.DoneGetContext() {
@Override
public void doneGetContext(IToken token, Exception error, IProcesses.ProcessContext context) {
// Errors are ignored
node.setProcessContext(context);
// Set the context name from the process context if available
if (context != null) node.setProperty(IProcessContextNodeProperties.PROPERTY_NAME, context.getName());
// Invoke the callback
cb2.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
}
});
innerCollector.initDone();
}
collector.initDone();
} else {
callback.done(RuntimeModelRefreshService.this, Status.OK_STATUS);
}
} else {
callback.done(RuntimeModelRefreshService.this, new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), error.getLocalizedMessage(), error));
}
}
});
}
/**
* Create a process context node instance for the given context id.
*
* @param contextId The context id. Must not be <code>null</code>.
* @return The process context node instance.
*/
/* default */ IProcessContextNode createContextNodeFrom(String contextId) {
Assert.isNotNull(contextId);
// Create a context node and associate the given context
IProcessContextNode node = getModel().getFactory().newInstance(IProcessContextNode.class);
// Set the context id
node.setProperty(IProcessContextNodeProperties.PROPERTY_ID, contextId);
return node;
}
// ----- Utility methods ------
/**
* Invoke all pending callbacks for the given context.
* <p>
* Each callback is invoked as single runnable dispatched to the
* TCF event dispatch thread.
*
* @param context The context. Must not be <code>null</code>.
* @param caller The caller of the callback or <code>null</code>.
* @param status The status. Must not be <code>null</code>.
*/
protected void invokeCallbacks(final IModelNode context, final Object caller, final IStatus status) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(context);
Assert.isNotNull(status);
List<ICallback> callbacks = ctx2cb.remove(context);
if (callbacks != null) {
for (final ICallback callback : callbacks) {
Protocol.invokeLater(new Runnable() {
@Override
public void run() {
callback.done(caller, status);
}
});
}
}
}
}
| true | true | public void refresh(final IModelNode node, final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(node);
// Get the parent model
final IRuntimeModel model = getModel();
Assert.isNotNull(model);
// If the model is already disposed, drop out immediately
if (model.isDisposed() || !(node instanceof IProcessContextNode)) {
if (callback != null) callback.done(this, Status.OK_STATUS);
return;
}
// Get the context id
final String contextId = node.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID);
if (contextId == null) {
if (callback != null) callback.done(this, Status.OK_STATUS);
return;
}
// A refresh for the passed in node is already running if the node
// is associated with a callback list in 'ctx2cb'.
final boolean isRefreshAlreadyRunning = ctx2cb.containsKey(node);
// Queue the callback to invoke once the refresh is done
List<ICallback> callbacks = ctx2cb.get(node);
if (callbacks == null) {
callbacks = new ArrayList<ICallback>();
ctx2cb.put(node, callbacks);
}
Assert.isNotNull(callbacks);
// Add the current callback to the list of callbacks
if (callback != null) callbacks.add(callback);
// If a refresh is already running, drop out. The callback is already
// queued and will be invoked once the refresh operation is done.
if (isRefreshAlreadyRunning) return;
// The refresh operation is building up a parallel data tree. Pass in an empty container
// to receive the fetched context properties and context children.
final IProcessContextNode container = model.getFactory().newInstance(IProcessContextNode.class);
// Mark the container as refresh in progress
final IAsyncRefreshableCtx containerRefreshable = (IAsyncRefreshableCtx)container.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(containerRefreshable);
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.IN_PROGRESS);
// The context id must be set to the container (asserted by the update service)
container.setProperty(IProcessContextNodeProperties.PROPERTY_ID, contextId);
// The container has the same type as the original node
container.setType(((IProcessContextNode)node).getType());
// Initiate the refresh of context
refreshContextLevel1(contextId, 2, container, new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Mark the container refresh as done
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.DONE);
// If the refresh succeeded, update the original node
if (status.isOK()) {
// Process the new context node and merge it with the original context node
model.getService(IRuntimeModelUpdateService.class).update(node, container);
// Walk the tree on check the children at level 2 to determine if there are
// nodes which got expanded by the user and must be refreshed therefore too.
final List<IProcessContextNode> children = new ArrayList<IProcessContextNode>();
// Get the first level children from the model
List<IProcessContextNode> candidates = ((IProcessContextNode)node).getChildren(IProcessContextNode.class);
for (IProcessContextNode candidate : candidates) {
// If the child list got not queried for the candidate, skip it
IAsyncRefreshableCtx refreshable = (IAsyncRefreshableCtx)candidate.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(refreshable);
if (refreshable.getQueryState(QueryType.CHILD_LIST) != QueryState.DONE) continue;
// Get the second level children and find those candidates where
// the child list query is marked done. Add those candidates to
// the list of children to refresh too.
List<IProcessContextNode> candidates2 = candidate.getChildren(IProcessContextNode.class);
for (IProcessContextNode candidate2 : candidates2) {
// Get the asynchronous refreshable for the candidate
refreshable = (IAsyncRefreshableCtx)candidate2.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(refreshable);
if (refreshable.getQueryState(QueryType.CHILD_LIST) != QueryState.DONE) continue;
// This child needs an additional refresh
children.add(candidate2);
}
}
// Run the auto-refresh logic for all children we have found
final ICallback callback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Invoke the callbacks
invokeCallbacks(model, RuntimeModelRefreshService.this, status);
}
};
// Create the callback collector to fire once all refresh operations are completed
final AsyncCallbackCollector collector = new AsyncCallbackCollector(callback, new CallbackInvocationDelegate());
// Get the first level of children and check if they are need to be refreshed
if (children.size() > 0) {
// Initiate the refresh of the children
doAutoRefresh(model, children.toArray(new IProcessContextNode[children.size()]), 0, collector);
}
// Mark the collector initialization done
collector.initDone();
} else {
// Invoke the callbacks
invokeCallbacks(node, RuntimeModelRefreshService.this, status);
}
}
});
}
| public void refresh(final IModelNode node, final ICallback callback) {
Assert.isTrue(Protocol.isDispatchThread(), "Illegal Thread Access"); //$NON-NLS-1$
Assert.isNotNull(node);
// Get the parent model
final IRuntimeModel model = getModel();
Assert.isNotNull(model);
// If the model is already disposed, drop out immediately
if (model.isDisposed() || !(node instanceof IProcessContextNode)) {
if (callback != null) callback.done(this, Status.OK_STATUS);
return;
}
// Get the context id
final String contextId = node.getStringProperty(IProcessContextNodeProperties.PROPERTY_ID);
if (contextId == null) {
if (callback != null) callback.done(this, Status.OK_STATUS);
return;
}
// A refresh for the passed in node is already running if the node
// is associated with a callback list in 'ctx2cb'.
final boolean isRefreshAlreadyRunning = ctx2cb.containsKey(node);
// Queue the callback to invoke once the refresh is done
List<ICallback> callbacks = ctx2cb.get(node);
if (callbacks == null) {
callbacks = new ArrayList<ICallback>();
ctx2cb.put(node, callbacks);
}
Assert.isNotNull(callbacks);
// Add the current callback to the list of callbacks
if (callback != null) callbacks.add(callback);
// If a refresh is already running, drop out. The callback is already
// queued and will be invoked once the refresh operation is done.
if (isRefreshAlreadyRunning) return;
// The refresh operation is building up a parallel data tree. Pass in an empty container
// to receive the fetched context properties and context children.
final IProcessContextNode container = model.getFactory().newInstance(IProcessContextNode.class);
// Mark the container as refresh in progress
final IAsyncRefreshableCtx containerRefreshable = (IAsyncRefreshableCtx)container.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(containerRefreshable);
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.IN_PROGRESS);
// The context id must be set to the container (asserted by the update service)
container.setProperty(IProcessContextNodeProperties.PROPERTY_ID, contextId);
// The container has the same type as the original node
container.setType(((IProcessContextNode)node).getType());
// Initiate the refresh of context
refreshContextLevel1(contextId, 2, container, new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Mark the container refresh as done
containerRefreshable.setQueryState(QueryType.CHILD_LIST, QueryState.DONE);
// If the refresh succeeded, update the original node
if (status.isOK()) {
// Process the new context node and merge it with the original context node
model.getService(IRuntimeModelUpdateService.class).update(node, container);
// Walk the tree on check the children at level 2 to determine if there are
// nodes which got expanded by the user and must be refreshed therefore too.
final List<IProcessContextNode> children = new ArrayList<IProcessContextNode>();
// Get the first level children from the model
List<IProcessContextNode> candidates = ((IProcessContextNode)node).getChildren(IProcessContextNode.class);
for (IProcessContextNode candidate : candidates) {
// If the child list got not queried for the candidate, skip it
IAsyncRefreshableCtx refreshable = (IAsyncRefreshableCtx)candidate.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(refreshable);
if (refreshable.getQueryState(QueryType.CHILD_LIST) != QueryState.DONE) continue;
// Get the second level children and find those candidates where
// the child list query is marked done. Add those candidates to
// the list of children to refresh too.
List<IProcessContextNode> candidates2 = candidate.getChildren(IProcessContextNode.class);
for (IProcessContextNode candidate2 : candidates2) {
// Get the asynchronous refreshable for the candidate
refreshable = (IAsyncRefreshableCtx)candidate2.getAdapter(IAsyncRefreshableCtx.class);
Assert.isNotNull(refreshable);
if (refreshable.getQueryState(QueryType.CHILD_LIST) != QueryState.DONE) continue;
// This child needs an additional refresh
children.add(candidate2);
}
}
// Run the auto-refresh logic for all children we have found
final ICallback callback = new Callback() {
@Override
protected void internalDone(Object caller, IStatus status) {
// Invoke the callbacks
invokeCallbacks(node, RuntimeModelRefreshService.this, status);
}
};
// Create the callback collector to fire once all refresh operations are completed
final AsyncCallbackCollector collector = new AsyncCallbackCollector(callback, new CallbackInvocationDelegate());
// Get the first level of children and check if they are need to be refreshed
if (children.size() > 0) {
// Initiate the refresh of the children
doAutoRefresh(model, children.toArray(new IProcessContextNode[children.size()]), 0, collector);
}
// Mark the collector initialization done
collector.initDone();
} else {
// Invoke the callbacks
invokeCallbacks(node, RuntimeModelRefreshService.this, status);
}
}
});
}
|
diff --git a/src/org/hackystat/projectbrowser/authentication/SigninPage.java b/src/org/hackystat/projectbrowser/authentication/SigninPage.java
index b3c5fb3..bf4d7cd 100644
--- a/src/org/hackystat/projectbrowser/authentication/SigninPage.java
+++ b/src/org/hackystat/projectbrowser/authentication/SigninPage.java
@@ -1,89 +1,89 @@
package org.hackystat.projectbrowser.authentication;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.hackystat.dailyprojectdata.client.DailyProjectDataClient;
import org.hackystat.projectbrowser.ProjectBrowserApplication;
import org.hackystat.projectbrowser.imageurl.ImageUrl;
import org.hackystat.sensorbase.client.SensorBaseClient;
import org.hackystat.telemetry.service.client.TelemetryClient;
/**
* Provides a signin page for either logging in with a previous username and password, or
* else registering with the system.
*
* @author Philip Johnson
*/
public class SigninPage extends WebPage {
/** Support serialization. */
private static final long serialVersionUID = 1L;
/**
* Create the SigninPage.
*/
public SigninPage() {
ProjectBrowserApplication app = (ProjectBrowserApplication)getApplication();
add(HeaderContributor.forCss(org.hackystat.projectbrowser.Start.class,
"style/boilerplate/screen.css", "screen"));
add(HeaderContributor.forCss(org.hackystat.projectbrowser.Start.class,
"style/boilerplate/print.css", "print"));
add(new Label("title", app.getApplicationName()));
add(new ImageUrl("application-logo", app.getApplicationLogo()));
add(new Label("application-name", (app.hasApplicationLogo() ? "" : app.getApplicationName())));
add(new SigninForm("signinForm"));
add(new RegisterForm("registerForm"));
List<String> serviceInfo = getServiceInfo();
add(new Label("available", serviceInfo.get(0)));
add(new Label("notAvailable", serviceInfo.get(1)));
}
/**
* Returns a list containing two strings. The first string indicates the services that
* were contacted successfully. The second string indicates the services that were not
* contacted successfully.
* @return A list of two strings indicating service availability.
*/
private List<String> getServiceInfo() {
List<String> serviceInfo = new ArrayList<String>();
StringBuffer available = new StringBuffer(20);
- StringBuffer notAvailable = new StringBuffer(20);
+ StringBuffer notAvailable = new StringBuffer(22);
available.append("Available services: ");
notAvailable.append("Unavailable services: ");
ProjectBrowserApplication app = (ProjectBrowserApplication)getApplication();
String sensorbase = app.getSensorBaseHost();
if (SensorBaseClient.isHost(sensorbase)) {
available.append(sensorbase);
}
else {
notAvailable.append(sensorbase);
}
String dpd = app.getDailyProjectDataHost();
if (DailyProjectDataClient.isHost(dpd)) {
available.append(' ').append(dpd);
}
else {
notAvailable.append(' ').append(dpd);
}
String telemetry = app.getTelemetryHost();
if (TelemetryClient.isHost(telemetry)) {
available.append(' ').append(telemetry);
}
else {
notAvailable.append(' ').append(telemetry);
}
String availableString = ((available.length() > 20) ?
available.toString() : "");
String notAvailableString = ((notAvailable.length() > 22) ?
notAvailable.toString() : "");
serviceInfo.add(availableString);
serviceInfo.add(notAvailableString);
return serviceInfo;
}
}
| true | true | private List<String> getServiceInfo() {
List<String> serviceInfo = new ArrayList<String>();
StringBuffer available = new StringBuffer(20);
StringBuffer notAvailable = new StringBuffer(20);
available.append("Available services: ");
notAvailable.append("Unavailable services: ");
ProjectBrowserApplication app = (ProjectBrowserApplication)getApplication();
String sensorbase = app.getSensorBaseHost();
if (SensorBaseClient.isHost(sensorbase)) {
available.append(sensorbase);
}
else {
notAvailable.append(sensorbase);
}
String dpd = app.getDailyProjectDataHost();
if (DailyProjectDataClient.isHost(dpd)) {
available.append(' ').append(dpd);
}
else {
notAvailable.append(' ').append(dpd);
}
String telemetry = app.getTelemetryHost();
if (TelemetryClient.isHost(telemetry)) {
available.append(' ').append(telemetry);
}
else {
notAvailable.append(' ').append(telemetry);
}
String availableString = ((available.length() > 20) ?
available.toString() : "");
String notAvailableString = ((notAvailable.length() > 22) ?
notAvailable.toString() : "");
serviceInfo.add(availableString);
serviceInfo.add(notAvailableString);
return serviceInfo;
}
| private List<String> getServiceInfo() {
List<String> serviceInfo = new ArrayList<String>();
StringBuffer available = new StringBuffer(20);
StringBuffer notAvailable = new StringBuffer(22);
available.append("Available services: ");
notAvailable.append("Unavailable services: ");
ProjectBrowserApplication app = (ProjectBrowserApplication)getApplication();
String sensorbase = app.getSensorBaseHost();
if (SensorBaseClient.isHost(sensorbase)) {
available.append(sensorbase);
}
else {
notAvailable.append(sensorbase);
}
String dpd = app.getDailyProjectDataHost();
if (DailyProjectDataClient.isHost(dpd)) {
available.append(' ').append(dpd);
}
else {
notAvailable.append(' ').append(dpd);
}
String telemetry = app.getTelemetryHost();
if (TelemetryClient.isHost(telemetry)) {
available.append(' ').append(telemetry);
}
else {
notAvailable.append(' ').append(telemetry);
}
String availableString = ((available.length() > 20) ?
available.toString() : "");
String notAvailableString = ((notAvailable.length() > 22) ?
notAvailable.toString() : "");
serviceInfo.add(availableString);
serviceInfo.add(notAvailableString);
return serviceInfo;
}
|
diff --git a/src/autosaveworld/threads/purge/WGpurge.java b/src/autosaveworld/threads/purge/WGpurge.java
index 53374ed..1718c64 100644
--- a/src/autosaveworld/threads/purge/WGpurge.java
+++ b/src/autosaveworld/threads/purge/WGpurge.java
@@ -1,127 +1,127 @@
package autosaveworld.threads.purge;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import autosaveworld.core.AutoSaveWorld;
public class WGpurge {
private AutoSaveWorld plugin;
public WGpurge(AutoSaveWorld plugin, long awaytime, boolean regenrg)
{
this.plugin = plugin;
WGPurgeTask(awaytime, regenrg);
}
private void WGPurgeTask(long awaytime, final boolean regenrg) {
WorldGuardPlugin wg = (WorldGuardPlugin) plugin.getServer()
.getPluginManager().getPlugin("WorldGuard");
plugin.debug("WG purge started");
//get all active players
HashSet<String> onlineplncs = new HashSet<String>();
for (Player plname : Bukkit.getOnlinePlayers()) {
onlineplncs.add(plname.getName().toLowerCase());
}
for (OfflinePlayer plname : Bukkit.getOfflinePlayers()) {
if (System.currentTimeMillis() - plname.getLastPlayed() < awaytime) {
onlineplncs.add(plname.getName().toLowerCase());
}
}
int deletedrg = 0;
List<World> worldlist = Bukkit.getWorlds();
for (final World w : worldlist) {
plugin.debug("Checking WG protections in world " + w.getName());
final RegionManager m = wg.getRegionManager(w);
// searching for inactive players in regions
List<String> rgtodel = new ArrayList<String>();
for (ProtectedRegion rg : m.getRegions().values()) {
plugin.debug("Checking region " + rg.getId());
ArrayList<String> pltodelete = new ArrayList<String>();
Set<String> ddpl = rg.getOwners().getPlayers();
for (String checkPlayer : ddpl) {
if (!onlineplncs.contains(checkPlayer)) {
pltodelete.add(checkPlayer);
}
}
// check region for remove (ignore regions without owners)
if (!ddpl.isEmpty()) {
if (pltodelete.size() == ddpl.size()) {
// adding region to removal list, we will work with them later
rgtodel.add(rg.getId());
plugin.debug("No active owners for region "+rg.getId()+" Added to removal list");
}
}
}
// now deal with the regions that must be deleted
for (final String delrg : rgtodel) {
plugin.debug("Purging region " + delrg);
plugin.purgeThread.wgrgregenrunning = true;
//regen should be done in main thread
Runnable rgregen = new Runnable()
{
BlockVector minpoint = m.getRegion(delrg).getMinimumPoint();
BlockVector maxpoint = m.getRegion(delrg).getMaximumPoint();
BukkitWorld lw = new BukkitWorld(w);
public void run()
{
try {
if (regenrg) {
plugin.debug("Regenerating region" + delrg);
new BukkitWorld(w).regenerate(
new CuboidRegion(lw,minpoint,maxpoint),
new EditSession(lw,Integer.MAX_VALUE)
);
}
plugin.debug("Deleting region " + delrg);
m.removeRegion(delrg);
m.save();
- plugin.purgeThread.wgrgregenrunning = true;
+ plugin.purgeThread.wgrgregenrunning = false;
} catch (Exception e) {}
}
};
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, rgregen);
//Wait until previous region regeneration is finished to avoid full main thread freezing
while (plugin.purgeThread.wgrgregenrunning)
{
try {Thread.sleep(100);} catch (InterruptedException e) {}
}
}
deletedrg += rgtodel.size();
}
plugin.debug("WG purge finished, deleted "+ deletedrg +" inactive regions");
}
}
| true | true | private void WGPurgeTask(long awaytime, final boolean regenrg) {
WorldGuardPlugin wg = (WorldGuardPlugin) plugin.getServer()
.getPluginManager().getPlugin("WorldGuard");
plugin.debug("WG purge started");
//get all active players
HashSet<String> onlineplncs = new HashSet<String>();
for (Player plname : Bukkit.getOnlinePlayers()) {
onlineplncs.add(plname.getName().toLowerCase());
}
for (OfflinePlayer plname : Bukkit.getOfflinePlayers()) {
if (System.currentTimeMillis() - plname.getLastPlayed() < awaytime) {
onlineplncs.add(plname.getName().toLowerCase());
}
}
int deletedrg = 0;
List<World> worldlist = Bukkit.getWorlds();
for (final World w : worldlist) {
plugin.debug("Checking WG protections in world " + w.getName());
final RegionManager m = wg.getRegionManager(w);
// searching for inactive players in regions
List<String> rgtodel = new ArrayList<String>();
for (ProtectedRegion rg : m.getRegions().values()) {
plugin.debug("Checking region " + rg.getId());
ArrayList<String> pltodelete = new ArrayList<String>();
Set<String> ddpl = rg.getOwners().getPlayers();
for (String checkPlayer : ddpl) {
if (!onlineplncs.contains(checkPlayer)) {
pltodelete.add(checkPlayer);
}
}
// check region for remove (ignore regions without owners)
if (!ddpl.isEmpty()) {
if (pltodelete.size() == ddpl.size()) {
// adding region to removal list, we will work with them later
rgtodel.add(rg.getId());
plugin.debug("No active owners for region "+rg.getId()+" Added to removal list");
}
}
}
// now deal with the regions that must be deleted
for (final String delrg : rgtodel) {
plugin.debug("Purging region " + delrg);
plugin.purgeThread.wgrgregenrunning = true;
//regen should be done in main thread
Runnable rgregen = new Runnable()
{
BlockVector minpoint = m.getRegion(delrg).getMinimumPoint();
BlockVector maxpoint = m.getRegion(delrg).getMaximumPoint();
BukkitWorld lw = new BukkitWorld(w);
public void run()
{
try {
if (regenrg) {
plugin.debug("Regenerating region" + delrg);
new BukkitWorld(w).regenerate(
new CuboidRegion(lw,minpoint,maxpoint),
new EditSession(lw,Integer.MAX_VALUE)
);
}
plugin.debug("Deleting region " + delrg);
m.removeRegion(delrg);
m.save();
plugin.purgeThread.wgrgregenrunning = true;
} catch (Exception e) {}
}
};
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, rgregen);
//Wait until previous region regeneration is finished to avoid full main thread freezing
while (plugin.purgeThread.wgrgregenrunning)
{
try {Thread.sleep(100);} catch (InterruptedException e) {}
}
}
deletedrg += rgtodel.size();
}
plugin.debug("WG purge finished, deleted "+ deletedrg +" inactive regions");
}
| private void WGPurgeTask(long awaytime, final boolean regenrg) {
WorldGuardPlugin wg = (WorldGuardPlugin) plugin.getServer()
.getPluginManager().getPlugin("WorldGuard");
plugin.debug("WG purge started");
//get all active players
HashSet<String> onlineplncs = new HashSet<String>();
for (Player plname : Bukkit.getOnlinePlayers()) {
onlineplncs.add(plname.getName().toLowerCase());
}
for (OfflinePlayer plname : Bukkit.getOfflinePlayers()) {
if (System.currentTimeMillis() - plname.getLastPlayed() < awaytime) {
onlineplncs.add(plname.getName().toLowerCase());
}
}
int deletedrg = 0;
List<World> worldlist = Bukkit.getWorlds();
for (final World w : worldlist) {
plugin.debug("Checking WG protections in world " + w.getName());
final RegionManager m = wg.getRegionManager(w);
// searching for inactive players in regions
List<String> rgtodel = new ArrayList<String>();
for (ProtectedRegion rg : m.getRegions().values()) {
plugin.debug("Checking region " + rg.getId());
ArrayList<String> pltodelete = new ArrayList<String>();
Set<String> ddpl = rg.getOwners().getPlayers();
for (String checkPlayer : ddpl) {
if (!onlineplncs.contains(checkPlayer)) {
pltodelete.add(checkPlayer);
}
}
// check region for remove (ignore regions without owners)
if (!ddpl.isEmpty()) {
if (pltodelete.size() == ddpl.size()) {
// adding region to removal list, we will work with them later
rgtodel.add(rg.getId());
plugin.debug("No active owners for region "+rg.getId()+" Added to removal list");
}
}
}
// now deal with the regions that must be deleted
for (final String delrg : rgtodel) {
plugin.debug("Purging region " + delrg);
plugin.purgeThread.wgrgregenrunning = true;
//regen should be done in main thread
Runnable rgregen = new Runnable()
{
BlockVector minpoint = m.getRegion(delrg).getMinimumPoint();
BlockVector maxpoint = m.getRegion(delrg).getMaximumPoint();
BukkitWorld lw = new BukkitWorld(w);
public void run()
{
try {
if (regenrg) {
plugin.debug("Regenerating region" + delrg);
new BukkitWorld(w).regenerate(
new CuboidRegion(lw,minpoint,maxpoint),
new EditSession(lw,Integer.MAX_VALUE)
);
}
plugin.debug("Deleting region " + delrg);
m.removeRegion(delrg);
m.save();
plugin.purgeThread.wgrgregenrunning = false;
} catch (Exception e) {}
}
};
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, rgregen);
//Wait until previous region regeneration is finished to avoid full main thread freezing
while (plugin.purgeThread.wgrgregenrunning)
{
try {Thread.sleep(100);} catch (InterruptedException e) {}
}
}
deletedrg += rgtodel.size();
}
plugin.debug("WG purge finished, deleted "+ deletedrg +" inactive regions");
}
|
diff --git a/src/com/google/caliper/CaliperRc.java b/src/com/google/caliper/CaliperRc.java
index d376431..963df15 100644
--- a/src/com/google/caliper/CaliperRc.java
+++ b/src/com/google/caliper/CaliperRc.java
@@ -1,53 +1,56 @@
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.caliper;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Created by IntelliJ IDEA. User: kevinb Date: Jan 20, 2010 Time: 9:37:37 AM To change this
* template use File | Settings | File Templates.
*/
public class CaliperRc {
public static final CaliperRc INSTANCE = new CaliperRc();
private final Properties properties = new Properties();
private CaliperRc() {
try {
- File dotCaliperRc = new File(System.getProperty("user.home"), ".caliperrc");
- if (dotCaliperRc.exists()) {
- properties.load(new FileInputStream(dotCaliperRc));
+ String caliperRcEnvVar = System.getenv("CALIPERRC");
+ File caliperRcFile = (caliperRcEnvVar == null)
+ ? new File(System.getProperty("user.home"), ".caliperrc")
+ : new File(caliperRcEnvVar);
+ if (caliperRcFile.exists()) {
+ properties.load(new FileInputStream(caliperRcFile));
} else {
// create it with a template
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getApiKey() {
return properties.getProperty("apiKey");
}
public String getPostUrl() {
return properties.getProperty("postUrl");
}
}
| true | true | private CaliperRc() {
try {
File dotCaliperRc = new File(System.getProperty("user.home"), ".caliperrc");
if (dotCaliperRc.exists()) {
properties.load(new FileInputStream(dotCaliperRc));
} else {
// create it with a template
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
| private CaliperRc() {
try {
String caliperRcEnvVar = System.getenv("CALIPERRC");
File caliperRcFile = (caliperRcEnvVar == null)
? new File(System.getProperty("user.home"), ".caliperrc")
: new File(caliperRcEnvVar);
if (caliperRcFile.exists()) {
properties.load(new FileInputStream(caliperRcFile));
} else {
// create it with a template
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/data/RequestScope.java b/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/data/RequestScope.java
index 3da9952fa..ecf1ae146 100644
--- a/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/data/RequestScope.java
+++ b/org.eclipse.help.webapp/src/org/eclipse/help/internal/webapp/data/RequestScope.java
@@ -1,174 +1,175 @@
/*******************************************************************************
* Copyright (c) 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.help.internal.webapp.data;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.help.HelpSystem;
import org.eclipse.help.base.AbstractHelpScope;
import org.eclipse.help.internal.base.HelpBasePlugin;
import org.eclipse.help.internal.base.HelpBaseResources;
import org.eclipse.help.internal.base.IHelpBaseConstants;
import org.eclipse.help.internal.base.scope.FilterScope;
import org.eclipse.help.internal.base.scope.IntersectionScope;
import org.eclipse.help.internal.base.scope.ScopeRegistry;
import org.eclipse.help.internal.base.scope.UniversalScope;
import org.eclipse.help.internal.base.scope.WorkingSetScope;
import org.eclipse.help.internal.webapp.servlet.CookieUtil;
import org.eclipse.help.internal.webapp.servlet.WebappWorkingSetManager;
import org.osgi.service.prefs.BackingStoreException;
public class RequestScope {
private static final String SCOPE_PARAMETER_NAME = "scope"; //$NON-NLS-1$
private static final String SCOPE_COOKIE_NAME = "filter"; //$NON-NLS-1$
/**
* Gets a scope object based upon the preferences and request
* @param isSearchFilter is true if this filter will be used to filter search results.
* Search results are already filtered by search scope and if this parameter is true search
* scopes will not be considered
* @return
*/
public static AbstractHelpScope getScope(HttpServletRequest req, HttpServletResponse resp, boolean isSearchFilter ) {
AbstractHelpScope[] scopeArray;
scopeArray = getActiveScopes(req, resp, isSearchFilter);
switch (scopeArray.length) {
case 0:
return new UniversalScope();
case 1:
return scopeArray[0];
default:
return new IntersectionScope(
scopeArray);
}
}
public static AbstractHelpScope[] getActiveScopes(HttpServletRequest req,
HttpServletResponse resp, boolean isSearchFilter) {
AbstractHelpScope[] scopeArray;
String scopeString;
List scopes = new ArrayList();
if (!HelpSystem.isShared()) {
scopes.add(new FilterScope()); // Workbench is always filtered
}
scopeString = getScopeString(req);
if (scopeString != null) {
StringTokenizer tokenizer = new StringTokenizer(scopeString, "/"); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
String nextScope = tokenizer.nextToken().trim();
AbstractHelpScope scope = ScopeRegistry.getInstance().getScope(nextScope);
if (scope != null) {
scopes.add(scope);
}
}
}
- // Add filter by search scope
- if (!isSearchFilter) {
+ // Add filter by search scope if not called from Help View
+ boolean isHelpViewTopic = "/ntopic".equals(req.getServletPath()); //$NON-NLS-1$
+ if (!isSearchFilter && !isHelpViewTopic) {
// Try for a working set
try {
WebappWorkingSetManager manager = new WebappWorkingSetManager(req,
resp, UrlUtil.getLocale(req, resp));
String wset = manager.getCurrentWorkingSet();
if (wset != null && wset.length() > 0) {
WorkingSetScope workingSetScope = new WorkingSetScope(wset,
manager, HelpBaseResources.SearchScopeFilterName);
scopes.add(workingSetScope);
}
} catch (Exception e) {
}
}
scopeArray = (AbstractHelpScope[]) scopes.toArray(new AbstractHelpScope[scopes.size()]);
return scopeArray;
}
private static String getScopeString(HttpServletRequest req) {
String scopeString;
if (HelpSystem.isShared()) {
scopeString = getScopeFromCookies(req);
} else {
scopeString = getScopeFromPreferences();
if (scopeString == null) {
scopeString = ScopeRegistry.ENABLEMENT_SCOPE_ID;
}
}
return scopeString;
}
public static void setScopeFromRequest(HttpServletRequest request, HttpServletResponse response) {
// See if there is a scope parameter, if so save as cookie or preference
String[] scope = request.getParameterValues(SCOPE_PARAMETER_NAME);
String scopeString = ""; //$NON-NLS-1$
// save scope (in session cookie) for later use in a user session
// If there are multiple values separate them with a '/'
if (scope != null) {
for (int s = 0; s < scope.length; s++) {
if (ScopeRegistry.getInstance().getScope(scope[s]) != null) {
if (scopeString.length() > 0) {
scopeString += '/';
}
scopeString += scope[s];
}
}
}
saveScope(scopeString, response);
}
public static void saveScope(String scope, HttpServletResponse response) {
if (HelpSystem.isShared()) {
if (response != null) {
CookieUtil.setCookieValue(SCOPE_COOKIE_NAME, scope, response);
}
} else {
InstanceScope instanceScope = new InstanceScope();
IEclipsePreferences pref = instanceScope.getNode(HelpBasePlugin.PLUGIN_ID);
pref.put(IHelpBaseConstants.P_KEY_HELP_SCOPE, scope);
try {
pref.flush();
} catch (BackingStoreException e) {
}
}
}
private static String getScopeFromCookies(HttpServletRequest request) {
// check if scope was passed earlier in this session
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int c = 0; c < cookies.length; c++) {
if (SCOPE_COOKIE_NAME.equals(cookies[c].getName())) {
return cookies[c].getValue();
}
}
}
return null;
}
private static String getScopeFromPreferences() {
String scope = Platform.getPreferencesService().getString
(HelpBasePlugin.PLUGIN_ID, IHelpBaseConstants.P_KEY_HELP_SCOPE, null, null);
return scope;
}
public static boolean filterBySearchScope(HttpServletRequest request) {
return true;
}
}
| true | true | public static AbstractHelpScope[] getActiveScopes(HttpServletRequest req,
HttpServletResponse resp, boolean isSearchFilter) {
AbstractHelpScope[] scopeArray;
String scopeString;
List scopes = new ArrayList();
if (!HelpSystem.isShared()) {
scopes.add(new FilterScope()); // Workbench is always filtered
}
scopeString = getScopeString(req);
if (scopeString != null) {
StringTokenizer tokenizer = new StringTokenizer(scopeString, "/"); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
String nextScope = tokenizer.nextToken().trim();
AbstractHelpScope scope = ScopeRegistry.getInstance().getScope(nextScope);
if (scope != null) {
scopes.add(scope);
}
}
}
// Add filter by search scope
if (!isSearchFilter) {
// Try for a working set
try {
WebappWorkingSetManager manager = new WebappWorkingSetManager(req,
resp, UrlUtil.getLocale(req, resp));
String wset = manager.getCurrentWorkingSet();
if (wset != null && wset.length() > 0) {
WorkingSetScope workingSetScope = new WorkingSetScope(wset,
manager, HelpBaseResources.SearchScopeFilterName);
scopes.add(workingSetScope);
}
} catch (Exception e) {
}
}
scopeArray = (AbstractHelpScope[]) scopes.toArray(new AbstractHelpScope[scopes.size()]);
return scopeArray;
}
| public static AbstractHelpScope[] getActiveScopes(HttpServletRequest req,
HttpServletResponse resp, boolean isSearchFilter) {
AbstractHelpScope[] scopeArray;
String scopeString;
List scopes = new ArrayList();
if (!HelpSystem.isShared()) {
scopes.add(new FilterScope()); // Workbench is always filtered
}
scopeString = getScopeString(req);
if (scopeString != null) {
StringTokenizer tokenizer = new StringTokenizer(scopeString, "/"); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
String nextScope = tokenizer.nextToken().trim();
AbstractHelpScope scope = ScopeRegistry.getInstance().getScope(nextScope);
if (scope != null) {
scopes.add(scope);
}
}
}
// Add filter by search scope if not called from Help View
boolean isHelpViewTopic = "/ntopic".equals(req.getServletPath()); //$NON-NLS-1$
if (!isSearchFilter && !isHelpViewTopic) {
// Try for a working set
try {
WebappWorkingSetManager manager = new WebappWorkingSetManager(req,
resp, UrlUtil.getLocale(req, resp));
String wset = manager.getCurrentWorkingSet();
if (wset != null && wset.length() > 0) {
WorkingSetScope workingSetScope = new WorkingSetScope(wset,
manager, HelpBaseResources.SearchScopeFilterName);
scopes.add(workingSetScope);
}
} catch (Exception e) {
}
}
scopeArray = (AbstractHelpScope[]) scopes.toArray(new AbstractHelpScope[scopes.size()]);
return scopeArray;
}
|
diff --git a/portalobjects/binding/src/main/java/org/gatein/management/portalobjects/binding/impl/site/PortalDataMarshaller.java b/portalobjects/binding/src/main/java/org/gatein/management/portalobjects/binding/impl/site/PortalDataMarshaller.java
index 1e31451..4ff14a9 100644
--- a/portalobjects/binding/src/main/java/org/gatein/management/portalobjects/binding/impl/site/PortalDataMarshaller.java
+++ b/portalobjects/binding/src/main/java/org/gatein/management/portalobjects/binding/impl/site/PortalDataMarshaller.java
@@ -1,302 +1,302 @@
/*
* JBoss, a division of Red Hat
* Copyright 2011, Red Hat Middleware, LLC, and individual
* contributors as indicated by the @authors tag. See the
* copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.gatein.management.portalobjects.binding.impl.site;
import org.exoplatform.portal.pom.data.BodyData;
import org.exoplatform.portal.pom.data.BodyType;
import org.exoplatform.portal.pom.data.ComponentData;
import org.exoplatform.portal.pom.data.ContainerData;
import org.exoplatform.portal.pom.data.PortalData;
import org.gatein.management.binding.api.BindingException;
import org.gatein.management.binding.api.Bindings;
import org.gatein.management.portalobjects.binding.impl.AbstractPomDataMarshaller;
import org.gatein.staxbuilder.reader.StaxReader;
import org.gatein.staxbuilder.reader.StaxReaderBuilder;
import org.gatein.staxbuilder.writer.StaxWriter;
import org.gatein.staxbuilder.writer.StaxWriterBuilder;
import javax.xml.stream.XMLStreamException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
* @version $Revision$
*/
@Bindings(classes = PortalData.class)
public class PortalDataMarshaller extends AbstractPomDataMarshaller<PortalData>
{
@Override
public void marshal(PortalData object, OutputStream outputStream) throws BindingException
{
try
{
StaxWriter writer = new StaxWriterBuilder().withOutputStream(outputStream).withEncoding("UTF-8").withDefaultFormatting().build();
writer.writeStartDocument();
// root element
writer.writeStartElement(Element.PORTAL_CONFIG);
writeGateinObjectsRootElement(writer);
marshalPortalData(writer, object);
writer.writeEndElement().writeEndDocument(); // End of portal-config, end document
}
catch (XMLStreamException e)
{
throw new BindingException(e);
}
}
@Override
public void marshalObjects(Collection<PortalData> objects, OutputStream outputStream) throws BindingException
{
try
{
StaxWriter writer = new StaxWriterBuilder().withOutputStream(outputStream).
withEncoding("UTF-8").withDefaultFormatting().build();
// gatein_objects format does not allow multiple portal config elements, but we can still support the marshalling and unmarshalling of such
writer.writeStartDocument().writeStartElement("portal-configs");
for (PortalData data : objects)
{
writer.writeStartElement(Element.PORTAL_CONFIG);
marshalPortalData(writer, data);
writer.writeEndElement(); // End of portal-config
}
writer.writeEndElement().writeEndDocument();
}
catch (XMLStreamException e)
{
throw new BindingException(e);
}
}
@Override
public PortalData unmarshal(InputStream is) throws BindingException
{
try
{
StaxReader reader = new StaxReaderBuilder().withInputStream(is).build();
if (reader.readNextTag().getLocalName().equals(Element.PORTAL_CONFIG.getLocalName()))
{
return unmarshalPortalData(reader);
}
else
{
throw new XMLStreamException("Unknown root element.", reader.currentReadEvent().getLocation());
}
}
catch (XMLStreamException e)
{
throw new BindingException(e);
}
}
@Override
public Collection<PortalData> unmarshalObjects(InputStream is) throws BindingException
{
try
{
StaxReader reader = new StaxReaderBuilder().withInputStream(is).build();
if (reader.readNextTag().getLocalName().equals(Element.PORTAL_CONFIGS.getLocalName()))
{
Collection<PortalData> data = new ArrayList<PortalData>();
while (reader.hasNext())
{
switch (reader.read().match().onElement(Element.class, Element.UNKNOWN, Element.SKIP))
{
case PORTAL_CONFIG:
data.add(unmarshalPortalData(reader));
break;
case UNKNOWN:
throw new XMLStreamException("Uknown element '" + reader.currentReadEvent().getLocalName() +
"' while unmarshalling multiple portal data's.", reader.currentReadEvent().getLocation());
case SKIP:
break;
default:
break;
}
}
return data;
}
else
{
throw new XMLStreamException("Unknown root element.", reader.currentReadEvent().getLocation());
}
}
catch (XMLStreamException e)
{
throw new BindingException(e);
}
}
private void marshalPortalData(StaxWriter writer, PortalData portalData) throws XMLStreamException
{
writer.writeElement(Element.PORTAL_NAME, portalData.getName());
writer.writeOptionalElement(Element.LOCALE, portalData.getLocale());
// Access permissions
marshalAccessPermissions(writer, portalData.getAccessPermissions());
// Edit permission
marshalEditPermission(writer, portalData.getEditPermission());
writer.writeOptionalElement(Element.SKIN, portalData.getSkin());
boolean propertiesWritten = false;
Map<String,String> properties = portalData.getProperties();
if (properties != null)
{
for (String key : properties.keySet())
{
if (!propertiesWritten)
{
writer.writeStartElement(Element.PROPERTIES);
propertiesWritten = true;
}
String value = properties.get(key);
if (value != null)
{
writer.writeStartElement(Element.PROPERTIES_ENTRY).
writeAttribute(Attribute.PROPERTIES_KEY, key).writeCharacters(value).writeEndElement();
}
}
if (propertiesWritten)
{
writer.writeEndElement();
}
}
ContainerData container = portalData.getPortalLayout();
if (container != null)
{
writer.writeStartElement(Element.PORTAL_LAYOUT);
List<ComponentData> children = container.getChildren();
if (children != null && !children.isEmpty())
{
for (ComponentData child : children)
{
marshalComponentData(writer, child);
}
}
writer.writeEndElement();
}
}
private PortalData unmarshalPortalData(StaxReader reader) throws XMLStreamException
{
String portalName = null;
String locale = null;
List<String> accessPermissions = Collections.emptyList();
String editPermission = null;
String skin = null;
- Map<String,String> properties = null;
+ Map<String,String> properties = Collections.emptyMap();
ContainerData portalLayout = null;
List<ComponentData> components = null;
reader.buildReadEvent().withNestedRead().untilElement(Element.PORTAL_CONFIG).end();
while (reader.hasNext())
{
switch (reader.read().match().onElement(Element.class, Element.UNKNOWN, Element.SKIP))
{
case PORTAL_NAME:
portalName = reader.currentReadEvent().elementText();
break;
case LOCALE:
locale = reader.currentReadEvent().elementText();
break;
case SKIN:
skin = reader.currentReadEvent().elementText();
break;
case PROPERTIES:
properties = new HashMap<String,String>();
break;
case PORTAL_LAYOUT:
components = new ArrayList<ComponentData>();
break;
case PAGE_BODY:
if (components == null)
{
throw new XMLStreamException("Unexpected " + Element.PAGE_BODY.getLocalName() +" without parent " + Element.PORTAL_LAYOUT.getLocalName());
}
components.add(new BodyData(null, BodyType.PAGE));
break;
case PROPERTIES_ENTRY:
int count = reader.currentReadEvent().getAttributeCount();
if (count == 0)
{
throw new XMLStreamException("No attribute for properties entry element.", reader.currentReadEvent().getLocation());
}
for (int i=0; i<count; i++)
{
String name = reader.currentReadEvent().getAttributeLocalName(i);
if (Attribute.PROPERTIES_KEY.getLocalName().equals(name))
{
String value = reader.currentReadEvent().getAttributeValue(i);
properties.put(name, value);
}
}
break;
case SKIP:
break;
case UNKNOWN:
if (isAccessPermissions(reader))
{
accessPermissions = unmarshalAccessPermissions(reader);
}
else if (isEditPermission(reader))
{
editPermission = unmarshalEditPermission(reader);
}
else if (isPortletApplication(reader))
{
if (components == null)
{
throw new XMLStreamException("Unexpected portlet application without parent " + Element.PORTAL_LAYOUT.getLocalName());
}
components.add(unmarshalPortletApplication(reader));
}
else
{
throw new XMLStreamException("Unknown element '" + reader.currentReadEvent().getLocalName() + " while unmarshalling portal data.");
}
break;
default:
break;
}
}
portalLayout = new ContainerData(null, null, null, null, null, null, null, null, null, null, Collections.<String>emptyList(), components);
return new PortalData(null, portalName, "", locale, accessPermissions, editPermission, properties, skin, portalLayout);
}
}
| true | true | private PortalData unmarshalPortalData(StaxReader reader) throws XMLStreamException
{
String portalName = null;
String locale = null;
List<String> accessPermissions = Collections.emptyList();
String editPermission = null;
String skin = null;
Map<String,String> properties = null;
ContainerData portalLayout = null;
List<ComponentData> components = null;
reader.buildReadEvent().withNestedRead().untilElement(Element.PORTAL_CONFIG).end();
while (reader.hasNext())
{
switch (reader.read().match().onElement(Element.class, Element.UNKNOWN, Element.SKIP))
{
case PORTAL_NAME:
portalName = reader.currentReadEvent().elementText();
break;
case LOCALE:
locale = reader.currentReadEvent().elementText();
break;
case SKIN:
skin = reader.currentReadEvent().elementText();
break;
case PROPERTIES:
properties = new HashMap<String,String>();
break;
case PORTAL_LAYOUT:
components = new ArrayList<ComponentData>();
break;
case PAGE_BODY:
if (components == null)
{
throw new XMLStreamException("Unexpected " + Element.PAGE_BODY.getLocalName() +" without parent " + Element.PORTAL_LAYOUT.getLocalName());
}
components.add(new BodyData(null, BodyType.PAGE));
break;
case PROPERTIES_ENTRY:
int count = reader.currentReadEvent().getAttributeCount();
if (count == 0)
{
throw new XMLStreamException("No attribute for properties entry element.", reader.currentReadEvent().getLocation());
}
for (int i=0; i<count; i++)
{
String name = reader.currentReadEvent().getAttributeLocalName(i);
if (Attribute.PROPERTIES_KEY.getLocalName().equals(name))
{
String value = reader.currentReadEvent().getAttributeValue(i);
properties.put(name, value);
}
}
break;
case SKIP:
break;
case UNKNOWN:
if (isAccessPermissions(reader))
{
accessPermissions = unmarshalAccessPermissions(reader);
}
else if (isEditPermission(reader))
{
editPermission = unmarshalEditPermission(reader);
}
else if (isPortletApplication(reader))
{
if (components == null)
{
throw new XMLStreamException("Unexpected portlet application without parent " + Element.PORTAL_LAYOUT.getLocalName());
}
components.add(unmarshalPortletApplication(reader));
}
else
{
throw new XMLStreamException("Unknown element '" + reader.currentReadEvent().getLocalName() + " while unmarshalling portal data.");
}
break;
default:
break;
}
}
portalLayout = new ContainerData(null, null, null, null, null, null, null, null, null, null, Collections.<String>emptyList(), components);
return new PortalData(null, portalName, "", locale, accessPermissions, editPermission, properties, skin, portalLayout);
}
| private PortalData unmarshalPortalData(StaxReader reader) throws XMLStreamException
{
String portalName = null;
String locale = null;
List<String> accessPermissions = Collections.emptyList();
String editPermission = null;
String skin = null;
Map<String,String> properties = Collections.emptyMap();
ContainerData portalLayout = null;
List<ComponentData> components = null;
reader.buildReadEvent().withNestedRead().untilElement(Element.PORTAL_CONFIG).end();
while (reader.hasNext())
{
switch (reader.read().match().onElement(Element.class, Element.UNKNOWN, Element.SKIP))
{
case PORTAL_NAME:
portalName = reader.currentReadEvent().elementText();
break;
case LOCALE:
locale = reader.currentReadEvent().elementText();
break;
case SKIN:
skin = reader.currentReadEvent().elementText();
break;
case PROPERTIES:
properties = new HashMap<String,String>();
break;
case PORTAL_LAYOUT:
components = new ArrayList<ComponentData>();
break;
case PAGE_BODY:
if (components == null)
{
throw new XMLStreamException("Unexpected " + Element.PAGE_BODY.getLocalName() +" without parent " + Element.PORTAL_LAYOUT.getLocalName());
}
components.add(new BodyData(null, BodyType.PAGE));
break;
case PROPERTIES_ENTRY:
int count = reader.currentReadEvent().getAttributeCount();
if (count == 0)
{
throw new XMLStreamException("No attribute for properties entry element.", reader.currentReadEvent().getLocation());
}
for (int i=0; i<count; i++)
{
String name = reader.currentReadEvent().getAttributeLocalName(i);
if (Attribute.PROPERTIES_KEY.getLocalName().equals(name))
{
String value = reader.currentReadEvent().getAttributeValue(i);
properties.put(name, value);
}
}
break;
case SKIP:
break;
case UNKNOWN:
if (isAccessPermissions(reader))
{
accessPermissions = unmarshalAccessPermissions(reader);
}
else if (isEditPermission(reader))
{
editPermission = unmarshalEditPermission(reader);
}
else if (isPortletApplication(reader))
{
if (components == null)
{
throw new XMLStreamException("Unexpected portlet application without parent " + Element.PORTAL_LAYOUT.getLocalName());
}
components.add(unmarshalPortletApplication(reader));
}
else
{
throw new XMLStreamException("Unknown element '" + reader.currentReadEvent().getLocalName() + " while unmarshalling portal data.");
}
break;
default:
break;
}
}
portalLayout = new ContainerData(null, null, null, null, null, null, null, null, null, null, Collections.<String>emptyList(), components);
return new PortalData(null, portalName, "", locale, accessPermissions, editPermission, properties, skin, portalLayout);
}
|
diff --git a/src/main/java/de/cismet/belis/server/search/BelisSearchStatement.java b/src/main/java/de/cismet/belis/server/search/BelisSearchStatement.java
index d00f5ca..58431d9 100644
--- a/src/main/java/de/cismet/belis/server/search/BelisSearchStatement.java
+++ b/src/main/java/de/cismet/belis/server/search/BelisSearchStatement.java
@@ -1,299 +1,300 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.belis.server.search;
import Sirius.server.middleware.interfaces.domainserver.MetaService;
import Sirius.server.middleware.types.MetaObjectNode;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Polygon;
import org.apache.log4j.Logger;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import de.cismet.cids.server.search.AbstractCidsServerSearch;
import de.cismet.cids.server.search.MetaObjectNodeServerSearch;
import de.cismet.cismap.commons.jtsgeometryfactories.PostGisGeometryFactory;
/**
* DOCUMENT ME!
*
* @author mroncoroni
* @version $Revision$, $Date$
*/
public class BelisSearchStatement extends AbstractCidsServerSearch implements MetaObjectNodeServerSearch {
//~ Static fields/initializers ---------------------------------------------
/** LOGGER. */
private static final transient Logger LOG = Logger.getLogger(BelisSearchStatement.class);
//~ Instance fields --------------------------------------------------------
private final boolean standort;
private final boolean schaltstelle;
private final boolean mauerlasche;
private final boolean leitung;
private final boolean abzweigdose;
private final boolean leuchte;
private Geometry geometry;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new BelisSearchStatement object.
*/
public BelisSearchStatement() {
this(true, false, true, true, true, true);
}
/**
* Creates a new BelisSearchStatement object.
*
* @param standort DOCUMENT ME!
* @param leuchte DOCUMENT ME!
* @param schaltstelle DOCUMENT ME!
* @param mauerlasche DOCUMENT ME!
* @param leitung DOCUMENT ME!
* @param abzweigdose DOCUMENT ME!
*/
public BelisSearchStatement(
final boolean standort,
final boolean leuchte,
final boolean schaltstelle,
final boolean mauerlasche,
final boolean leitung,
final boolean abzweigdose) {
this.standort = standort;
this.leuchte = leuchte;
this.schaltstelle = schaltstelle;
this.mauerlasche = mauerlasche;
this.leitung = leitung;
this.abzweigdose = abzweigdose;
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Geometry getGeometry() {
return geometry;
}
/**
* DOCUMENT ME!
*
* @param geometry DOCUMENT ME!
*/
public void setGeometry(final Geometry geometry) {
this.geometry = geometry;
}
@Override
public Collection<MetaObjectNode> performServerSearch() {
try {
if (!standort && !leuchte && !schaltstelle && !mauerlasche && !leitung && !abzweigdose) {
return new ArrayList<MetaObjectNode>();
}
final ArrayList<String> union = new ArrayList<String>();
final ArrayList<String> join = new ArrayList<String>();
if (standort) {
union.add(
"SELECT 29 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Standort'::text AS searchIntoClass FROM tdta_standort_mast");
// join.add("");
}
if (leuchte) {
union.add(
"SELECT 29 AS classid, tdta_standort_mast.id AS objectid, tdta_leuchten.id AS searchIntoId, tdta_standort_mast.fk_geom AS fk_geom, 'Leuchte'::text AS searchIntoClass FROM tdta_leuchten LEFT JOIN tdta_standort_mast ON tdta_leuchten.fk_standort = tdta_standort_mast.id");
// join.add("");
}
if (schaltstelle) {
union.add(
"SELECT 15 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Schaltstelle'::text AS searchIntoClass FROM schaltstelle");
}
if (mauerlasche) {
union.add(
"SELECT 14 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Mauerlasche'::text AS searchIntoClass FROM mauerlasche");
}
if (leitung) {
union.add(
"SELECT 11 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Leitung'::text AS searchIntoClass FROM leitung");
}
if (abzweigdose) {
union.add(
"SELECT 5 AS classid, id AS objectid, fk_geom, 'Abzweigdose'::text AS searchIntoClass FROM abzweigdose");
}
final String implodedUnion = implodeArray(union.toArray(new String[0]), " UNION ");
final String implodedJoin = implodeArray(join.toArray(new String[0]), " LEFT JOIN ");
String query = "SELECT DISTINCT classid, objectid"
+ " FROM (" + implodedUnion + ") AS geom_objects"
+ " LEFT JOIN tdta_standort_mast ON geom_objects.searchIntoClass = 'Standort' AND tdta_standort_mast.id = geom_objects.searchIntoId"
+ " LEFT JOIN tdta_leuchten ON geom_objects.searchIntoClass = 'Leuchte' AND tdta_leuchten.id = geom_objects.searchIntoId"
+ " LEFT JOIN schaltstelle ON geom_objects.searchIntoClass = 'Schaltstelle' AND schaltstelle.id = geom_objects.searchIntoId"
+ " LEFT JOIN mauerlasche ON geom_objects.searchIntoClass = 'Mauerlasche' AND mauerlasche.id = geom_objects.searchIntoId"
+ " LEFT JOIN leitung ON geom_objects.searchIntoClass = 'Leitung' AND leitung.id = geom_objects.searchIntoId"
+ " LEFT JOIN abzweigdose ON geom_objects.searchIntoClass = 'Abzweigdose' AND abzweigdose.id = geom_objects.searchIntoId"
+ ", geom"
+ " WHERE geom.id = geom_objects.fk_geom"
+ " AND"
+ " (tdta_standort_mast.id IS NOT null"
+ " OR tdta_leuchten.id IS NOT null"
+ " OR schaltstelle.id IS NOT null"
+ " OR mauerlasche.id IS NOT null"
+ " OR leitung.id IS NOT null"
+ " OR abzweigdose.id IS NOT null"
+ " )";
if (geometry != null) {
final String geostring = PostGisGeometryFactory.getPostGisCompliantDbString(geometry);
if ((geometry instanceof Polygon) || (geometry instanceof MultiPolygon)) {
query += " AND geo_field &&\n"
+ "st_buffer(\n"
+ "GeometryFromText('" + geostring + "')\n"
+ ", 0.000001)\n"
+ "and intersects(geo_field,st_buffer(GeometryFromText('" + geostring
+ "'), 0.000001))";
} else {
query += " AND geo_field &&\n"
+ "st_buffer(\n"
+ "GeometryFromText('" + geostring + "')\n"
+ ", 0.000001)\n"
+ "and intersects(geo_field, GeometryFromText('" + geostring + "'))";
}
}
final String andQueryPart = getAndQueryPart();
if ((andQueryPart != null) && !andQueryPart.trim().isEmpty()) {
query += " AND " + andQueryPart;
}
final List<MetaObjectNode> result = new ArrayList<MetaObjectNode>();
final MetaService ms = (MetaService)getActiveLocalServers().get("BELIS");
- final ArrayList<ArrayList> searchResult = ms.performCustomSearch(query);LOG.fatal(query);
+ final ArrayList<ArrayList> searchResult = ms.performCustomSearch(query);
+ LOG.fatal(query);
for (final ArrayList al : searchResult) {
final int cid = (Integer)al.get(0);
final int oid = (Integer)al.get(1);
- final MetaObjectNode mon = new MetaObjectNode("BELIS", oid, cid, "");
+ final MetaObjectNode mon = new MetaObjectNode("BELIS", oid, cid, null);
result.add(mon);
}
return result;
} catch (RemoteException ex) {
LOG.error("Problem", ex);
throw new RuntimeException(ex);
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected String getAndQueryPart() {
return null;
}
/**
* DOCUMENT ME!
*
* @param field DOCUMENT ME!
* @param id DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static String generateIdQuery(final String field, final Integer id) {
final String query;
if (id != null) {
query = field + " = " + id + "";
} else {
query = "TRUE";
}
return query;
}
/**
* DOCUMENT ME!
*
* @param field DOCUMENT ME!
* @param like DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static String generateLikeQuery(final String field, final String like) {
final String query;
if (like != null) {
query = field + " like '%" + like + "%'";
} else {
query = "TRUE";
}
return query;
}
/**
* DOCUMENT ME!
*
* @param field DOCUMENT ME!
* @param von DOCUMENT ME!
* @param bis DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static String generateVonBisQuery(final String field, final String von, final String bis) {
final String query;
if (von != null) {
if (bis != null) {
query = field + " BETWEEN '" + von + "' AND '" + bis + "'";
} else {
query = field + " >= '" + von + "'";
}
} else if (bis != null) {
query = field + " <= '" + bis + "'";
} else {
query = "TRUE";
}
return query;
}
/**
* DOCUMENT ME!
*
* @param inputArray DOCUMENT ME!
* @param glueString DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static String implodeArray(final String[] inputArray, final String glueString) {
String output = "";
if (inputArray.length > 0) {
final StringBuilder sb = new StringBuilder();
sb.append(inputArray[0]);
for (int i = 1; i < inputArray.length; i++) {
sb.append(glueString);
sb.append(inputArray[i]);
}
output = sb.toString();
}
return output;
}
}
| false | true | public Collection<MetaObjectNode> performServerSearch() {
try {
if (!standort && !leuchte && !schaltstelle && !mauerlasche && !leitung && !abzweigdose) {
return new ArrayList<MetaObjectNode>();
}
final ArrayList<String> union = new ArrayList<String>();
final ArrayList<String> join = new ArrayList<String>();
if (standort) {
union.add(
"SELECT 29 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Standort'::text AS searchIntoClass FROM tdta_standort_mast");
// join.add("");
}
if (leuchte) {
union.add(
"SELECT 29 AS classid, tdta_standort_mast.id AS objectid, tdta_leuchten.id AS searchIntoId, tdta_standort_mast.fk_geom AS fk_geom, 'Leuchte'::text AS searchIntoClass FROM tdta_leuchten LEFT JOIN tdta_standort_mast ON tdta_leuchten.fk_standort = tdta_standort_mast.id");
// join.add("");
}
if (schaltstelle) {
union.add(
"SELECT 15 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Schaltstelle'::text AS searchIntoClass FROM schaltstelle");
}
if (mauerlasche) {
union.add(
"SELECT 14 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Mauerlasche'::text AS searchIntoClass FROM mauerlasche");
}
if (leitung) {
union.add(
"SELECT 11 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Leitung'::text AS searchIntoClass FROM leitung");
}
if (abzweigdose) {
union.add(
"SELECT 5 AS classid, id AS objectid, fk_geom, 'Abzweigdose'::text AS searchIntoClass FROM abzweigdose");
}
final String implodedUnion = implodeArray(union.toArray(new String[0]), " UNION ");
final String implodedJoin = implodeArray(join.toArray(new String[0]), " LEFT JOIN ");
String query = "SELECT DISTINCT classid, objectid"
+ " FROM (" + implodedUnion + ") AS geom_objects"
+ " LEFT JOIN tdta_standort_mast ON geom_objects.searchIntoClass = 'Standort' AND tdta_standort_mast.id = geom_objects.searchIntoId"
+ " LEFT JOIN tdta_leuchten ON geom_objects.searchIntoClass = 'Leuchte' AND tdta_leuchten.id = geom_objects.searchIntoId"
+ " LEFT JOIN schaltstelle ON geom_objects.searchIntoClass = 'Schaltstelle' AND schaltstelle.id = geom_objects.searchIntoId"
+ " LEFT JOIN mauerlasche ON geom_objects.searchIntoClass = 'Mauerlasche' AND mauerlasche.id = geom_objects.searchIntoId"
+ " LEFT JOIN leitung ON geom_objects.searchIntoClass = 'Leitung' AND leitung.id = geom_objects.searchIntoId"
+ " LEFT JOIN abzweigdose ON geom_objects.searchIntoClass = 'Abzweigdose' AND abzweigdose.id = geom_objects.searchIntoId"
+ ", geom"
+ " WHERE geom.id = geom_objects.fk_geom"
+ " AND"
+ " (tdta_standort_mast.id IS NOT null"
+ " OR tdta_leuchten.id IS NOT null"
+ " OR schaltstelle.id IS NOT null"
+ " OR mauerlasche.id IS NOT null"
+ " OR leitung.id IS NOT null"
+ " OR abzweigdose.id IS NOT null"
+ " )";
if (geometry != null) {
final String geostring = PostGisGeometryFactory.getPostGisCompliantDbString(geometry);
if ((geometry instanceof Polygon) || (geometry instanceof MultiPolygon)) {
query += " AND geo_field &&\n"
+ "st_buffer(\n"
+ "GeometryFromText('" + geostring + "')\n"
+ ", 0.000001)\n"
+ "and intersects(geo_field,st_buffer(GeometryFromText('" + geostring
+ "'), 0.000001))";
} else {
query += " AND geo_field &&\n"
+ "st_buffer(\n"
+ "GeometryFromText('" + geostring + "')\n"
+ ", 0.000001)\n"
+ "and intersects(geo_field, GeometryFromText('" + geostring + "'))";
}
}
final String andQueryPart = getAndQueryPart();
if ((andQueryPart != null) && !andQueryPart.trim().isEmpty()) {
query += " AND " + andQueryPart;
}
final List<MetaObjectNode> result = new ArrayList<MetaObjectNode>();
final MetaService ms = (MetaService)getActiveLocalServers().get("BELIS");
final ArrayList<ArrayList> searchResult = ms.performCustomSearch(query);LOG.fatal(query);
for (final ArrayList al : searchResult) {
final int cid = (Integer)al.get(0);
final int oid = (Integer)al.get(1);
final MetaObjectNode mon = new MetaObjectNode("BELIS", oid, cid, "");
result.add(mon);
}
return result;
} catch (RemoteException ex) {
LOG.error("Problem", ex);
throw new RuntimeException(ex);
}
}
| public Collection<MetaObjectNode> performServerSearch() {
try {
if (!standort && !leuchte && !schaltstelle && !mauerlasche && !leitung && !abzweigdose) {
return new ArrayList<MetaObjectNode>();
}
final ArrayList<String> union = new ArrayList<String>();
final ArrayList<String> join = new ArrayList<String>();
if (standort) {
union.add(
"SELECT 29 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Standort'::text AS searchIntoClass FROM tdta_standort_mast");
// join.add("");
}
if (leuchte) {
union.add(
"SELECT 29 AS classid, tdta_standort_mast.id AS objectid, tdta_leuchten.id AS searchIntoId, tdta_standort_mast.fk_geom AS fk_geom, 'Leuchte'::text AS searchIntoClass FROM tdta_leuchten LEFT JOIN tdta_standort_mast ON tdta_leuchten.fk_standort = tdta_standort_mast.id");
// join.add("");
}
if (schaltstelle) {
union.add(
"SELECT 15 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Schaltstelle'::text AS searchIntoClass FROM schaltstelle");
}
if (mauerlasche) {
union.add(
"SELECT 14 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Mauerlasche'::text AS searchIntoClass FROM mauerlasche");
}
if (leitung) {
union.add(
"SELECT 11 AS classid, id AS objectid, id AS searchIntoId, fk_geom, 'Leitung'::text AS searchIntoClass FROM leitung");
}
if (abzweigdose) {
union.add(
"SELECT 5 AS classid, id AS objectid, fk_geom, 'Abzweigdose'::text AS searchIntoClass FROM abzweigdose");
}
final String implodedUnion = implodeArray(union.toArray(new String[0]), " UNION ");
final String implodedJoin = implodeArray(join.toArray(new String[0]), " LEFT JOIN ");
String query = "SELECT DISTINCT classid, objectid"
+ " FROM (" + implodedUnion + ") AS geom_objects"
+ " LEFT JOIN tdta_standort_mast ON geom_objects.searchIntoClass = 'Standort' AND tdta_standort_mast.id = geom_objects.searchIntoId"
+ " LEFT JOIN tdta_leuchten ON geom_objects.searchIntoClass = 'Leuchte' AND tdta_leuchten.id = geom_objects.searchIntoId"
+ " LEFT JOIN schaltstelle ON geom_objects.searchIntoClass = 'Schaltstelle' AND schaltstelle.id = geom_objects.searchIntoId"
+ " LEFT JOIN mauerlasche ON geom_objects.searchIntoClass = 'Mauerlasche' AND mauerlasche.id = geom_objects.searchIntoId"
+ " LEFT JOIN leitung ON geom_objects.searchIntoClass = 'Leitung' AND leitung.id = geom_objects.searchIntoId"
+ " LEFT JOIN abzweigdose ON geom_objects.searchIntoClass = 'Abzweigdose' AND abzweigdose.id = geom_objects.searchIntoId"
+ ", geom"
+ " WHERE geom.id = geom_objects.fk_geom"
+ " AND"
+ " (tdta_standort_mast.id IS NOT null"
+ " OR tdta_leuchten.id IS NOT null"
+ " OR schaltstelle.id IS NOT null"
+ " OR mauerlasche.id IS NOT null"
+ " OR leitung.id IS NOT null"
+ " OR abzweigdose.id IS NOT null"
+ " )";
if (geometry != null) {
final String geostring = PostGisGeometryFactory.getPostGisCompliantDbString(geometry);
if ((geometry instanceof Polygon) || (geometry instanceof MultiPolygon)) {
query += " AND geo_field &&\n"
+ "st_buffer(\n"
+ "GeometryFromText('" + geostring + "')\n"
+ ", 0.000001)\n"
+ "and intersects(geo_field,st_buffer(GeometryFromText('" + geostring
+ "'), 0.000001))";
} else {
query += " AND geo_field &&\n"
+ "st_buffer(\n"
+ "GeometryFromText('" + geostring + "')\n"
+ ", 0.000001)\n"
+ "and intersects(geo_field, GeometryFromText('" + geostring + "'))";
}
}
final String andQueryPart = getAndQueryPart();
if ((andQueryPart != null) && !andQueryPart.trim().isEmpty()) {
query += " AND " + andQueryPart;
}
final List<MetaObjectNode> result = new ArrayList<MetaObjectNode>();
final MetaService ms = (MetaService)getActiveLocalServers().get("BELIS");
final ArrayList<ArrayList> searchResult = ms.performCustomSearch(query);
LOG.fatal(query);
for (final ArrayList al : searchResult) {
final int cid = (Integer)al.get(0);
final int oid = (Integer)al.get(1);
final MetaObjectNode mon = new MetaObjectNode("BELIS", oid, cid, null);
result.add(mon);
}
return result;
} catch (RemoteException ex) {
LOG.error("Problem", ex);
throw new RuntimeException(ex);
}
}
|
diff --git a/core/src/java/liquibase/database/MySQLDatabase.java b/core/src/java/liquibase/database/MySQLDatabase.java
index f236c663..fdc2568a 100644
--- a/core/src/java/liquibase/database/MySQLDatabase.java
+++ b/core/src/java/liquibase/database/MySQLDatabase.java
@@ -1,143 +1,143 @@
package liquibase.database;
import liquibase.database.sql.RawSqlStatement;
import liquibase.database.sql.SqlStatement;
import liquibase.exception.JDBCException;
import java.sql.Connection;
/**
* Encapsulates MySQL database support.
*/
public class MySQLDatabase extends AbstractDatabase {
public static final String PRODUCT_NAME = "MySQL";
public String getProductName() {
return "MySQL";
}
public String getTypeName() {
return "mysql";
}
public String getConnectionUsername() throws JDBCException {
return super.getConnectionUsername().replaceAll("\\@.*", "");
}
public boolean isCorrectDatabaseImplementation(Connection conn) throws JDBCException {
return PRODUCT_NAME.equalsIgnoreCase(getDatabaseProductName(conn));
}
public String getDefaultDriver(String url) {
if (url.startsWith("jdbc:mysql")) {
return "com.mysql.jdbc.Driver";
}
return null;
}
public String getBooleanType() {
return "TINYINT(1)";
}
public String getCurrencyType() {
return "DECIMAL";
}
public String getUUIDType() {
return "CHAR(36)";
}
public String getClobType() {
return "TEXT";
}
public String getBlobType() {
return "BLOB";
}
public String getDateTimeType() {
return "DATETIME";
}
public boolean supportsSequences() {
return false;
}
public boolean supportsInitiallyDeferrableColumns() {
return false;
}
public String getCurrentDateTimeFunction() {
return "NOW()";
}
public String getLineComment() {
return "--";
}
public String getFalseBooleanValue() {
return "0";
}
public String getTrueBooleanValue() {
return "1";
}
public String getConcatSql(String ... values) {
StringBuffer returnString = new StringBuffer();
returnString.append("CONCAT_WS(");
for (String value : values) {
returnString.append(value).append(", ");
}
return returnString.toString().replaceFirst(", $", ")");
}
public boolean supportsTablespaces() {
return false;
}
protected String getDefaultDatabaseSchemaName() throws JDBCException {
return super.getDefaultDatabaseSchemaName().replaceFirst("\\@.*","");
}
public String convertRequestedSchemaToSchema(String requestedSchema) throws JDBCException {
if (requestedSchema == null) {
return getDefaultDatabaseSchemaName();
}
return requestedSchema;
}
public String convertRequestedSchemaToCatalog(String requestedSchema) throws JDBCException {
return requestedSchema;
}
public SqlStatement getViewDefinitionSql(String schemaName, String viewName) throws JDBCException {
return new RawSqlStatement("select view_definition from information_schema.views where table_name='" + viewName + "' AND table_schema='" + schemaName + "'");
}
public String escapeTableName(String schemaName, String tableName) {
if(schemaName != null) {
return "`" + schemaName + "`.`" + tableName + "`";
}
return "`" + tableName + "`";
}
public String escapeColumnName(String columnName) {
return "`" + columnName + "`";
}
public String escapeColumnNameList(String columnNames) {
StringBuffer sb = new StringBuffer();
- for(String columnName : columnNames.split(", ")) {
+ for(String columnName : columnNames.split(",")) {
if(sb.length() > 0) {
sb.append(", ");
}
- sb.append("`").append(columnName).append("`");
+ sb.append("`").append(columnName.trim()).append("`");
}
return sb.toString();
}
}
| false | true | public String escapeColumnNameList(String columnNames) {
StringBuffer sb = new StringBuffer();
for(String columnName : columnNames.split(", ")) {
if(sb.length() > 0) {
sb.append(", ");
}
sb.append("`").append(columnName).append("`");
}
return sb.toString();
}
| public String escapeColumnNameList(String columnNames) {
StringBuffer sb = new StringBuffer();
for(String columnName : columnNames.split(",")) {
if(sb.length() > 0) {
sb.append(", ");
}
sb.append("`").append(columnName.trim()).append("`");
}
return sb.toString();
}
|
diff --git a/src/edu/nccu/floodfire/controller/QueryTweetScheduleController.java b/src/edu/nccu/floodfire/controller/QueryTweetScheduleController.java
index 98c0493..91cc3d5 100644
--- a/src/edu/nccu/floodfire/controller/QueryTweetScheduleController.java
+++ b/src/edu/nccu/floodfire/controller/QueryTweetScheduleController.java
@@ -1,277 +1,277 @@
package edu.nccu.floodfire.controller;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import edu.nccu.floodfire.batch.TwitterJob;
import edu.nccu.floodfire.constants.SystemConstants;
import edu.nccu.floodfire.entity.Event;
import edu.nccu.floodfire.entity.Job;
import edu.nccu.floodfire.service.ManagementService;
import edu.nccu.floodfire.util.DateUtil;
import edu.nccu.floodfire.util.JobseqUtil;
import edu.nccu.floodfire.util.TwitterConfiguration;
public class QueryTweetScheduleController implements Controller {
private String viewPage;
/**
* 1.使用者設定好Job資訊後,送出後會到此controller
* 2.此controller會啟動一隻scheduler Job,參看TwitterJob.java
* 3.TwitterJob.java需要tokenId當參數,2013/8/4修改規格為系統任取一個token
* 4.系統會回傳此job的jobSeq和還剩下多少token可以使用回畫面
*/
@SuppressWarnings({ "rawtypes"})
public ModelAndView handleRequest(HttpServletRequest req,
HttpServletResponse res) throws Exception {
req.setCharacterEncoding("UTF-8");
ApplicationContext applicationContext =WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
ManagementService managementService = (ManagementService)applicationContext.getBean("managementService");
String queryType = req.getParameter("queryType");
String queryFunc = req.getParameter("queryFunc");
String addJobEventName = req.getParameter("addJobEventName");
Event event = new Event();
event.setEventName(addJobEventName);
String user = (String)req.getSession().getAttribute("user");
String thisDate = DateUtil.getCurrentYYYYMMDD();
String jobSeq = "";
String keyword = "";
if("search".equals(queryType))
{
if("byKeyword".equals(queryFunc))
{
keyword = req.getParameter("keyword");
jobSeq = thisDate + "?" + "queryType" + "=" + queryType +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setSearchJobseq(jobSeq);
Scheduler scheduler = createScheduler(jobSeq);
createSearchJob(jobSeq,queryType,queryFunc,keyword, managementService, applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq,user,queryType,queryFunc,event,keyword,managementService);
}
}
else if("stream".equals(queryType))
{
if("byKeyword".equals(queryFunc))
{
keyword = req.getParameter("keyword");
jobSeq = thisDate + "?" + "queryType" + "=" + queryType +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setStreamJobseq(jobSeq);
Scheduler scheduler = createScheduler(jobSeq);
createStreamJob(jobSeq,queryType,queryFunc,keyword,managementService,applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq,user,queryType,queryFunc,event,keyword,managementService);
}
}
else if("mix".equals(queryType))
{
if("byKeyword".equals(queryFunc))
{
keyword = req.getParameter("keyword");
String jobSeq1 = thisDate + "?" + "queryType" + "=" + "search" +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setSearchJobseq(jobSeq1);
- Scheduler scheduler = createScheduler(jobSeq);
+ Scheduler scheduler = createScheduler(jobSeq1);
createSearchJob(jobSeq1,"search",queryFunc,keyword, managementService, applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq1,user,"search",queryFunc,event,keyword,managementService);
String jobSeq2 = thisDate + "?" + "queryType" + "=" + "stream" +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setStreamJobseq(jobSeq2);
- scheduler = createScheduler(jobSeq);
- createStreamJob(jobSeq,queryType,queryFunc,keyword,managementService,applicationContext,scheduler);
+ scheduler = createScheduler(jobSeq2);
+ createStreamJob(jobSeq2,queryType,queryFunc,keyword,managementService,applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq2,user,"stream",queryFunc,event,keyword,managementService);
jobSeq = jobSeq1 +";<br>"+ jobSeq2;
}
}
List<?> list = managementService.queryAllToken();
int tokenUsable =0;
for(int i=0;i<list.size();i++)
{
List sublist = (List)list.get(i);
if("0".equals(sublist.get(2)))
{
tokenUsable ++;
}
}
Object[] o =new Object[2];
o[0] = tokenUsable;
o[1] = jobSeq;
return new ModelAndView(viewPage,"o",o);
}
@SuppressWarnings({ "rawtypes"})
private void createSearchJob(String jobSeq,String queryType,String queryFunc,String keyword,ManagementService managementService,ApplicationContext applicationContext,Scheduler scheduler)
{
try {
String[] rtn = managementService.lockRandomTokenAndFrequencyToUse(jobSeq);
String tokenId = rtn[0];
String frequency = rtn[1];
List list = (List)managementService.getTokenByWildCard(null, tokenId);
List subList = (List)list.get(0);
TwitterConfiguration twitterConfiguration = new TwitterConfiguration(""+subList.get(4),""+subList.get(5),
""+subList.get(2), ""+subList.get(3));
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("twitterConfiguration", twitterConfiguration);
jobDataMap.put("applicationContext", applicationContext);
jobDataMap.put("jobSeq", jobSeq);
JobDetail job = newJob(TwitterJob.class)
.withIdentity("myJob", "group1") // name "myJob", group "group1"
.usingJobData("queryType", "search")
.usingJobData("keyword", keyword)
.usingJobData(jobDataMap)
.build();
CronTrigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.withSchedule(cronSchedule("0/"+frequency+" * * * * ?"))
.build();
scheduler.scheduleJob(job, trigger);
scheduler.start();
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes"})
private void createStreamJob(String jobSeq,String queryType,String queryFunc,String keyword,ManagementService managementService,ApplicationContext applicationContext,Scheduler scheduler)
{
try {
String[] rtn = managementService.lockRandomTokenAndFrequencyToUse(jobSeq);
String tokenId = rtn[0];
List list = (List)managementService.getTokenByWildCard(null, tokenId);
List subList = (List)list.get(0);
TwitterConfiguration twitterConfiguration = new TwitterConfiguration(""+subList.get(4),""+subList.get(5),
""+subList.get(2), ""+subList.get(3));
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("twitterConfiguration", twitterConfiguration);
jobDataMap.put("applicationContext", applicationContext);
jobDataMap.put("jobSeq", jobSeq);
JobDetail job = newJob(TwitterJob.class)
.withIdentity("job1", "group1") // name "myJob", group "group1"
.usingJobData("queryType", "stream")
.usingJobData("keyword", keyword)
.usingJobData(jobDataMap)
.build();
SimpleTrigger trigger = (SimpleTrigger) newTrigger()
.withIdentity("trigger1", "group1")
.startAt(new Date()) // some Date
.forJob("job1", "group1") // identify job with name, group strings
.build();
scheduler.scheduleJob(job, trigger);
scheduler.start();
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void addJobToDatabase(String jobSeq,String user,String queryType,String queryFunc,Event event,String keyword,ManagementService managementService)
{
Job job = new Job();
job.setJob_Seq(jobSeq);
job.setJobStatus("1");
job.setCreateId(user);
if("search".equals(queryType))
{
job.setQueryType("1");
}
else if("stream".equals(queryType))
{
job.setQueryType("2");
}
job.setQueryFunction(queryFunc);
job.setStartTime(new Date()+"");
job.setEvent(event);
job.setKeyword(keyword);
managementService.addJob(job);
}
public void setViewPage(String viewPage) {
this.viewPage = viewPage;
}
public Scheduler createScheduler(String jobSeq)
{
StdSchedulerFactory sf = new StdSchedulerFactory();
Properties props = new Properties();
props.put("org.quartz.scheduler.instanceName", jobSeq);
props.put("org.quartz.threadPool.threadCount", "3");
Scheduler scheduler = null;
try {
sf.initialize(props);
scheduler = sf.getScheduler();
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return scheduler;
}
@SuppressWarnings("unchecked")
public void putSchedulerPool(Scheduler scheduler)
{
try {
SystemConstants.SCHEDULER_POOL.put(scheduler.getSchedulerName(), scheduler);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
| false | true | public ModelAndView handleRequest(HttpServletRequest req,
HttpServletResponse res) throws Exception {
req.setCharacterEncoding("UTF-8");
ApplicationContext applicationContext =WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
ManagementService managementService = (ManagementService)applicationContext.getBean("managementService");
String queryType = req.getParameter("queryType");
String queryFunc = req.getParameter("queryFunc");
String addJobEventName = req.getParameter("addJobEventName");
Event event = new Event();
event.setEventName(addJobEventName);
String user = (String)req.getSession().getAttribute("user");
String thisDate = DateUtil.getCurrentYYYYMMDD();
String jobSeq = "";
String keyword = "";
if("search".equals(queryType))
{
if("byKeyword".equals(queryFunc))
{
keyword = req.getParameter("keyword");
jobSeq = thisDate + "?" + "queryType" + "=" + queryType +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setSearchJobseq(jobSeq);
Scheduler scheduler = createScheduler(jobSeq);
createSearchJob(jobSeq,queryType,queryFunc,keyword, managementService, applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq,user,queryType,queryFunc,event,keyword,managementService);
}
}
else if("stream".equals(queryType))
{
if("byKeyword".equals(queryFunc))
{
keyword = req.getParameter("keyword");
jobSeq = thisDate + "?" + "queryType" + "=" + queryType +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setStreamJobseq(jobSeq);
Scheduler scheduler = createScheduler(jobSeq);
createStreamJob(jobSeq,queryType,queryFunc,keyword,managementService,applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq,user,queryType,queryFunc,event,keyword,managementService);
}
}
else if("mix".equals(queryType))
{
if("byKeyword".equals(queryFunc))
{
keyword = req.getParameter("keyword");
String jobSeq1 = thisDate + "?" + "queryType" + "=" + "search" +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setSearchJobseq(jobSeq1);
Scheduler scheduler = createScheduler(jobSeq);
createSearchJob(jobSeq1,"search",queryFunc,keyword, managementService, applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq1,user,"search",queryFunc,event,keyword,managementService);
String jobSeq2 = thisDate + "?" + "queryType" + "=" + "stream" +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setStreamJobseq(jobSeq2);
scheduler = createScheduler(jobSeq);
createStreamJob(jobSeq,queryType,queryFunc,keyword,managementService,applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq2,user,"stream",queryFunc,event,keyword,managementService);
jobSeq = jobSeq1 +";<br>"+ jobSeq2;
}
}
List<?> list = managementService.queryAllToken();
int tokenUsable =0;
for(int i=0;i<list.size();i++)
{
List sublist = (List)list.get(i);
if("0".equals(sublist.get(2)))
{
tokenUsable ++;
}
}
Object[] o =new Object[2];
o[0] = tokenUsable;
o[1] = jobSeq;
return new ModelAndView(viewPage,"o",o);
}
| public ModelAndView handleRequest(HttpServletRequest req,
HttpServletResponse res) throws Exception {
req.setCharacterEncoding("UTF-8");
ApplicationContext applicationContext =WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
ManagementService managementService = (ManagementService)applicationContext.getBean("managementService");
String queryType = req.getParameter("queryType");
String queryFunc = req.getParameter("queryFunc");
String addJobEventName = req.getParameter("addJobEventName");
Event event = new Event();
event.setEventName(addJobEventName);
String user = (String)req.getSession().getAttribute("user");
String thisDate = DateUtil.getCurrentYYYYMMDD();
String jobSeq = "";
String keyword = "";
if("search".equals(queryType))
{
if("byKeyword".equals(queryFunc))
{
keyword = req.getParameter("keyword");
jobSeq = thisDate + "?" + "queryType" + "=" + queryType +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setSearchJobseq(jobSeq);
Scheduler scheduler = createScheduler(jobSeq);
createSearchJob(jobSeq,queryType,queryFunc,keyword, managementService, applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq,user,queryType,queryFunc,event,keyword,managementService);
}
}
else if("stream".equals(queryType))
{
if("byKeyword".equals(queryFunc))
{
keyword = req.getParameter("keyword");
jobSeq = thisDate + "?" + "queryType" + "=" + queryType +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setStreamJobseq(jobSeq);
Scheduler scheduler = createScheduler(jobSeq);
createStreamJob(jobSeq,queryType,queryFunc,keyword,managementService,applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq,user,queryType,queryFunc,event,keyword,managementService);
}
}
else if("mix".equals(queryType))
{
if("byKeyword".equals(queryFunc))
{
keyword = req.getParameter("keyword");
String jobSeq1 = thisDate + "?" + "queryType" + "=" + "search" +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setSearchJobseq(jobSeq1);
Scheduler scheduler = createScheduler(jobSeq1);
createSearchJob(jobSeq1,"search",queryFunc,keyword, managementService, applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq1,user,"search",queryFunc,event,keyword,managementService);
String jobSeq2 = thisDate + "?" + "queryType" + "=" + "stream" +"&" + "keyword" + "=" + keyword +"&" + "user"+"="+user;
JobseqUtil.setStreamJobseq(jobSeq2);
scheduler = createScheduler(jobSeq2);
createStreamJob(jobSeq2,queryType,queryFunc,keyword,managementService,applicationContext,scheduler);
putSchedulerPool(scheduler);
addJobToDatabase(jobSeq2,user,"stream",queryFunc,event,keyword,managementService);
jobSeq = jobSeq1 +";<br>"+ jobSeq2;
}
}
List<?> list = managementService.queryAllToken();
int tokenUsable =0;
for(int i=0;i<list.size();i++)
{
List sublist = (List)list.get(i);
if("0".equals(sublist.get(2)))
{
tokenUsable ++;
}
}
Object[] o =new Object[2];
o[0] = tokenUsable;
o[1] = jobSeq;
return new ModelAndView(viewPage,"o",o);
}
|
diff --git a/javasrc/src/org/ccnx/ccn/profiles/VersioningProfile.java b/javasrc/src/org/ccnx/ccn/profiles/VersioningProfile.java
index 3a1cbc012..a8dda3f84 100644
--- a/javasrc/src/org/ccnx/ccn/profiles/VersioningProfile.java
+++ b/javasrc/src/org/ccnx/ccn/profiles/VersioningProfile.java
@@ -1,572 +1,576 @@
package org.ccnx.ccn.profiles;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidParameterException;
import java.sql.Timestamp;
import java.util.ArrayList;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.ContentVerifier;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.impl.support.DataUtils.Tuple;
import org.ccnx.ccn.io.CCNVersionedInputStream;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.ExcludeAny;
import org.ccnx.ccn.protocol.ExcludeComponent;
import org.ccnx.ccn.protocol.Exclude;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.PublisherID;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
import org.ccnx.ccn.protocol.SignedInfo;
/**
* Versions, when present, usually occupy the penultimate component of the CCN name,
* not counting the digest component. A name may actually incorporate multiple
* versions, where the rightmost version is the version of "this" object, if it
* has one, and previous (parent) versions are the versions of the objects of
* which this object is a part. The most common location of a version, if present,
* is in the next to last component of the name, where the last component is a
* segment number (which is generally always present; versions themselves are
* optional). More complicated segmentation profiles occur, where a versioned
* object has components that are structured and named in ways other than segments --
* and may themselves have individual versions (e.g. if the components of such
* a composite object are written as CCNNetworkObjects and automatically pick
* up an (unnecessary) version in their own right). Versioning operations therefore
* take context from their caller about where to expect to find a version,
* and attempt to ignore other versions in the name.
*
* Versions may be chosen based on time.
* The first byte of the version component is 0xFD. The remaining bytes are a
* big-endian binary number. If based on time they are expressed in units of
* 2**(-12) seconds since the start of Unix time, using the minimum number of
* bytes. The time portion will thus take 48 bits until quite a few centuries
* from now (Sun, 20 Aug 4147 07:32:16 GMT). With 12 bits of precision, it allows
* for sub-millisecond resolution. The client generating the version stamp
* should try to avoid using a stamp earlier than (or the same as) any
* version of the file, to the extent that it knows about it. It should
* also avoid generating stamps that are unreasonably far in the future.
*/
public class VersioningProfile implements CCNProfile {
public static final byte VERSION_MARKER = (byte)0xFD;
public static final byte [] FIRST_VERSION_MARKER = new byte []{VERSION_MARKER};
public static final byte FF = (byte) 0xFF;
public static final byte OO = (byte) 0x00;
/**
* Add a version field to a ContentName.
* @return ContentName with a version appended. Does not affect previous versions.
*/
public static ContentName addVersion(ContentName name, long version) {
// Need a minimum-bytes big-endian representation of version.
byte [] vcomp = null;
if (0 == version) {
vcomp = FIRST_VERSION_MARKER;
} else {
byte [] varr = BigInteger.valueOf(version).toByteArray();
vcomp = new byte[varr.length + 1];
vcomp[0] = VERSION_MARKER;
System.arraycopy(varr, 0, vcomp, 1, varr.length);
}
return new ContentName(name, vcomp);
}
/**
* Converts a timestamp into a fixed point representation, with 12 bits in the fractional
* component, and adds this to the ContentName as a version field. The timestamp is rounded
* to the nearest value in the fixed point representation.
* <p>
* This allows versions to be recorded as a timestamp with a 1/4096 second accuracy.
* @see #addVersion(ContentName, long)
*/
public static ContentName addVersion(ContentName name, Timestamp version) {
if (null == version)
throw new IllegalArgumentException("Version cannot be null!");
return addVersion(name, DataUtils.timestampToBinaryTime12AsLong(version));
}
/**
* Add a version field based on the current time, accurate to 1/4096 second.
* @see #addVersion(ContentName, Timestamp)
*/
public static ContentName addVersion(ContentName name) {
return addVersion(name, SignedInfo.now());
}
/**
* Adds a version to a ContentName; if there is a terminal version there already,
* first removes it.
*/
public static ContentName updateVersion(ContentName name, long version) {
return addVersion(cutTerminalVersion(name).first(), version);
}
/**
* Adds a version to a ContentName; if there is a terminal version there already,
* first removes it.
*/
public static ContentName updateVersion(ContentName name, Timestamp version) {
return addVersion(cutTerminalVersion(name).first(), version);
}
/**
* Add updates the version field based on the current time, accurate to 1/4096 second.
* @see #updateVersion(ContentName, Timestamp)
*/
public static ContentName updateVersion(ContentName name) {
return updateVersion(name, SignedInfo.now());
}
/**
* Finds the last component that looks like a version in name.
* @param name
* @return the index of the last version component in the name, or -1 if there is no version
* component in the name
*/
public static int findLastVersionComponent(ContentName name) {
int i = name.count();
for (;i >= 0; i--)
if (isVersionComponent(name.component(i)))
return i;
return -1;
}
/**
* Checks to see if this name has a validly formatted version field anywhere in it.
*/
public static boolean containsVersion(ContentName name) {
return findLastVersionComponent(name) != -1;
}
/**
* Checks to see if this name has a validly formatted version field either in final
* component or in next to last component with final component being a segment marker.
*/
public static boolean hasTerminalVersion(ContentName name) {
if ((name.count() > 0) &&
((isVersionComponent(name.lastComponent()) ||
((name.count() > 1) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2)))))) {
return true;
}
return false;
}
/**
* Check a name component to see if it is a valid version field
*/
public static boolean isVersionComponent(byte [] nameComponent) {
return (null != nameComponent) && (0 != nameComponent.length) &&
(VERSION_MARKER == nameComponent[0]) &&
((nameComponent.length == 1) || (nameComponent[1] != 0));
}
public static boolean isBaseVersionComponent(byte [] nameComponent) {
return (isVersionComponent(nameComponent) && (1 == nameComponent.length));
}
/**
* Remove a terminal version marker (one that is either the last component of name, or
* the next to last component of name followed by a segment marker) if one exists, otherwise
* return name as it was passed in.
* @param name
* @return
*/
public static Tuple<ContentName, byte[]> cutTerminalVersion(ContentName name) {
if (name.count() > 0) {
if (isVersionComponent(name.lastComponent())) {
return new Tuple<ContentName, byte []>(name.parent(), name.lastComponent());
} else if ((name.count() > 2) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2))) {
return new Tuple<ContentName, byte []>(name.cut(name.count()-2), name.component(name.count()-2));
}
}
return new Tuple<ContentName, byte []>(name, null);
}
/**
* Take a name which may have one or more version components in it,
* and strips the last one and all following components. If no version components
* present, returns the name as handed in.
*/
public static ContentName cutLastVersion(ContentName name) {
int offset = findLastVersionComponent(name);
return (offset == -1) ? name : new ContentName(offset, name.components());
}
/**
* Function to get the version field as a long. Starts from the end and checks each name component for the version marker.
* @param name
* @return long
* @throws VersionMissingException
*/
public static long getLastVersionAsLong(ContentName name) throws VersionMissingException {
int i = findLastVersionComponent(name);
if (i == -1)
throw new VersionMissingException();
return getVersionComponentAsLong(name.component(i));
}
public static long getVersionComponentAsLong(byte [] versionComponent) {
byte [] versionData = new byte[versionComponent.length - 1];
System.arraycopy(versionComponent, 1, versionData, 0, versionComponent.length - 1);
if (versionData.length == 0)
return 0;
return new BigInteger(versionData).longValue();
}
public static Timestamp getVersionComponentAsTimestamp(byte [] versionComponent) {
return versionLongToTimestamp(getVersionComponentAsLong(versionComponent));
}
/**
* Extract the version from this name as a Timestamp.
* @throws VersionMissingException
*/
public static Timestamp getLastVersionAsTimestamp(ContentName name) throws VersionMissingException {
long time = getLastVersionAsLong(name);
return DataUtils.binaryTime12ToTimestamp(time);
}
/**
* Returns null if no version, otherwise returns the last version in the name.
* @param name
* @return
*/
public static Timestamp getLastVersionAsTimestampIfVersioned(ContentName name) {
int versionComponent = findLastVersionComponent(name);
if (versionComponent < 0)
return null;
return getVersionComponentAsTimestamp(name.component(versionComponent));
}
public static Timestamp getTerminalVersionAsTimestampIfVersioned(ContentName name) {
if (!hasTerminalVersion(name))
return null;
int versionComponent = findLastVersionComponent(name);
if (versionComponent < 0)
return null;
return getVersionComponentAsTimestamp(name.component(versionComponent));
}
public static Timestamp versionLongToTimestamp(long version) {
return DataUtils.binaryTime12ToTimestamp(version);
}
/**
* Control whether versions start at 0 or 1.
* @return
*/
public static final int baseVersion() { return 0; }
/**
* Compares terminal version (versions at the end of, or followed by only a segment
* marker) of a name to a given timestamp.
* @param left
* @param right
* @return
*/
public static int compareVersions(
Timestamp left,
ContentName right) {
if (!hasTerminalVersion(right)) {
throw new IllegalArgumentException("Both names to compare must be versioned!");
}
try {
return left.compareTo(getLastVersionAsTimestamp(right));
} catch (VersionMissingException e) {
throw new IllegalArgumentException("Name that isVersioned returns true for throws VersionMissingException!: " + right);
}
}
public static int compareVersionComponents(
byte [] left,
byte [] right) throws VersionMissingException {
// Propagate correct exception to callers.
if ((null == left) || (null == right))
throw new VersionMissingException("Must compare two versions!");
// DKS TODO -- should be able to just compare byte arrays, but would have to check version
return getVersionComponentAsTimestamp(left).compareTo(getVersionComponentAsTimestamp(right));
}
/**
* See if version is a version of parent (not commutative).
* @return
*/
public static boolean isVersionOf(ContentName version, ContentName parent) {
Tuple<ContentName, byte []>versionParts = cutTerminalVersion(version);
if (!parent.equals(versionParts.first())) {
return false; // not versions of the same thing
}
if (null == versionParts.second())
return false; // version isn't a version
return true;
}
/**
* This compares two names, with terminal versions, and determines whether one is later than the other.
* @param laterVersion
* @param earlierVersion
* @return
* @throws VersionMissingException
*/
public static boolean isLaterVersionOf(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException {
// TODO -- remove temporary warning
Log.warning("SEMANTICS CHANGED: if experiencing unexpected behavior, check to see if you want to call isLaterVerisionOf or startsWithLaterVersionOf");
Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion);
Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion);
if (!laterVersionParts.first().equals(earlierVersionParts.first())) {
return false; // not versions of the same thing
}
return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second()) > 0);
}
/**
* Finds out if you have a versioned name, and a ContentObject that might have a versioned name which is
* a later version of the given name, even if that CO name might not refer to a segment of the original name.
* For example, given a name /parc/foo.txt/<version1> or /parc/foo.txt/<version1>/<segment>
* and /parc/foo.txt/<version2>/<stuff>, return true, whether <stuff> is a segment marker, a whole
* bunch of repo write information, or whatever.
* @param newName Will check to see if this name begins with something which is a later version of previousVersion.
* @param previousVersion The name to compare to, must have a terminal version or be unversioned.
* @return
*/
public static boolean startsWithLaterVersionOf(ContentName newName, ContentName previousVersion) {
// If no version, treat whole name as prefix and any version as a later version.
Tuple<ContentName, byte []>previousVersionParts = cutTerminalVersion(previousVersion);
if (!previousVersionParts.first().isPrefixOf(newName))
return false;
if (null == previousVersionParts.second()) {
return ((newName.count() > previousVersionParts.first().count()) &&
VersioningProfile.isVersionComponent(newName.component(previousVersionParts.first().count())));
}
try {
return (compareVersionComponents(newName.component(previousVersionParts.first().count()), previousVersionParts.second()) > 0);
} catch (VersionMissingException e) {
return false; // newName doesn't have to have a version there...
}
}
public static int compareTerminalVersions(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException {
Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion);
Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion);
if (!laterVersionParts.first().equals(earlierVersionParts.first())) {
throw new IllegalArgumentException("Names not versions of the same name!");
}
return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second()));
}
/**
* Builds an Exclude filter that excludes components before or @ start, and components after
* the last valid version.
* @param startingVersionComponent The latest version component we know about. Can be null or
* VersioningProfile.isBaseVersionComponent() == true to indicate that we want to start
* from 0 (we don't have a known version we're trying to update). This exclude filter will
* find versions *after* the version represented in startingVersionComponent.
* @return An exclude filter.
* @throws InvalidParameterException
*/
public static Exclude acceptVersions(byte [] startingVersionComponent) {
byte [] start = null;
// initially exclude name components just before the first version, whether that is the
// 0th version or the version passed in
if ((null == startingVersionComponent) || VersioningProfile.isBaseVersionComponent(startingVersionComponent)) {
start = new byte [] { VersioningProfile.VERSION_MARKER, VersioningProfile.OO, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF };
} else {
start = startingVersionComponent;
}
ArrayList<Exclude.Element> ees = new ArrayList<Exclude.Element>();
ees.add(new ExcludeAny());
ees.add(new ExcludeComponent(start));
ees.add(new ExcludeComponent(new byte [] {
VERSION_MARKER+1, OO, OO, OO, OO, OO, OO } ));
ees.add(new ExcludeAny());
return new Exclude(ees);
}
/**
* Active methods. Want to provide profile-specific methods that:
* - find the latest version without regard to what is below it
* - if no version given, gets the latest version
* - if a starting version given, gets the latest version available *after* that version;
* will time out if no such newer version exists
* Returns a content object, which may or may not be a segment of the latest version, but the
* latest version information is available from its name.
*
* - find the first segment of the latest version of a name
* - if no version given, gets the first segment of the latest version
* - if a starting version given, gets the latest version available *after* that version or times out
* Will ensure that what it returns is a segment of a version of that object.
*
* - generate an interest designed to find the first segment of the latest version
* of a name, in the above form; caller is responsible for checking and re-issuing
*/
/**
* Generate an interest that will find the leftmost child of the latest version. It
* will ensure that the next to last segment is a version, and the last segment (excluding
* digest) is the leftmost child available. But it can't guarantee that the latter is
* a segment. Because most data is segmented, length constraints will make it very
* likely, however.
* @param startingVersion
* @return
*/
public static Interest firstBlockLatestVersionInterest(ContentName startingVersion, PublisherPublicKeyDigest publisher) {
// by the time we look for extra components we will have a version on our name if it
// doesn't have one already, so look for names with 2 extra components -- segment and digest.
return latestVersionInterest(startingVersion, 3, publisher);
}
/**
* Generate an interest that will find a descendant of the latest version of startingVersion,
* after any existing version component. If additionalNameComponents is non-null, it will
* find a descendant with exactly that many name components after the version (including
* the digest). The latest version is the rightmost child of the desired prefix, however,
* this interest will find leftmost descendants of that rightmost child. With appropriate
* length limitations, can be used to find segments of the latest version (though that
* will work more effectively with appropriate segment numbering).
*/
public static Interest latestVersionInterest(ContentName startingVersion, Integer additionalNameComponents, PublisherPublicKeyDigest publisher) {
if (hasTerminalVersion(startingVersion)) {
// Has a version. Make sure it doesn't have a segment; find a version after this one.
startingVersion = SegmentationProfile.segmentRoot(startingVersion);
} else {
// Doesn't have a version. Add the "0" version, so we are finding any version after that.
ContentName firstVersionName = addVersion(startingVersion, baseVersion());
startingVersion = firstVersionName;
}
byte [] versionComponent = startingVersion.lastComponent();
Interest constructedInterest = Interest.last(startingVersion, acceptVersions(versionComponent), startingVersion.count() - 1);
if (null != additionalNameComponents) {
constructedInterest.maxSuffixComponents(additionalNameComponents);
constructedInterest.minSuffixComponents(additionalNameComponents);
}
if (null != publisher) {
constructedInterest.publisherID(new PublisherID(publisher));
}
return constructedInterest;
}
/**
* Gets the latest version using a single interest/response. There may be newer versions available
* if you ask again passing in the version found (i.e. each response will be the latest version
* a given responder knows about. Further queries will move past that responder to other responders,
* who may have newer information.)
*
* @param name If the name ends in a version then this method explicitly looks for a newer version
* than that, and will time out if no such later version exists. If the name does not end in a
* version then this call just looks for the latest version.
* @param publisher Currently unused, will limit query to a specific publisher.
* @param timeout
* @return A ContentObject with the latest version, or null if the query timed out. Note - the content
* returned could be any name under this new version - by default it will get the leftmost item,
* but right now that is generally a repo start write, not a segment. Changing the marker values
* used will fix that.
* TODO fix marker values
* @result Returns a matching ContentObject, *unverified*.
* @throws IOException
* DKS TODO -- doesn't use publisher
* DKS TODO -- specify separately latest version known?
*/
public static ContentObject getLatestVersion(ContentName startingVersion,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle library) throws IOException {
ContentName latestVersionFound = startingVersion;
while (true) {
Interest getLatestInterest = latestVersionInterest(latestVersionFound, null, publisher);
ContentObject co = library.get(getLatestInterest, timeout);
if (co == null) {
Log.info("Null returned from getLatest for name: " + startingVersion);
return null;
}
// What we get should be a block representing a later version of name. It might
// be an actual segment of a versioned object, but it might also be an ancillary
// object - e.g. a repo message -- which starts with a particular version of name.
if (startsWithLaterVersionOf(co.name(), startingVersion)) {
// we got a valid version!
Log.info("Got latest version: " + co.name());
// Now need to verify the block we got
if (verifier.verify(co)) {
return co;
}
Log.warning("VERIFICATION FAILURE: " + co.name() + ", need to find better way to decide what to do next.");
} else {
Log.info("Rejected potential candidate version: " + co.name() + " not a later version of " + startingVersion);
}
latestVersionFound = new ContentName(getLatestInterest.name().count(), co.name().components());
}
}
/**
* - find the first segment of the latest version of a name
* - if no version given, gets the first segment of the latest version
* - if a starting version given, gets the latest version available *after* that version or times out
* Will ensure that what it returns is a segment of a version of that object.
* * @param desiredName The name of the object we are looking for the first segment of.
* If (VersioningProfile.hasTerminalVersion(desiredName) == false), will get latest version it can
* find of desiredName.
* If desiredName has a terminal version, will try to find the first block of content whose
* version is *after* desiredName (i.e. getLatestVersion starting from desiredName).
* @param startingSegmentNumber The desired block number, or SegmentationProfile.baseSegment if null.
* @param publisher, if one is specified.
* @param timeout
* @return The first block of a stream with a version later than desiredName, or null if timeout is reached.
* This block is *unverified*.
* @throws IOException
*/
public static ContentObject getFirstBlockOfLatestVersion(ContentName startingVersion,
Long startingSegmentNumber,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle library) throws IOException {
Log.info("getFirstBlockOfLatestVersion: getting version later than " + startingVersion);
- int prefixLength = hasTerminalVersion(startingVersion) ? startingVersion.count() : startingVersion.count() + 1;
+ ContentName prefix = startingVersion;
+ if (hasTerminalVersion(prefix)) {
+ prefix = startingVersion.parent();
+ }
+ int versionedLength = prefix.count() + 1;
Interest getLatestInterest = firstBlockLatestVersionInterest(startingVersion, publisher);
ContentObject result = library.get(getLatestInterest, timeout);
if (null != result){
Log.info("getFirstBlockOfLatestVersion: retrieved latest version object " + result.name() + " type: " + result.signedInfo().getTypeName());
// Now we know the version. Did we luck out and get first block?
- if (CCNVersionedInputStream.isFirstSegment(startingVersion, result, startingSegmentNumber)) {
+ if (CCNVersionedInputStream.isFirstSegment(prefix, result, startingSegmentNumber)) {
Log.info("getFirstBlockOfLatestVersion: got first block on first try: " + result.name());
// Now need to verify the block we got
if (!verifier.verify(result)) {
// TODO rework to allow retries
Log.info("Block failed to verify! Need to robustify method!");
return null;
}
return result;
}
// This isn't the first block. Might be simply a later (cached) segment, or might be something
// crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion
// is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock
// above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got,
// which works fine only if we have the wrong segment rather than some other beast entirely (like metadata).
// So chop off the new name just after the (first) version, and use that. If getLatestVersion is working
// right, that should be the right thing.
- startingVersion = result.name().cut(prefixLength);
+ startingVersion = result.name().cut(versionedLength);
Log.info("CHILD SELECTOR FAILURE: getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion);
// this will verify
return SegmentationProfile.getSegment(startingVersion, startingSegmentNumber, null, timeout, verifier, library); // now that we have the latest version, go back for the first block.
} else {
Log.info("getFirstBlockOfLatestVersion: no block available for later version of " + startingVersion);
}
return result;
}
}
| false | true | public static ContentObject getFirstBlockOfLatestVersion(ContentName startingVersion,
Long startingSegmentNumber,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle library) throws IOException {
Log.info("getFirstBlockOfLatestVersion: getting version later than " + startingVersion);
int prefixLength = hasTerminalVersion(startingVersion) ? startingVersion.count() : startingVersion.count() + 1;
Interest getLatestInterest = firstBlockLatestVersionInterest(startingVersion, publisher);
ContentObject result = library.get(getLatestInterest, timeout);
if (null != result){
Log.info("getFirstBlockOfLatestVersion: retrieved latest version object " + result.name() + " type: " + result.signedInfo().getTypeName());
// Now we know the version. Did we luck out and get first block?
if (CCNVersionedInputStream.isFirstSegment(startingVersion, result, startingSegmentNumber)) {
Log.info("getFirstBlockOfLatestVersion: got first block on first try: " + result.name());
// Now need to verify the block we got
if (!verifier.verify(result)) {
// TODO rework to allow retries
Log.info("Block failed to verify! Need to robustify method!");
return null;
}
return result;
}
// This isn't the first block. Might be simply a later (cached) segment, or might be something
// crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion
// is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock
// above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got,
// which works fine only if we have the wrong segment rather than some other beast entirely (like metadata).
// So chop off the new name just after the (first) version, and use that. If getLatestVersion is working
// right, that should be the right thing.
startingVersion = result.name().cut(prefixLength);
Log.info("CHILD SELECTOR FAILURE: getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion);
// this will verify
return SegmentationProfile.getSegment(startingVersion, startingSegmentNumber, null, timeout, verifier, library); // now that we have the latest version, go back for the first block.
} else {
Log.info("getFirstBlockOfLatestVersion: no block available for later version of " + startingVersion);
}
return result;
}
| public static ContentObject getFirstBlockOfLatestVersion(ContentName startingVersion,
Long startingSegmentNumber,
PublisherPublicKeyDigest publisher,
long timeout,
ContentVerifier verifier,
CCNHandle library) throws IOException {
Log.info("getFirstBlockOfLatestVersion: getting version later than " + startingVersion);
ContentName prefix = startingVersion;
if (hasTerminalVersion(prefix)) {
prefix = startingVersion.parent();
}
int versionedLength = prefix.count() + 1;
Interest getLatestInterest = firstBlockLatestVersionInterest(startingVersion, publisher);
ContentObject result = library.get(getLatestInterest, timeout);
if (null != result){
Log.info("getFirstBlockOfLatestVersion: retrieved latest version object " + result.name() + " type: " + result.signedInfo().getTypeName());
// Now we know the version. Did we luck out and get first block?
if (CCNVersionedInputStream.isFirstSegment(prefix, result, startingSegmentNumber)) {
Log.info("getFirstBlockOfLatestVersion: got first block on first try: " + result.name());
// Now need to verify the block we got
if (!verifier.verify(result)) {
// TODO rework to allow retries
Log.info("Block failed to verify! Need to robustify method!");
return null;
}
return result;
}
// This isn't the first block. Might be simply a later (cached) segment, or might be something
// crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion
// is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock
// above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got,
// which works fine only if we have the wrong segment rather than some other beast entirely (like metadata).
// So chop off the new name just after the (first) version, and use that. If getLatestVersion is working
// right, that should be the right thing.
startingVersion = result.name().cut(versionedLength);
Log.info("CHILD SELECTOR FAILURE: getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion);
// this will verify
return SegmentationProfile.getSegment(startingVersion, startingSegmentNumber, null, timeout, verifier, library); // now that we have the latest version, go back for the first block.
} else {
Log.info("getFirstBlockOfLatestVersion: no block available for later version of " + startingVersion);
}
return result;
}
|
diff --git a/src/chalmers/TDA367/B17/view/Scoreboard.java b/src/chalmers/TDA367/B17/view/Scoreboard.java
index ee43ecd..8cd9f7b 100644
--- a/src/chalmers/TDA367/B17/view/Scoreboard.java
+++ b/src/chalmers/TDA367/B17/view/Scoreboard.java
@@ -1,57 +1,57 @@
package chalmers.TDA367.B17.view;
import org.newdawn.slick.Color;
import org.newdawn.slick.Font;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.geom.Vector2f;
import chalmers.TDA367.B17.Tansk;
import chalmers.TDA367.B17.controller.GameController;
import chalmers.TDA367.B17.model.Player;
public class Scoreboard {
private Font scoreboardFont;
private MenuButton toMenuButton;
private MenuButton restartButton;
private Vector2f position;
private int width;
private int height;
public Scoreboard(){
width = 350;
height = 350;
position = new Vector2f(Tansk.SCREEN_WIDTH/2-width/2, Tansk.SCREEN_HEIGHT/2-height/2);
toMenuButton = new MenuButton((int)(position.x + 15), (int)(position.y + height-60), GameController.getInstance().getImageHandler().getSprite("button_menu"),
GameController.getInstance().getImageHandler().getSprite("button_menu_pressed"),
GameController.getInstance().getImageHandler().getSprite("button_menu_hover"));
restartButton = new MenuButton((int)(position.x + width - 165), (int)(position.y + height-60), GameController.getInstance().getImageHandler().getSprite("button_restart"),
GameController.getInstance().getImageHandler().getSprite("button_restart_pressed"),
GameController.getInstance().getImageHandler().getSprite("button_restart_hover"));
scoreboardFont = new TrueTypeFont(new java.awt.Font("Verdana", java.awt.Font.PLAIN, 22), true);
}
public void render(Graphics g){
g.setLineWidth(15);
g.setColor(new Color(100, 100, 100, 255));
int tmpYOffset = 10;
g.fillRect(position.x, position.y, width, height);
g.setColor(Color.black);
g.drawRect(position.x, position.y, width, height);
g.setLineWidth(1);
g.setFont(scoreboardFont);
for(Player p: GameController.getInstance().getGameMode().getPlayerList()){
- g.drawString(p.getName() + ": " + p.getScore(), position.x+70, position.y+tmpYOffset);
+ g.drawString(p.getName() + ": " + p.getScore(), position.x+20, position.y+tmpYOffset);
tmpYOffset += 30;
}
toMenuButton.draw();
restartButton.draw();
}
}
| true | true | public void render(Graphics g){
g.setLineWidth(15);
g.setColor(new Color(100, 100, 100, 255));
int tmpYOffset = 10;
g.fillRect(position.x, position.y, width, height);
g.setColor(Color.black);
g.drawRect(position.x, position.y, width, height);
g.setLineWidth(1);
g.setFont(scoreboardFont);
for(Player p: GameController.getInstance().getGameMode().getPlayerList()){
g.drawString(p.getName() + ": " + p.getScore(), position.x+70, position.y+tmpYOffset);
tmpYOffset += 30;
}
toMenuButton.draw();
restartButton.draw();
}
| public void render(Graphics g){
g.setLineWidth(15);
g.setColor(new Color(100, 100, 100, 255));
int tmpYOffset = 10;
g.fillRect(position.x, position.y, width, height);
g.setColor(Color.black);
g.drawRect(position.x, position.y, width, height);
g.setLineWidth(1);
g.setFont(scoreboardFont);
for(Player p: GameController.getInstance().getGameMode().getPlayerList()){
g.drawString(p.getName() + ": " + p.getScore(), position.x+20, position.y+tmpYOffset);
tmpYOffset += 30;
}
toMenuButton.draw();
restartButton.draw();
}
|
diff --git a/src/main/java/org/zeroturnaround/jenkins/LiveRebelDeployPublisher.java b/src/main/java/org/zeroturnaround/jenkins/LiveRebelDeployPublisher.java
index c26093c..280f0b0 100644
--- a/src/main/java/org/zeroturnaround/jenkins/LiveRebelDeployPublisher.java
+++ b/src/main/java/org/zeroturnaround/jenkins/LiveRebelDeployPublisher.java
@@ -1,188 +1,188 @@
package org.zeroturnaround.jenkins;
/*****************************************************************
Copyright 2011 ZeroTurnaround 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.
*****************************************************************/
import com.zeroturnaround.liverebel.api.CommandCenterFactory;
import com.zeroturnaround.liverebel.api.ConnectException;
import com.zeroturnaround.liverebel.api.Forbidden;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.plugins.deploy.ContainerAdapter;
import hudson.plugins.deploy.ContainerAdapterDescriptor;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import hudson.util.FormValidation;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@SuppressWarnings("UnusedDeclaration")
public class LiveRebelDeployPublisher extends Notifier implements Serializable {
public final String artifacts;
public final ContainerAdapter adapter;
public boolean useCargo() {
return adapter != null;
}
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public LiveRebelDeployPublisher(String artifacts, ContainerAdapter adapter) {
this.artifacts = artifacts;
this.adapter = adapter;
}
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
if (!build.getResult().equals(Result.SUCCESS)) return false;
DeployPluginProxy deployPluginProxy = new DeployPluginProxy(adapter, build, launcher, listener);
CommandCenterFactory commandCenterFactory = new CommandCenterFactory().
setUrl(getDescriptor().getLrUrl()).
setVerbose(true).
authenticate(getDescriptor().getAuthToken());
return new LiveRebelProxy(commandCenterFactory, build.getWorkspace().list(artifacts), useCargo(), listener, deployPluginProxy).performRelease();
}
// Overridden for better type safety.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.BUILD;
}
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public DescriptorImpl(){
load();
}
private String authToken;
private String lrUrl;
public String getAuthToken() {
return authToken;
}
public String getLrUrl(){
return lrUrl;
}
@SuppressWarnings("UnusedDeclaration")
public FormValidation doCheckLrUrl(@QueryParameter("lrUrl") final String value) throws IOException, ServletException {
if (value != null && value.length() > 0) {
try {
new URL(value);
} catch (Exception e) {
return FormValidation.error("Should be a valid URL.");
}
}
return FormValidation.ok();
}
@SuppressWarnings("UnusedDeclaration")
public FormValidation doCheckAuthToken(@QueryParameter("authToken") final String value) throws IOException, ServletException {
if (value == null || value.length() != 36)
return FormValidation.error("Should be a valid authentication token.");
return FormValidation.ok();
}
@SuppressWarnings("UnusedDeclaration")
public FormValidation doTestConnection(@QueryParameter("authToken") final String authToken, @QueryParameter("lrUrl") final String lrUrl) throws IOException, ServletException {
try {
new CommandCenterFactory().setUrl(lrUrl).setVerbose(false).authenticate(authToken).newCommandCenter();
return FormValidation.ok("Success");
}
catch (Forbidden e){
return FormValidation.error("Please, provide right authentication token!");
}
catch (ConnectException e){
- return FormValidation.error("Could not connect to LiveRebel Url (%s). LiveRebel should be running.", e.getURL());
+ return FormValidation.error("Could not connect to LiveRebel at (%s)", e.getURL());
}
catch (Exception e) {
return FormValidation.error(e.getMessage());
}
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Deploy artifacts with LiveRebel";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
// To persist global configuration information,
// set that to properties and call save().
authToken = formData.getString("authToken");
lrUrl = "https://" + formData.getString("lrUrl").replaceFirst("http://", "").replaceFirst("https://", "");
save();
return super.configure(req,formData);
}
@SuppressWarnings("UnusedDeclaration")
public FormValidation doCheckArtifacts(@AncestorInPath AbstractProject project, @QueryParameter String value) throws IOException, ServletException {
if (value == null || value.length() == 0)
return FormValidation.error("Please, provide at least one artifact.");
else {
return FilePath.validateFileMask(project.getSomeWorkspace(), value);
}
}
@SuppressWarnings("UnusedDeclaration")
public List<ContainerAdapterDescriptor> getContainerAdapters() {
List<ContainerAdapterDescriptor> r = new ArrayList<ContainerAdapterDescriptor>(ContainerAdapter.all());
Collections.sort(r, new Comparator<ContainerAdapterDescriptor>() {
public int compare(ContainerAdapterDescriptor o1, ContainerAdapterDescriptor o2) {
return o1.getDisplayName().compareTo(o2.getDisplayName());
}
});
return r;
}
}
}
| true | true | public FormValidation doTestConnection(@QueryParameter("authToken") final String authToken, @QueryParameter("lrUrl") final String lrUrl) throws IOException, ServletException {
try {
new CommandCenterFactory().setUrl(lrUrl).setVerbose(false).authenticate(authToken).newCommandCenter();
return FormValidation.ok("Success");
}
catch (Forbidden e){
return FormValidation.error("Please, provide right authentication token!");
}
catch (ConnectException e){
return FormValidation.error("Could not connect to LiveRebel Url (%s). LiveRebel should be running.", e.getURL());
}
catch (Exception e) {
return FormValidation.error(e.getMessage());
}
}
| public FormValidation doTestConnection(@QueryParameter("authToken") final String authToken, @QueryParameter("lrUrl") final String lrUrl) throws IOException, ServletException {
try {
new CommandCenterFactory().setUrl(lrUrl).setVerbose(false).authenticate(authToken).newCommandCenter();
return FormValidation.ok("Success");
}
catch (Forbidden e){
return FormValidation.error("Please, provide right authentication token!");
}
catch (ConnectException e){
return FormValidation.error("Could not connect to LiveRebel at (%s)", e.getURL());
}
catch (Exception e) {
return FormValidation.error(e.getMessage());
}
}
|
diff --git a/src/org/linphone/InCallActivity.java b/src/org/linphone/InCallActivity.java
index b509dcb..f5f7f8c 100644
--- a/src/org/linphone/InCallActivity.java
+++ b/src/org/linphone/InCallActivity.java
@@ -1,1412 +1,1412 @@
package org.linphone;
/*
InCallActivity.java
Copyright (C) 2012 Belledonne Communications, Grenoble, France
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.
*/
import java.util.Arrays;
import java.util.List;
import org.linphone.LinphoneSimpleListener.LinphoneOnCallEncryptionChangedListener;
import org.linphone.LinphoneSimpleListener.LinphoneOnCallStateChangedListener;
import org.linphone.core.LinphoneAddress;
import org.linphone.core.LinphoneCall;
import org.linphone.core.LinphoneCall.State;
import org.linphone.core.LinphoneCallParams;
import org.linphone.core.LinphoneCore;
import org.linphone.core.LinphoneCoreException;
import org.linphone.core.LinphoneCoreFactory;
import org.linphone.mediastream.Log;
import org.linphone.mediastream.video.capture.hwconf.AndroidCameraConfiguration;
import org.linphone.ui.AvatarWithShadow;
import org.linphone.ui.Numpad;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* @author Sylvain Berfini
*/
public class InCallActivity extends FragmentActivity implements
LinphoneOnCallStateChangedListener,
LinphoneOnCallEncryptionChangedListener,
OnClickListener {
private final static int SECONDS_BEFORE_HIDING_CONTROLS = 3000;
private final static int SECONDS_BEFORE_DENYING_CALL_UPDATE = 30000;
private static InCallActivity instance;
private Handler mHandler = new Handler();
private Handler mControlsHandler = new Handler();
private Runnable mControls;
private ImageView pause, hangUp, dialer, switchCamera, conference;
private TextView video, micro, speaker, options, addCall, transfer;
private TextView audioRoute, routeSpeaker, routeReceiver, routeBluetooth;
private LinearLayout routeLayout;
private StatusFragment status;
private AudioCallFragment audioCallFragment;
private VideoCallFragment videoCallFragment;
private boolean isSpeakerEnabled = false, isMicMuted = false, isVideoEnabled, isTransferAllowed, isAnimationDisabled;
private ViewGroup mControlsLayout;
private Numpad numpad;
private int cameraNumber;
private Animation slideOutLeftToRight, slideInRightToLeft, slideInBottomToTop, slideInTopToBottom, slideOutBottomToTop, slideOutTopToBottom;
private CountDownTimer timer;
private AcceptCallUpdateDialog callUpdateDialog;
private boolean isVideoCallPaused = false;
private TableLayout callsList;
private LayoutInflater inflater;
private ViewGroup container;
private boolean isConferenceRunning = false;
private boolean showCallListInVideo = false;
public static InCallActivity instance() {
return instance;
}
public static boolean isInstanciated() {
return instance != null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
setContentView(R.layout.incall);
isVideoEnabled = getIntent().getExtras() != null && getIntent().getExtras().getBoolean("VideoEnabled");
isTransferAllowed = getApplicationContext().getResources().getBoolean(R.bool.allow_transfers);
showCallListInVideo = getApplicationContext().getResources().getBoolean(R.bool.show_current_calls_above_video);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
isAnimationDisabled = getApplicationContext().getResources().getBoolean(R.bool.disable_animations) || !prefs.getBoolean(getString(R.string.pref_animation_enable_key), false);
cameraNumber = AndroidCameraConfiguration.retrieveCameras().length;
if (findViewById(R.id.fragmentContainer) != null) {
initUI();
if (LinphoneManager.getLc().getCallsNb() > 0) {
LinphoneCall call = LinphoneManager.getLc().getCalls()[0];
if (LinphoneUtils.isCallEstablished(call)) {
isVideoEnabled = call.getCurrentParamsCopy().getVideoEnabled() && !call.getRemoteParams().isLowBandwidthEnabled();
enableAndRefreshInCallActions();
}
}
if (savedInstanceState != null) {
// Fragment already created, no need to create it again (else it will generate a memory leak with duplicated fragments)
isSpeakerEnabled = savedInstanceState.getBoolean("Speaker");
isMicMuted = savedInstanceState.getBoolean("Mic");
isVideoCallPaused = savedInstanceState.getBoolean("VideoCallPaused");
refreshInCallActions();
return;
}
Fragment callFragment;
if (isVideoEnabled) {
callFragment = new VideoCallFragment();
videoCallFragment = (VideoCallFragment) callFragment;
if (cameraNumber > 1) {
switchCamera.setVisibility(View.VISIBLE);
}
} else {
callFragment = new AudioCallFragment();
audioCallFragment = (AudioCallFragment) callFragment;
switchCamera.setVisibility(View.INVISIBLE);
}
callFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer, callFragment).commitAllowingStateLoss();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("Speaker", isSpeakerEnabled);
outState.putBoolean("Mic", isMicMuted);
outState.putBoolean("VideoCallPaused", isVideoCallPaused);
super.onSaveInstanceState(outState);
}
private void initUI() {
inflater = LayoutInflater.from(this);
container = (ViewGroup) findViewById(R.id.topLayout);
callsList = (TableLayout) findViewById(R.id.calls);
if (!showCallListInVideo) {
callsList.setVisibility(View.GONE);
}
video = (TextView) findViewById(R.id.video);
video.setOnClickListener(this);
video.setEnabled(false);
micro = (TextView) findViewById(R.id.micro);
micro.setOnClickListener(this);
// micro.setEnabled(false);
speaker = (TextView) findViewById(R.id.speaker);
speaker.setOnClickListener(this);
// speaker.setEnabled(false);
addCall = (TextView) findViewById(R.id.addCall);
addCall.setOnClickListener(this);
addCall.setEnabled(false);
transfer = (TextView) findViewById(R.id.transfer);
transfer.setOnClickListener(this);
transfer.setEnabled(false);
options = (TextView) findViewById(R.id.options);
options.setOnClickListener(this);
options.setEnabled(false);
pause = (ImageView) findViewById(R.id.pause);
pause.setOnClickListener(this);
pause.setEnabled(false);
hangUp = (ImageView) findViewById(R.id.hangUp);
hangUp.setOnClickListener(this);
conference = (ImageView) findViewById(R.id.conference);
conference.setOnClickListener(this);
dialer = (ImageView) findViewById(R.id.dialer);
dialer.setOnClickListener(this);
dialer.setEnabled(false);
numpad = (Numpad) findViewById(R.id.numpad);
try {
routeLayout = (LinearLayout) findViewById(R.id.routesLayout);
audioRoute = (TextView) findViewById(R.id.audioRoute);
audioRoute.setOnClickListener(this);
routeSpeaker = (TextView) findViewById(R.id.routeSpeaker);
routeSpeaker.setOnClickListener(this);
routeReceiver = (TextView) findViewById(R.id.routeReceiver);
routeReceiver.setOnClickListener(this);
routeBluetooth = (TextView) findViewById(R.id.routeBluetooth);
routeBluetooth.setOnClickListener(this);
} catch (NullPointerException npe) {
Log.e("Audio routes menu disabled on tablets for now");
}
switchCamera = (ImageView) findViewById(R.id.switchCamera);
switchCamera.setOnClickListener(this);
mControlsLayout = (ViewGroup) findViewById(R.id.menu);
if (!isTransferAllowed) {
addCall.setBackgroundResource(R.drawable.options_add_call);
}
if (!isAnimationDisabled) {
slideInRightToLeft = AnimationUtils.loadAnimation(this, R.anim.slide_in_right_to_left);
slideOutLeftToRight = AnimationUtils.loadAnimation(this, R.anim.slide_out_left_to_right);
slideInBottomToTop = AnimationUtils.loadAnimation(this, R.anim.slide_in_bottom_to_top);
slideInTopToBottom = AnimationUtils.loadAnimation(this, R.anim.slide_in_top_to_bottom);
slideOutBottomToTop = AnimationUtils.loadAnimation(this, R.anim.slide_out_bottom_to_top);
slideOutTopToBottom = AnimationUtils.loadAnimation(this, R.anim.slide_out_top_to_bottom);
}
if (LinphoneManager.getInstance().isBluetoothScoConnected) {
try {
routeLayout.setVisibility(View.VISIBLE);
+ audioRoute.setVisibility(View.VISIBLE);
+ speaker.setVisibility(View.GONE);
} catch (NullPointerException npe) {}
- audioRoute.setVisibility(View.VISIBLE);
- speaker.setVisibility(View.GONE);
} else {
try {
routeLayout.setVisibility(View.GONE);
+ audioRoute.setVisibility(View.GONE);
+ speaker.setVisibility(View.VISIBLE);
} catch (NullPointerException npe) {}
- audioRoute.setVisibility(View.GONE);
- speaker.setVisibility(View.VISIBLE);
}
}
private void refreshInCallActions() {
if (mHandler == null) {
mHandler = new Handler();
}
mHandler.post(new Runnable() {
@Override
public void run() {
if (!isVideoActivatedInSettings()) {
video.setEnabled(false);
} else {
if (isVideoEnabled) {
video.setBackgroundResource(R.drawable.video_on);
} else {
video.setBackgroundResource(R.drawable.video_off);
}
}
try {
if (isSpeakerEnabled) {
speaker.setBackgroundResource(R.drawable.speaker_on);
routeSpeaker.setBackgroundResource(R.drawable.route_speaker_on);
routeReceiver.setBackgroundResource(R.drawable.route_receiver_off);
routeBluetooth.setBackgroundResource(R.drawable.route_bluetooth_off);
} else {
speaker.setBackgroundResource(R.drawable.speaker_off);
routeSpeaker.setBackgroundResource(R.drawable.route_speaker_off);
if (LinphoneManager.getInstance().isUsingBluetoothAudioRoute) {
routeReceiver.setBackgroundResource(R.drawable.route_receiver_off);
routeBluetooth.setBackgroundResource(R.drawable.route_bluetooth_on);
} else {
routeReceiver.setBackgroundResource(R.drawable.route_receiver_on);
routeBluetooth.setBackgroundResource(R.drawable.route_bluetooth_off);
}
}
} catch (NullPointerException npe) {
Log.e("Audio routes menu disabled on tablets for now");
}
if (isMicMuted) {
micro.setBackgroundResource(R.drawable.micro_off);
} else {
micro.setBackgroundResource(R.drawable.micro_on);
}
if (LinphoneManager.getLc().getCallsNb() > 1) {
conference.setVisibility(View.VISIBLE);
pause.setVisibility(View.GONE);
} else {
conference.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
List<LinphoneCall> pausedCalls = LinphoneUtils.getCallsInState(LinphoneManager.getLc(), Arrays.asList(State.Paused));
if (pausedCalls.size() == 1) {
pause.setImageResource(R.drawable.pause_on);
} else {
pause.setImageResource(R.drawable.pause_off);
}
}
}
});
}
private void enableAndRefreshInCallActions() {
if (mHandler == null) {
mHandler = new Handler();
}
mHandler.post(new Runnable() {
@Override
public void run() {
addCall.setEnabled(LinphoneManager.getLc().getCallsNb() < LinphoneManager.getLc().getMaxCalls());
transfer.setEnabled(getResources().getBoolean(R.bool.allow_transfers));
options.setEnabled(!getResources().getBoolean(R.bool.disable_options_in_call) && (addCall.isEnabled() || transfer.isEnabled()));
video.setEnabled(true);
micro.setEnabled(true);
speaker.setEnabled(true);
transfer.setEnabled(true);
pause.setEnabled(true);
dialer.setEnabled(true);
conference.setEnabled(true);
refreshInCallActions();
}
});
}
public void updateStatusFragment(StatusFragment statusFragment) {
status = statusFragment;
}
private boolean isVideoActivatedInSettings() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean settingsVideoEnabled = prefs.getBoolean(getString(R.string.pref_video_enable_key), false);
return settingsVideoEnabled;
}
@Override
public void onClick(View v) {
int id = v.getId();
if (isVideoEnabled) {
displayVideoCallControlsIfHidden();
}
if (id == R.id.video) {
isVideoEnabled = !isVideoEnabled;
switchVideo(isVideoEnabled, true);
}
else if (id == R.id.micro) {
toggleMicro();
}
else if (id == R.id.speaker) {
toggleSpeaker();
}
else if (id == R.id.addCall) {
goBackToDialer();
}
else if (id == R.id.pause) {
pauseOrResumeCall();
}
else if (id == R.id.hangUp) {
hangUp();
}
else if (id == R.id.dialer) {
hideOrDisplayNumpad();
}
else if (id == R.id.conference) {
enterConference();
}
else if (id == R.id.switchCamera) {
if (videoCallFragment != null) {
videoCallFragment.switchCamera();
}
}
else if (id == R.id.transfer) {
goBackToDialerAndDisplayTransferButton();
}
else if (id == R.id.options) {
hideOrDisplayCallOptions();
}
else if (id == R.id.audioRoute) {
hideOrDisplayAudioRoutes();
}
else if (id == R.id.routeBluetooth) {
LinphoneManager.getInstance().routeAudioToBluetooth();
isSpeakerEnabled = false;
routeBluetooth.setBackgroundResource(R.drawable.route_bluetooth_on);
routeReceiver.setBackgroundResource(R.drawable.route_receiver_off);
routeSpeaker.setBackgroundResource(R.drawable.route_speaker_off);
hideOrDisplayAudioRoutes();
}
else if (id == R.id.routeReceiver) {
LinphoneManager.getInstance().routeAudioToReceiver();
isSpeakerEnabled = false;
routeBluetooth.setBackgroundResource(R.drawable.route_bluetooth_off);
routeReceiver.setBackgroundResource(R.drawable.route_receiver_on);
routeSpeaker.setBackgroundResource(R.drawable.route_speaker_off);
hideOrDisplayAudioRoutes();
}
else if (id == R.id.routeSpeaker) {
LinphoneManager.getInstance().routeAudioToSpeaker();
isSpeakerEnabled = true;
routeBluetooth.setBackgroundResource(R.drawable.route_bluetooth_off);
routeReceiver.setBackgroundResource(R.drawable.route_receiver_off);
routeSpeaker.setBackgroundResource(R.drawable.route_speaker_on);
hideOrDisplayAudioRoutes();
}
else if (id == R.id.callStatus) {
LinphoneCall call = (LinphoneCall) v.getTag();
pauseOrResumeCall(call);
}
else if (id == R.id.conferenceStatus) {
pauseOrResumeConference();
}
}
public void displayCustomToast(final String message, final int duration) {
mHandler.post(new Runnable() {
@Override
public void run() {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastRoot));
TextView toastText = (TextView) layout.findViewById(R.id.toastMessage);
toastText.setText(message);
final Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(duration);
toast.setView(layout);
toast.show();
}
});
}
private void switchVideo(final boolean displayVideo, final boolean isInitiator) {
final LinphoneCall call = LinphoneManager.getLc().getCalls()[0];
if (call == null) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
if (!displayVideo) {
if (isInitiator) {
LinphoneCallParams params = call.getCurrentParamsCopy();
params.setVideoEnabled(false);
LinphoneManager.getLc().updateCall(call, params);
}
showAudioView();
} else {
if (!call.getRemoteParams().isLowBandwidthEnabled()) {
LinphoneManager.getInstance().addVideo();
showVideoView();
} else {
displayCustomToast(getString(R.string.error_low_bandwidth), Toast.LENGTH_LONG);
}
}
}
});
}
private void showAudioView() {
video.setBackgroundResource(R.drawable.video_on);
LinphoneManager.startProximitySensorForActivity(InCallActivity.this);
replaceFragmentVideoByAudio();
setCallControlsVisibleAndRemoveCallbacks();
}
private void showVideoView() {
isSpeakerEnabled = true;
LinphoneManager.getInstance().routeAudioToSpeaker();
speaker.setBackgroundResource(R.drawable.speaker_on);
video.setBackgroundResource(R.drawable.video_off);
LinphoneManager.stopProximitySensorForActivity(InCallActivity.this);
replaceFragmentAudioByVideo();
displayVideoCallControlsIfHidden();
}
private void replaceFragmentVideoByAudio() {
audioCallFragment = new AudioCallFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, audioCallFragment);
try {
transaction.commitAllowingStateLoss();
} catch (Exception e) {
}
}
private void replaceFragmentAudioByVideo() {
// Hiding controls to let displayVideoCallControlsIfHidden add them plus the callback
mControlsLayout.setVisibility(View.GONE);
switchCamera.setVisibility(View.INVISIBLE);
videoCallFragment = new VideoCallFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, videoCallFragment);
try {
transaction.commitAllowingStateLoss();
} catch (Exception e) {
}
}
private void toggleMicro() {
LinphoneCore lc = LinphoneManager.getLc();
isMicMuted = !isMicMuted;
lc.muteMic(isMicMuted);
if (isMicMuted) {
micro.setBackgroundResource(R.drawable.micro_off);
} else {
micro.setBackgroundResource(R.drawable.micro_on);
}
}
private void toggleSpeaker() {
isSpeakerEnabled = !isSpeakerEnabled;
if (isSpeakerEnabled) {
LinphoneManager.getInstance().routeAudioToSpeaker();
speaker.setBackgroundResource(R.drawable.speaker_on);
LinphoneManager.getLc().enableSpeaker(isSpeakerEnabled);
} else {
LinphoneManager.getInstance().routeAudioToReceiver();
speaker.setBackgroundResource(R.drawable.speaker_off);
}
}
private void pauseOrResumeCall() {
LinphoneCore lc = LinphoneManager.getLc();
LinphoneCall call = lc.getCurrentCall();
pauseOrResumeCall(call);
}
public void pauseOrResumeCall(LinphoneCall call) {
LinphoneCore lc = LinphoneManager.getLc();
if (call != null && LinphoneUtils.isCallRunning(call)) {
if (call.isInConference()) {
lc.removeFromConference(call);
if (lc.getConferenceSize() <= 1) {
lc.leaveConference();
}
} else {
lc.pauseCall(call);
if (isVideoEnabled) {
isVideoCallPaused = true;
showAudioView();
}
pause.setImageResource(R.drawable.pause_on);
}
} else {
List<LinphoneCall> pausedCalls = LinphoneUtils.getCallsInState(lc, Arrays.asList(State.Paused));
if (pausedCalls.size() == 1) {
LinphoneCall callToResume = pausedCalls.get(0);
if ((call != null && callToResume.equals(call)) || call == null) {
lc.resumeCall(callToResume);
if (isVideoCallPaused) {
isVideoCallPaused = false;
showVideoView();
}
pause.setImageResource(R.drawable.pause_off);
}
} else if (call != null) {
lc.resumeCall(call);
if (isVideoCallPaused) {
isVideoCallPaused = false;
showVideoView();
}
pause.setImageResource(R.drawable.pause_off);
}
}
}
private void hangUp() {
LinphoneCore lc = LinphoneManager.getLc();
LinphoneCall currentCall = lc.getCurrentCall();
if (currentCall != null) {
lc.terminateCall(currentCall);
} else if (lc.isInConference()) {
lc.terminateConference();
} else {
lc.terminateAllCalls();
}
}
private void enterConference() {
LinphoneManager.getLc().addAllToConference();
}
public void pauseOrResumeConference() {
LinphoneCore lc = LinphoneManager.getLc();
if (lc.isInConference()) {
lc.leaveConference();
} else {
lc.enterConference();
}
}
public void displayVideoCallControlsIfHidden() {
if (mControlsLayout != null) {
if (mControlsLayout.getVisibility() != View.VISIBLE) {
if (isAnimationDisabled) {
mControlsLayout.setVisibility(View.VISIBLE);
callsList.setVisibility(showCallListInVideo ? View.VISIBLE : View.GONE);
if (cameraNumber > 1) {
switchCamera.setVisibility(View.VISIBLE);
}
} else {
Animation animation = slideInBottomToTop;
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mControlsLayout.setVisibility(View.VISIBLE);
callsList.setVisibility(showCallListInVideo ? View.VISIBLE : View.GONE);
if (cameraNumber > 1) {
switchCamera.setVisibility(View.VISIBLE);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
animation.setAnimationListener(null);
}
});
mControlsLayout.startAnimation(animation);
if (cameraNumber > 1) {
switchCamera.startAnimation(slideInTopToBottom);
}
}
}
resetControlsHidingCallBack();
}
}
public void resetControlsHidingCallBack() {
if (mControlsHandler != null && mControls != null) {
mControlsHandler.removeCallbacks(mControls);
}
mControls = null;
if (isVideoEnabled && mControlsHandler != null) {
mControlsHandler.postDelayed(mControls = new Runnable() {
public void run() {
hideNumpad();
if (isAnimationDisabled) {
transfer.setVisibility(View.INVISIBLE);
addCall.setVisibility(View.INVISIBLE);
mControlsLayout.setVisibility(View.GONE);
callsList.setVisibility(View.GONE);
switchCamera.setVisibility(View.INVISIBLE);
numpad.setVisibility(View.GONE);
options.setBackgroundResource(R.drawable.options);
} else {
Animation animation = slideOutTopToBottom;
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
video.setEnabled(false); // HACK: Used to avoid controls from being hided if video is switched while controls are hiding
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
video.setEnabled(true); // HACK: Used to avoid controls from being hided if video is switched while controls are hiding
transfer.setVisibility(View.INVISIBLE);
addCall.setVisibility(View.INVISIBLE);
mControlsLayout.setVisibility(View.GONE);
callsList.setVisibility(View.GONE);
switchCamera.setVisibility(View.INVISIBLE);
numpad.setVisibility(View.GONE);
options.setBackgroundResource(R.drawable.options);
animation.setAnimationListener(null);
}
});
mControlsLayout.startAnimation(animation);
if (cameraNumber > 1) {
switchCamera.startAnimation(slideOutBottomToTop);
}
}
}
}, SECONDS_BEFORE_HIDING_CONTROLS);
}
}
public void setCallControlsVisibleAndRemoveCallbacks() {
if (mControlsHandler != null && mControls != null) {
mControlsHandler.removeCallbacks(mControls);
}
mControls = null;
mControlsLayout.setVisibility(View.VISIBLE);
callsList.setVisibility(View.VISIBLE);
switchCamera.setVisibility(View.INVISIBLE);
}
private void hideNumpad() {
if (numpad == null || numpad.getVisibility() != View.VISIBLE) {
return;
}
dialer.setImageResource(R.drawable.dialer_alt);
if (isAnimationDisabled) {
numpad.setVisibility(View.GONE);
} else {
Animation animation = slideOutTopToBottom;
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
numpad.setVisibility(View.GONE);
animation.setAnimationListener(null);
}
});
numpad.startAnimation(animation);
}
}
private void hideOrDisplayNumpad() {
if (numpad == null) {
return;
}
if (numpad.getVisibility() == View.VISIBLE) {
hideNumpad();
} else {
dialer.setImageResource(R.drawable.dialer_alt_back);
if (isAnimationDisabled) {
numpad.setVisibility(View.VISIBLE);
} else {
Animation animation = slideInBottomToTop;
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
numpad.setVisibility(View.VISIBLE);
animation.setAnimationListener(null);
}
});
numpad.startAnimation(animation);
}
}
}
private void hideAnimatedPortraitCallOptions() {
Animation animation = slideOutLeftToRight;
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (isTransferAllowed) {
transfer.setVisibility(View.INVISIBLE);
}
addCall.setVisibility(View.INVISIBLE);
animation.setAnimationListener(null);
}
});
if (isTransferAllowed) {
transfer.startAnimation(animation);
}
addCall.startAnimation(animation);
}
private void hideAnimatedLandscapeCallOptions() {
Animation animation = slideOutTopToBottom;
if (isTransferAllowed) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
transfer.setAnimation(null);
transfer.setVisibility(View.INVISIBLE);
animation = AnimationUtils.loadAnimation(InCallActivity.this, R.anim.slide_out_top_to_bottom); // Reload animation to prevent transfer button to blink
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
addCall.setVisibility(View.INVISIBLE);
}
});
addCall.startAnimation(animation);
}
});
transfer.startAnimation(animation);
} else {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
addCall.setVisibility(View.INVISIBLE);
}
});
addCall.startAnimation(animation);
}
}
private void showAnimatedPortraitCallOptions() {
Animation animation = slideInRightToLeft;
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
options.setBackgroundResource(R.drawable.options_alt);
if (isTransferAllowed) {
transfer.setVisibility(View.VISIBLE);
}
addCall.setVisibility(View.VISIBLE);
animation.setAnimationListener(null);
}
});
if (isTransferAllowed) {
transfer.startAnimation(animation);
}
addCall.startAnimation(animation);
}
private void showAnimatedLandscapeCallOptions() {
Animation animation = slideInBottomToTop;
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
addCall.setAnimation(null);
options.setBackgroundResource(R.drawable.options_alt);
addCall.setVisibility(View.VISIBLE);
if (isTransferAllowed) {
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
transfer.setVisibility(View.VISIBLE);
}
});
transfer.startAnimation(animation);
}
}
});
addCall.startAnimation(animation);
}
private void hideOrDisplayAudioRoutes()
{
if (routeSpeaker.getVisibility() == View.VISIBLE) {
routeSpeaker.setVisibility(View.INVISIBLE);
routeBluetooth.setVisibility(View.INVISIBLE);
routeReceiver.setVisibility(View.INVISIBLE);
audioRoute.setSelected(false);
} else {
routeSpeaker.setVisibility(View.VISIBLE);
routeBluetooth.setVisibility(View.VISIBLE);
routeReceiver.setVisibility(View.VISIBLE);
audioRoute.setSelected(true);
}
}
private void hideOrDisplayCallOptions() {
boolean isOrientationLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
if (addCall.getVisibility() == View.VISIBLE) {
options.setBackgroundResource(R.drawable.options);
if (isAnimationDisabled) {
if (isTransferAllowed) {
transfer.setVisibility(View.INVISIBLE);
}
addCall.setVisibility(View.INVISIBLE);
} else {
if (isOrientationLandscape) {
hideAnimatedLandscapeCallOptions();
} else {
hideAnimatedPortraitCallOptions();
}
}
options.setSelected(false);
} else {
if (isAnimationDisabled) {
if (isTransferAllowed) {
transfer.setVisibility(View.VISIBLE);
}
addCall.setVisibility(View.VISIBLE);
options.setBackgroundResource(R.drawable.options_alt);
} else {
if (isOrientationLandscape) {
showAnimatedLandscapeCallOptions();
} else {
showAnimatedPortraitCallOptions();
}
}
options.setSelected(true);
transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null);
}
}
public void goBackToDialer() {
Intent intent = new Intent();
intent.putExtra("Transfer", false);
setResult(Activity.RESULT_FIRST_USER, intent);
finish();
}
private void goBackToDialerAndDisplayTransferButton() {
Intent intent = new Intent();
intent.putExtra("Transfer", true);
setResult(Activity.RESULT_FIRST_USER, intent);
finish();
}
private void acceptCallUpdate(boolean accept) {
if (timer != null) {
timer.cancel();
}
if (callUpdateDialog != null) {
callUpdateDialog.dismissAllowingStateLoss();
}
LinphoneCall call = LinphoneManager.getLc().getCurrentCall();
if (call == null) {
return;
}
LinphoneCallParams params = call.getCurrentParamsCopy();
if (accept) {
params.setVideoEnabled(true);
LinphoneManager.getLc().enableVideo(true, true);
}
try {
LinphoneManager.getLc().acceptCallUpdate(call, params);
} catch (LinphoneCoreException e) {
e.printStackTrace();
}
}
public void startIncomingCallActivity() {
startActivity(new Intent(this, IncomingCallActivity.class));
}
@Override
public void onCallStateChanged(final LinphoneCall call, State state, String message) {
if (LinphoneManager.getLc().getCallsNb() == 0) {
finish();
return;
}
if (state == State.IncomingReceived) {
startIncomingCallActivity();
return;
}
if (state == State.StreamsRunning) {
boolean isVideoEnabledInCall = call.getCurrentParamsCopy().getVideoEnabled();
if (isVideoEnabledInCall != isVideoEnabled) {
isVideoEnabled = isVideoEnabledInCall;
switchVideo(isVideoEnabled, false);
}
LinphoneManager.getLc().enableSpeaker(isSpeakerEnabled);
isMicMuted = LinphoneManager.getLc().isMicMuted();
enableAndRefreshInCallActions();
if (status != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
status.refreshStatusItems(call, isVideoEnabled);
}
});
}
}
refreshInCallActions();
mHandler.post(new Runnable() {
@Override
public void run() {
refreshCallList(getResources());
}
});
if (state == State.CallUpdatedByRemote) {
// If the correspondent proposes video while audio call
boolean isVideoEnabled = LinphoneManager.getInstance().isVideoEnabled();
if (!isVideoEnabled) {
acceptCallUpdate(false);
return;
}
boolean remoteVideo = call.getRemoteParams().getVideoEnabled();
boolean localVideo = call.getCurrentParamsCopy().getVideoEnabled();
boolean autoAcceptCameraPolicy = LinphoneManager.getInstance().isAutoAcceptCamera();
if (remoteVideo && !localVideo && !autoAcceptCameraPolicy && !LinphoneManager.getLc().isInConference()) {
mHandler.post(new Runnable() {
public void run() {
showAcceptCallUpdateDialog();
timer = new CountDownTimer(SECONDS_BEFORE_DENYING_CALL_UPDATE, 1000) {
public void onTick(long millisUntilFinished) { }
public void onFinish() {
acceptCallUpdate(false);
}
}.start();
}
});
}
// else if (remoteVideo && !LinphoneManager.getLc().isInConference() && autoAcceptCameraPolicy) {
// mHandler.post(new Runnable() {
// @Override
// public void run() {
// acceptCallUpdate(true);
// }
// });
// }
}
mHandler.post(new Runnable() {
public void run() {
transfer.setEnabled(LinphoneManager.getLc().getCurrentCall() != null);
}
});
}
private void showAcceptCallUpdateDialog() {
FragmentManager fm = getSupportFragmentManager();
callUpdateDialog = new AcceptCallUpdateDialog();
callUpdateDialog.show(fm, "Accept Call Update Dialog");
}
@Override
public void onCallEncryptionChanged(final LinphoneCall call, boolean encrypted, String authenticationToken) {
if (status != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
status.refreshStatusItems(call, call.getCurrentParamsCopy().getVideoEnabled());
}
});
}
}
@Override
protected void onResume() {
instance = this;
if (isVideoEnabled) {
displayVideoCallControlsIfHidden();
} else {
LinphoneManager.startProximitySensorForActivity(this);
setCallControlsVisibleAndRemoveCallbacks();
}
super.onResume();
LinphoneManager.addListener(this);
refreshCallList(getResources());
}
@Override
protected void onPause() {
super.onPause();
if (mControlsHandler != null && mControls != null) {
mControlsHandler.removeCallbacks(mControls);
}
mControls = null;
if (!isVideoEnabled) {
LinphoneManager.stopProximitySensorForActivity(this);
}
LinphoneManager.removeListener(this);
}
@Override
protected void onDestroy() {
if (mControlsHandler != null && mControls != null) {
mControlsHandler.removeCallbacks(mControls);
}
mControls = null;
mControlsHandler = null;
mHandler = null;
unbindDrawables(findViewById(R.id.topLayout));
instance = null;
super.onDestroy();
System.gc();
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ImageView) {
view.setOnClickListener(null);
}
if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (LinphoneUtils.onKeyVolumeAdjust(keyCode)) return true;
if (LinphoneUtils.onKeyBackGoHome(this, keyCode, event)) return true;
return super.onKeyDown(keyCode, event);
}
public void bindAudioFragment(AudioCallFragment fragment) {
audioCallFragment = fragment;
}
public void bindVideoFragment(VideoCallFragment fragment) {
videoCallFragment = fragment;
}
@SuppressLint("ValidFragment")
class AcceptCallUpdateDialog extends DialogFragment {
public AcceptCallUpdateDialog() {
// Empty constructor required for DialogFragment
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.accept_call_update_dialog, container);
getDialog().setTitle(R.string.call_update_title);
Button yes = (Button) view.findViewById(R.id.yes);
yes.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Call Update Accepted");
acceptCallUpdate(true);
}
});
Button no = (Button) view.findViewById(R.id.no);
no.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Call Update Denied");
acceptCallUpdate(false);
}
});
return view;
}
}
private void displayConferenceHeader() {
LinearLayout conferenceHeader = (LinearLayout) inflater.inflate(R.layout.conference_header, container, false);
ImageView conferenceState = (ImageView) conferenceHeader.findViewById(R.id.conferenceStatus);
conferenceState.setOnClickListener(this);
if (LinphoneManager.getLc().isInConference()) {
conferenceState.setImageResource(R.drawable.play);
} else {
conferenceState.setImageResource(R.drawable.pause);
}
callsList.addView(conferenceHeader);
}
private void displayCall(Resources resources, LinphoneCall call, int index) {
String sipUri = call.getRemoteAddress().asStringUriOnly();
LinphoneAddress lAddress = LinphoneCoreFactory.instance().createLinphoneAddress(sipUri);
// Control Row
LinearLayout callView = (LinearLayout) inflater.inflate(R.layout.active_call_control_row, container, false);
setContactName(callView, lAddress, sipUri, resources);
displayCallStatusIconAndReturnCallPaused(callView, call);
setRowBackground(callView, index);
registerCallDurationTimer(callView, call);
callsList.addView(callView);
// Image Row
LinearLayout imageView = (LinearLayout) inflater.inflate(R.layout.active_call_image_row, container, false);
Uri pictureUri = LinphoneUtils.findUriPictureOfContactAndSetDisplayName(lAddress, imageView.getContext().getContentResolver());
displayOrHideContactPicture(imageView, pictureUri, false);
callsList.addView(imageView);
callView.setTag(imageView);
callView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (v.getTag() != null) {
View imageView = (View) v.getTag();
if (imageView.getVisibility() == View.VISIBLE)
imageView.setVisibility(View.GONE);
else
imageView.setVisibility(View.VISIBLE);
callsList.invalidate();
}
}
});
}
private void setContactName(LinearLayout callView, LinphoneAddress lAddress, String sipUri, Resources resources) {
TextView contact = (TextView) callView.findViewById(R.id.contactNameOrNumber);
LinphoneUtils.findUriPictureOfContactAndSetDisplayName(lAddress, callView.getContext().getContentResolver());
String displayName = lAddress.getDisplayName();
if (displayName == null) {
if (resources.getBoolean(R.bool.only_display_username_if_unknown) && LinphoneUtils.isSipAddress(sipUri)) {
contact.setText(LinphoneUtils.getUsernameFromAddress(sipUri));
} else {
contact.setText(sipUri);
}
} else {
contact.setText(displayName);
}
}
private boolean displayCallStatusIconAndReturnCallPaused(LinearLayout callView, LinphoneCall call) {
boolean isCallPaused, isInConference;
ImageView callState = (ImageView) callView.findViewById(R.id.callStatus);
callState.setTag(call);
callState.setOnClickListener(this);
if (call.getState() == State.Paused || call.getState() == State.PausedByRemote || call.getState() == State.Pausing) {
callState.setImageResource(R.drawable.pause);
isCallPaused = true;
isInConference = false;
} else if (call.getState() == State.OutgoingInit || call.getState() == State.OutgoingProgress || call.getState() == State.OutgoingRinging) {
callState.setImageResource(R.drawable.call_state_ringing_default);
isCallPaused = false;
isInConference = false;
} else {
if (isConferenceRunning && call.isInConference()) {
callState.setImageResource(R.drawable.remove);
isInConference = true;
} else {
callState.setImageResource(R.drawable.play);
isInConference = false;
}
isCallPaused = false;
}
return isCallPaused || isInConference;
}
private void displayOrHideContactPicture(LinearLayout callView, Uri pictureUri, boolean hide) {
AvatarWithShadow contactPicture = (AvatarWithShadow) callView.findViewById(R.id.contactPicture);
if (pictureUri != null) {
LinphoneUtils.setImagePictureFromUri(callView.getContext(), contactPicture.getView(), Uri.parse(pictureUri.toString()), R.drawable.unknown_small);
}
callView.setVisibility(hide ? View.GONE : View.VISIBLE);
}
private void setRowBackground(LinearLayout callView, int index) {
int backgroundResource;
if (index == 0) {
// backgroundResource = active ? R.drawable.cell_call_first_highlight : R.drawable.cell_call_first;
backgroundResource = R.drawable.cell_call_first;
} else {
// backgroundResource = active ? R.drawable.cell_call_highlight : R.drawable.cell_call;
backgroundResource = R.drawable.cell_call;
}
callView.setBackgroundResource(backgroundResource);
}
private void registerCallDurationTimer(View v, LinphoneCall call) {
int callDuration = call.getDuration();
if (callDuration == 0 && call.getState() != State.StreamsRunning) {
return;
}
Chronometer timer = (Chronometer) v.findViewById(R.id.callTimer);
if (timer == null) {
throw new IllegalArgumentException("no callee_duration view found");
}
timer.setBase(SystemClock.elapsedRealtime() - 1000 * callDuration);
timer.start();
}
public void refreshCallList(Resources resources) {
if (callsList == null) {
return;
}
callsList.removeAllViews();
int index = 0;
if (LinphoneManager.getLc().getCallsNb() == 0) {
goBackToDialer();
return;
}
isConferenceRunning = LinphoneManager.getLc().getConferenceSize() > 1;
if (isConferenceRunning) {
displayConferenceHeader();
index++;
}
for (LinphoneCall call : LinphoneManager.getLc().getCalls()) {
displayCall(resources, call, index);
index++;
}
callsList.invalidate();
}
}
| false | true | private void initUI() {
inflater = LayoutInflater.from(this);
container = (ViewGroup) findViewById(R.id.topLayout);
callsList = (TableLayout) findViewById(R.id.calls);
if (!showCallListInVideo) {
callsList.setVisibility(View.GONE);
}
video = (TextView) findViewById(R.id.video);
video.setOnClickListener(this);
video.setEnabled(false);
micro = (TextView) findViewById(R.id.micro);
micro.setOnClickListener(this);
// micro.setEnabled(false);
speaker = (TextView) findViewById(R.id.speaker);
speaker.setOnClickListener(this);
// speaker.setEnabled(false);
addCall = (TextView) findViewById(R.id.addCall);
addCall.setOnClickListener(this);
addCall.setEnabled(false);
transfer = (TextView) findViewById(R.id.transfer);
transfer.setOnClickListener(this);
transfer.setEnabled(false);
options = (TextView) findViewById(R.id.options);
options.setOnClickListener(this);
options.setEnabled(false);
pause = (ImageView) findViewById(R.id.pause);
pause.setOnClickListener(this);
pause.setEnabled(false);
hangUp = (ImageView) findViewById(R.id.hangUp);
hangUp.setOnClickListener(this);
conference = (ImageView) findViewById(R.id.conference);
conference.setOnClickListener(this);
dialer = (ImageView) findViewById(R.id.dialer);
dialer.setOnClickListener(this);
dialer.setEnabled(false);
numpad = (Numpad) findViewById(R.id.numpad);
try {
routeLayout = (LinearLayout) findViewById(R.id.routesLayout);
audioRoute = (TextView) findViewById(R.id.audioRoute);
audioRoute.setOnClickListener(this);
routeSpeaker = (TextView) findViewById(R.id.routeSpeaker);
routeSpeaker.setOnClickListener(this);
routeReceiver = (TextView) findViewById(R.id.routeReceiver);
routeReceiver.setOnClickListener(this);
routeBluetooth = (TextView) findViewById(R.id.routeBluetooth);
routeBluetooth.setOnClickListener(this);
} catch (NullPointerException npe) {
Log.e("Audio routes menu disabled on tablets for now");
}
switchCamera = (ImageView) findViewById(R.id.switchCamera);
switchCamera.setOnClickListener(this);
mControlsLayout = (ViewGroup) findViewById(R.id.menu);
if (!isTransferAllowed) {
addCall.setBackgroundResource(R.drawable.options_add_call);
}
if (!isAnimationDisabled) {
slideInRightToLeft = AnimationUtils.loadAnimation(this, R.anim.slide_in_right_to_left);
slideOutLeftToRight = AnimationUtils.loadAnimation(this, R.anim.slide_out_left_to_right);
slideInBottomToTop = AnimationUtils.loadAnimation(this, R.anim.slide_in_bottom_to_top);
slideInTopToBottom = AnimationUtils.loadAnimation(this, R.anim.slide_in_top_to_bottom);
slideOutBottomToTop = AnimationUtils.loadAnimation(this, R.anim.slide_out_bottom_to_top);
slideOutTopToBottom = AnimationUtils.loadAnimation(this, R.anim.slide_out_top_to_bottom);
}
if (LinphoneManager.getInstance().isBluetoothScoConnected) {
try {
routeLayout.setVisibility(View.VISIBLE);
} catch (NullPointerException npe) {}
audioRoute.setVisibility(View.VISIBLE);
speaker.setVisibility(View.GONE);
} else {
try {
routeLayout.setVisibility(View.GONE);
} catch (NullPointerException npe) {}
audioRoute.setVisibility(View.GONE);
speaker.setVisibility(View.VISIBLE);
}
}
| private void initUI() {
inflater = LayoutInflater.from(this);
container = (ViewGroup) findViewById(R.id.topLayout);
callsList = (TableLayout) findViewById(R.id.calls);
if (!showCallListInVideo) {
callsList.setVisibility(View.GONE);
}
video = (TextView) findViewById(R.id.video);
video.setOnClickListener(this);
video.setEnabled(false);
micro = (TextView) findViewById(R.id.micro);
micro.setOnClickListener(this);
// micro.setEnabled(false);
speaker = (TextView) findViewById(R.id.speaker);
speaker.setOnClickListener(this);
// speaker.setEnabled(false);
addCall = (TextView) findViewById(R.id.addCall);
addCall.setOnClickListener(this);
addCall.setEnabled(false);
transfer = (TextView) findViewById(R.id.transfer);
transfer.setOnClickListener(this);
transfer.setEnabled(false);
options = (TextView) findViewById(R.id.options);
options.setOnClickListener(this);
options.setEnabled(false);
pause = (ImageView) findViewById(R.id.pause);
pause.setOnClickListener(this);
pause.setEnabled(false);
hangUp = (ImageView) findViewById(R.id.hangUp);
hangUp.setOnClickListener(this);
conference = (ImageView) findViewById(R.id.conference);
conference.setOnClickListener(this);
dialer = (ImageView) findViewById(R.id.dialer);
dialer.setOnClickListener(this);
dialer.setEnabled(false);
numpad = (Numpad) findViewById(R.id.numpad);
try {
routeLayout = (LinearLayout) findViewById(R.id.routesLayout);
audioRoute = (TextView) findViewById(R.id.audioRoute);
audioRoute.setOnClickListener(this);
routeSpeaker = (TextView) findViewById(R.id.routeSpeaker);
routeSpeaker.setOnClickListener(this);
routeReceiver = (TextView) findViewById(R.id.routeReceiver);
routeReceiver.setOnClickListener(this);
routeBluetooth = (TextView) findViewById(R.id.routeBluetooth);
routeBluetooth.setOnClickListener(this);
} catch (NullPointerException npe) {
Log.e("Audio routes menu disabled on tablets for now");
}
switchCamera = (ImageView) findViewById(R.id.switchCamera);
switchCamera.setOnClickListener(this);
mControlsLayout = (ViewGroup) findViewById(R.id.menu);
if (!isTransferAllowed) {
addCall.setBackgroundResource(R.drawable.options_add_call);
}
if (!isAnimationDisabled) {
slideInRightToLeft = AnimationUtils.loadAnimation(this, R.anim.slide_in_right_to_left);
slideOutLeftToRight = AnimationUtils.loadAnimation(this, R.anim.slide_out_left_to_right);
slideInBottomToTop = AnimationUtils.loadAnimation(this, R.anim.slide_in_bottom_to_top);
slideInTopToBottom = AnimationUtils.loadAnimation(this, R.anim.slide_in_top_to_bottom);
slideOutBottomToTop = AnimationUtils.loadAnimation(this, R.anim.slide_out_bottom_to_top);
slideOutTopToBottom = AnimationUtils.loadAnimation(this, R.anim.slide_out_top_to_bottom);
}
if (LinphoneManager.getInstance().isBluetoothScoConnected) {
try {
routeLayout.setVisibility(View.VISIBLE);
audioRoute.setVisibility(View.VISIBLE);
speaker.setVisibility(View.GONE);
} catch (NullPointerException npe) {}
} else {
try {
routeLayout.setVisibility(View.GONE);
audioRoute.setVisibility(View.GONE);
speaker.setVisibility(View.VISIBLE);
} catch (NullPointerException npe) {}
}
}
|
diff --git a/src/com/android/phone/BluetoothAtPhonebook.java b/src/com/android/phone/BluetoothAtPhonebook.java
index 55072ed0..5bac1228 100644
--- a/src/com/android/phone/BluetoothAtPhonebook.java
+++ b/src/com/android/phone/BluetoothAtPhonebook.java
@@ -1,419 +1,420 @@
/*
* 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.phone;
import android.bluetooth.AtCommandHandler;
import android.bluetooth.AtCommandResult;
import android.bluetooth.AtParser;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
/**
* Helper for managing phonebook presentation over AT commands
* @hide
*/
public class BluetoothAtPhonebook {
private static final String TAG = "BtAtPhonebook";
private static final boolean DBG = false;
/** The projection to use when querying the call log database in response
* to AT+CPBR for the MC, RC, and DC phone books (missed, received, and
* dialed calls respectively)
*/
private static final String[] CALLS_PROJECTION = new String[] {
Calls._ID, Calls.NUMBER
};
/** The projection to use when querying the contacts database in response
* to AT+CPBR for the ME phonebook (saved phone numbers).
*/
private static final String[] PHONES_PROJECTION = new String[] {
Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone.TYPE
};
/** Android supports as many phonebook entries as the flash can hold, but
* BT periphals don't. Limit the number we'll report. */
private static final int MAX_PHONEBOOK_SIZE = 16384;
private static final String OUTGOING_CALL_WHERE = Calls.TYPE + "=" + Calls.OUTGOING_TYPE;
private static final String INCOMING_CALL_WHERE = Calls.TYPE + "=" + Calls.INCOMING_TYPE;
private static final String MISSED_CALL_WHERE = Calls.TYPE + "=" + Calls.MISSED_TYPE;
private static final String VISIBLE_PHONEBOOK_WHERE = Phone.IN_VISIBLE_GROUP + "=1";
private class PhonebookResult {
public Cursor cursor; // result set of last query
public int numberColumn;
public int typeColumn;
public int nameColumn;
};
private final Context mContext;
private final BluetoothHandsfree mHandsfree;
private String mCurrentPhonebook;
private final HashMap<String, PhonebookResult> mPhonebooks =
new HashMap<String, PhonebookResult>(4);
public BluetoothAtPhonebook(Context context, BluetoothHandsfree handsfree) {
mContext = context;
mHandsfree = handsfree;
mPhonebooks.put("DC", new PhonebookResult()); // dialled calls
mPhonebooks.put("RC", new PhonebookResult()); // received calls
mPhonebooks.put("MC", new PhonebookResult()); // missed calls
mPhonebooks.put("ME", new PhonebookResult()); // mobile phonebook
mCurrentPhonebook = "ME"; // default to mobile phonebook
}
/** Returns the last dialled number, or null if no numbers have been called */
public String getLastDialledNumber() {
String[] projection = {Calls.NUMBER};
Cursor cursor = mContext.getContentResolver().query(Calls.CONTENT_URI, projection,
Calls.TYPE + "=" + Calls.OUTGOING_TYPE, null, Calls.DEFAULT_SORT_ORDER +
" LIMIT 1");
if (cursor.getCount() < 1) {
cursor.close();
return null;
}
cursor.moveToNext();
int column = cursor.getColumnIndexOrThrow(Calls.NUMBER);
String number = cursor.getString(column);
cursor.close();
return number;
}
public void register(AtParser parser) {
// Select Character Set
// Always send UTF-8, but pretend to support IRA and GSM for compatability
// TODO: Implement IRA and GSM encoding instead of faking it
parser.register("+CSCS", new AtCommandHandler() {
@Override
public AtCommandResult handleReadCommand() {
return new AtCommandResult("+CSCS: \"UTF-8\"");
}
@Override
public AtCommandResult handleSetCommand(Object[] args) {
if (args.length < 1) {
return new AtCommandResult(AtCommandResult.ERROR);
}
if (((String)args[0]).equals("\"GSM\"") || ((String)args[0]).equals("\"IRA\"") ||
((String)args[0]).equals("\"UTF-8\"") ||
((String)args[0]).equals("\"UTF8\"") ) {
return new AtCommandResult(AtCommandResult.OK);
} else {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
}
}
@Override
public AtCommandResult handleTestCommand() {
return new AtCommandResult( "+CSCS: (\"UTF-8\",\"IRA\",\"GSM\")");
}
});
// Select PhoneBook memory Storage
parser.register("+CPBS", new AtCommandHandler() {
@Override
public AtCommandResult handleReadCommand() {
// Return current size and max size
if ("SM".equals(mCurrentPhonebook)) {
return new AtCommandResult("+CPBS: \"SM\",0," + getMaxPhoneBookSize(0));
}
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, true);
if (pbr == null) {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
}
int size = pbr.cursor.getCount();
return new AtCommandResult("+CPBS: \"" + mCurrentPhonebook + "\"," +
size + "," + getMaxPhoneBookSize(size));
}
@Override
public AtCommandResult handleSetCommand(Object[] args) {
// Select phonebook memory
if (args.length < 1 || !(args[0] instanceof String)) {
return new AtCommandResult(AtCommandResult.ERROR);
}
String pb = ((String)args[0]).trim();
while (pb.endsWith("\"")) pb = pb.substring(0, pb.length() - 1);
while (pb.startsWith("\"")) pb = pb.substring(1, pb.length());
if (getPhonebookResult(pb, false) == null && !"SM".equals(pb)) {
if (DBG) log("Dont know phonebook: '" + pb + "'");
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
}
mCurrentPhonebook = pb;
return new AtCommandResult(AtCommandResult.OK);
}
@Override
public AtCommandResult handleTestCommand() {
return new AtCommandResult("+CPBS: (\"ME\",\"SM\",\"DC\",\"RC\",\"MC\")");
}
});
// Read PhoneBook Entries
parser.register("+CPBR", new AtCommandHandler() {
@Override
public AtCommandResult handleSetCommand(Object[] args) {
// Phone Book Read Request
// AT+CPBR=<index1>[,<index2>]
// Parse indexes
int index1;
int index2;
if (args.length < 1 || !(args[0] instanceof Integer)) {
return new AtCommandResult(AtCommandResult.ERROR);
} else {
index1 = (Integer)args[0];
}
if (args.length == 1) {
index2 = index1;
} else if (!(args[1] instanceof Integer)) {
return mHandsfree.reportCmeError(BluetoothCmeError.TEXT_HAS_INVALID_CHARS);
} else {
index2 = (Integer)args[1];
}
// Shortcut SM phonebook
if ("SM".equals(mCurrentPhonebook)) {
return new AtCommandResult(AtCommandResult.OK);
}
// Check phonebook
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, false);
if (pbr == null) {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
}
// More sanity checks
// Send OK instead of ERROR if these checks fail.
// When we send error, certain kits like BMW disconnect the
// Handsfree connection.
if (pbr.cursor.getCount() == 0 || index1 <= 0 || index2 < index1 ||
index2 > pbr.cursor.getCount() || index1 > pbr.cursor.getCount()) {
return new AtCommandResult(AtCommandResult.OK);
}
// Process
AtCommandResult result = new AtCommandResult(AtCommandResult.OK);
int errorDetected = -1; // no error
pbr.cursor.moveToPosition(index1 - 1);
for (int index = index1; index <= index2; index++) {
String number = pbr.cursor.getString(pbr.numberColumn);
String name = null;
int type = -1;
if (pbr.nameColumn == -1) {
// try caller id lookup
// TODO: This code is horribly inefficient. I saw it
// take 7 seconds to process 100 missed calls.
Cursor c = mContext.getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.TYPE},
null, null, null);
if (c != null) {
if (c.moveToFirst()) {
name = c.getString(0);
type = c.getInt(1);
}
c.close();
}
if (DBG && name == null) log("Caller ID lookup failed for " + number);
} else {
name = pbr.cursor.getString(pbr.nameColumn);
}
if (name == null) name = "";
name = name.trim();
if (name.length() > 28) name = name.substring(0, 28);
if (pbr.typeColumn != -1) {
type = pbr.cursor.getInt(pbr.typeColumn);
name = name + "/" + getPhoneType(type);
}
+ if (number == null) number = "";
int regionType = PhoneNumberUtils.toaFromString(number);
number = number.trim();
number = PhoneNumberUtils.stripSeparators(number);
if (number.length() > 30) number = number.substring(0, 30);
if (number.equals("-1")) {
// unknown numbers are stored as -1 in our database
number = "";
name = "unknown";
}
result.addResponse("+CPBR: " + index + ",\"" + number + "\"," +
regionType + ",\"" + name + "\"");
if (!pbr.cursor.moveToNext()) {
break;
}
}
return result;
}
@Override
public AtCommandResult handleTestCommand() {
/* Ideally we should return the maximum range of valid index's
* for the selected phone book, but this causes problems for the
* Parrot CK3300. So instead send just the range of currently
* valid index's.
*/
int size;
if ("SM".equals(mCurrentPhonebook)) {
size = 0;
} else {
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, false);
if (pbr == null) {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
}
size = pbr.cursor.getCount();
}
if (size == 0) {
/* Sending "+CPBR: (1-0)" can confused some carkits, send "1-1"
* instead */
size = 1;
}
return new AtCommandResult("+CPBR: (1-" + size + "),30,30");
}
});
}
/** Get the most recent result for the given phone book,
* with the cursor ready to go.
* If force then re-query that phonebook
* Returns null if the cursor is not ready
*/
private synchronized PhonebookResult getPhonebookResult(String pb, boolean force) {
if (pb == null) {
return null;
}
PhonebookResult pbr = mPhonebooks.get(pb);
if (pbr == null) {
pbr = new PhonebookResult();
}
if (force || pbr.cursor == null) {
if (!queryPhonebook(pb, pbr)) {
return null;
}
}
if (pbr.cursor == null) {
return null;
}
return pbr;
}
private synchronized boolean queryPhonebook(String pb, PhonebookResult pbr) {
String where;
boolean ancillaryPhonebook = true;
if (pb.equals("ME")) {
ancillaryPhonebook = false;
where = VISIBLE_PHONEBOOK_WHERE;
} else if (pb.equals("DC")) {
where = OUTGOING_CALL_WHERE;
} else if (pb.equals("RC")) {
where = INCOMING_CALL_WHERE;
} else if (pb.equals("MC")) {
where = MISSED_CALL_WHERE;
} else {
return false;
}
if (pbr.cursor != null) {
pbr.cursor.close();
pbr.cursor = null;
}
if (ancillaryPhonebook) {
pbr.cursor = mContext.getContentResolver().query(
Calls.CONTENT_URI, CALLS_PROJECTION, where, null,
Calls.DEFAULT_SORT_ORDER + " LIMIT " + MAX_PHONEBOOK_SIZE);
pbr.numberColumn = pbr.cursor.getColumnIndexOrThrow(Calls.NUMBER);
pbr.typeColumn = -1;
pbr.nameColumn = -1;
} else {
// Pass in the package name of the Bluetooth PBAB support so that this
// AT phonebook support uses the same access rights as the PBAB code.
Uri uri = Phone.CONTENT_URI.buildUpon()
.appendQueryParameter(ContactsContract.REQUESTING_PACKAGE_PARAM_KEY,
"com.android.bluetooth")
.build();
pbr.cursor = mContext.getContentResolver().query(uri, PHONES_PROJECTION, where, null,
Phone.NUMBER + " LIMIT " + MAX_PHONEBOOK_SIZE);
pbr.numberColumn = pbr.cursor.getColumnIndex(Phone.NUMBER);
pbr.typeColumn = pbr.cursor.getColumnIndex(Phone.TYPE);
pbr.nameColumn = pbr.cursor.getColumnIndex(Phone.DISPLAY_NAME);
}
Log.i(TAG, "Refreshed phonebook " + pb + " with " + pbr.cursor.getCount() + " results");
return true;
}
private synchronized int getMaxPhoneBookSize(int currSize) {
// some car kits ignore the current size and request max phone book
// size entries. Thus, it takes a long time to transfer all the
// entries. Use a heuristic to calculate the max phone book size
// considering future expansion.
// maxSize = currSize + currSize / 2 rounded up to nearest power of 2
// If currSize < 100, use 100 as the currSize
int maxSize = (currSize < 100) ? 100 : currSize;
maxSize += maxSize / 2;
return roundUpToPowerOfTwo(maxSize);
}
private int roundUpToPowerOfTwo(int x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
private static String getPhoneType(int type) {
switch (type) {
case Phone.TYPE_HOME:
return "H";
case Phone.TYPE_MOBILE:
return "M";
case Phone.TYPE_WORK:
return "W";
case Phone.TYPE_FAX_HOME:
case Phone.TYPE_FAX_WORK:
return "F";
case Phone.TYPE_OTHER:
case Phone.TYPE_CUSTOM:
default:
return "O";
}
}
private static void log(String msg) {
Log.d(TAG, msg);
}
}
| true | true | public void register(AtParser parser) {
// Select Character Set
// Always send UTF-8, but pretend to support IRA and GSM for compatability
// TODO: Implement IRA and GSM encoding instead of faking it
parser.register("+CSCS", new AtCommandHandler() {
@Override
public AtCommandResult handleReadCommand() {
return new AtCommandResult("+CSCS: \"UTF-8\"");
}
@Override
public AtCommandResult handleSetCommand(Object[] args) {
if (args.length < 1) {
return new AtCommandResult(AtCommandResult.ERROR);
}
if (((String)args[0]).equals("\"GSM\"") || ((String)args[0]).equals("\"IRA\"") ||
((String)args[0]).equals("\"UTF-8\"") ||
((String)args[0]).equals("\"UTF8\"") ) {
return new AtCommandResult(AtCommandResult.OK);
} else {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
}
}
@Override
public AtCommandResult handleTestCommand() {
return new AtCommandResult( "+CSCS: (\"UTF-8\",\"IRA\",\"GSM\")");
}
});
// Select PhoneBook memory Storage
parser.register("+CPBS", new AtCommandHandler() {
@Override
public AtCommandResult handleReadCommand() {
// Return current size and max size
if ("SM".equals(mCurrentPhonebook)) {
return new AtCommandResult("+CPBS: \"SM\",0," + getMaxPhoneBookSize(0));
}
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, true);
if (pbr == null) {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
}
int size = pbr.cursor.getCount();
return new AtCommandResult("+CPBS: \"" + mCurrentPhonebook + "\"," +
size + "," + getMaxPhoneBookSize(size));
}
@Override
public AtCommandResult handleSetCommand(Object[] args) {
// Select phonebook memory
if (args.length < 1 || !(args[0] instanceof String)) {
return new AtCommandResult(AtCommandResult.ERROR);
}
String pb = ((String)args[0]).trim();
while (pb.endsWith("\"")) pb = pb.substring(0, pb.length() - 1);
while (pb.startsWith("\"")) pb = pb.substring(1, pb.length());
if (getPhonebookResult(pb, false) == null && !"SM".equals(pb)) {
if (DBG) log("Dont know phonebook: '" + pb + "'");
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
}
mCurrentPhonebook = pb;
return new AtCommandResult(AtCommandResult.OK);
}
@Override
public AtCommandResult handleTestCommand() {
return new AtCommandResult("+CPBS: (\"ME\",\"SM\",\"DC\",\"RC\",\"MC\")");
}
});
// Read PhoneBook Entries
parser.register("+CPBR", new AtCommandHandler() {
@Override
public AtCommandResult handleSetCommand(Object[] args) {
// Phone Book Read Request
// AT+CPBR=<index1>[,<index2>]
// Parse indexes
int index1;
int index2;
if (args.length < 1 || !(args[0] instanceof Integer)) {
return new AtCommandResult(AtCommandResult.ERROR);
} else {
index1 = (Integer)args[0];
}
if (args.length == 1) {
index2 = index1;
} else if (!(args[1] instanceof Integer)) {
return mHandsfree.reportCmeError(BluetoothCmeError.TEXT_HAS_INVALID_CHARS);
} else {
index2 = (Integer)args[1];
}
// Shortcut SM phonebook
if ("SM".equals(mCurrentPhonebook)) {
return new AtCommandResult(AtCommandResult.OK);
}
// Check phonebook
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, false);
if (pbr == null) {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
}
// More sanity checks
// Send OK instead of ERROR if these checks fail.
// When we send error, certain kits like BMW disconnect the
// Handsfree connection.
if (pbr.cursor.getCount() == 0 || index1 <= 0 || index2 < index1 ||
index2 > pbr.cursor.getCount() || index1 > pbr.cursor.getCount()) {
return new AtCommandResult(AtCommandResult.OK);
}
// Process
AtCommandResult result = new AtCommandResult(AtCommandResult.OK);
int errorDetected = -1; // no error
pbr.cursor.moveToPosition(index1 - 1);
for (int index = index1; index <= index2; index++) {
String number = pbr.cursor.getString(pbr.numberColumn);
String name = null;
int type = -1;
if (pbr.nameColumn == -1) {
// try caller id lookup
// TODO: This code is horribly inefficient. I saw it
// take 7 seconds to process 100 missed calls.
Cursor c = mContext.getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.TYPE},
null, null, null);
if (c != null) {
if (c.moveToFirst()) {
name = c.getString(0);
type = c.getInt(1);
}
c.close();
}
if (DBG && name == null) log("Caller ID lookup failed for " + number);
} else {
name = pbr.cursor.getString(pbr.nameColumn);
}
if (name == null) name = "";
name = name.trim();
if (name.length() > 28) name = name.substring(0, 28);
if (pbr.typeColumn != -1) {
type = pbr.cursor.getInt(pbr.typeColumn);
name = name + "/" + getPhoneType(type);
}
int regionType = PhoneNumberUtils.toaFromString(number);
number = number.trim();
number = PhoneNumberUtils.stripSeparators(number);
if (number.length() > 30) number = number.substring(0, 30);
if (number.equals("-1")) {
// unknown numbers are stored as -1 in our database
number = "";
name = "unknown";
}
result.addResponse("+CPBR: " + index + ",\"" + number + "\"," +
regionType + ",\"" + name + "\"");
if (!pbr.cursor.moveToNext()) {
break;
}
}
return result;
}
@Override
public AtCommandResult handleTestCommand() {
/* Ideally we should return the maximum range of valid index's
* for the selected phone book, but this causes problems for the
* Parrot CK3300. So instead send just the range of currently
* valid index's.
*/
int size;
if ("SM".equals(mCurrentPhonebook)) {
size = 0;
} else {
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, false);
if (pbr == null) {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
}
size = pbr.cursor.getCount();
}
if (size == 0) {
/* Sending "+CPBR: (1-0)" can confused some carkits, send "1-1"
* instead */
size = 1;
}
return new AtCommandResult("+CPBR: (1-" + size + "),30,30");
}
});
}
| public void register(AtParser parser) {
// Select Character Set
// Always send UTF-8, but pretend to support IRA and GSM for compatability
// TODO: Implement IRA and GSM encoding instead of faking it
parser.register("+CSCS", new AtCommandHandler() {
@Override
public AtCommandResult handleReadCommand() {
return new AtCommandResult("+CSCS: \"UTF-8\"");
}
@Override
public AtCommandResult handleSetCommand(Object[] args) {
if (args.length < 1) {
return new AtCommandResult(AtCommandResult.ERROR);
}
if (((String)args[0]).equals("\"GSM\"") || ((String)args[0]).equals("\"IRA\"") ||
((String)args[0]).equals("\"UTF-8\"") ||
((String)args[0]).equals("\"UTF8\"") ) {
return new AtCommandResult(AtCommandResult.OK);
} else {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
}
}
@Override
public AtCommandResult handleTestCommand() {
return new AtCommandResult( "+CSCS: (\"UTF-8\",\"IRA\",\"GSM\")");
}
});
// Select PhoneBook memory Storage
parser.register("+CPBS", new AtCommandHandler() {
@Override
public AtCommandResult handleReadCommand() {
// Return current size and max size
if ("SM".equals(mCurrentPhonebook)) {
return new AtCommandResult("+CPBS: \"SM\",0," + getMaxPhoneBookSize(0));
}
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, true);
if (pbr == null) {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
}
int size = pbr.cursor.getCount();
return new AtCommandResult("+CPBS: \"" + mCurrentPhonebook + "\"," +
size + "," + getMaxPhoneBookSize(size));
}
@Override
public AtCommandResult handleSetCommand(Object[] args) {
// Select phonebook memory
if (args.length < 1 || !(args[0] instanceof String)) {
return new AtCommandResult(AtCommandResult.ERROR);
}
String pb = ((String)args[0]).trim();
while (pb.endsWith("\"")) pb = pb.substring(0, pb.length() - 1);
while (pb.startsWith("\"")) pb = pb.substring(1, pb.length());
if (getPhonebookResult(pb, false) == null && !"SM".equals(pb)) {
if (DBG) log("Dont know phonebook: '" + pb + "'");
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_SUPPORTED);
}
mCurrentPhonebook = pb;
return new AtCommandResult(AtCommandResult.OK);
}
@Override
public AtCommandResult handleTestCommand() {
return new AtCommandResult("+CPBS: (\"ME\",\"SM\",\"DC\",\"RC\",\"MC\")");
}
});
// Read PhoneBook Entries
parser.register("+CPBR", new AtCommandHandler() {
@Override
public AtCommandResult handleSetCommand(Object[] args) {
// Phone Book Read Request
// AT+CPBR=<index1>[,<index2>]
// Parse indexes
int index1;
int index2;
if (args.length < 1 || !(args[0] instanceof Integer)) {
return new AtCommandResult(AtCommandResult.ERROR);
} else {
index1 = (Integer)args[0];
}
if (args.length == 1) {
index2 = index1;
} else if (!(args[1] instanceof Integer)) {
return mHandsfree.reportCmeError(BluetoothCmeError.TEXT_HAS_INVALID_CHARS);
} else {
index2 = (Integer)args[1];
}
// Shortcut SM phonebook
if ("SM".equals(mCurrentPhonebook)) {
return new AtCommandResult(AtCommandResult.OK);
}
// Check phonebook
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, false);
if (pbr == null) {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
}
// More sanity checks
// Send OK instead of ERROR if these checks fail.
// When we send error, certain kits like BMW disconnect the
// Handsfree connection.
if (pbr.cursor.getCount() == 0 || index1 <= 0 || index2 < index1 ||
index2 > pbr.cursor.getCount() || index1 > pbr.cursor.getCount()) {
return new AtCommandResult(AtCommandResult.OK);
}
// Process
AtCommandResult result = new AtCommandResult(AtCommandResult.OK);
int errorDetected = -1; // no error
pbr.cursor.moveToPosition(index1 - 1);
for (int index = index1; index <= index2; index++) {
String number = pbr.cursor.getString(pbr.numberColumn);
String name = null;
int type = -1;
if (pbr.nameColumn == -1) {
// try caller id lookup
// TODO: This code is horribly inefficient. I saw it
// take 7 seconds to process 100 missed calls.
Cursor c = mContext.getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup.TYPE},
null, null, null);
if (c != null) {
if (c.moveToFirst()) {
name = c.getString(0);
type = c.getInt(1);
}
c.close();
}
if (DBG && name == null) log("Caller ID lookup failed for " + number);
} else {
name = pbr.cursor.getString(pbr.nameColumn);
}
if (name == null) name = "";
name = name.trim();
if (name.length() > 28) name = name.substring(0, 28);
if (pbr.typeColumn != -1) {
type = pbr.cursor.getInt(pbr.typeColumn);
name = name + "/" + getPhoneType(type);
}
if (number == null) number = "";
int regionType = PhoneNumberUtils.toaFromString(number);
number = number.trim();
number = PhoneNumberUtils.stripSeparators(number);
if (number.length() > 30) number = number.substring(0, 30);
if (number.equals("-1")) {
// unknown numbers are stored as -1 in our database
number = "";
name = "unknown";
}
result.addResponse("+CPBR: " + index + ",\"" + number + "\"," +
regionType + ",\"" + name + "\"");
if (!pbr.cursor.moveToNext()) {
break;
}
}
return result;
}
@Override
public AtCommandResult handleTestCommand() {
/* Ideally we should return the maximum range of valid index's
* for the selected phone book, but this causes problems for the
* Parrot CK3300. So instead send just the range of currently
* valid index's.
*/
int size;
if ("SM".equals(mCurrentPhonebook)) {
size = 0;
} else {
PhonebookResult pbr = getPhonebookResult(mCurrentPhonebook, false);
if (pbr == null) {
return mHandsfree.reportCmeError(BluetoothCmeError.OPERATION_NOT_ALLOWED);
}
size = pbr.cursor.getCount();
}
if (size == 0) {
/* Sending "+CPBR: (1-0)" can confused some carkits, send "1-1"
* instead */
size = 1;
}
return new AtCommandResult("+CPBR: (1-" + size + "),30,30");
}
});
}
|
diff --git a/src/simpleserver/thread/AutoFreeSpaceChecker.java b/src/simpleserver/thread/AutoFreeSpaceChecker.java
index 99e3f10..8cbbf95 100644
--- a/src/simpleserver/thread/AutoFreeSpaceChecker.java
+++ b/src/simpleserver/thread/AutoFreeSpaceChecker.java
@@ -1,112 +1,112 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package simpleserver.thread;
import static simpleserver.util.Util.*;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;
import simpleserver.Server;
public class AutoFreeSpaceChecker {
private static final int period = 5 * 60 * 1000;
private final Timer timer;
private final Server server;
public AutoFreeSpaceChecker(Server server) {
check(false);
timer = new Timer();
timer.schedule(new Checker(), 0, period);
this.server = server;
}
// TODO maybe adapt to current files considered for backup or only check space
// of map
public void check(boolean beforeBackup) {
try {
long neededSizeKb = 0;
if (beforeBackup) {
neededSizeKb += Math.round(FileUtils.sizeOfDirectory(server.getWorldDirectory()) / 1024) * 2;
} else {
neededSizeKb = 50 * 1024;
}
long freeSpaceKb = FileSystemUtils.freeSpaceKb();
if (freeSpaceKb < neededSizeKb) {
println("Warning: You have only " +
Math.round(freeSpaceKb / 1024) +
" MB free space in this drive!");
println("Trying to delete old backups...");
int filesDeleted = 0;
while (FileSystemUtils.freeSpaceKb() < neededSizeKb) {
File firstCreatedFile = AutoBackup.oldestBackup();
if (firstCreatedFile != null) {
println("Deleting: " + firstCreatedFile.getPath());
firstCreatedFile.delete();
filesDeleted++;
} else {
println("No backups found...");
return;
}
}
if (filesDeleted > 1) {
println("Deleted " + filesDeleted + " backup archives.");
} else {
println("Deleted 1 backup archive.");
}
}
} catch (IOException e) {
println(e);
println("Free Space Checker Failed!");
} catch (IllegalArgumentException e) {
println(e);
- println("Backup space calculation failed because of a was file deleted during action. Trying again later.");
+ println("Unable to calculate backup space because a file was deleted unexpectedly. SimpleServer will retry backup at a later time.");
}
}
public void cleanup() {
timer.cancel();
}
private final class Checker extends TimerTask {
private Checker() {
super();
}
@Override
public void run() {
check(false);
}
}
}
| true | true | public void check(boolean beforeBackup) {
try {
long neededSizeKb = 0;
if (beforeBackup) {
neededSizeKb += Math.round(FileUtils.sizeOfDirectory(server.getWorldDirectory()) / 1024) * 2;
} else {
neededSizeKb = 50 * 1024;
}
long freeSpaceKb = FileSystemUtils.freeSpaceKb();
if (freeSpaceKb < neededSizeKb) {
println("Warning: You have only " +
Math.round(freeSpaceKb / 1024) +
" MB free space in this drive!");
println("Trying to delete old backups...");
int filesDeleted = 0;
while (FileSystemUtils.freeSpaceKb() < neededSizeKb) {
File firstCreatedFile = AutoBackup.oldestBackup();
if (firstCreatedFile != null) {
println("Deleting: " + firstCreatedFile.getPath());
firstCreatedFile.delete();
filesDeleted++;
} else {
println("No backups found...");
return;
}
}
if (filesDeleted > 1) {
println("Deleted " + filesDeleted + " backup archives.");
} else {
println("Deleted 1 backup archive.");
}
}
} catch (IOException e) {
println(e);
println("Free Space Checker Failed!");
} catch (IllegalArgumentException e) {
println(e);
println("Backup space calculation failed because of a was file deleted during action. Trying again later.");
}
}
| public void check(boolean beforeBackup) {
try {
long neededSizeKb = 0;
if (beforeBackup) {
neededSizeKb += Math.round(FileUtils.sizeOfDirectory(server.getWorldDirectory()) / 1024) * 2;
} else {
neededSizeKb = 50 * 1024;
}
long freeSpaceKb = FileSystemUtils.freeSpaceKb();
if (freeSpaceKb < neededSizeKb) {
println("Warning: You have only " +
Math.round(freeSpaceKb / 1024) +
" MB free space in this drive!");
println("Trying to delete old backups...");
int filesDeleted = 0;
while (FileSystemUtils.freeSpaceKb() < neededSizeKb) {
File firstCreatedFile = AutoBackup.oldestBackup();
if (firstCreatedFile != null) {
println("Deleting: " + firstCreatedFile.getPath());
firstCreatedFile.delete();
filesDeleted++;
} else {
println("No backups found...");
return;
}
}
if (filesDeleted > 1) {
println("Deleted " + filesDeleted + " backup archives.");
} else {
println("Deleted 1 backup archive.");
}
}
} catch (IOException e) {
println(e);
println("Free Space Checker Failed!");
} catch (IllegalArgumentException e) {
println(e);
println("Unable to calculate backup space because a file was deleted unexpectedly. SimpleServer will retry backup at a later time.");
}
}
|
diff --git a/openid-connect-client/src/main/java/org/mitre/openid/connect/client/AbstractOIDCAuthenticationFilter.java b/openid-connect-client/src/main/java/org/mitre/openid/connect/client/AbstractOIDCAuthenticationFilter.java
index 998b0391..8c2a22fe 100644
--- a/openid-connect-client/src/main/java/org/mitre/openid/connect/client/AbstractOIDCAuthenticationFilter.java
+++ b/openid-connect-client/src/main/java/org/mitre/openid/connect/client/AbstractOIDCAuthenticationFilter.java
@@ -1,655 +1,655 @@
/*******************************************************************************
* Copyright 2012 The MITRE Corporation
*
* 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.mitre.openid.connect.client;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.mitre.jwt.model.JwtClaims;
import org.mitre.jwt.signer.JwsAlgorithm;
import org.mitre.jwt.signer.JwtSigner;
import org.mitre.jwt.signer.impl.RsaSigner;
import org.mitre.jwt.signer.service.JwtSigningAndValidationService;
import org.mitre.jwt.signer.service.impl.JwtSigningAndValidationServiceDefault;
import org.mitre.key.fetch.KeyFetcher;
import org.mitre.openid.connect.config.OIDCServerConfiguration;
import org.mitre.openid.connect.model.IdToken;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Abstract OpenID Connect Authentication Filter class
*
* @author nemonik
*
*/
public class AbstractOIDCAuthenticationFilter extends
AbstractAuthenticationProcessingFilter {
protected static final String REDIRECT_URI_SESION_VARIABLE = "redirect_uri";
protected static final String STATE_SESSION_VARIABLE = "state";
protected final static String NONCE_SESSION_VARIABLE = "nonce";
protected final static int HTTP_SOCKET_TIMEOUT = 30000;
protected final static String DEFAULT_SCOPE = "openid";
protected final static String FILTER_PROCESSES_URL = "/openid_connect_login";
private Map<OIDCServerConfiguration, JwtSigningAndValidationService> validationServices = new HashMap<OIDCServerConfiguration, JwtSigningAndValidationService>();
/**
* Builds the redirect_uri that will be sent to the Authorization Endpoint.
* By default returns the URL of the current request minus zero or more
* fields of the URL's query string.
*
* @param request
* the current request which is being processed by this filter
* @param ignoreFields
* an array of field names to ignore.
* @return a URL built from the messaged parameters.
*/
public static String buildRedirectURI(HttpServletRequest request, String[] ignoreFields) {
List<String> ignore = (ignoreFields != null) ? Arrays.asList(ignoreFields) : null;
boolean isFirst = true;
StringBuffer sb = request.getRequestURL();
for (Enumeration<?> e = request.getParameterNames(); e.hasMoreElements();) {
String name = (String) e.nextElement();
if ((ignore == null) || (!ignore.contains(name))) {
// Assume for simplicity that there is only one value
String value = request.getParameter(name);
if (value == null) {
continue;
}
if (isFirst) {
sb.append("?");
isFirst = false;
}
sb.append(name).append("=").append(value);
if (e.hasMoreElements()) {
sb.append("&");
}
}
}
return sb.toString();
}
/**
* Return the URL w/ GET parameters
*
* @param baseURI
* A String containing the protocol, server address, path, and
* program as per "http://server/path/program"
* @param queryStringFields
* A map where each key is the field name and the associated
* key's value is the field value used to populate the URL's
* query string
* @return A String representing the URL in form of
* http://server/path/program?query_string from the messaged
* parameters.
*/
public static String buildURL(String baseURI, Map<String, String> queryStringFields) {
// TODO: replace this with URIUtils call
StringBuilder URLBuilder = new StringBuilder(baseURI);
char appendChar = '?';
for (Map.Entry<String, String> param : queryStringFields.entrySet()) {
try {
URLBuilder.append(appendChar)
.append(param.getKey())
.append('=')
.append(URLEncoder.encode(param.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException uee) {
throw new IllegalStateException(uee);
}
appendChar = '&';
}
return URLBuilder.toString();
}
protected String errorRedirectURI;
protected String scope;
protected int httpSocketTimeout = HTTP_SOCKET_TIMEOUT;
/**
* OpenIdConnectAuthenticationFilter constructor
*/
protected AbstractOIDCAuthenticationFilter() {
super(FILTER_PROCESSES_URL);
}
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
Assert.notNull(errorRedirectURI, "An Error Redirect URI must be supplied");
// prepend the spec necessary DEFAULT_SCOPE
setScope((scope != null && !scope.isEmpty()) ? DEFAULT_SCOPE + " " + scope : DEFAULT_SCOPE);
}
/*
* (non-Javadoc)
*
* @see org.springframework.security.web.authentication.
* AbstractAuthenticationProcessingFilter
* #attemptAuthentication(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
logger.debug("Request: "
+ request.getRequestURI()
+ (StringUtils.isNotBlank(request.getQueryString()) ? "?"
+ request.getQueryString() : ""));
return null;
}
/**
* Handles the authorization grant response
*
* @param authorizationCode
* The Authorization grant code
* @param request
* The request from which to extract parameters and perform the
* authentication
* @return The authenticated user token, or null if authentication is
* incomplete.
* @throws Exception
* @throws UnsupportedEncodingException
*/
protected Authentication handleAuthorizationGrantResponse(String authorizationCode, HttpServletRequest request, OIDCServerConfiguration serverConfig) {
final boolean debug = logger.isDebugEnabled();
HttpSession session = request.getSession();
// check for state
String storedState = getStoredState(session);
if (!StringUtils.isBlank(storedState)) {
String state = request.getParameter("state");
if (!storedState.equals(state)) {
throw new AuthenticationServiceException("State parameter mismatch on return. Expected " + storedState + " got " + state);
}
}
// Handle Token Endpoint interaction
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout));
//
// TODO: basic auth is untested (it wasn't working last I
// tested)
// UsernamePasswordCredentials credentials = new
// UsernamePasswordCredentials(serverConfig.getClientId(),
// serverConfig.getClientSecret());
// ((DefaultHttpClient)
// httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY,
// credentials);
//
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.add("grant_type", "authorization_code");
form.add("code", authorizationCode);
String redirectUri = getStoredRedirectUri(session);
if (redirectUri != null) {
form.add("redirect_uri", redirectUri);
}
// pass clientId and clientSecret in post of request
form.add("client_id", serverConfig.getClientId());
form.add("client_secret", serverConfig.getClientSecret());
if (debug) {
logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointUrl());
logger.debug("form = " + form);
}
String jsonString = null;
try {
jsonString = restTemplate.postForObject(
serverConfig.getTokenEndpointUrl(), form, String.class);
} catch (HttpClientErrorException httpClientErrorException) {
// Handle error
logger.error("Token Endpoint error response: "
+ httpClientErrorException.getStatusText() + " : "
+ httpClientErrorException.getMessage());
throw new AuthenticationServiceException(
"Unable to obtain Access Token.");
}
logger.debug("from TokenEndpoint jsonString = " + jsonString);
JsonElement jsonRoot = new JsonParser().parse(jsonString);
if (!jsonRoot.isJsonObject()) {
throw new AuthenticationServiceException("Token Endpoint did not return a JSON object: " + jsonRoot);
}
JsonObject tokenResponse = jsonRoot.getAsJsonObject();
if (tokenResponse.get("error") != null) {
// Handle error
String error = tokenResponse.get("error")
.getAsString();
logger.error("Token Endpoint returned: " + error);
throw new AuthenticationServiceException("Unable to obtain Access Token. Token Endpoint returned: " + error);
} else {
// Extract the id_token to insert into the
// OpenIdConnectAuthenticationToken
// get out all the token strings
String accessTokenValue = null;
String idTokenValue = null;
String refreshTokenValue = null;
if (tokenResponse.has("access_token")) {
accessTokenValue = tokenResponse.get("access_token").getAsString();
} else {
throw new AuthenticationServiceException("Token Endpoint did not return an access_token: " + jsonString);
}
if (tokenResponse.has("id_token")) {
idTokenValue = tokenResponse.get("id_token").getAsString();
} else {
logger.error("Token Endpoint did not return an id_token");
throw new AuthenticationServiceException("Token Endpoint did not return an id_token");
}
if (tokenResponse.has("refresh_token")) {
refreshTokenValue = tokenResponse.get("refresh_token").getAsString();
}
IdToken idToken = IdToken.parse(idTokenValue); // TODO: catch parsing errors?
// validate our ID Token over a number of tests
JwtClaims idClaims = idToken.getClaims();
// check the signature
JwtSigningAndValidationService jwtValidator = getValidatorForServer(serverConfig);
if (jwtValidator != null) {
if(!jwtValidator.validateSignature(idToken.toString())) {
throw new AuthenticationServiceException("Signature validation failed");
}
} else {
logger.info("No validation service found. Skipping signature validation");
}
// check the issuer
if (idClaims.getIssuer() == null) {
throw new AuthenticationServiceException("Id Token Issuer is null");
} else if (!idClaims.getIssuer().equals(serverConfig.getIssuer())){
throw new AuthenticationServiceException("Issuers do not match, expected " + serverConfig.getIssuer() + " got " + idClaims.getIssuer());
}
// check expiration
if (idClaims.getExpiration() == null) {
throw new AuthenticationServiceException("Id Token does not have required expiration claim");
} else {
// it's not null, see if it's expired
Date now = new Date();
- if (!now.after(idClaims.getExpiration())) {
+ if (now.after(idClaims.getExpiration())) {
throw new AuthenticationServiceException("Id Token is expired: " + idClaims.getExpiration());
}
}
// check audience
if (idClaims.getAudience() == null) {
throw new AuthenticationServiceException("Id token audience is null");
} else if (!idClaims.getAudience().equals(serverConfig.getClientId())) {
throw new AuthenticationServiceException("Audience does not match, expected " + serverConfig.getClientId() + " got " + idClaims.getAudience());
}
// check issued at
if (idClaims.getIssuedAt() == null) {
throw new AuthenticationServiceException("Id Token does not have required issued-at claim");
} else {
// since it's not null, see if it was issued in the future
Date now = new Date();
if (now.before(idClaims.getIssuedAt())) {
throw new AuthenticationServiceException("Id Token was issued in the future: " + idClaims.getIssuedAt());
}
}
// compare the nonce to our stored claim
String nonce = idClaims.getNonce();
if (StringUtils.isBlank(nonce)) {
logger.error("ID token did not contain a nonce claim.");
throw new AuthenticationServiceException("ID token did not contain a nonce claim.");
}
String storedNonce = getStoredNonce(session);
if (!nonce.equals(storedNonce)) {
logger.error("Possible replay attack detected! The comparison of the nonce in the returned "
+ "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");
throw new AuthenticationServiceException(
"Possible replay attack detected! The comparison of the nonce in the returned "
+ "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");
}
// pull the user_id out as a claim on the id_token
String userId = idToken.getTokenClaims().getUserId();
// construct an OpenIdConnectAuthenticationToken and return a Authentication object w/the userId and the idToken
OpenIdConnectAuthenticationToken token = new OpenIdConnectAuthenticationToken(userId, idClaims.getIssuer(), serverConfig, idTokenValue, accessTokenValue, refreshTokenValue);
Authentication authentication = this.getAuthenticationManager().authenticate(token);
return authentication;
}
}
/**
* Initiate an Authorization request
*
* @param request
* The request from which to extract parameters and perform the
* authentication
* @param response
* The response, needed to set a cookie and do a redirect as part
* of a multi-stage authentication process
* @param serverConfiguration
* @throws IOException
* If an input or output exception occurs
*/
protected void handleAuthorizationRequest(HttpServletRequest request,
HttpServletResponse response, OIDCServerConfiguration serverConfiguration) throws IOException {
HttpSession session = request.getSession();
Map<String, String> urlVariables = new HashMap<String, String>();
// Required parameters:
urlVariables.put("response_type", "code");
urlVariables.put("client_id", serverConfiguration.getClientId());
urlVariables.put("scope", scope);
String redirectURI = buildRedirectURI(request, null);
urlVariables.put("redirect_uri", redirectURI);
session.setAttribute(REDIRECT_URI_SESION_VARIABLE, redirectURI);
// Create a string value used to associate a user agent session
// with an ID Token to mitigate replay attacks. The value is
// passed through unmodified to the ID Token. One method is to
// store a random value as a signed session cookie, and pass the
// value in the nonce parameter.
String nonce = createNonce(session);
urlVariables.put("nonce", nonce);
String state = createState(session);
urlVariables.put("state", state);
// Optional parameters:
// TODO: display, prompt, request, request_uri
String authRequest = AbstractOIDCAuthenticationFilter.buildURL(serverConfiguration.getAuthorizationEndpointUrl(), urlVariables);
logger.debug("Auth Request: " + authRequest);
response.sendRedirect(authRequest);
}
/**
* Handle Authorization Endpoint error
*
* @param request
* The request from which to extract parameters and handle the
* error
* @param response
* The response, needed to do a redirect to display the error
* @throws IOException
* If an input or output exception occurs
*/
protected void handleError(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String error = request.getParameter("error");
String errorDescription = request.getParameter("error_description");
String errorURI = request.getParameter("error_uri");
Map<String, String> requestParams = new HashMap<String, String>();
requestParams.put("error", error);
if (errorDescription != null) {
requestParams.put("error_description", errorDescription);
}
if (errorURI != null) {
requestParams.put("error_uri", errorURI);
}
response.sendRedirect(AbstractOIDCAuthenticationFilter.buildURL(
errorRedirectURI, requestParams));
}
public void setErrorRedirectURI(String errorRedirectURI) {
this.errorRedirectURI = errorRedirectURI;
}
public void setScope(String scope) {
this.scope = scope;
}
/**
* Get the named stored session variable as a string. Return null if not found or not a string.
* @param session
* @param key
* @return
*/
private static String getStoredSessionString(HttpSession session, String key) {
Object o = session.getAttribute(key);
if (o != null && o instanceof String) {
return o.toString();
} else {
return null;
}
}
/**
* Create a cryptographically random nonce and store it in the session
* @param session
* @return
*/
protected static String createNonce(HttpSession session) {
String nonce = new BigInteger(50, new SecureRandom()).toString(16);
session.setAttribute(NONCE_SESSION_VARIABLE, nonce);
return nonce;
}
/**
* Get the nonce we stored in the session
* @param session
* @return
*/
protected static String getStoredNonce(HttpSession session) {
return getStoredSessionString(session, NONCE_SESSION_VARIABLE);
}
/**
* Create a cryptographically random state and store it in the session
* @param session
* @return
*/
protected static String createState(HttpSession session) {
String state = new BigInteger(50, new SecureRandom()).toString(16);
session.setAttribute(STATE_SESSION_VARIABLE, state);
return state;
}
/**
* Get the state we stored in the session
* @param session
* @return
*/
protected static String getStoredState(HttpSession session) {
return getStoredSessionString(session, STATE_SESSION_VARIABLE);
}
/**
* Get the stored redirect URI that we used on the way out
* @param serverConfig
* @return
*/
protected static String getStoredRedirectUri(HttpSession session) {
return getStoredSessionString(session, REDIRECT_URI_SESION_VARIABLE);
}
protected JwtSigningAndValidationService getValidatorForServer(OIDCServerConfiguration serverConfig) {
if(getValidationServices().containsKey(serverConfig)){
return validationServices.get(serverConfig);
} else {
KeyFetcher keyFetch = new KeyFetcher();
PublicKey signingKey = null;
if (serverConfig.getJwkSigningUrl() != null) {
// prefer the JWK
signingKey = keyFetch.retrieveJwkKey(serverConfig);
} else if (serverConfig.getX509SigningUrl() != null) {
// use the x509 only if JWK isn't configured
signingKey = keyFetch.retrieveX509Key(serverConfig);
} else {
// no keys configured
logger.warn("No server key URLs configured for " + serverConfig.getIssuer());
}
if (signingKey != null) {
Map<String, JwtSigner> signers = new HashMap<String, JwtSigner>();
if (signingKey instanceof RSAPublicKey) {
RSAPublicKey rsaKey = (RSAPublicKey)signingKey;
// build an RSA signer
RsaSigner signer256 = new RsaSigner(JwsAlgorithm.RS256.getJwaName(), rsaKey, null);
RsaSigner signer384 = new RsaSigner(JwsAlgorithm.RS384.getJwaName(), rsaKey, null);
RsaSigner signer512 = new RsaSigner(JwsAlgorithm.RS512.getJwaName(), rsaKey, null);
signers.put(serverConfig.getIssuer() + JwsAlgorithm.RS256.getJwaName(), signer256);
signers.put(serverConfig.getIssuer() + JwsAlgorithm.RS384.getJwaName(), signer384);
signers.put(serverConfig.getIssuer() + JwsAlgorithm.RS512.getJwaName(), signer512);
}
JwtSigningAndValidationService signingAndValidationService = new JwtSigningAndValidationServiceDefault(signers);
validationServices.put(serverConfig, signingAndValidationService);
return signingAndValidationService;
} else {
// there were either no keys returned or no URLs configured to fetch them, assume no checking on key signatures
return null;
}
}
}
public Map<OIDCServerConfiguration, JwtSigningAndValidationService> getValidationServices() {
return validationServices;
}
public void setValidationServices(
Map<OIDCServerConfiguration, JwtSigningAndValidationService> validationServices) {
this.validationServices = validationServices;
}
}
| true | true | protected Authentication handleAuthorizationGrantResponse(String authorizationCode, HttpServletRequest request, OIDCServerConfiguration serverConfig) {
final boolean debug = logger.isDebugEnabled();
HttpSession session = request.getSession();
// check for state
String storedState = getStoredState(session);
if (!StringUtils.isBlank(storedState)) {
String state = request.getParameter("state");
if (!storedState.equals(state)) {
throw new AuthenticationServiceException("State parameter mismatch on return. Expected " + storedState + " got " + state);
}
}
// Handle Token Endpoint interaction
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout));
//
// TODO: basic auth is untested (it wasn't working last I
// tested)
// UsernamePasswordCredentials credentials = new
// UsernamePasswordCredentials(serverConfig.getClientId(),
// serverConfig.getClientSecret());
// ((DefaultHttpClient)
// httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY,
// credentials);
//
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.add("grant_type", "authorization_code");
form.add("code", authorizationCode);
String redirectUri = getStoredRedirectUri(session);
if (redirectUri != null) {
form.add("redirect_uri", redirectUri);
}
// pass clientId and clientSecret in post of request
form.add("client_id", serverConfig.getClientId());
form.add("client_secret", serverConfig.getClientSecret());
if (debug) {
logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointUrl());
logger.debug("form = " + form);
}
String jsonString = null;
try {
jsonString = restTemplate.postForObject(
serverConfig.getTokenEndpointUrl(), form, String.class);
} catch (HttpClientErrorException httpClientErrorException) {
// Handle error
logger.error("Token Endpoint error response: "
+ httpClientErrorException.getStatusText() + " : "
+ httpClientErrorException.getMessage());
throw new AuthenticationServiceException(
"Unable to obtain Access Token.");
}
logger.debug("from TokenEndpoint jsonString = " + jsonString);
JsonElement jsonRoot = new JsonParser().parse(jsonString);
if (!jsonRoot.isJsonObject()) {
throw new AuthenticationServiceException("Token Endpoint did not return a JSON object: " + jsonRoot);
}
JsonObject tokenResponse = jsonRoot.getAsJsonObject();
if (tokenResponse.get("error") != null) {
// Handle error
String error = tokenResponse.get("error")
.getAsString();
logger.error("Token Endpoint returned: " + error);
throw new AuthenticationServiceException("Unable to obtain Access Token. Token Endpoint returned: " + error);
} else {
// Extract the id_token to insert into the
// OpenIdConnectAuthenticationToken
// get out all the token strings
String accessTokenValue = null;
String idTokenValue = null;
String refreshTokenValue = null;
if (tokenResponse.has("access_token")) {
accessTokenValue = tokenResponse.get("access_token").getAsString();
} else {
throw new AuthenticationServiceException("Token Endpoint did not return an access_token: " + jsonString);
}
if (tokenResponse.has("id_token")) {
idTokenValue = tokenResponse.get("id_token").getAsString();
} else {
logger.error("Token Endpoint did not return an id_token");
throw new AuthenticationServiceException("Token Endpoint did not return an id_token");
}
if (tokenResponse.has("refresh_token")) {
refreshTokenValue = tokenResponse.get("refresh_token").getAsString();
}
IdToken idToken = IdToken.parse(idTokenValue); // TODO: catch parsing errors?
// validate our ID Token over a number of tests
JwtClaims idClaims = idToken.getClaims();
// check the signature
JwtSigningAndValidationService jwtValidator = getValidatorForServer(serverConfig);
if (jwtValidator != null) {
if(!jwtValidator.validateSignature(idToken.toString())) {
throw new AuthenticationServiceException("Signature validation failed");
}
} else {
logger.info("No validation service found. Skipping signature validation");
}
// check the issuer
if (idClaims.getIssuer() == null) {
throw new AuthenticationServiceException("Id Token Issuer is null");
} else if (!idClaims.getIssuer().equals(serverConfig.getIssuer())){
throw new AuthenticationServiceException("Issuers do not match, expected " + serverConfig.getIssuer() + " got " + idClaims.getIssuer());
}
// check expiration
if (idClaims.getExpiration() == null) {
throw new AuthenticationServiceException("Id Token does not have required expiration claim");
} else {
// it's not null, see if it's expired
Date now = new Date();
if (!now.after(idClaims.getExpiration())) {
throw new AuthenticationServiceException("Id Token is expired: " + idClaims.getExpiration());
}
}
// check audience
if (idClaims.getAudience() == null) {
throw new AuthenticationServiceException("Id token audience is null");
} else if (!idClaims.getAudience().equals(serverConfig.getClientId())) {
throw new AuthenticationServiceException("Audience does not match, expected " + serverConfig.getClientId() + " got " + idClaims.getAudience());
}
// check issued at
if (idClaims.getIssuedAt() == null) {
throw new AuthenticationServiceException("Id Token does not have required issued-at claim");
} else {
// since it's not null, see if it was issued in the future
Date now = new Date();
if (now.before(idClaims.getIssuedAt())) {
throw new AuthenticationServiceException("Id Token was issued in the future: " + idClaims.getIssuedAt());
}
}
// compare the nonce to our stored claim
String nonce = idClaims.getNonce();
if (StringUtils.isBlank(nonce)) {
logger.error("ID token did not contain a nonce claim.");
throw new AuthenticationServiceException("ID token did not contain a nonce claim.");
}
String storedNonce = getStoredNonce(session);
if (!nonce.equals(storedNonce)) {
logger.error("Possible replay attack detected! The comparison of the nonce in the returned "
+ "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");
throw new AuthenticationServiceException(
"Possible replay attack detected! The comparison of the nonce in the returned "
+ "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");
}
// pull the user_id out as a claim on the id_token
String userId = idToken.getTokenClaims().getUserId();
// construct an OpenIdConnectAuthenticationToken and return a Authentication object w/the userId and the idToken
OpenIdConnectAuthenticationToken token = new OpenIdConnectAuthenticationToken(userId, idClaims.getIssuer(), serverConfig, idTokenValue, accessTokenValue, refreshTokenValue);
Authentication authentication = this.getAuthenticationManager().authenticate(token);
return authentication;
}
}
| protected Authentication handleAuthorizationGrantResponse(String authorizationCode, HttpServletRequest request, OIDCServerConfiguration serverConfig) {
final boolean debug = logger.isDebugEnabled();
HttpSession session = request.getSession();
// check for state
String storedState = getStoredState(session);
if (!StringUtils.isBlank(storedState)) {
String state = request.getParameter("state");
if (!storedState.equals(state)) {
throw new AuthenticationServiceException("State parameter mismatch on return. Expected " + storedState + " got " + state);
}
}
// Handle Token Endpoint interaction
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout));
//
// TODO: basic auth is untested (it wasn't working last I
// tested)
// UsernamePasswordCredentials credentials = new
// UsernamePasswordCredentials(serverConfig.getClientId(),
// serverConfig.getClientSecret());
// ((DefaultHttpClient)
// httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY,
// credentials);
//
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.add("grant_type", "authorization_code");
form.add("code", authorizationCode);
String redirectUri = getStoredRedirectUri(session);
if (redirectUri != null) {
form.add("redirect_uri", redirectUri);
}
// pass clientId and clientSecret in post of request
form.add("client_id", serverConfig.getClientId());
form.add("client_secret", serverConfig.getClientSecret());
if (debug) {
logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointUrl());
logger.debug("form = " + form);
}
String jsonString = null;
try {
jsonString = restTemplate.postForObject(
serverConfig.getTokenEndpointUrl(), form, String.class);
} catch (HttpClientErrorException httpClientErrorException) {
// Handle error
logger.error("Token Endpoint error response: "
+ httpClientErrorException.getStatusText() + " : "
+ httpClientErrorException.getMessage());
throw new AuthenticationServiceException(
"Unable to obtain Access Token.");
}
logger.debug("from TokenEndpoint jsonString = " + jsonString);
JsonElement jsonRoot = new JsonParser().parse(jsonString);
if (!jsonRoot.isJsonObject()) {
throw new AuthenticationServiceException("Token Endpoint did not return a JSON object: " + jsonRoot);
}
JsonObject tokenResponse = jsonRoot.getAsJsonObject();
if (tokenResponse.get("error") != null) {
// Handle error
String error = tokenResponse.get("error")
.getAsString();
logger.error("Token Endpoint returned: " + error);
throw new AuthenticationServiceException("Unable to obtain Access Token. Token Endpoint returned: " + error);
} else {
// Extract the id_token to insert into the
// OpenIdConnectAuthenticationToken
// get out all the token strings
String accessTokenValue = null;
String idTokenValue = null;
String refreshTokenValue = null;
if (tokenResponse.has("access_token")) {
accessTokenValue = tokenResponse.get("access_token").getAsString();
} else {
throw new AuthenticationServiceException("Token Endpoint did not return an access_token: " + jsonString);
}
if (tokenResponse.has("id_token")) {
idTokenValue = tokenResponse.get("id_token").getAsString();
} else {
logger.error("Token Endpoint did not return an id_token");
throw new AuthenticationServiceException("Token Endpoint did not return an id_token");
}
if (tokenResponse.has("refresh_token")) {
refreshTokenValue = tokenResponse.get("refresh_token").getAsString();
}
IdToken idToken = IdToken.parse(idTokenValue); // TODO: catch parsing errors?
// validate our ID Token over a number of tests
JwtClaims idClaims = idToken.getClaims();
// check the signature
JwtSigningAndValidationService jwtValidator = getValidatorForServer(serverConfig);
if (jwtValidator != null) {
if(!jwtValidator.validateSignature(idToken.toString())) {
throw new AuthenticationServiceException("Signature validation failed");
}
} else {
logger.info("No validation service found. Skipping signature validation");
}
// check the issuer
if (idClaims.getIssuer() == null) {
throw new AuthenticationServiceException("Id Token Issuer is null");
} else if (!idClaims.getIssuer().equals(serverConfig.getIssuer())){
throw new AuthenticationServiceException("Issuers do not match, expected " + serverConfig.getIssuer() + " got " + idClaims.getIssuer());
}
// check expiration
if (idClaims.getExpiration() == null) {
throw new AuthenticationServiceException("Id Token does not have required expiration claim");
} else {
// it's not null, see if it's expired
Date now = new Date();
if (now.after(idClaims.getExpiration())) {
throw new AuthenticationServiceException("Id Token is expired: " + idClaims.getExpiration());
}
}
// check audience
if (idClaims.getAudience() == null) {
throw new AuthenticationServiceException("Id token audience is null");
} else if (!idClaims.getAudience().equals(serverConfig.getClientId())) {
throw new AuthenticationServiceException("Audience does not match, expected " + serverConfig.getClientId() + " got " + idClaims.getAudience());
}
// check issued at
if (idClaims.getIssuedAt() == null) {
throw new AuthenticationServiceException("Id Token does not have required issued-at claim");
} else {
// since it's not null, see if it was issued in the future
Date now = new Date();
if (now.before(idClaims.getIssuedAt())) {
throw new AuthenticationServiceException("Id Token was issued in the future: " + idClaims.getIssuedAt());
}
}
// compare the nonce to our stored claim
String nonce = idClaims.getNonce();
if (StringUtils.isBlank(nonce)) {
logger.error("ID token did not contain a nonce claim.");
throw new AuthenticationServiceException("ID token did not contain a nonce claim.");
}
String storedNonce = getStoredNonce(session);
if (!nonce.equals(storedNonce)) {
logger.error("Possible replay attack detected! The comparison of the nonce in the returned "
+ "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");
throw new AuthenticationServiceException(
"Possible replay attack detected! The comparison of the nonce in the returned "
+ "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");
}
// pull the user_id out as a claim on the id_token
String userId = idToken.getTokenClaims().getUserId();
// construct an OpenIdConnectAuthenticationToken and return a Authentication object w/the userId and the idToken
OpenIdConnectAuthenticationToken token = new OpenIdConnectAuthenticationToken(userId, idClaims.getIssuer(), serverConfig, idTokenValue, accessTokenValue, refreshTokenValue);
Authentication authentication = this.getAuthenticationManager().authenticate(token);
return authentication;
}
}
|
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/ui/TraktSyncActivity.java b/SeriesGuide/src/com/battlelancer/seriesguide/ui/TraktSyncActivity.java
index ae06b7d08..0aea0645e 100644
--- a/SeriesGuide/src/com/battlelancer/seriesguide/ui/TraktSyncActivity.java
+++ b/SeriesGuide/src/com/battlelancer/seriesguide/ui/TraktSyncActivity.java
@@ -1,184 +1,184 @@
/*
* Copyright 2011 Uwe Trottmann
*
* 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.battlelancer.seriesguide.ui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import com.actionbarsherlock.app.ActionBar;
import com.battlelancer.seriesguide.provider.SeriesContract.Shows;
import com.battlelancer.seriesguide.util.TraktSync;
import com.google.analytics.tracking.android.EasyTracker;
import com.uwetrottmann.seriesguide.R;
public class TraktSyncActivity extends BaseActivity {
private static final int DIALOG_SELECT_SHOWS = 100;
private static final String TAG = "TraktSyncActivity";
private TraktSync mSyncTask;
private CheckBox mSyncUnseenEpisodes;
private View mContainer;
public void fireTrackerEvent(String label) {
EasyTracker.getTracker().trackEvent(TAG, "Click", label, (long) 0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trakt_sync);
final ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
mContainer = findViewById(R.id.syncbuttons);
mSyncUnseenEpisodes = (CheckBox) findViewById(R.id.checkBoxSyncUnseen);
// Sync to SeriesGuide button
final Button syncToDeviceButton = (Button) findViewById(R.id.syncToDeviceButton);
syncToDeviceButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
fireTrackerEvent("Sync to SeriesGuide");
if (mSyncTask == null
|| (mSyncTask != null && mSyncTask.getStatus() == AsyncTask.Status.FINISHED)) {
mSyncTask = (TraktSync) new TraktSync(TraktSyncActivity.this, mContainer,
false, mSyncUnseenEpisodes.isChecked()).execute();
}
}
});
// Sync to trakt button
final Button syncToTraktButton = (Button) findViewById(R.id.syncToTraktButton);
syncToTraktButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_SELECT_SHOWS);
}
});
}
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSyncUnseenEpisodes = prefs.getBoolean(
SeriesGuidePreferences.KEY_SYNC_UNSEEN_EPISODES, false);
mSyncUnseenEpisodes.setChecked(isSyncUnseenEpisodes);
}
@Override
protected void onPause() {
super.onPause();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean(SeriesGuidePreferences.KEY_SYNC_UNSEEN_EPISODES,
mSyncUnseenEpisodes.isChecked()).commit();
}
@Override
protected void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mSyncTask != null && mSyncTask.getStatus() == AsyncTask.Status.RUNNING) {
mSyncTask.cancel(true);
mSyncTask = null;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_SELECT_SHOWS:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle(R.string.trakt_synctotrakt);
+ builder.setTitle(R.string.trakt_upload);
final Cursor shows = getContentResolver().query(Shows.CONTENT_URI, new String[] {
Shows._ID, Shows.TITLE, Shows.SYNCENABLED
}, null, null, Shows.TITLE + " ASC");
String[] showTitles = new String[shows.getCount()];
boolean[] syncEnabled = new boolean[shows.getCount()];
for (int i = 0; i < showTitles.length; i++) {
shows.moveToNext();
showTitles[i] = shows.getString(1);
syncEnabled[i] = shows.getInt(2) == 1;
}
builder.setMultiChoiceItems(showTitles, syncEnabled,
new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
shows.moveToFirst();
shows.move(which);
final String showId = shows.getString(0);
final ContentValues values = new ContentValues();
values.put(Shows.SYNCENABLED, isChecked);
getContentResolver().update(Shows.buildShowUri(showId), values,
null, null);
}
});
- builder.setPositiveButton(R.string.trakt_synctotrakt,
+ builder.setPositiveButton(R.string.trakt_upload,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
fireTrackerEvent("Sync to trakt");
if (mSyncTask == null
|| (mSyncTask != null && mSyncTask.getStatus() == AsyncTask.Status.FINISHED)) {
mSyncTask = (TraktSync) new TraktSync(TraktSyncActivity.this,
mContainer, true, mSyncUnseenEpisodes.isChecked())
.execute();
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
}
return null;
}
}
| false | true | protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_SELECT_SHOWS:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.trakt_synctotrakt);
final Cursor shows = getContentResolver().query(Shows.CONTENT_URI, new String[] {
Shows._ID, Shows.TITLE, Shows.SYNCENABLED
}, null, null, Shows.TITLE + " ASC");
String[] showTitles = new String[shows.getCount()];
boolean[] syncEnabled = new boolean[shows.getCount()];
for (int i = 0; i < showTitles.length; i++) {
shows.moveToNext();
showTitles[i] = shows.getString(1);
syncEnabled[i] = shows.getInt(2) == 1;
}
builder.setMultiChoiceItems(showTitles, syncEnabled,
new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
shows.moveToFirst();
shows.move(which);
final String showId = shows.getString(0);
final ContentValues values = new ContentValues();
values.put(Shows.SYNCENABLED, isChecked);
getContentResolver().update(Shows.buildShowUri(showId), values,
null, null);
}
});
builder.setPositiveButton(R.string.trakt_synctotrakt,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
fireTrackerEvent("Sync to trakt");
if (mSyncTask == null
|| (mSyncTask != null && mSyncTask.getStatus() == AsyncTask.Status.FINISHED)) {
mSyncTask = (TraktSync) new TraktSync(TraktSyncActivity.this,
mContainer, true, mSyncUnseenEpisodes.isChecked())
.execute();
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
}
return null;
}
| protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_SELECT_SHOWS:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.trakt_upload);
final Cursor shows = getContentResolver().query(Shows.CONTENT_URI, new String[] {
Shows._ID, Shows.TITLE, Shows.SYNCENABLED
}, null, null, Shows.TITLE + " ASC");
String[] showTitles = new String[shows.getCount()];
boolean[] syncEnabled = new boolean[shows.getCount()];
for (int i = 0; i < showTitles.length; i++) {
shows.moveToNext();
showTitles[i] = shows.getString(1);
syncEnabled[i] = shows.getInt(2) == 1;
}
builder.setMultiChoiceItems(showTitles, syncEnabled,
new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
shows.moveToFirst();
shows.move(which);
final String showId = shows.getString(0);
final ContentValues values = new ContentValues();
values.put(Shows.SYNCENABLED, isChecked);
getContentResolver().update(Shows.buildShowUri(showId), values,
null, null);
}
});
builder.setPositiveButton(R.string.trakt_upload,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
fireTrackerEvent("Sync to trakt");
if (mSyncTask == null
|| (mSyncTask != null && mSyncTask.getStatus() == AsyncTask.Status.FINISHED)) {
mSyncTask = (TraktSync) new TraktSync(TraktSyncActivity.this,
mContainer, true, mSyncUnseenEpisodes.isChecked())
.execute();
}
}
});
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
}
return null;
}
|
diff --git a/java/modules/extensions/src/org/apache/synapse/mediators/spring/SpringMediator.java b/java/modules/extensions/src/org/apache/synapse/mediators/spring/SpringMediator.java
index 2b8b4eece..3e0296d32 100644
--- a/java/modules/extensions/src/org/apache/synapse/mediators/spring/SpringMediator.java
+++ b/java/modules/extensions/src/org/apache/synapse/mediators/spring/SpringMediator.java
@@ -1,133 +1,133 @@
/*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.synapse.mediators.spring;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.MessageContext;
import org.apache.synapse.SynapseException;
import org.apache.synapse.Mediator;
import org.apache.synapse.config.Util;
import org.apache.synapse.config.Property;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.InputStreamResource;
/**
* This mediator allows Spring beans implementing the org.apache.synapse.Mediator
* interface to mediate messages passing through Synapse.
*
* A Spring mediator is instantiated by Spring (see www.springframework.org). The mediator
* refers to a Spring bean name, and also either a Spring configuration defined to Synapse
* or an inlined Spring configuration.
*/
public class SpringMediator implements Mediator {
private static final Log log = LogFactory.getLog(SpringMediator.class);
/**
* The Spring bean ref to be used
*/
private String beanName = null;
/**
* The named Spring config to be used
*/
private String configKey = null;
/**
* The Spring ApplicationContext to be used
*/
private ApplicationContext appContext = null;
public boolean mediate(MessageContext synCtx) {
Property dp = synCtx.getConfiguration().getPropertyObject(configKey);
// if the configKey refers to a dynamic property
- if (dp != null) {
+ if (dp != null && dp.getType() == Property.DYNAMIC_TYPE) {
if (!dp.isCached() || dp.isExpired()) {
buildAppContext(synCtx);
}
// if the property is not a DynamicProperty, we will create an ApplicationContext only once
} else {
if (appContext == null) {
buildAppContext(synCtx);
}
}
if (appContext != null) {
Object o = appContext.getBean(beanName);
if (o != null && Mediator.class.isAssignableFrom(o.getClass())) {
Mediator m = (Mediator) o;
return m.mediate(synCtx);
} else {
handleException("Could not load bean named : " + beanName +
" from the Spring configuration with key : " + configKey);
}
} else {
handleException("Cannot reference Spring application context with key : " + configKey);
}
return true;
}
private synchronized void buildAppContext(MessageContext synCtx) {
log.debug("Creating Spring ApplicationContext from property key : " + configKey);
GenericApplicationContext appContext = new GenericApplicationContext();
XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(appContext);
xbdr.setValidating(false);
xbdr.loadBeanDefinitions(new InputStreamResource(
Util.getStreamSource(
synCtx.getConfiguration().getProperty(configKey)).getInputStream()));
appContext.refresh();
this.appContext = appContext;
}
private void handleException(String msg) {
log.error(msg);
throw new SynapseException(msg);
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public String getConfigKey() {
return configKey;
}
public void setConfigKey(String configKey) {
this.configKey = configKey;
}
public ApplicationContext getAppContext() {
return appContext;
}
public void setAppContext(ApplicationContext appContext) {
this.appContext = appContext;
}
public String getType() {
return "SpringMediator";
}
}
| true | true | public boolean mediate(MessageContext synCtx) {
Property dp = synCtx.getConfiguration().getPropertyObject(configKey);
// if the configKey refers to a dynamic property
if (dp != null) {
if (!dp.isCached() || dp.isExpired()) {
buildAppContext(synCtx);
}
// if the property is not a DynamicProperty, we will create an ApplicationContext only once
} else {
if (appContext == null) {
buildAppContext(synCtx);
}
}
if (appContext != null) {
Object o = appContext.getBean(beanName);
if (o != null && Mediator.class.isAssignableFrom(o.getClass())) {
Mediator m = (Mediator) o;
return m.mediate(synCtx);
} else {
handleException("Could not load bean named : " + beanName +
" from the Spring configuration with key : " + configKey);
}
} else {
handleException("Cannot reference Spring application context with key : " + configKey);
}
return true;
}
| public boolean mediate(MessageContext synCtx) {
Property dp = synCtx.getConfiguration().getPropertyObject(configKey);
// if the configKey refers to a dynamic property
if (dp != null && dp.getType() == Property.DYNAMIC_TYPE) {
if (!dp.isCached() || dp.isExpired()) {
buildAppContext(synCtx);
}
// if the property is not a DynamicProperty, we will create an ApplicationContext only once
} else {
if (appContext == null) {
buildAppContext(synCtx);
}
}
if (appContext != null) {
Object o = appContext.getBean(beanName);
if (o != null && Mediator.class.isAssignableFrom(o.getClass())) {
Mediator m = (Mediator) o;
return m.mediate(synCtx);
} else {
handleException("Could not load bean named : " + beanName +
" from the Spring configuration with key : " + configKey);
}
} else {
handleException("Cannot reference Spring application context with key : " + configKey);
}
return true;
}
|
diff --git a/src/de/ueller/gps/nmea/NmeaMessage.java b/src/de/ueller/gps/nmea/NmeaMessage.java
index c6c38c11..a2e2f50e 100644
--- a/src/de/ueller/gps/nmea/NmeaMessage.java
+++ b/src/de/ueller/gps/nmea/NmeaMessage.java
@@ -1,300 +1,299 @@
package de.ueller.gps.nmea;
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* Copyright (c) 2008 Kai Krueger apm at users dot sourceforge dot net
* See Copying
*/
/**
* Geographic Location in Lat/Lon
* field #: 0 1 2 3 4
* sentence: GLL,####.##,N,#####.##,W
*1, Lat (deg, min, hundredths); 2, North or South; 3, Lon; 4, West
*or East.
*
*Geographic Location in Time Differences
* field #: 0 1 2 3 4 5
* sentence: GTD,#####.#,#####.#,#####.#,#####.#,#####.#
*1-5, TD's for secondaries 1 through 5, respectively.
*
*Bearing to Dest wpt from Origin wpt
* field #: 0 1 2 3 4 5 6
* sentence: BOD,###,T,###,M,####,####
*1-2, brg,True; 3-4, brg, Mag; 5, dest wpt; 6, org wpt.
*
*Vector Track and Speed Over Ground (SOG)
* field #: 0 1 2 3 4 5 6 7 8
* sentence: VTG,###,T,###,M,##.#,N,##.#,K
*1-2, brg, True; 3-4, brg, Mag; 5-6, speed, kNots; 7-8, speed,
*Kilometers/hr.
*
*Cross Track Error
* field #: 0 1 2 3 4 5
* sentence: XTE,A,A,#.##,L,N
*1, blink/SNR (A=valid, V=invalid); 2, cycle lock (A/V); 3-5, dist
*off, Left or Right, Nautical miles or Kilometers.
*
*Autopilot (format A)
* field #: 0 1 2 3 4 5 6 7 8 9 10
* sentence: APA,A,A,#.##,L,N,A,A,###,M,####
*1, blink/SNR (A/V); 2 cycle lock (A/V); 3-5, dist off, Left or
*Right, Nautical miles or Kilometers; 6-7, arrival circle, arrival
*perpendicular (A/V); 8-9, brg, Magnetic; 10, dest wpt.
*
*Bearing to Waypoint along Great Circle
* fld: 0 1 2 3 4 5 6 7 8 9 10 11 12
* sen: BWC,HHMMSS,####.##,N,#####.##,W,###,T,###,M,###.#,N,####
*1, Hours, Minutes, Seconds of universal time code; 2-3, Lat, N/S;
*4-5, Lon, W/E; 6-7, brg, True; 8-9, brg, Mag; 10-12, range,
*Nautical miles or Kilometers, dest wpt.
*
*BWR: Bearing to Waypoint, Rhumbline, BPI: Bearing to Point of
*Interest, all follow data field format of BWC.
*
*/
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import de.ueller.gps.data.Position;
import de.ueller.gps.data.Satelit;
import de.ueller.gps.tools.StringTokenizer;
import de.ueller.gpsMid.mapData.QueueReader;
import de.ueller.midlet.gps.LocationMsgReceiver;
import de.ueller.midlet.gps.Logger;
public class NmeaMessage {
protected static final Logger logger = Logger.getInstance(NmeaMessage.class,Logger.TRACE);
public StringBuffer buffer=new StringBuffer(80);
private static String spChar=",";
private float head,speed,alt;
private final LocationMsgReceiver receiver;
private int mAllSatellites;
private int qual;
private boolean lastMsgGSV=false;
private Satelit satelit[]=new Satelit[12];
private Calendar cal = Calendar.getInstance();
public NmeaMessage(LocationMsgReceiver receiver) {
this.receiver = receiver;
}
public StringBuffer getBuffer() {
return buffer;
}
public void decodeMessageOld() {
String [] param = StringTokenizer.getArray(buffer.toString(), spChar);
String sentence=param[0];
try {
receiver.receiveMessage("got " + sentence );
if (lastMsgGSV && ! "GSV".equals(sentence)){
receiver.receiveStatelit(satelit);
satelit=new Satelit[12];
lastMsgGSV=false;
}
if ("GLL".equals(sentence)){
float lat=getLat(param[1]);
if (param[2].startsWith("S")){
lat *= -1f;
}
float lon=getLon(param[3]);
if (param[4].startsWith("W")){
lat *= -1f;
}
Position p=new Position(lat,lon,0f,speed,head,0,null);
receiver.receivePosItion(p);
} else if ("GGA".equals(sentence)){
// time
// lat
float lat=getLat(param[2]);
if ("S".equals(param[3])){
lat= -lat;
}
// lon
float lon=getLon(param[4]);
if ("W".equals(param[5])){
lon=-lon;
}
// quality
qual = getIntegerToken((String)param[6]);
// no of Sat;
mAllSatellites = getIntegerToken((String)param[7]);
// Relative accuracy of horizontal position
// meters above mean sea level
alt=getFloatToken(param[9]);
// Height of geoid above WGS84 ellipsoid
Position p=new Position(lat,lon,alt,speed,head,0,null);
receiver.receivePosItion(p);
} else if ("VTG".equals(sentence)){
head=getFloatToken(param[1]);
//NMEA is in knots, but GpsMid uses m/s
speed=getFloatToken(param[7])*0.5144444f;
} else if ("GSV".equals(sentence)) {
int j;
j=(getIntegerToken(param[2])-1)*4;
mAllSatellites = getIntegerToken(param[3]);
for (int i=4; i < param.length && j < 12; i+=4, j++) {
if (satelit[j]==null){
satelit[j]=new Satelit();
}
satelit[j].id=getIntegerToken(param[i]);
satelit[j].elev=getIntegerToken(param[i+1]);
satelit[j].azimut=getIntegerToken(param[i+2]);
}
lastMsgGSV=true;
}
} catch (RuntimeException e) {
logger.error("Error while decoding "+sentence + " " + e.getMessage());
}
}
public void decodeMessage() {
decodeMessage(buffer.toString());
}
public void decodeMessage(String nmea_sentence) {
Vector param = StringTokenizer.getVector(nmea_sentence, spChar);
String sentence=(String)param.elementAt(0);
try {
// receiver.receiveMessage("got "+buffer.toString() );
if (lastMsgGSV && ! "GSV".equals(sentence)){
receiver.receiveStatelit(satelit);
satelit=new Satelit[12];
lastMsgGSV=false;
}
if ("GGA".equals(sentence)){
// time
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
// lat
float lat=getLat((String)param.elementAt(2));
if ("S".equals((String)param.elementAt(3))){
lat= -lat;
}
// lon
float lon=getLon((String)param.elementAt(4));
if ("W".equals((String)param.elementAt(5))){
lon=-lon;
}
// quality
qual = getIntegerToken((String)param.elementAt(6));
// no of Sat;
mAllSatellites = getIntegerToken((String)param.elementAt(7));
// Relative accuracy of horizontal position
// meters above mean sea level
alt=getFloatToken((String)param.elementAt(9));
// Height of geoid above WGS84 ellipsoid
} else if ("RMC".equals(sentence)){
/* RMC encodes the recomended minimum information */
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
//Status A=active or V=Void.
String valSolution = (String)param.elementAt(2);
if (valSolution.equals("V")) {
this.qual = 0;
receiver.receiveSolution("No");
return;
}
if (valSolution.equalsIgnoreCase("A") && this.qual == 0) this.qual = 1;
//Latitude
float lat=getLat((String)param.elementAt(3));
if ("S".equals((String)param.elementAt(4))){
lat= -lat;
}
//Longitude
float lon=getLon((String)param.elementAt(5));
if ("W".equals((String)param.elementAt(6))){
lon=-lon;
}
//Speed over the ground in knots
//GpsMid uses m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
//Track angle in degrees
head=getFloatToken((String)param.elementAt(8));
//Date
int date_tmp = getIntegerToken((String)param.elementAt(9));
cal.set(Calendar.YEAR, 2000 + date_tmp % 100);
cal.set(Calendar.MONTH, ((date_tmp / 100) % 100) - 1);
cal.set(Calendar.DAY_OF_MONTH, (date_tmp / 10000) % 100);
//Magnetic Variation
Position p=new Position(lat,lon,alt,speed,head,0,cal.getTime());
receiver.receivePosItion(p);
if (this.qual > 1) {
receiver.receiveSolution("D" + mAllSatellites + "S");
} else {
receiver.receiveSolution(mAllSatellites + "S");
}
} else if ("VTG".equals(sentence)){
head=getFloatToken((String)param.elementAt(1));
//Convert from knots to m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
} else if ("GSV".equals(sentence)) {
/* GSV encodes the satelites that are currently in view
* A maximum of 4 satelites are reported per message,
* if more are visible, then they are split over multiple messages *
*/
int j;
// Calculate which satelites are in this message (message number * 4)
j=(getIntegerToken((String)param.elementAt(2))-1)*4;
- mAllSatellites = getIntegerToken((String)param.elementAt(3));
for (int i=4; i < param.size() && j < 12; i+=4, j++) {
if (satelit[j]==null){
satelit[j]=new Satelit();
}
satelit[j].id=getIntegerToken((String)param.elementAt(i));
satelit[j].elev=getIntegerToken((String)param.elementAt(i+1));
satelit[j].azimut=getIntegerToken((String)param.elementAt(i+2));
//SNR (not stored at the moment)
}
lastMsgGSV=true;
}
} catch (RuntimeException e) {
logger.error("Error while decoding "+sentence + " " + e.getMessage());
}
}
private int getIntegerToken(String s){
if (s==null || s.length()==0)
return 0;
return Integer.parseInt(s);
}
private float getFloatToken(String s){
if (s==null || s.length()==0)
return 0;
return Float.parseFloat(s);
}
private float getLat(String s){
if (s.length() < 2)
return 0.0f;
int lat=Integer.parseInt(s.substring(0,2));
float latf=Float.parseFloat(s.substring(2));
return lat+latf/60;
}
private float getLon(String s){
if (s.length() < 3)
return 0.0f;
int lon=Integer.parseInt(s.substring(0,3));
float lonf=Float.parseFloat(s.substring(3));
return lon+lonf/60;
}
}
| true | true | public void decodeMessage(String nmea_sentence) {
Vector param = StringTokenizer.getVector(nmea_sentence, spChar);
String sentence=(String)param.elementAt(0);
try {
// receiver.receiveMessage("got "+buffer.toString() );
if (lastMsgGSV && ! "GSV".equals(sentence)){
receiver.receiveStatelit(satelit);
satelit=new Satelit[12];
lastMsgGSV=false;
}
if ("GGA".equals(sentence)){
// time
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
// lat
float lat=getLat((String)param.elementAt(2));
if ("S".equals((String)param.elementAt(3))){
lat= -lat;
}
// lon
float lon=getLon((String)param.elementAt(4));
if ("W".equals((String)param.elementAt(5))){
lon=-lon;
}
// quality
qual = getIntegerToken((String)param.elementAt(6));
// no of Sat;
mAllSatellites = getIntegerToken((String)param.elementAt(7));
// Relative accuracy of horizontal position
// meters above mean sea level
alt=getFloatToken((String)param.elementAt(9));
// Height of geoid above WGS84 ellipsoid
} else if ("RMC".equals(sentence)){
/* RMC encodes the recomended minimum information */
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
//Status A=active or V=Void.
String valSolution = (String)param.elementAt(2);
if (valSolution.equals("V")) {
this.qual = 0;
receiver.receiveSolution("No");
return;
}
if (valSolution.equalsIgnoreCase("A") && this.qual == 0) this.qual = 1;
//Latitude
float lat=getLat((String)param.elementAt(3));
if ("S".equals((String)param.elementAt(4))){
lat= -lat;
}
//Longitude
float lon=getLon((String)param.elementAt(5));
if ("W".equals((String)param.elementAt(6))){
lon=-lon;
}
//Speed over the ground in knots
//GpsMid uses m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
//Track angle in degrees
head=getFloatToken((String)param.elementAt(8));
//Date
int date_tmp = getIntegerToken((String)param.elementAt(9));
cal.set(Calendar.YEAR, 2000 + date_tmp % 100);
cal.set(Calendar.MONTH, ((date_tmp / 100) % 100) - 1);
cal.set(Calendar.DAY_OF_MONTH, (date_tmp / 10000) % 100);
//Magnetic Variation
Position p=new Position(lat,lon,alt,speed,head,0,cal.getTime());
receiver.receivePosItion(p);
if (this.qual > 1) {
receiver.receiveSolution("D" + mAllSatellites + "S");
} else {
receiver.receiveSolution(mAllSatellites + "S");
}
} else if ("VTG".equals(sentence)){
head=getFloatToken((String)param.elementAt(1));
//Convert from knots to m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
} else if ("GSV".equals(sentence)) {
/* GSV encodes the satelites that are currently in view
* A maximum of 4 satelites are reported per message,
* if more are visible, then they are split over multiple messages *
*/
int j;
// Calculate which satelites are in this message (message number * 4)
j=(getIntegerToken((String)param.elementAt(2))-1)*4;
mAllSatellites = getIntegerToken((String)param.elementAt(3));
for (int i=4; i < param.size() && j < 12; i+=4, j++) {
if (satelit[j]==null){
satelit[j]=new Satelit();
}
satelit[j].id=getIntegerToken((String)param.elementAt(i));
satelit[j].elev=getIntegerToken((String)param.elementAt(i+1));
satelit[j].azimut=getIntegerToken((String)param.elementAt(i+2));
//SNR (not stored at the moment)
}
lastMsgGSV=true;
}
} catch (RuntimeException e) {
logger.error("Error while decoding "+sentence + " " + e.getMessage());
}
}
| public void decodeMessage(String nmea_sentence) {
Vector param = StringTokenizer.getVector(nmea_sentence, spChar);
String sentence=(String)param.elementAt(0);
try {
// receiver.receiveMessage("got "+buffer.toString() );
if (lastMsgGSV && ! "GSV".equals(sentence)){
receiver.receiveStatelit(satelit);
satelit=new Satelit[12];
lastMsgGSV=false;
}
if ("GGA".equals(sentence)){
// time
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
// lat
float lat=getLat((String)param.elementAt(2));
if ("S".equals((String)param.elementAt(3))){
lat= -lat;
}
// lon
float lon=getLon((String)param.elementAt(4));
if ("W".equals((String)param.elementAt(5))){
lon=-lon;
}
// quality
qual = getIntegerToken((String)param.elementAt(6));
// no of Sat;
mAllSatellites = getIntegerToken((String)param.elementAt(7));
// Relative accuracy of horizontal position
// meters above mean sea level
alt=getFloatToken((String)param.elementAt(9));
// Height of geoid above WGS84 ellipsoid
} else if ("RMC".equals(sentence)){
/* RMC encodes the recomended minimum information */
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
//Status A=active or V=Void.
String valSolution = (String)param.elementAt(2);
if (valSolution.equals("V")) {
this.qual = 0;
receiver.receiveSolution("No");
return;
}
if (valSolution.equalsIgnoreCase("A") && this.qual == 0) this.qual = 1;
//Latitude
float lat=getLat((String)param.elementAt(3));
if ("S".equals((String)param.elementAt(4))){
lat= -lat;
}
//Longitude
float lon=getLon((String)param.elementAt(5));
if ("W".equals((String)param.elementAt(6))){
lon=-lon;
}
//Speed over the ground in knots
//GpsMid uses m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
//Track angle in degrees
head=getFloatToken((String)param.elementAt(8));
//Date
int date_tmp = getIntegerToken((String)param.elementAt(9));
cal.set(Calendar.YEAR, 2000 + date_tmp % 100);
cal.set(Calendar.MONTH, ((date_tmp / 100) % 100) - 1);
cal.set(Calendar.DAY_OF_MONTH, (date_tmp / 10000) % 100);
//Magnetic Variation
Position p=new Position(lat,lon,alt,speed,head,0,cal.getTime());
receiver.receivePosItion(p);
if (this.qual > 1) {
receiver.receiveSolution("D" + mAllSatellites + "S");
} else {
receiver.receiveSolution(mAllSatellites + "S");
}
} else if ("VTG".equals(sentence)){
head=getFloatToken((String)param.elementAt(1));
//Convert from knots to m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
} else if ("GSV".equals(sentence)) {
/* GSV encodes the satelites that are currently in view
* A maximum of 4 satelites are reported per message,
* if more are visible, then they are split over multiple messages *
*/
int j;
// Calculate which satelites are in this message (message number * 4)
j=(getIntegerToken((String)param.elementAt(2))-1)*4;
for (int i=4; i < param.size() && j < 12; i+=4, j++) {
if (satelit[j]==null){
satelit[j]=new Satelit();
}
satelit[j].id=getIntegerToken((String)param.elementAt(i));
satelit[j].elev=getIntegerToken((String)param.elementAt(i+1));
satelit[j].azimut=getIntegerToken((String)param.elementAt(i+2));
//SNR (not stored at the moment)
}
lastMsgGSV=true;
}
} catch (RuntimeException e) {
logger.error("Error while decoding "+sentence + " " + e.getMessage());
}
}
|
diff --git a/src/main/java/org/spiffyui/spiffyforms/server/User.java b/src/main/java/org/spiffyui/spiffyforms/server/User.java
index fc1a782..e211aa6 100644
--- a/src/main/java/org/spiffyui/spiffyforms/server/User.java
+++ b/src/main/java/org/spiffyui/spiffyforms/server/User.java
@@ -1,235 +1,235 @@
/*******************************************************************************
*
* 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.spiffyui.spiffyforms.server;
import java.text.DateFormat;
import java.util.Iterator;
import java.util.Date;
import java.util.HashMap;
import javax.ws.rs.GET;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.WebApplicationException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
// The Java class will be hosted at the URI path "/users"
@Path("/users/{arg1}")
public class User {
static final String RESULT_SUCCESS = "{\"result\" : \"success\"}";
@Context UriInfo uriInfo;
// this Java method finds a particular user in the list of users
static JSONObject findUserInArray(String userID){
JSONArray users = Users.getUserList();
if (users == null)
return null;
JSONObject user = null;
int len = users.length();
try {
for (int i=0; i<len; i++) {
user = users.getJSONObject(i);
if (user != null){
String id = user.getString("userID");
if (userID.equals(id)){
// found it!
return user;
}
}
}
} catch (JSONException je){
// not going to happen in this demo app
}
// if we got here then we didn't find it
return null;
}
// this Java method finds a particular user in the list of users
static int findUserIndexInArray(String userID){
JSONArray users = Users.getUserList();
if (users == null)
return -1;
JSONObject user = null;
int len = users.length();
try {
for (int i=0; i<len; i++) {
user = users.getJSONObject(i);
if (user != null){
String id = user.getString("userID");
if (userID.equals(id)){
// found it!
return i;
}
}
}
} catch (JSONException je){
// not going to happen in this demo app
}
// if we got here then we didn't find it
return -1;
}
// The Java method will process HTTP GET requests
@GET
// The Java method will produce content identified by the MIME Media
// type "application/JSON"
@Produces("application/json")
// This method returns a JSONObject containing the user info
// for the userID passed in the arg1 parameter on the URL
- public String getUserInfo() {
+ public Response getUserInfo() {
MultivaluedMap<String, String> params = uriInfo.getPathParameters();
String userid = params.getFirst("arg1");
if (userid == null){
throw new WebApplicationException(400);
}
JSONObject user = findUserInArray(userid);
if (user == null) {
try {
JSONObject reason = new JSONObject();
reason.put("Text", "User id \""+ userid+"\" not found");
JSONObject subcode = new JSONObject();
subcode.put("Value", "0");
JSONObject code = new JSONObject();
code.put("Subcode", subcode);
code.put("Value", Response.Status.NOT_FOUND);
JSONObject fault = new JSONObject();
fault.put("Code", code);
fault.put("Reason", reason);
Response.ResponseBuilder rb = Response.status(Response.Status.NOT_FOUND);
rb.entity(fault.toString());
Response response = rb.build();
throw new WebApplicationException(response);
} catch (JSONException je){
// this is extremely unlikely to happen with the static data used here.
throw new WebApplicationException(500);
}
}
Response.ResponseBuilder rb = Response.created();
rb.entity(user.toString());
return rb.build();
}
@POST
// The Java method will produce content identified by the MIME Media
// type "application/JSON"
@Produces("application/JSON")
// This method attempts to create new user info based on the info
// in the input string
public String createUser(String input) {
MultivaluedMap<String, String> params = uriInfo.getPathParameters();
String userID = params.getFirst("arg1");
// we know that userID is not null because of the Path annotation
// do we already have this user?
if (findUserInArray(userID) != null){
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
try {
JSONArray userList = Users.getUserList();
if (userList != null){
userList.put(new JSONObject(input));
}
} catch (JSONException je){
// input string was probably not correctly formatted JSON.
// we could perhaps be more informative here.
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
return RESULT_SUCCESS;
}
@PUT
// Modify the information stored for a given user.
// The Java method will produce content identified by the MIME Media
// type "application/JSON"
@Produces("application/json")
@Consumes("application/json")
public String updateUser(String input) {
MultivaluedMap<String, String> params = uriInfo.getPathParameters();
String userID = params.getFirst("arg1");
// we know userID is non-null
JSONObject storedUser = findUserInArray(userID);
if (storedUser != null){
try {
JSONObject inputUser = new JSONObject(input);
Iterator iter = inputUser.keys();
while (iter.hasNext()){
String key = (String)iter.next();
storedUser.put(key, inputUser.get(key));
}
} catch (JSONException je){
// I don't know what could make this happen
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
} else {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return RESULT_SUCCESS;
}
@DELETE
// The Java method will produce content identified by the MIME Media
// type "application/JSON"
@Produces("application/JSON")
public String deleteUser(String input) {
MultivaluedMap<String, String> params = uriInfo.getPathParameters();
String userID = params.getFirst("arg1");
// we know userID is non-null
int i = findUserIndexInArray(userID);
if (i != -1){ // -1 means not found
JSONArray userList = Users.getUserList();
try {
userList.put(i, (Object) null);
} catch (JSONException e) {
e.printStackTrace();
}
return "{\"success\":true}";
} else {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}
}
| true | true | public String getUserInfo() {
MultivaluedMap<String, String> params = uriInfo.getPathParameters();
String userid = params.getFirst("arg1");
if (userid == null){
throw new WebApplicationException(400);
}
JSONObject user = findUserInArray(userid);
if (user == null) {
try {
JSONObject reason = new JSONObject();
reason.put("Text", "User id \""+ userid+"\" not found");
JSONObject subcode = new JSONObject();
subcode.put("Value", "0");
JSONObject code = new JSONObject();
code.put("Subcode", subcode);
code.put("Value", Response.Status.NOT_FOUND);
JSONObject fault = new JSONObject();
fault.put("Code", code);
fault.put("Reason", reason);
Response.ResponseBuilder rb = Response.status(Response.Status.NOT_FOUND);
rb.entity(fault.toString());
Response response = rb.build();
throw new WebApplicationException(response);
} catch (JSONException je){
// this is extremely unlikely to happen with the static data used here.
throw new WebApplicationException(500);
}
}
Response.ResponseBuilder rb = Response.created();
rb.entity(user.toString());
return rb.build();
}
| public Response getUserInfo() {
MultivaluedMap<String, String> params = uriInfo.getPathParameters();
String userid = params.getFirst("arg1");
if (userid == null){
throw new WebApplicationException(400);
}
JSONObject user = findUserInArray(userid);
if (user == null) {
try {
JSONObject reason = new JSONObject();
reason.put("Text", "User id \""+ userid+"\" not found");
JSONObject subcode = new JSONObject();
subcode.put("Value", "0");
JSONObject code = new JSONObject();
code.put("Subcode", subcode);
code.put("Value", Response.Status.NOT_FOUND);
JSONObject fault = new JSONObject();
fault.put("Code", code);
fault.put("Reason", reason);
Response.ResponseBuilder rb = Response.status(Response.Status.NOT_FOUND);
rb.entity(fault.toString());
Response response = rb.build();
throw new WebApplicationException(response);
} catch (JSONException je){
// this is extremely unlikely to happen with the static data used here.
throw new WebApplicationException(500);
}
}
Response.ResponseBuilder rb = Response.created();
rb.entity(user.toString());
return rb.build();
}
|
diff --git a/src/main/java/info/somethingodd/OddItem/OddItemCommandExecutor.java b/src/main/java/info/somethingodd/OddItem/OddItemCommandExecutor.java
index 5f1661a..0fbb3fd 100644
--- a/src/main/java/info/somethingodd/OddItem/OddItemCommandExecutor.java
+++ b/src/main/java/info/somethingodd/OddItem/OddItemCommandExecutor.java
@@ -1,84 +1,85 @@
/* 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 info.somethingodd.OddItem;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* @author Gordon Pettey ([email protected])
*/
public class OddItemCommandExecutor implements CommandExecutor {
private OddItemBase oddItemBase;
/**
* Constructor
* @param oddItemBase Base plugin
*/
public OddItemCommandExecutor(OddItemBase oddItemBase) {
this.oddItemBase = oddItemBase;
}
/**
* @inheritDoc
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("odditem")) {
if (sender.hasPermission("odditem.alias")) {
switch (args.length) {
case 0:
if (sender instanceof Player) {
ItemStack itemStack = ((Player) sender).getItemInHand();
if (itemStack.getTypeId() > 255)
+ itemStack = new ItemStack(itemStack.getTypeId());
itemStack.setDurability((short) 0);
sender.sendMessage(OddItem.getAliases(itemStack).toString());
return true;
}
break;
case 1:
try {
sender.sendMessage(OddItem.getAliases(args[0]).toString());
} catch (IllegalArgumentException e) {
sender.sendMessage("[OddItem] No such alias. Similar: " + e.getMessage());
}
return true;
}
} else {
sender.sendMessage("DENIED");
}
} else if (command.getName().equals("odditeminfo")) {
if (sender.hasPermission("odditem.info")) {
sender.sendMessage("[OddItem] " + OddItem.items.itemCount() + " items with " + OddItem.items.aliasCount() + " aliases");
sender.sendMessage("[OddItem] " + OddItem.groups.groupCount() + " groups with " + OddItem.groups.aliasCount() + " aliases");
} else {
sender.sendMessage("DENIED");
}
return true;
} else if (command.getName().equals("odditemreload")) {
if (sender.hasPermission("odditem.reload")) {
sender.sendMessage("[OddItem] Reloading...");
OddItem.clear();
new OddItemConfiguration(oddItemBase).configure();
} else {
sender.sendMessage("DENIED");
}
return true;
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("odditem")) {
if (sender.hasPermission("odditem.alias")) {
switch (args.length) {
case 0:
if (sender instanceof Player) {
ItemStack itemStack = ((Player) sender).getItemInHand();
if (itemStack.getTypeId() > 255)
itemStack.setDurability((short) 0);
sender.sendMessage(OddItem.getAliases(itemStack).toString());
return true;
}
break;
case 1:
try {
sender.sendMessage(OddItem.getAliases(args[0]).toString());
} catch (IllegalArgumentException e) {
sender.sendMessage("[OddItem] No such alias. Similar: " + e.getMessage());
}
return true;
}
} else {
sender.sendMessage("DENIED");
}
} else if (command.getName().equals("odditeminfo")) {
if (sender.hasPermission("odditem.info")) {
sender.sendMessage("[OddItem] " + OddItem.items.itemCount() + " items with " + OddItem.items.aliasCount() + " aliases");
sender.sendMessage("[OddItem] " + OddItem.groups.groupCount() + " groups with " + OddItem.groups.aliasCount() + " aliases");
} else {
sender.sendMessage("DENIED");
}
return true;
} else if (command.getName().equals("odditemreload")) {
if (sender.hasPermission("odditem.reload")) {
sender.sendMessage("[OddItem] Reloading...");
OddItem.clear();
new OddItemConfiguration(oddItemBase).configure();
} else {
sender.sendMessage("DENIED");
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("odditem")) {
if (sender.hasPermission("odditem.alias")) {
switch (args.length) {
case 0:
if (sender instanceof Player) {
ItemStack itemStack = ((Player) sender).getItemInHand();
if (itemStack.getTypeId() > 255)
itemStack = new ItemStack(itemStack.getTypeId());
itemStack.setDurability((short) 0);
sender.sendMessage(OddItem.getAliases(itemStack).toString());
return true;
}
break;
case 1:
try {
sender.sendMessage(OddItem.getAliases(args[0]).toString());
} catch (IllegalArgumentException e) {
sender.sendMessage("[OddItem] No such alias. Similar: " + e.getMessage());
}
return true;
}
} else {
sender.sendMessage("DENIED");
}
} else if (command.getName().equals("odditeminfo")) {
if (sender.hasPermission("odditem.info")) {
sender.sendMessage("[OddItem] " + OddItem.items.itemCount() + " items with " + OddItem.items.aliasCount() + " aliases");
sender.sendMessage("[OddItem] " + OddItem.groups.groupCount() + " groups with " + OddItem.groups.aliasCount() + " aliases");
} else {
sender.sendMessage("DENIED");
}
return true;
} else if (command.getName().equals("odditemreload")) {
if (sender.hasPermission("odditem.reload")) {
sender.sendMessage("[OddItem] Reloading...");
OddItem.clear();
new OddItemConfiguration(oddItemBase).configure();
} else {
sender.sendMessage("DENIED");
}
return true;
}
return false;
}
|
diff --git a/src/edu/sc/seis/sod/tools/TimeParser.java b/src/edu/sc/seis/sod/tools/TimeParser.java
index 4f95090d9..b3a2e3b3a 100644
--- a/src/edu/sc/seis/sod/tools/TimeParser.java
+++ b/src/edu/sc/seis/sod/tools/TimeParser.java
@@ -1,86 +1,92 @@
package edu.sc.seis.sod.tools;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.ParseException;
import com.martiansoftware.jsap.StringParser;
import edu.iris.Fissures.model.TimeInterval;
import edu.iris.Fissures.model.UnitImpl;
import edu.sc.seis.fissuresUtil.chooser.ClockUtil;
import edu.sc.seis.sod.SodUtil;
public class TimeParser extends StringParser {
/**
* @param - should unspecified fields be floored or ceilinged.
*/
public TimeParser(boolean ceiling){
this.ceiling = ceiling;
}
public Object parse(String arg) throws ParseException {
if(arg.equals("now")) {
return "<now/>";
} else if(arg.equals(PREVIOUS_DAY_BEGIN)) {
arg = PREVIOUS_DAY;
+ }else if(arg.equals("network")){
+ if(ceiling){
+ return "<networkEndTime/>";
+ }else{
+ return "<networkStartTime/>";
+ }
}
Matcher m = datePattern.matcher(arg);
if(!m.matches()) {
throw new ParseException("A time must be formatted as YYYY[[[[[-MM]-DD]-hh]-mm]-ss] like 2006-11-19, not '"
+ arg + "'");
}
Calendar cal = SodUtil.createCalendar(Integer.parseInt(m.group(1)),
extract(m, 2),
extract(m, 3),
extract(m, 4),
extract(m, 5),
extract(m, 6),
ceiling);
DateFormat passcalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
passcalFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
return passcalFormat.format(cal.getTime());
}
private int extract(Matcher m, int i) {
if(m.group(i) == null) {
return -1;
}
return Integer.parseInt(m.group(i));
}
private Pattern datePattern = Pattern.compile("(\\d{4})-?(\\d{2})?-?(\\d{2})?-?(\\d{2})?-?(\\d{2})?-?(\\d{2})?");
public static FlaggedOption createYesterdayParam(String name,
String helpMessage,
boolean ceiling) {
return createParam(name, PREVIOUS_DAY_BEGIN, helpMessage, ceiling);
}
public static FlaggedOption createParam(String name,
String defaultTime,
String helpMessage,
boolean ceiling) {
return new FlaggedOption(name,
new TimeParser(ceiling),
defaultTime,
false,
name.charAt(0),
name,
helpMessage);
}
private boolean ceiling;
private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
private static final String PREVIOUS_DAY = df.format(ClockUtil.now()
.subtract(new TimeInterval(1, UnitImpl.DAY)));
private static String PREVIOUS_DAY_BEGIN = "the previous day, "
+ PREVIOUS_DAY;
}
| true | true | public Object parse(String arg) throws ParseException {
if(arg.equals("now")) {
return "<now/>";
} else if(arg.equals(PREVIOUS_DAY_BEGIN)) {
arg = PREVIOUS_DAY;
}
Matcher m = datePattern.matcher(arg);
if(!m.matches()) {
throw new ParseException("A time must be formatted as YYYY[[[[[-MM]-DD]-hh]-mm]-ss] like 2006-11-19, not '"
+ arg + "'");
}
Calendar cal = SodUtil.createCalendar(Integer.parseInt(m.group(1)),
extract(m, 2),
extract(m, 3),
extract(m, 4),
extract(m, 5),
extract(m, 6),
ceiling);
DateFormat passcalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
passcalFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
return passcalFormat.format(cal.getTime());
}
| public Object parse(String arg) throws ParseException {
if(arg.equals("now")) {
return "<now/>";
} else if(arg.equals(PREVIOUS_DAY_BEGIN)) {
arg = PREVIOUS_DAY;
}else if(arg.equals("network")){
if(ceiling){
return "<networkEndTime/>";
}else{
return "<networkStartTime/>";
}
}
Matcher m = datePattern.matcher(arg);
if(!m.matches()) {
throw new ParseException("A time must be formatted as YYYY[[[[[-MM]-DD]-hh]-mm]-ss] like 2006-11-19, not '"
+ arg + "'");
}
Calendar cal = SodUtil.createCalendar(Integer.parseInt(m.group(1)),
extract(m, 2),
extract(m, 3),
extract(m, 4),
extract(m, 5),
extract(m, 6),
ceiling);
DateFormat passcalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
passcalFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
return passcalFormat.format(cal.getTime());
}
|
diff --git a/src/main/java/org/atlasapi/query/v2/BaseController.java b/src/main/java/org/atlasapi/query/v2/BaseController.java
index d0bfa5b57..e9ea77a71 100644
--- a/src/main/java/org/atlasapi/query/v2/BaseController.java
+++ b/src/main/java/org/atlasapi/query/v2/BaseController.java
@@ -1,84 +1,84 @@
package org.atlasapi.query.v2;
import static org.atlasapi.output.Annotation.defaultAnnotations;
import java.io.IOException;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.atlasapi.application.ApplicationConfiguration;
import org.atlasapi.application.query.ApplicationConfigurationFetcher;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.output.AtlasErrorSummary;
import org.atlasapi.output.AtlasModelWriter;
import org.atlasapi.persistence.logging.AdapterLog;
import org.atlasapi.persistence.logging.AdapterLogEntry;
import org.atlasapi.persistence.logging.AdapterLogEntry.Severity;
import org.atlasapi.query.content.parser.ApplicationConfigurationIncludingQueryBuilder;
import org.atlasapi.query.content.parser.QueryStringBackedQueryBuilder;
import org.joda.time.DateTime;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.metabroadcast.common.base.Maybe;
import com.metabroadcast.common.time.DateTimeZones;
public abstract class BaseController<T> {
protected static final Splitter URI_SPLITTER = Splitter.on(",").omitEmptyStrings().trimResults();
protected final ApplicationConfigurationIncludingQueryBuilder builder;
protected final AdapterLog log;
protected final AtlasModelWriter<? super T> outputter;
private final QueryParameterAnnotationsExtractor annotationExtractor;
private final ApplicationConfigurationFetcher configFetcher;
protected BaseController(ApplicationConfigurationFetcher configFetcher, AdapterLog log, AtlasModelWriter<? super T> outputter) {
this.configFetcher = configFetcher;
this.log = log;
this.outputter = outputter;
this.builder = new ApplicationConfigurationIncludingQueryBuilder(new QueryStringBackedQueryBuilder(), configFetcher);
this.annotationExtractor = new QueryParameterAnnotationsExtractor();
}
protected void errorViewFor(HttpServletRequest request, HttpServletResponse response, AtlasErrorSummary ae) throws IOException {
log.record(new AdapterLogEntry(ae.id(), Severity.ERROR, new DateTime(DateTimeZones.UTC)).withCause(ae.exception()).withSource(this.getClass()));
outputter.writeError(request, response, ae);
}
protected void modelAndViewFor(HttpServletRequest request, HttpServletResponse response, T queryResult) throws IOException {
if (queryResult == null) {
errorViewFor(request, response, AtlasErrorSummary.forException(new NullPointerException("Query result was null")));
} else {
outputter.writeTo(request, response, queryResult, annotationExtractor.extract(request).or(defaultAnnotations()));
}
}
protected ApplicationConfiguration appConfig(HttpServletRequest request) {
Maybe<ApplicationConfiguration> config = configFetcher.configurationFor(request);
return config.hasValue() ? config.requireValue() : ApplicationConfiguration.DEFAULT_CONFIGURATION;
}
protected Set<Publisher> publishers(String publisherString, ApplicationConfiguration config) {
- Set<Publisher> appPublishers = ImmutableSet.copyOf(config.orderdPublishers());
+ Set<Publisher> appPublishers = ImmutableSet.copyOf(config.getEnabledSources());
if (Strings.isNullOrEmpty(publisherString)) {
return appPublishers;
}
ImmutableSet.Builder<Publisher> publishers = ImmutableSet.builder();
for (String publisherKey: URI_SPLITTER.split(publisherString)) {
Maybe<Publisher> publisher = Publisher.fromKey(publisherKey);
if (publisher.hasValue()) {
publishers.add(publisher.requireValue());
}
}
return Sets.intersection(publishers.build(), appPublishers);
}
}
| true | true | protected Set<Publisher> publishers(String publisherString, ApplicationConfiguration config) {
Set<Publisher> appPublishers = ImmutableSet.copyOf(config.orderdPublishers());
if (Strings.isNullOrEmpty(publisherString)) {
return appPublishers;
}
ImmutableSet.Builder<Publisher> publishers = ImmutableSet.builder();
for (String publisherKey: URI_SPLITTER.split(publisherString)) {
Maybe<Publisher> publisher = Publisher.fromKey(publisherKey);
if (publisher.hasValue()) {
publishers.add(publisher.requireValue());
}
}
return Sets.intersection(publishers.build(), appPublishers);
}
| protected Set<Publisher> publishers(String publisherString, ApplicationConfiguration config) {
Set<Publisher> appPublishers = ImmutableSet.copyOf(config.getEnabledSources());
if (Strings.isNullOrEmpty(publisherString)) {
return appPublishers;
}
ImmutableSet.Builder<Publisher> publishers = ImmutableSet.builder();
for (String publisherKey: URI_SPLITTER.split(publisherString)) {
Maybe<Publisher> publisher = Publisher.fromKey(publisherKey);
if (publisher.hasValue()) {
publishers.add(publisher.requireValue());
}
}
return Sets.intersection(publishers.build(), appPublishers);
}
|
diff --git a/src/test/java/org/weymouth/demo/model/DataTest.java b/src/test/java/org/weymouth/demo/model/DataTest.java
index d51d2ad..fcf9320 100755
--- a/src/test/java/org/weymouth/demo/model/DataTest.java
+++ b/src/test/java/org/weymouth/demo/model/DataTest.java
@@ -1,17 +1,18 @@
package org.weymouth.demo.model;
import junit.framework.Assert;
import org.junit.Test;
public class DataTest {
@Test
public void test(){
String probe = "probe";
Data d = new Data(probe);
String data = d.getData();
+ data = null;
Assert.assertNotNull(data);
Assert.assertEquals(probe, data);
}
}
| true | true | public void test(){
String probe = "probe";
Data d = new Data(probe);
String data = d.getData();
Assert.assertNotNull(data);
Assert.assertEquals(probe, data);
}
| public void test(){
String probe = "probe";
Data d = new Data(probe);
String data = d.getData();
data = null;
Assert.assertNotNull(data);
Assert.assertEquals(probe, data);
}
|
diff --git a/DistributedGroupMembership/src/MembershipController.java b/DistributedGroupMembership/src/MembershipController.java
index c025f30..9026867 100644
--- a/DistributedGroupMembership/src/MembershipController.java
+++ b/DistributedGroupMembership/src/MembershipController.java
@@ -1,157 +1,157 @@
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.bind.JAXBException;
public class MembershipController {
//private static int contactPort = 61233;
//private static int failSeconds = 5;
public static void sendJoinGroup(String contactIP, int contactPort) throws JAXBException {
String msg = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<join></join>\n";
try {
Supplier.send(contactIP, contactPort, msg);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sendLeaveGroup(String contactIP, int contactPort) {
String msg = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<leave></leave>\n";
try {
Supplier.send(contactIP, contactPort, msg);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sendGossip(MembershipList list, int contactPort, String ownIP) throws SocketException, UnknownHostException, JAXBException {
ArrayList<MembershipEntry> memList = list.get();
//There can be multiple IPs on the computer. We assume that the first IP OwnIP gets is the interface which is connected to the LAN
//ArrayList<String> ownIPs = OwnIP.find();
//Randomly pick nodes to send the gossip to. Total of n/2+1 nodes, but avoid our own IP in ownIPs.get(0)
for(int i = 0;i < memList.size()/2+1;i++) {
int randNum = (int)(Math.random() * ((memList.size()-1) + 1));
if(randNum == -1)
return;
MembershipEntry mE = memList.get(randNum);
String contactIP = mE.getIPAddress();
// For testing purpose, I commented the filter so that messages are also sent back to our own machine
/*
if(contactIP.equals(ownIP)) {
i = i-1;
continue;
}
*/
String marshalledMessage = DstrMarshaller.toXML(memList);
try {
Supplier.send(contactIP, contactPort, marshalledMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void updateMembershipList(MembershipList own, ArrayList<MembershipEntry> receivedMemList, int failSeconds) {
ArrayList<MembershipEntry> ownMemList = own.get();
for(int i = 0; i < own.get().size(); i++) {
System.out.print(own.get().get(i).getIPAddress() + " ");
}
System.out.println("");
// System.out.println(own.get().size());
for(int i = 0;i < receivedMemList.size();i++) {
//Keep track of whether or not we're already tracking each node in the received member list.
boolean ownMemListContainsReceived = false;
for(int j = 0;j < ownMemList.size();j++) {
String receivedIP = receivedMemList.get(i).getIPAddress();
long receivedJoinedtstamp = receivedMemList.get(i).getJoinedtstamp();
String ownListIP = ownMemList.get(j).getIPAddress();
long ownListJoinedtstamp = ownMemList.get(j).getJoinedtstamp();
//If IP and joinedTsmp of the received entry are the same as in our list, the entry exists
// and we check if there're any updates to do.
if(receivedIP.equals(ownListIP) && receivedJoinedtstamp == ownListJoinedtstamp) {
System.out.println("found: " + ownListIP);
ownMemListContainsReceived = true;
int recListHeartbeat = receivedMemList.get(i).getHeartbeatCounter();
int ownListHeartbeat = ownMemList.get(j).getHeartbeatCounter();
//long recListLastUpdate = receivedMemList.get(i).getLastupdtstamp();
//long ownListLastUpdate = ownMemList.get(j).getLastupdtstamp();
//If the heartbeat of the received list is higher, we update our own list.
if(recListHeartbeat > ownListHeartbeat) {
ownMemList.get(j).setHeartbeat(recListHeartbeat);
long currentTime = new Date().getTime()/1000;
ownMemList.get(j).setLastUpdTstamp(currentTime);
}
break;
}
else if(receivedIP.equals(ownListIP)) {
System.out.println(receivedIP + ": " + receivedJoinedtstamp);
System.out.println(ownListIP + ": " + ownListJoinedtstamp);
}
}
// If we are at the end of our own list and we didn't find an entry in our own list but it appears in the
// received list, we add it.
- if(!ownMemListContainsReceived) {
+ if(!ownMemListContainsReceived && !receivedMemList.get(i).getFailedFlag()) {
System.out.println(receivedMemList.get(i).getIPAddress() + " is not in our list. Adding.");
long currentTime = new Date().getTime()/1000;
receivedMemList.get(i).setLastUpdTstamp(currentTime);
ownMemList.add(receivedMemList.get(i));
}
}
//In this loop, we mark all nodes as failed which are older than currentTime minus failSeconds.
//If a node is marked as failed and the lastUpdate timestamp is older than currentTime - (failSeconds * 2) sec, it is deleted.
for(int i = 0;i < ownMemList.size();i++) {
long currentTime = new Date().getTime()/1000;
long lastUpdate = ownMemList.get(i).getLastupdtstamp();
boolean failedFlag = ownMemList.get(i).getFailedFlag();
if(currentTime - (failSeconds * 2) > lastUpdate && failedFlag == true) {
ownMemList.remove(i);
continue;
} else if(currentTime - failSeconds > lastUpdate) {
ownMemList.get(i).setFailedFlag(true);
}
}
}
}
| true | true | public static void updateMembershipList(MembershipList own, ArrayList<MembershipEntry> receivedMemList, int failSeconds) {
ArrayList<MembershipEntry> ownMemList = own.get();
for(int i = 0; i < own.get().size(); i++) {
System.out.print(own.get().get(i).getIPAddress() + " ");
}
System.out.println("");
// System.out.println(own.get().size());
for(int i = 0;i < receivedMemList.size();i++) {
//Keep track of whether or not we're already tracking each node in the received member list.
boolean ownMemListContainsReceived = false;
for(int j = 0;j < ownMemList.size();j++) {
String receivedIP = receivedMemList.get(i).getIPAddress();
long receivedJoinedtstamp = receivedMemList.get(i).getJoinedtstamp();
String ownListIP = ownMemList.get(j).getIPAddress();
long ownListJoinedtstamp = ownMemList.get(j).getJoinedtstamp();
//If IP and joinedTsmp of the received entry are the same as in our list, the entry exists
// and we check if there're any updates to do.
if(receivedIP.equals(ownListIP) && receivedJoinedtstamp == ownListJoinedtstamp) {
System.out.println("found: " + ownListIP);
ownMemListContainsReceived = true;
int recListHeartbeat = receivedMemList.get(i).getHeartbeatCounter();
int ownListHeartbeat = ownMemList.get(j).getHeartbeatCounter();
//long recListLastUpdate = receivedMemList.get(i).getLastupdtstamp();
//long ownListLastUpdate = ownMemList.get(j).getLastupdtstamp();
//If the heartbeat of the received list is higher, we update our own list.
if(recListHeartbeat > ownListHeartbeat) {
ownMemList.get(j).setHeartbeat(recListHeartbeat);
long currentTime = new Date().getTime()/1000;
ownMemList.get(j).setLastUpdTstamp(currentTime);
}
break;
}
else if(receivedIP.equals(ownListIP)) {
System.out.println(receivedIP + ": " + receivedJoinedtstamp);
System.out.println(ownListIP + ": " + ownListJoinedtstamp);
}
}
// If we are at the end of our own list and we didn't find an entry in our own list but it appears in the
// received list, we add it.
if(!ownMemListContainsReceived) {
System.out.println(receivedMemList.get(i).getIPAddress() + " is not in our list. Adding.");
long currentTime = new Date().getTime()/1000;
receivedMemList.get(i).setLastUpdTstamp(currentTime);
ownMemList.add(receivedMemList.get(i));
}
}
//In this loop, we mark all nodes as failed which are older than currentTime minus failSeconds.
//If a node is marked as failed and the lastUpdate timestamp is older than currentTime - (failSeconds * 2) sec, it is deleted.
for(int i = 0;i < ownMemList.size();i++) {
long currentTime = new Date().getTime()/1000;
long lastUpdate = ownMemList.get(i).getLastupdtstamp();
boolean failedFlag = ownMemList.get(i).getFailedFlag();
if(currentTime - (failSeconds * 2) > lastUpdate && failedFlag == true) {
ownMemList.remove(i);
continue;
} else if(currentTime - failSeconds > lastUpdate) {
ownMemList.get(i).setFailedFlag(true);
}
}
}
| public static void updateMembershipList(MembershipList own, ArrayList<MembershipEntry> receivedMemList, int failSeconds) {
ArrayList<MembershipEntry> ownMemList = own.get();
for(int i = 0; i < own.get().size(); i++) {
System.out.print(own.get().get(i).getIPAddress() + " ");
}
System.out.println("");
// System.out.println(own.get().size());
for(int i = 0;i < receivedMemList.size();i++) {
//Keep track of whether or not we're already tracking each node in the received member list.
boolean ownMemListContainsReceived = false;
for(int j = 0;j < ownMemList.size();j++) {
String receivedIP = receivedMemList.get(i).getIPAddress();
long receivedJoinedtstamp = receivedMemList.get(i).getJoinedtstamp();
String ownListIP = ownMemList.get(j).getIPAddress();
long ownListJoinedtstamp = ownMemList.get(j).getJoinedtstamp();
//If IP and joinedTsmp of the received entry are the same as in our list, the entry exists
// and we check if there're any updates to do.
if(receivedIP.equals(ownListIP) && receivedJoinedtstamp == ownListJoinedtstamp) {
System.out.println("found: " + ownListIP);
ownMemListContainsReceived = true;
int recListHeartbeat = receivedMemList.get(i).getHeartbeatCounter();
int ownListHeartbeat = ownMemList.get(j).getHeartbeatCounter();
//long recListLastUpdate = receivedMemList.get(i).getLastupdtstamp();
//long ownListLastUpdate = ownMemList.get(j).getLastupdtstamp();
//If the heartbeat of the received list is higher, we update our own list.
if(recListHeartbeat > ownListHeartbeat) {
ownMemList.get(j).setHeartbeat(recListHeartbeat);
long currentTime = new Date().getTime()/1000;
ownMemList.get(j).setLastUpdTstamp(currentTime);
}
break;
}
else if(receivedIP.equals(ownListIP)) {
System.out.println(receivedIP + ": " + receivedJoinedtstamp);
System.out.println(ownListIP + ": " + ownListJoinedtstamp);
}
}
// If we are at the end of our own list and we didn't find an entry in our own list but it appears in the
// received list, we add it.
if(!ownMemListContainsReceived && !receivedMemList.get(i).getFailedFlag()) {
System.out.println(receivedMemList.get(i).getIPAddress() + " is not in our list. Adding.");
long currentTime = new Date().getTime()/1000;
receivedMemList.get(i).setLastUpdTstamp(currentTime);
ownMemList.add(receivedMemList.get(i));
}
}
//In this loop, we mark all nodes as failed which are older than currentTime minus failSeconds.
//If a node is marked as failed and the lastUpdate timestamp is older than currentTime - (failSeconds * 2) sec, it is deleted.
for(int i = 0;i < ownMemList.size();i++) {
long currentTime = new Date().getTime()/1000;
long lastUpdate = ownMemList.get(i).getLastupdtstamp();
boolean failedFlag = ownMemList.get(i).getFailedFlag();
if(currentTime - (failSeconds * 2) > lastUpdate && failedFlag == true) {
ownMemList.remove(i);
continue;
} else if(currentTime - failSeconds > lastUpdate) {
ownMemList.get(i).setFailedFlag(true);
}
}
}
|
diff --git a/src/uk/ac/cam/db538/dexter/dex/code/DexCode_AssemblingState.java b/src/uk/ac/cam/db538/dexter/dex/code/DexCode_AssemblingState.java
index 1a2c014b..d7d448c0 100644
--- a/src/uk/ac/cam/db538/dexter/dex/code/DexCode_AssemblingState.java
+++ b/src/uk/ac/cam/db538/dexter/dex/code/DexCode_AssemblingState.java
@@ -1,47 +1,49 @@
package uk.ac.cam.db538.dexter.dex.code;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import lombok.val;
import uk.ac.cam.db538.dexter.dex.DexAssemblingCache;
import uk.ac.cam.db538.dexter.dex.code.insn.DexInstruction;
public class DexCode_AssemblingState {
@Getter private DexCode code;
@Getter private DexAssemblingCache cache;
private Map<DexRegister, Integer> registerAllocation;
private Map<DexCodeElement, Long> elementOffsets;
public DexCode_AssemblingState(DexCode code, DexAssemblingCache cache, Map<DexRegister, Integer> regAlloc) {
this.cache = cache;
this.registerAllocation = regAlloc;
this.code = code;
// initialise elementOffsets
// start by setting the size of each instruction to 1
// later on, it will get increased iteratively
this.elementOffsets = new HashMap<DexCodeElement, Long>();
- long offset = 0;
- for (val elem : code.getInstructionList()) {
- elementOffsets.put(elem, offset);
- if (elem instanceof DexInstruction)
- offset += 1;
+ if (this.code != null) {
+ long offset = 0;
+ for (val elem : this.code.getInstructionList()) {
+ elementOffsets.put(elem, offset);
+ if (elem instanceof DexInstruction)
+ offset += 1;
+ }
}
}
public Map<DexRegister, Integer> getRegisterAllocation() {
return Collections.unmodifiableMap(registerAllocation);
}
public Map<DexCodeElement, Long> getElementOffsets() {
return Collections.unmodifiableMap(elementOffsets);
}
public void setElementOffset(DexCodeElement elem, long offset) {
elementOffsets.put(elem, offset);
}
}
| true | true | public DexCode_AssemblingState(DexCode code, DexAssemblingCache cache, Map<DexRegister, Integer> regAlloc) {
this.cache = cache;
this.registerAllocation = regAlloc;
this.code = code;
// initialise elementOffsets
// start by setting the size of each instruction to 1
// later on, it will get increased iteratively
this.elementOffsets = new HashMap<DexCodeElement, Long>();
long offset = 0;
for (val elem : code.getInstructionList()) {
elementOffsets.put(elem, offset);
if (elem instanceof DexInstruction)
offset += 1;
}
}
| public DexCode_AssemblingState(DexCode code, DexAssemblingCache cache, Map<DexRegister, Integer> regAlloc) {
this.cache = cache;
this.registerAllocation = regAlloc;
this.code = code;
// initialise elementOffsets
// start by setting the size of each instruction to 1
// later on, it will get increased iteratively
this.elementOffsets = new HashMap<DexCodeElement, Long>();
if (this.code != null) {
long offset = 0;
for (val elem : this.code.getInstructionList()) {
elementOffsets.put(elem, offset);
if (elem instanceof DexInstruction)
offset += 1;
}
}
}
|
diff --git a/src/com/jpii/navalbattle/util/WindowLib.java b/src/com/jpii/navalbattle/util/WindowLib.java
index c0583d87..659549cc 100644
--- a/src/com/jpii/navalbattle/util/WindowLib.java
+++ b/src/com/jpii/navalbattle/util/WindowLib.java
@@ -1,81 +1,80 @@
package com.jpii.navalbattle.util;
import java.awt.DisplayMode;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class WindowLib {
JFrame wnd;
int sizew, sizeh,ox,oy;
boolean ready = false;
Timer evilHackTimer;
public WindowLib(JFrame wnd) {
this.wnd = wnd;
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
update();
}
};
evilHackTimer = new Timer(75,al);
evilHackTimer.start();
}
private void update() {
if (wnd != null) {
if (ready) {
wnd.toFront();
}
else {
evilHackTimer.stop();
}
}
else {
evilHackTimer.stop();
}
}
public boolean showFullscreen() {
//evilHackTimer.start();
- NativeLib.setTransparency(wnd, 0.5f);
if (FileUtils.getPlatform() == OS.windows) {
ready = true;
if (wnd == null)
return false;
int clientWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
int clientHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
ox = wnd.getLocation().x;
oy = wnd.getLocation().y;
sizew = wnd.getWidth();
sizeh = wnd.getHeight();
wnd.dispose();
wnd.setUndecorated(true);
wnd.setSize(clientWidth, clientHeight);
wnd.setVisible(true);
wnd.setLocation(new Point(0,0));
try
{
wnd.toFront();
wnd.setAlwaysOnTop(true);
}
catch (Exception ex) {
return false;
}
return true;
}
return false;
}
public void hideFullscreen() {
wnd.dispose();
wnd.setUndecorated(false);
wnd.setVisible(true);
wnd.setSize(sizew, sizeh);
wnd.setAlwaysOnTop(false);
wnd.setLocation(ox,oy);
wnd.toFront();
ready = false;
evilHackTimer.stop();
}
}
| true | true | public boolean showFullscreen() {
//evilHackTimer.start();
NativeLib.setTransparency(wnd, 0.5f);
if (FileUtils.getPlatform() == OS.windows) {
ready = true;
if (wnd == null)
return false;
int clientWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
int clientHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
ox = wnd.getLocation().x;
oy = wnd.getLocation().y;
sizew = wnd.getWidth();
sizeh = wnd.getHeight();
wnd.dispose();
wnd.setUndecorated(true);
wnd.setSize(clientWidth, clientHeight);
wnd.setVisible(true);
wnd.setLocation(new Point(0,0));
try
{
wnd.toFront();
wnd.setAlwaysOnTop(true);
}
catch (Exception ex) {
return false;
}
return true;
}
return false;
}
| public boolean showFullscreen() {
//evilHackTimer.start();
if (FileUtils.getPlatform() == OS.windows) {
ready = true;
if (wnd == null)
return false;
int clientWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
int clientHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
ox = wnd.getLocation().x;
oy = wnd.getLocation().y;
sizew = wnd.getWidth();
sizeh = wnd.getHeight();
wnd.dispose();
wnd.setUndecorated(true);
wnd.setSize(clientWidth, clientHeight);
wnd.setVisible(true);
wnd.setLocation(new Point(0,0));
try
{
wnd.toFront();
wnd.setAlwaysOnTop(true);
}
catch (Exception ex) {
return false;
}
return true;
}
return false;
}
|
diff --git a/table/src/main/uk/ac/starlink/table/formats/AsciiStarTable.java b/table/src/main/uk/ac/starlink/table/formats/AsciiStarTable.java
index 62fe5bb76..8760120e2 100644
--- a/table/src/main/uk/ac/starlink/table/formats/AsciiStarTable.java
+++ b/table/src/main/uk/ac/starlink/table/formats/AsciiStarTable.java
@@ -1,410 +1,414 @@
package uk.ac.starlink.table.formats;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import uk.ac.starlink.table.ColumnInfo;
import uk.ac.starlink.table.DefaultValueInfo;
import uk.ac.starlink.table.DescribedValue;
import uk.ac.starlink.table.TableFormatException;
import uk.ac.starlink.table.ValueInfo;
import uk.ac.starlink.util.DataSource;
/**
* Simple ASCII-format table. This reader attempts to make sensible
* decisions about what is a table and what is not, but inevitably it
* will not be able to read ASCII tables in any format.
* <p>
* Here are the rules:
* <ul>
* <li>Bytes in the file are interpreted as ASCII characters</li>
* <li>Each table row is represented by a single line of text</li>
* <li>Lines are terminated by one or more contiguous line termination
* characters: line feed (0x0A) or carriage return (0x0D)</li>
* <li>Within a line, fields are separated by one or more whitespace
* characters: space (" ") or tab (0x09)</li>
* <li>A field is either an unquoted sequence of non-whitespace characters,
* or a sequence of non-newline characters between matching
* single (') or double (") quote characters -
* spaces are therefore allowed in quoted fields</li>
* <li>Within a quoted field, whitespace characters are permitted and are
* treated literally</li>
* <li>Within a quoted field, any character preceded by a backslash character
* ("\") is treated literally. This allows quote characters to appear
* within a quoted string.</li>
* <li>An empty quoted string (two adjacent quotes) or the string
* "<code>null</code>" (unquoted) represents the null value</li>
* <li>All data lines must contain the same number of fields (this is the
* number of columns in the table)</li>
* <li>The data type of a column is guessed according to the fields that
* appear in the table. If all the fields in one column can be parsed
* as integers (or null values), then that column will turn into an
* integer-type column. The types that are tried, in order of
* preference, are:
* <code>Boolean</code>,
* <code>Short</code>
* <code>Integer</code>,
* <code>Long</code>,
* <code>Float</code>,
* <code>Double</code>,
* <code>String</code>
* </li>
* <li>Empty lines are ignored</li>
* <li>Anything after a hash character "#" (except one in a quoted string)
* on a line is ignored as far as table data goes;
* any line which starts with a "!" is also ignored.
* However, lines which start with a "#" or "!" at the start of the table
* (before any data lines) will be interpreted as metadata as follows:
* <ul>
* <li>The last "#"/"!"-starting line before the first data line may
* contain
* the column names. If it has the same number of fields as
* there are columns in the table, each field will be taken to be
* the title of the corresponding column. Otherwise, it will be
* taken as a normal comment line.</li>
* <li>Any comment lines before the first data line not covered by the
* above will be concatenated to form the "description" parameter
* of the table.</li>
* </ul>
* </li>
* </ul>
*
* @author Mark Taylor (Starlink)
*/
public class AsciiStarTable extends StreamStarTable {
private List comments_;
private boolean dataStarted_;
/**
* Constructs a new AsciiStarTable from a datasource.
*
* @param datsrc the data source containing the table text
* @throws TableFormatException if the input stream doesn't appear to
* form a ASCII-format table
* @throws IOException if some I/O error occurs
*/
public AsciiStarTable( DataSource datsrc )
throws TableFormatException, IOException {
super( datsrc );
}
protected Metadata obtainMetadata()
throws TableFormatException, IOException {
/* Get an input stream. */
PushbackInputStream in = getInputStream();
/* Look at each row in it counting cells and assessing what sort of
* data they look like. */
RowEvaluator evaluator = new RowEvaluator();
comments_ = new ArrayList();
long lrow = 0;
try {
for ( List row; ( row = readRow( in ) ) != null; ) {
lrow++;
evaluator.submitRow( row );
}
}
catch ( TableFormatException e ) {
throw new TableFormatException( e.getMessage() + " at row " + lrow,
e );
}
finally {
if ( in != null ) {
in.close();
}
}
/* Get and check the metadata. */
Metadata meta = evaluator.getMetadata();
if ( meta.nrow_ == 0 ) {
throw new TableFormatException( "No rows" );
}
/* Try to make use of any comment lines we read. */
interpretComments( meta.colInfos_ );
comments_ = null;
return meta;
}
/**
* Tries to make sense of any comment lines which have been read.
* It may make changes to the initial <tt>colInfos</tt> set with
* which it is provided.
*
* @param colInfos column infos already worked out for this table
*/
private void interpretComments( ColumnInfo[] colInfos ) throws IOException {
trimLines( comments_ );
int ncol = colInfos.length;
/* Try to interpret the last remaining comment line as a set of
* column headings. */
if ( comments_.size() > 0 ) {
String hline = (String) comments_.get( comments_.size() - 1 );
List headings = readHeadings( new PushbackInputStream(
new ByteArrayInputStream( hline.getBytes() ) ) );
/* If this line looks like a set of headings (there are the
* right number of fields) modify the colinfos accordingly and
* remove it from the set of comments. */
if ( headings.size() == ncol ) {
comments_.remove( comments_.size() - 1 );
for ( int i = 0; i < ncol; i++ ) {
colInfos[ i ].setName( (String) headings.get( i ) );
}
trimLines( comments_ );
}
}
/* If there are any other comment lines, concatenate them and bung
* them into a description parameter. */
if ( comments_.size() > 0 ) {
StringBuffer dbuf = new StringBuffer();
for ( Iterator it = comments_.iterator(); it.hasNext(); ) {
dbuf.append( (String) it.next() );
if ( it.hasNext() ) {
dbuf.append( '\n' );
}
}
ValueInfo descriptionInfo =
new DefaultValueInfo( "Description", String.class,
"Comments included in text file" );
getParameters().add( new DescribedValue( descriptionInfo,
dbuf.toString() ) );
}
}
/**
* Reads the next row of data from a given stream.
* Ignorable rows are skipped; comments may be stashed away.
*
* @param in input stream
* @return list of Strings one for each cell in the row, or
* <tt>null</tt> for end of stream
*/
protected List readRow( PushbackInputStream in ) throws IOException {
List cellList = new ArrayList();
while ( cellList.size() == 0 ) {
boolean startLine = true;
for ( boolean endLine = false; ! endLine; ) {
int c = in.read();
switch ( (char) c ) {
- case '\r':
- case '\n':
case END:
if ( cellList.size() == 0 ) {
return null;
}
endLine = true;
break;
+ case '\r':
+ case '\n':
+ if ( cellList.size() != 0 ) {
+ endLine = true;
+ }
+ break;
case '#':
if ( ! dataStarted_ ) {
comments_.add( eatLine( in ) );
}
else {
eatLine( in );
}
endLine = true;
break;
case ' ':
case '\t':
break;
case '"':
case '\'':
in.unread( c );
cellList.add( readString( in ) );
break;
case '!':
if ( startLine ) {
if ( ! dataStarted_ ) {
comments_.add( eatLine( in ) );
}
else {
eatLine( in );
}
endLine = true;
break;
}
// if not at start of line fall through to...
default:
in.unread( c );
String tok = readToken( in );
cellList.add( "null".equals( tok ) ? "" : tok );
}
startLine = false;
}
}
dataStarted_ = true;
return cellList;
}
/**
* Reads and discards any characters up to the end of the line.
*
* @param stream the stream to read
*/
private String eatLine( InputStream stream ) throws IOException {
StringBuffer buffer = new StringBuffer();
for ( boolean done = false; ! done; ) {
int c = stream.read();
switch ( (char) c ) {
case '\n':
case '\r':
case END:
done = true;
break;
default:
buffer.append( (char) c );
}
}
return buffer.toString();
}
/**
* Reads a quoted string from a given stream. The string may be
* delimited by single or double quotes. Any character following a
* backslash will be included literally. It is an error for the
* line or stream to end inside the string.
*
* @param stream the stream to read from
* @return the (undelimited) string
* @throws TableFormatException if the line or stream finishes
* inside the string
* @throws IOException if some I/O error occurs
*/
private String readString( InputStream stream ) throws IOException {
char delimiter = (char) stream.read();
StringBuffer buffer = new StringBuffer();
while ( true ) {
int c = stream.read();
if ( c == delimiter ) {
break;
}
else {
switch ( (char) c ) {
case '\r':
case '\n':
throw new TableFormatException(
"End of line within a string literal" );
case '\\':
buffer.append( (char) stream.read() );
break;
case END:
throw new TableFormatException(
"End of file within a string literal" );
default:
buffer.append( (char) c );
}
}
}
return buffer.toString();
}
/**
* Reads a token from the given stream.
* All consecutive non-whitespace characters from the given point are
* read and returned as a single string.
*
* @param stream the stream to read from
* @return the token that was read
* @throws IOException if an I/O error occurs
*/
private String readToken( PushbackInputStream stream ) throws IOException {
StringBuffer buffer = new StringBuffer();
for ( boolean done = false; ! done; ) {
int c = stream.read();
switch ( (char) c ) {
case '\n':
case '\r':
stream.unread( c );
done = true;
break;
case ' ':
case '\t':
case END:
done = true;
break;
default:
buffer.append( (char) c );
}
}
return buffer.toString();
}
/**
* Reads a row of headings from a stream. This is speculative; it
* will interpret the remaining characters in a row as if it is a
* set of text titles for following columns. When the rest of the
* table has been read, if the number of items in this array turns
* out to match the number of columns, we will use these strings
* as column headings. Otherwise, we will throw them away.
*
* @param stream the input stream
*/
private List readHeadings( PushbackInputStream stream ) throws IOException {
List headings = new ArrayList();
for ( boolean done = false; ! done; ) {
int c = stream.read();
switch ( (char) c ) {
case '\r':
case '\n':
done = true;
break;
case ' ':
case '\t':
break;
case '"':
case '\'':
stream.unread( c );
headings.add( readString( stream ) );
break;
case END:
done = true;
break;
default:
stream.unread( c );
headings.add( readToken( stream ) );
}
}
return headings;
}
/**
* Trims blank strings from the top and bottom of a list of strings.
*
* @param lines a List of String objects to trim
*/
private static void trimLines( List lines ) {
/* Strip any blank lines from the top. */
for ( ListIterator it = lines.listIterator( 0 ); it.hasNext(); ) {
String line = (String) it.next();
if ( line.trim().length() == 0 ) {
it.remove();
}
else {
break;
}
}
/* Strip any blank lines from the bottom. */
for ( ListIterator it = lines.listIterator( lines.size() );
it.hasPrevious(); ) {
String line = (String) it.previous();
if ( line.trim().length() == 0 ) {
it.remove();
}
else {
break;
}
}
}
}
| false | true | protected List readRow( PushbackInputStream in ) throws IOException {
List cellList = new ArrayList();
while ( cellList.size() == 0 ) {
boolean startLine = true;
for ( boolean endLine = false; ! endLine; ) {
int c = in.read();
switch ( (char) c ) {
case '\r':
case '\n':
case END:
if ( cellList.size() == 0 ) {
return null;
}
endLine = true;
break;
case '#':
if ( ! dataStarted_ ) {
comments_.add( eatLine( in ) );
}
else {
eatLine( in );
}
endLine = true;
break;
case ' ':
case '\t':
break;
case '"':
case '\'':
in.unread( c );
cellList.add( readString( in ) );
break;
case '!':
if ( startLine ) {
if ( ! dataStarted_ ) {
comments_.add( eatLine( in ) );
}
else {
eatLine( in );
}
endLine = true;
break;
}
// if not at start of line fall through to...
default:
in.unread( c );
String tok = readToken( in );
cellList.add( "null".equals( tok ) ? "" : tok );
}
startLine = false;
}
}
dataStarted_ = true;
return cellList;
}
| protected List readRow( PushbackInputStream in ) throws IOException {
List cellList = new ArrayList();
while ( cellList.size() == 0 ) {
boolean startLine = true;
for ( boolean endLine = false; ! endLine; ) {
int c = in.read();
switch ( (char) c ) {
case END:
if ( cellList.size() == 0 ) {
return null;
}
endLine = true;
break;
case '\r':
case '\n':
if ( cellList.size() != 0 ) {
endLine = true;
}
break;
case '#':
if ( ! dataStarted_ ) {
comments_.add( eatLine( in ) );
}
else {
eatLine( in );
}
endLine = true;
break;
case ' ':
case '\t':
break;
case '"':
case '\'':
in.unread( c );
cellList.add( readString( in ) );
break;
case '!':
if ( startLine ) {
if ( ! dataStarted_ ) {
comments_.add( eatLine( in ) );
}
else {
eatLine( in );
}
endLine = true;
break;
}
// if not at start of line fall through to...
default:
in.unread( c );
String tok = readToken( in );
cellList.add( "null".equals( tok ) ? "" : tok );
}
startLine = false;
}
}
dataStarted_ = true;
return cellList;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.